blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d4549e303ce6b5ec20efa6abbe088f61ffeb40ea | 343773ae835dbbaefde9f653f9211570bd8455d6 | /src/main/java/teamroots/embers/api/power/IEmberPacketProducer.java | 808c2e9465bafa7959a83ae732eacd1ad8e1a5f0 | [
"MIT"
] | permissive | DaedalusGame/EmbersRekindled | a06895d5bc3d0cf6739965828eab96edcdd35a78 | a2437713ea29ee9ca76b3e14f6e67f8e8862ccaa | refs/heads/rekindled | 2022-05-01T12:03:20.268625 | 2021-03-03T19:13:27 | 2021-03-03T19:13:27 | 135,477,242 | 41 | 37 | MIT | 2022-03-26T17:47:02 | 2018-05-30T17:38:40 | Java | UTF-8 | Java | false | false | 215 | java | package teamroots.embers.api.power;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public interface IEmberPacketProducer {
void setTargetPosition(BlockPos pos, EnumFacing side);
}
| [
"bordlistian@hotmail.de"
] | bordlistian@hotmail.de |
13941806b10815ffa1d28cc90a457ce99a5b22fa | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/27/27_91412c601b16af910a0d6d7e90499f12ad8aabfa/TextField/27_91412c601b16af910a0d6d7e90499f12ad8aabfa_TextField_t.java | 03c9dd5ca87303b690144bfe232140cf0b30cce2 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 189,228 | java | //#condition polish.usePolishGui
/*
* Copyright (c) 2004-2009 Robert Virkus / Enough Software
*
* This file is part of J2ME Polish.
*
* J2ME Polish is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* J2ME Polish is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with J2ME Polish; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Commercial licenses are also available, please
* refer to the accompanying LICENSE.txt or visit
* http://www.j2mepolish.org for details.
*/
package de.enough.polish.ui;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
//#if polish.TextField.useVirtualKeyboard
import de.enough.polish.ui.keyboard.view.KeyboardView;
//#endif
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
//#if polish.android
import android.view.View;
import android.view.View.MeasureSpec;
//#endif
//#if polish.TextField.useDirectInput && polish.TextField.usePredictiveInput && !(polish.blackberry || polish.android)
import de.enough.polish.predictive.TextBuilder;
import de.enough.polish.predictive.trie.TrieProvider;
//#endif
import de.enough.polish.util.ArrayList;
import de.enough.polish.util.DeviceControl;
import de.enough.polish.util.DeviceInfo;
import de.enough.polish.util.DrawUtil;
import de.enough.polish.util.IntHashMap;
import de.enough.polish.util.Locale;
import de.enough.polish.util.Properties;
import de.enough.polish.util.TextUtil;
import de.enough.polish.util.WrappedText;
//#if polish.blackberry
import de.enough.polish.blackberry.ui.FixedPointDecimalTextFilter;
import de.enough.polish.blackberry.ui.PolishTextField;
import de.enough.polish.blackberry.ui.PolishEditField;
import de.enough.polish.blackberry.ui.PolishOneLineField;
import de.enough.polish.blackberry.ui.PolishPasswordEditField;
import de.enough.polish.blackberry.ui.PolishEmailAddressEditField;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.text.TextFilter;
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
import com.nokia.mid.ui.TextEditor;
import com.nokia.mid.ui.TextEditorListener;
//#endif
//#if polish.api.windows
import de.enough.polish.windows.Keyboard;
//#endif
//#if polish.android
import de.enough.polish.android.lcdui.AndroidDisplay;
import de.enough.polish.android.lcdui.AndroidTextField;
import de.enough.polish.android.lcdui.AndroidTextFieldImpl;
import de.enough.polish.android.midlet.MidletBridge;
//#endif
/**
* A <code>TextField</code> is an editable text component that may be
* placed into
* a <A HREF="../../../javax/microedition/lcdui/Form.html"><CODE>Form</CODE></A>. It can be
* given a piece of text that is used as the initial value.
*
* <P>A <code>TextField</code> has a maximum size, which is the
* maximum number of characters
* that can be stored in the object at any time (its capacity). This limit is
* enforced when the <code>TextField</code> instance is constructed,
* when the user is editing text within the <code>TextField</code>, as well as
* when the application program calls methods on the
* <code>TextField</code> that modify its
* contents. The maximum size is the maximum stored capacity and is unrelated
* to the number of characters that may be displayed at any given time.
* The number of characters displayed and their arrangement into rows and
* columns are determined by the device. </p>
*
* <p>The implementation may place a boundary on the maximum size, and the
* maximum size actually assigned may be smaller than the application had
* requested. The value actually assigned will be reflected in the value
* returned by <A HREF="../../../javax/microedition/lcdui/TextField.html#getMaxSize()"><CODE>getMaxSize()</CODE></A>. A defensively-written
* application should compare this value to the maximum size requested and be
* prepared to handle cases where they differ.</p>
*
* <a name="constraints"></a>
* <h3>Input Constraints</h3>
*
* <P>The <code>TextField</code> shares the concept of <em>input
* constraints</em> with the <A HREF="../../../javax/microedition/lcdui/TextBox.html"><CODE>TextBox</CODE></A> class. The different
* constraints allow the application to request that the user's input be
* restricted in a variety of ways. The implementation is required to
* restrict the user's input as requested by the application. For example, if
* the application requests the <code>NUMERIC</code> constraint on a
* <code>TextField</code>, the
* implementation must allow only numeric characters to be entered. </p>
*
* <p>The <em>actual contents</em> of the text object are set and modified by
* and are
* reported to the application through the <code>TextBox</code> and
* <code>TextField</code> APIs. The <em>displayed contents</em> may differ
* from the actual contents if the implementation has chosen to provide
* special formatting suitable for the text object's constraint setting.
* For example, a <code>PHONENUMBER</code> field might be displayed with
* digit separators and punctuation as
* appropriate for the phone number conventions in use, grouping the digits
* into country code, area code, prefix, etc. Any spaces or punctuation
* provided are not considered part of the text object's actual contents. For
* example, a text object with the <code>PHONENUMBER</code>
* constraint might display as
* follows:</p>
*
* <pre><code>
* (408) 555-1212
* </code></pre>
*
* <p>but the actual contents of the object visible to the application
* through the APIs would be the string
* "<code>4085551212</code>".
* The <code>size</code> method reflects the number of characters in the
* actual contents, not the number of characters that are displayed, so for
* this example the <code>size</code> method would return <code>10</code>.</p>
*
* <p>Some constraints, such as <code>DECIMAL</code>, require the
* implementation to perform syntactic validation of the contents of the text
* object. The syntax checking is performed on the actual contents of the
* text object, which may differ from the displayed contents as described
* above. Syntax checking is performed on the initial contents passed to the
* constructors, and it is also enforced for all method calls that affect the
* contents of the text object. The methods and constructors throw
* <code>IllegalArgumentException</code> if they would result in the contents
* of the text object not conforming to the required syntax.</p>
*
* <p>The value passed to the <A HREF="../../../javax/microedition/lcdui/TextField.html#setConstraints(int)"><CODE>setConstraints()</CODE></A> method
* consists of a restrictive constraint setting described above, as well as a
* variety of flag bits that modify the behavior of text entry and display.
* The value of the restrictive constraint setting is in the low order
* <code>16</code> bits
* of the value, and it may be extracted by combining the constraint value
* with the <code>CONSTRAINT_MASK</code> constant using the bit-wise
* <code>AND</code> (<code>&</code>) operator.
* The restrictive constraint settings are as follows:
*
* <blockquote><code>
* ANY<br>
* EMAILADDR<br>
* NUMERIC<br>
* PHONENUMBER<br>
* URL<br>
* DECIMAL<br>
* </code></blockquote>
*
* <p>The modifier flags reside in the high order <code>16</code> bits
* of the constraint
* value, that is, those in the complement of the
* <code>CONSTRAINT_MASK</code> constant.
* The modifier flags may be tested individually by combining the constraint
* value with a modifier flag using the bit-wise <code>AND</code>
* (<code>&</code>) operator. The
* modifier flags are as follows:
*
* <blockquote><code>
* PASSWORD<br>
* UNEDITABLE<br>
* SENSITIVE<br>
* NON_PREDICTIVE<br>
* INITIAL_CAPS_WORD<br>
* INITIAL_CAPS_SENTENCE<br>
* </code></blockquote>
*
* <a name="modes"></a>
* <h3>Input Modes</h3>
*
* <p>The <code>TextField</code> shares the concept of <em>input
* modes</em> with the <A HREF="../../../javax/microedition/lcdui/TextBox.html"><CODE>TextBox</CODE></A> class. The application can request that the
* implementation use a particular input mode when the user initiates editing
* of a <code>TextField</code> or <code>TextBox</code>. The input
* mode is a concept that exists within
* the user interface for text entry on a particular device. The application
* does not request an input mode directly, since the user interface for text
* entry is not standardized across devices. Instead, the application can
* request that the entry of certain characters be made convenient. It can do
* this by passing the name of a Unicode character subset to the <A HREF="../../../javax/microedition/lcdui/TextField.html#setInitialInputMode(java.lang.String)"><CODE>setInitialInputMode()</CODE></A> method. Calling this method
* requests that the implementation set the mode of the text entry user
* interface so that it is convenient for the user to enter characters in this
* subset. The application can also request that the input mode have certain
* behavioral characteristics by setting modifier flags in the constraints
* value.
*
* <p>The requested input mode should be used whenever the user initiates the
* editing of a <code>TextBox</code> or <code>TextField</code> object.
* If the user had changed input
* modes in a previous editing session, the application's requested input mode
* should take precedence over the previous input mode set by the user.
* However, the input mode is not restrictive, and the user is allowed to
* change the input mode at any time during editing. If editing is already in
* progress, calls to the <code>setInitialInputMode</code> method do not
* affect the current input mode, but instead take effect at the next time the
* user initiates editing of this text object.
*
* <p>The initial input mode is a hint to the implementation. If the
* implementation cannot provide an input mode that satisfies the
* application's request, it should use a default input mode.
*
* <P>The input mode that results from the application's request is not a
* restriction on the set of characters the user is allowed to enter. The
* user MUST be allowed to switch input modes to enter any character that is
* allowed within the current constraint setting. The constraint
* setting takes precedence over an input mode request, and the implementation
* may refuse to supply a particular input mode if it is inconsistent with the
* current constraint setting.
*
* <P>For example, if the current constraint is <code>ANY</code>, the call</P>
*
* <TABLE BORDER="2">
* <TR>
* <TD ROWSPAN="1" COLSPAN="1">
* <pre><code>
* setInitialInputMode("MIDP_UPPERCASE_LATIN"); </code></pre>
* </TD>
* </TR>
* </TABLE>
*
* <p>should set the initial input mode to allow entry of uppercase Latin
* characters. This does not restrict input to these characters, and the user
* will be able to enter other characters by switching the input mode to allow
* entry of numerals or lowercase Latin letters. However, if the current
* constraint is <code>NUMERIC</code>, the implementation may ignore
* the request to set an
* initial input mode allowing <code>MIDP_UPPERCASE_LATIN</code>
* characters because these
* characters are not allowed in a <code>TextField</code> whose
* constraint is <code>NUMERIC</code>. In
* this case, the implementation may instead use an input mode that allows
* entry of numerals, since such an input mode is most appropriate for entry
* of data under the <code>NUMERIC</code> constraint.
*
* <P>A string is used to name the Unicode character subset passed as a
* parameter to the
* <A HREF="../../../javax/microedition/lcdui/TextField.html#setInitialInputMode(java.lang.String)"><CODE>setInitialInputMode()</CODE></A> method.
* String comparison is case sensitive.
*
* <P>Unicode character blocks can be named by adding the prefix
* "<code>UCB</code>_" to the
* the string names of fields representing Unicode character blocks as defined
* in the J2SE class <code>java.lang.Character.UnicodeBlock</code>. Any
* Unicode character block may be named in this fashion. For convenience, the
* most common Unicode character blocks are listed below.
*
* <blockquote><code>
* UCB_BASIC_LATIN<br>
* UCB_GREEK<br>
* UCB_CYRILLIC<br>
* UCB_ARMENIAN<br>
* UCB_HEBREW<br>
* UCB_ARABIC<br>
* UCB_DEVANAGARI<br>
* UCB_BENGALI<br>
* UCB_THAI<br>
* UCB_HIRAGANA<br>
* UCB_KATAKANA<br>
* UCB_HANGUL_SYLLABLES<br>
* </code></blockquote>
*
* <P>"Input subsets" as defined by the J2SE class
* <code>java.awt.im.InputSubset</code> may be named by adding the prefix
* "<code>IS_</code>" to the string names of fields
* representing input subsets as defined
* in that class. Any defined input subset may be used. For convenience, the
* names of the currently defined input subsets are listed below.
*
* <blockquote><code>
* IS_FULLWIDTH_DIGITS<br>
* IS_FULLWIDTH_LATIN<br>
* IS_HALFWIDTH_KATAKANA<br>
* IS_HANJA<br>
* IS_KANJI<br>
* IS_LATIN<br>
* IS_LATIN_DIGITS<br>
* IS_SIMPLIFIED_HANZI<br>
* IS_TRADITIONAL_HANZI<br>
* </code></blockquote>
*
* <P>MIDP has also defined the following character subsets:
*
* <blockquote>
* <code>MIDP_UPPERCASE_LATIN</code> - the subset of
* <code>IS_LATIN</code> that corresponds to
* uppercase Latin letters
* </blockquote>
* <blockquote>
* <code>MIDP_LOWERCASE_LATIN</code> - the subset of
* <code>IS_LATIN</code> that corresponds to
* lowercase Latin letters
* </blockquote>
*
* <p>
* Finally, implementation-specific character subsets may be named with
* strings that have a prefix of "<code>X_</code>". In
* order to avoid namespace conflicts,
* it is recommended that implementation-specific names include the name of
* the defining company or organization after the initial
* "<code>X_</code>" prefix.
*
* <p> For example, a Japanese language application might have a particular
* <code>TextField</code> that the application intends to be used
* primarily for input of
* words that are "loaned" from languages other than Japanese. The
* application might request an input mode facilitating Hiragana input by
* issuing the following method call:</p>
*
* <TABLE BORDER="2">
* <TR>
* <TD ROWSPAN="1" COLSPAN="1">
* <pre><code>
* textfield.setInitialInputMode("UCB_HIRAGANA"); </code></pre>
* </TD>
* </TR>
* </TABLE>
* <h3>Implementation Note</h3>
*
* <p>Implementations need not compile in all the strings listed above.
* Instead, they need only to compile in the strings that name Unicode
* character subsets that they support. If the subset name passed by the
* application does not match a known subset name, the request should simply
* be ignored without error, and a default input mode should be used. This
* lets implementations support this feature reasonably inexpensively.
* However, it has the consequence that the application cannot tell whether
* its request has been accepted, nor whether the Unicode character subset it
* has requested is actually a valid subset.
* <HR>
*
* @author Robert Virkus, robert@enough.de
* @author Andrew Barnes, andy@geni.com.au basic implementation of direct input
* @since MIDP 1.0
*/
public class TextField extends StringItem
//#if polish.TextField.useDirectInput && !(polish.blackberry || polish.android)
//#define tmp.forceDirectInput
//#define tmp.directInput
//#elif polish.css.textfield-direct-input && !(polish.blackberry || polish.android)
//#define tmp.directInput
//#define tmp.allowDirectInput
//#elif polish.api.windows
//#define tmp.forceDirectInput
//#define tmp.directInput
//#endif
//#if polish.TextField.useDirectInput && polish.TextField.usePredictiveInput && !(polish.blackberry || polish.android)
//#define tmp.usePredictiveInput
//#endif
//#if tmp.directInput && polish.TextField.useDynamicCharset
//#define tmp.useDynamicCharset
//#endif
//#if polish.TextField.supportSymbolsEntry && tmp.directInput
//#define tmp.supportsSymbolEntry
//#if !polish.css.style.textFieldSymbolTable && !polish.css.style.textFieldSymbolList
//#abort You need to define the ".textFieldSymbolList" CSS style when enabling the polish.TextField.supportSymbolsEntry option.
//#endif
//#endif
//#if !(polish.blackberry || polish.doja) || tmp.supportsSymbolEntry
//#defineorappend tmp.implements=CommandListener
//#define tmp.implementsCommandListener
//#endif
//#if polish.TextField.suppressCommands
//#define tmp.suppressCommands
//#if polish.key.maybeSupportsAsciiKeyMap
//#defineorappend tmp.implements=ItemCommandListener
//#define tmp.implementsItemCommandListener
//#endif
//#else
//#defineorappend tmp.implements=ItemCommandListener
//#define tmp.implementsItemCommandListener
//#endif
//#if polish.blackberry
//#defineorappend tmp.implements=FieldChangeListener
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
//#defineorappend tmp.implements=TextEditorListener
//#endif
//#if polish.LibraryBuild
//#define tmp.implementsCommandListener
//#define tmp.implementsItemCommandListener
implements CommandListener, ItemCommandListener
//#if polish.blackberry
// , FieldChangeListener
//#endif
//#elif tmp.implements:defined
//#= implements ${tmp.implements}
//#endif
{
/**
* The user is allowed to enter any text.
* <A HREF="Form.html#linebreak">Line breaks</A> may be entered.
*
* <P>Constant <code>0</code> is assigned to <code>ANY</code>.</P>
*/
public static final int ANY = 0;
/**
* The user is allowed to enter an e-mail address.
*
* <P>Constant <code>1</code> is assigned to <code>EMAILADDR</code>.</P>
*
*/
public static final int EMAILADDR = 1;
/**
* The user is allowed to enter only an integer value. The implementation
* must restrict the contents either to be empty or to consist of an
* optional minus sign followed by a string of one or more decimal
* numerals. Unless the value is empty, it will be successfully parsable
* using <A HREF="../../../java/lang/Integer.html#parseInt(java.lang.String)"><CODE>Integer.parseInt(String)</CODE></A>.
*
* <P>The minus sign consumes space in the text object. It is thus
* impossible to enter negative numbers into a text object whose maximum
* size is <code>1</code>.</P>
*
* <P>Constant <code>2</code> is assigned to <code>NUMERIC</code>.</P>
*
*/
public static final int NUMERIC = 2;
/**
* The user is allowed to enter a phone number. The phone number is a
* special
* case, since a phone-based implementation may be linked to the
* native phone
* dialing application. The implementation may automatically start a phone
* dialer application that is initialized so that pressing a single key
* would be enough to make a call. The call must not made automatically
* without requiring user's confirmation. Implementations may also
* provide a feature to look up the phone number in the device's phone or
* address database.
*
* <P>The exact set of characters allowed is specific to the device and to
* the device's network and may include non-numeric characters, such as a
* "+" prefix character.</P>
*
* <P>Some platforms may provide the capability to initiate voice calls
* using the <A HREF="../../../javax/microedition/midlet/MIDlet.html#platformRequest(java.lang.String)"><CODE>MIDlet.platformRequest</CODE></A> method.</P>
*
* <P>Constant <code>3</code> is assigned to <code>PHONENUMBER</code>.</P>
*
*/
public static final int PHONENUMBER = 3;
/**
* The user is allowed to enter a URL.
*
* <P>Constant <code>4</code> is assigned to <code>URL</code>.</P>
*
*/
public static final int URL = 4;
/**
* The user is allowed to enter numeric values with optional decimal
* fractions, for example "-123", "0.123", or
* ".5".
*
* <p>The implementation may display a period "." or a
* comma "," for the decimal fraction separator, depending on
* the conventions in use on the device. Similarly, the implementation
* may display other device-specific characters as part of a decimal
* string, such as spaces or commas for digit separators. However, the
* only characters allowed in the actual contents of the text object are
* period ".", minus sign "-", and the decimal
* digits.</p>
*
* <p>The actual contents of a <code>DECIMAL</code> text object may be
* empty. If the actual contents are not empty, they must conform to a
* subset of the syntax for a <code>FloatingPointLiteral</code> as defined
* by the <em>Java Language Specification</em>, section 3.10.2. This
* subset syntax is defined as follows: the actual contents
* must consist of an optional minus sign
* "-", followed by one or more whole-number decimal digits,
* followed by an optional fraction separator, followed by zero or more
* decimal fraction digits. The whole-number decimal digits may be
* omitted if the fraction separator and one or more decimal fraction
* digits are present.</p>
*
* <p>The syntax defined above is also enforced whenever the application
* attempts to set or modify the contents of the text object by calling
* a constructor or a method.</p>
*
* <p>Parsing this string value into a numeric value suitable for
* computation is the responsibility of the application. If the contents
* are not empty, the result can be parsed successfully by
* <code>Double.valueOf</code> and related methods if they are present
* in the runtime environment. </p>
*
* <p>The sign and the fraction separator consume space in the text
* object. Applications should account for this when assigning a maximum
* size for the text object.</p>
*
* <P>Constant <code>5</code> is assigned to <code>DECIMAL</code>.</p>
*
*
* @since MIDP 2.0
*/
public static final int DECIMAL = 5;
/**
* The user is allowed to enter numeric values with two decimal
* fractions, for example "-123.00", "0.13", or
* "0.50".
*
* <p>Numbers are appended in the last decimal fraction by default, so when "1" is pressed this results
* in "0.01". Similarly pressing "1", "2" and "3" results in "1.23".
* </p>
* <p>Sample usage:</p>
* <pre>
* TextField cashRegister = new TextField("Price: ", null, 5, UiAccess.CONSTRAINT_FIXED_POINT_DECIMAL );
* </pre>
*
* <p>Constant <code>20</code> is assigned to <code>FIXED_POINT_DECIMAL</code>.</p>
*
* @since J2ME Polish 2.1.3
* @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL
* @see #setNumberOfDecimalFractions(int)
* @see #getNumberOfDecimalFractions()
* @see #convertToFixedPointDecimal(String)
* @see #convertToFixedPointDecimal(String, boolean)
*/
public static final int FIXED_POINT_DECIMAL = 20;
/**
* Indicates that the text entered is confidential data that should be
* obscured whenever possible. The contents may be visible while the
* user is entering data. However, the contents must never be divulged
* to the user. In particular, the existing contents must not be shown
* when the user edits the contents. The means by which the contents
* are obscured is implementation-dependent. For example, each
* character of the data might be masked with a
* "<code>*</code>" character. The
* <code>PASSWORD</code> modifier is useful for entering
* confidential information
* such as passwords or personal identification numbers (PINs).
*
* <p>Data entered into a <code>PASSWORD</code> field is treated
* similarly to <code>SENSITIVE</code>
* in that the implementation must never store the contents into a
* dictionary or table for use in predictive, auto-completing, or other
* accelerated input schemes. If the <code>PASSWORD</code> bit is
* set in a constraint
* value, the <code>SENSITIVE</code> and
* <code>NON_PREDICTIVE</code> bits are also considered to be
* set, regardless of their actual values. In addition, the
* <code>INITIAL_CAPS_WORD</code> and
* <code>INITIAL_CAPS_SENTENCE</code> flag bits should be ignored
* even if they are set.</p>
*
* <p>The <code>PASSWORD</code> modifier can be combined with
* other input constraints
* by using the bit-wise <code>OR</code> operator (<code>|</code>).
* The <code>PASSWORD</code> modifier is not
* useful with some constraint values such as
* <code>EMAILADDR</code>, <code>PHONENUMBER</code>,
* and <code>URL</code>. These combinations are legal, however,
* and no exception is
* thrown if such a constraint is specified.</p>
*
* <p>Constant <code>0x10000</code> is assigned to
* <code>PASSWORD</code>.</p>
*
*/
public static final int PASSWORD = 0x10000;
/**
* Indicates that editing is currently disallowed. When this flag is set,
* the implementation must prevent the user from changing the text
* contents of this object. The implementation should also provide a
* visual indication that the object's text cannot be edited. The intent
* of this flag is that this text object has the potential to be edited,
* and that there are circumstances where the application will clear this
* flag and allow the user to edit the contents.
*
* <p>The <code>UNEDITABLE</code> modifier can be combined with
* other input constraints
* by using the bit-wise <code>OR</code> operator (<code>|</code>).
*
* <p>Constant <code>0x20000</code> is assigned to <code>UNEDITABLE</code>.</p>
*
*
* @since MIDP 2.0
*/
public static final int UNEDITABLE = 0x20000;
/**
* Indicates that the text entered is sensitive data that the
* implementation must never store into a dictionary or table for use in
* predictive, auto-completing, or other accelerated input schemes. A
* credit card number is an example of sensitive data.
*
* <p>The <code>SENSITIVE</code> modifier can be combined with other input
* constraints by using the bit-wise <code>OR</code> operator
* (<code>|</code>).</p>
*
* <p>Constant <code>0x40000</code> is assigned to
* <code>SENSITIVE</code>.</p>
*
*
* @since MIDP 2.0
*/
public static final int SENSITIVE = 0x40000;
/**
* Indicates that the text entered does not consist of words that are
* likely to be found in dictionaries typically used by predictive input
* schemes. If this bit is clear, the implementation is allowed to (but
* is not required to) use predictive input facilities. If this bit is
* set, the implementation should not use any predictive input facilities,
* but it instead should allow character-by-character text entry.
*
* <p>The <code>NON_PREDICTIVE</code> modifier can be combined
* with other input
* constraints by using the bit-wise <code>OR</code> operator
* (<code>|</code>).
*
* <P>Constant <code>0x80000</code> is assigned to
* <code>NON_PREDICTIVE</code>.</P>
*
*
* @since MIDP 2.0
*/
public static final int NON_PREDICTIVE = 0x80000;
/**
* This flag is a hint to the implementation that during text editing, the
* initial letter of each word should be capitalized. This hint should be
* honored only on devices for which automatic capitalization is
* appropriate and when the character set of the text being edited has the
* notion of upper case and lower case letters. The definition of
* word boundaries is implementation-specific.
*
* <p>If the application specifies both the
* <code>INITIAL_CAPS_WORD</code> and the
* <code>INITIAL_CAPS_SENTENCE</code> flags,
* <code>INITIAL_CAPS_WORD</code> behavior should be used.
*
* <p>The <code>INITIAL_CAPS_WORD</code> modifier can be combined
* with other input
* constraints by using the bit-wise <code>OR</code> operator
* (<code>|</code>).
*
* <p>Constant <code>0x100000</code> is assigned to
* <code>INITIAL_CAPS_WORD</code>.
*
*
* @since MIDP 2.0
*/
public static final int INITIAL_CAPS_WORD = 0x100000;
/**
* This flag is a hint to the implementation that during text editing, the
* initial letter of each sentence should be capitalized. This hint
* should be honored only on devices for which automatic capitalization is
* appropriate and when the character set of the text being edited has the
* notion of upper case and lower case letters. The definition of
* sentence boundaries is implementation-specific.
*
* <p>If the application specifies both the
* <code>INITIAL_CAPS_WORD</code> and the
* <code>INITIAL_CAPS_SENTENCE</code> flags,
* <code>INITIAL_CAPS_WORD</code> behavior should be used.
*
* <p>The <code>INITIAL_CAPS_SENTENCE</code> modifier can be
* combined with other input
* constraints by using the bit-wise <code>OR</code> operator
* (<code>|</code>).
*
* <p>Constant <code>0x200000</code> is assigned to
* <code>INITIAL_CAPS_SENTENCE</code>.
*
*
* @since MIDP 2.0
*/
public static final int INITIAL_CAPS_SENTENCE = 0x200000;
/**
* A flag to hint to the implementation that during text editing,the
* initial letter of each sentence should NOT be capitalized.
*/
public static final int INITIAL_CAPS_NEVER = 0x400000;
/**
* The mask value for determining the constraint mode.
* The application should
* use the bit-wise <code>AND</code> operation with a value returned by
* <code>getConstraints()</code> and
* <code>CONSTRAINT_MASK</code> in order to retrieve the current
* constraint mode,
* in order to remove any modifier flags such as the
* <code>PASSWORD</code> flag.
*
* <P>Constant <code>0xFFFF</code> is assigned to
* <code>CONSTRAINT_MASK</code>.</P>
*/
public static final int CONSTRAINT_MASK = 0xFFFF;
// clear command is used in DateField, too:
//#ifdef polish.command.clear.priority:defined
//#= private final static int CLEAR_PRIORITY = ${polish.command.clear.priority};
//#else
private final static int CLEAR_PRIORITY = 8;
//#endif
//#ifdef polish.command.clear.type:defined
//#= private final static int CLEAR_TYPE = ${polish.command.clear.type};
//#else
private final static int CLEAR_TYPE = Command.ITEM;
//#endif
//#ifdef polish.i18n.useDynamicTranslations
/**
* Command for clearing the complete text of this field
*/
public static Command CLEAR_CMD = new Command( Locale.get("polish.command.clear"), CLEAR_TYPE, CLEAR_PRIORITY );
//#elifdef polish.command.clear:defined
//#= public static final Command CLEAR_CMD = new Command( "${polish.command.clear}", CLEAR_TYPE, CLEAR_PRIORITY );
//#else
//# public static final Command CLEAR_CMD = new Command( "Clear", CLEAR_TYPE, CLEAR_PRIORITY );
//#endif
//#ifndef tmp.suppressCommands
//#if (polish.TextField.suppressDeleteCommand != true) && !polish.blackberry && !polish.TextField.keepDeleteCommand
//#define tmp.updateDeleteCommand
//#endif
//#ifdef polish.command.delete.priority:defined
//#= private final static int DELETE_PRIORITY = ${polish.command.delete.priority};
//#else
private final static int DELETE_PRIORITY = 1;
//#endif
// the delete command is a Command.ITEM type when the extended menubar is used in conjunction with a defined return-key,
// because CANCEL will be mapped on special keys like the return key on Sony Ericsson devices.
private final static int DELETE_TYPE =
//#ifdef polish.command.delete.type:defined
//#= ${polish.command.delete.type};
//#elif polish.MenuBar.useExtendedMenuBar && (polish.key.ReturnKey:defined || polish.css.repaint-previous-screen && polish.hasPointerEvents)
//# Command.ITEM;
//#else
Command.CANCEL;
//#endif
//#ifdef polish.i18n.useDynamicTranslations
public static Command DELETE_CMD = new Command( Locale.get("polish.command.delete"), DELETE_TYPE, DELETE_PRIORITY );
//#elifdef polish.command.delete:defined
//#= public static final Command DELETE_CMD = new Command( "${polish.command.delete}", DELETE_TYPE, DELETE_PRIORITY );
//#else
//# public static final Command DELETE_CMD = new Command( "Delete", DELETE_TYPE, DELETE_PRIORITY );
//#endif
//#endif
//#if polish.key.maybeSupportsAsciiKeyMap
//#ifdef polish.command.switch_keyboard.priority:defined
//#= private final static int SWITCH_KEYBOARD_PRIORITY = ${polish.command.switch_keyboard.priority};
//#else
private final static int SWITCH_KEYBOARD_PRIORITY = 1;
//#endif
private static Command SWITCH_KEYBOARD_CMD = new Command (Locale.get("polish.command.switch_keyboard"), Command.ITEM, SWITCH_KEYBOARD_PRIORITY);
//#endif
/** valid input characters for local parts of email addresses, apart from 0..9 and a..z. */
private static final String VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS = ".-_@!#$%&'*+/=?^`{|}~";
/** valid input characters for domain names, apart from 0..9 and a..z. */
private static final String VALID_DOMAIN_CHARACTERS = "._-";
private int maxSize;
private int constraints = -1;
//#ifdef polish.css.textfield-caret-color
private int caretColor = -1;
//#endif
private char editingCaretChar = '|';
protected char caretChar = '|';
protected boolean showCaret;
private long lastCaretSwitch;
protected String title;
private String passwordText;
private boolean isPassword;
private boolean enableDirectInput;
private boolean noNewLine = false;
private boolean noComplexInput = false;
//#if (!tmp.suppressCommands && !tmp.supportsSymbolEntry) || tmp.supportsSymbolEntry
private ItemCommandListener additionalItemCommandListener;
//#endif
// this is outside of the tmp.directInput block, so that it can be referenced from the UiAccess class
protected int inputMode; // the current input mode
//#if tmp.directInput || polish.android
private int caretPosition; // the position of the caret in the text
//#endif
//#if tmp.directInput
//#if tmp.supportsSymbolEntry
protected static List symbolsList;
//#if polish.TextField.Symbols:defined
//#= private static String[] definedSymbols = ${ stringarray(polish.TextField.Symbols)};
//#else
protected static String[] definedSymbols = {"&","@","/","\\","<",">","(",")","{","}","[","]",".","+","-","*",":","_","\"","#","$","%",":)",":(",";)",":x",":D",":P"};
//private static String definedSymbols = "@/\\<>(){}.,+-*:_\"#$%";
//#endif
//#ifdef polish.command.entersymbol.priority:defined
//#= private static int ENTER_SYMBOL_PRIORITY = ${polish.command.entersymbol.priority};
//#else
private static int ENTER_SYMBOL_PRIORITY = 9;
//#endif
//#ifdef polish.i18n.useDynamicTranslations
public static Command ENTER_SYMBOL_CMD = new Command( Locale.get("polish.command.entersymbol"), Command.SCREEN, ENTER_SYMBOL_PRIORITY );
//#elifdef polish.command.entersymbol:defined
//#= public static final Command ENTER_SYMBOL_CMD = new Command( "${polish.command.entersymbol}", Command.SCREEN, ENTER_SYMBOL_PRIORITY );
//#else
//# public static final Command ENTER_SYMBOL_CMD = new Command( "Add Symbol", Command.SCREEN, ENTER_SYMBOL_PRIORITY );
//#endif
//#endif
private boolean isKeyDown;
//#ifdef polish.TextField.InputTimeout:defined
//#= private static final int INPUT_TIMEOUT = ${polish.TextField.InputTimeout};
//#else
private static final int INPUT_TIMEOUT = 1000;
//#endif
/** input mode for lowercase characters */
public static final int MODE_LOWERCASE = 0;
/** input mode for entering one uppercase followed by lowercase characters */
public static final int MODE_FIRST_UPPERCASE = 1; // only the first character should be written in uppercase
/** input mode for uppercase characters */
public static final int MODE_UPPERCASE = 2;
/** input mode for numeric characters */
public static final int MODE_NUMBERS = 3;
/** input mode for input using a separete native TextBox */
public static final int MODE_NATIVE = 4;
//#ifdef polish.key.ChangeInputModeKey:defined
//#= protected static final int KEY_CHANGE_MODE = ${polish.key.ChangeInputModeKey};
//#elif ${polish.vendor} == Generic
public static final int KEY_CHANGE_MODE = DeviceInfo.getKeyInputModeSwitch();
//#else
//# public static final int KEY_CHANGE_MODE = Canvas.KEY_POUND;
//#endif
//#ifdef polish.key.ClearKey:defined
//#= public static final int KEY_DELETE = ${polish.key.ClearKey};
//#else
public static final int KEY_DELETE = -8 ; //Canvas.KEY_STAR;
//#endif
//#if polish.key.shift:defined
//#= private static final int KEY_SHIFT = ${polish.key.shift};
//#else
private static final int KEY_SHIFT = -50;
//#endif
private boolean nextCharUppercase; // is needed for the FIRST_UPPERCASE-mode
private boolean prepareNextCharUppercase;
private String[] realTextLines; // the textLines with spaces and line breaks at the end
private String originalRowText; // current line including spaces and line breaks at the end
private int caretColumn; // the current column of the caret, 0 is the first column
private int caretRow; // the current row of the caret, 0 is the first row
private int caretX;
private int caretY;
private int caretWidth;
//#ifdef polish.css.textfield-show-length
private boolean showLength;
//#endif
private int lastKey; // the last key which has been pressed
long lastInputTime; // the last time a key has been pressed
private int characterIndex; // the index within the available characters of the current key
// the characters for each key:
//#ifdef polish.TextField.charactersKey1:defined
//#= private static String charactersKey1 = "${polish.TextField.charactersKey1}";
//#else
private static String charactersKey1 = ".,!?\u00bf:/()@_-+1'\";";
//#endif
//#ifdef polish.TextField.charactersKey2:defined
//#= private static String charactersKey2 = "${polish.TextField.charactersKey2}";
//#else
private static String charactersKey2 = "abc2\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7";
//#endif
//#ifdef polish.TextField.charactersKey3:defined
//#= private static String charactersKey3 = "${polish.TextField.charactersKey3}";
//#else
private static String charactersKey3 = "def3\u00e8\u00e9\u00ea\u00eb";
//#endif
//#ifdef polish.TextField.charactersKey4:defined
//#= private static String charactersKey4 = "${polish.TextField.charactersKey4}";
//#else
private static String charactersKey4 = "ghi4\u00ec\u00ed\u00ee\u00ef";
//#endif
//#ifdef polish.TextField.charactersKey5:defined
//#= private static String charactersKey5 = "${polish.TextField.charactersKey5}";
//#else
private static String charactersKey5 = "jkl5";
//#endif
//#ifdef polish.TextField.charactersKey6:defined
//#= private static String charactersKey6 = "${polish.TextField.charactersKey6}";
//#else
private static String charactersKey6 = "mno6\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6";
//#endif
//#ifdef polish.TextField.charactersKey7:defined
//#= private static String charactersKey7 = "${polish.TextField.charactersKey7}";
//#else
private static String charactersKey7 = "pqrs7\u00df";
//#endif
//#ifdef polish.TextField.charactersKey8:defined
//#= private static String charactersKey8 = "${polish.TextField.charactersKey8}";
//#else
private static String charactersKey8 = "tuv8\u00f9\u00fa\u00fb\u00fc";
//#endif
//#ifdef polish.TextField.charactersKey9:defined
//#= private static String charactersKey9 = "${polish.TextField.charactersKey9}";
//#else
private static String charactersKey9 = "wxyz9\u00fd";
//#endif
//#ifdef polish.TextField.charactersKey0:defined
//#= private static String charactersKey0 = "${polish.TextField.charactersKey0}";
//#else
protected static String charactersKey0 = " 0";
//#endif
//#ifdef polish.TextField.charactersKeyStar:defined
//#= protected static String charactersKeyStar = "${polish.TextField.charactersKeyStar}";
//#else
protected static String charactersKeyStar = ".,!?\u00bf:/@_-+1'\";";
//#endif
//#ifdef polish.TextField.charactersKeyPound:defined
//#= protected static String charactersKeyPound = "${polish.TextField.charactersKeyPound}";
//#else
protected static String charactersKeyPound = null;
//#endif
/** map of characters that can be triggered witht the 0..9 and #, * keys */
public static String[] CHARACTERS = new String[]{ charactersKey0, charactersKey1, charactersKey2, charactersKey3, charactersKey4, charactersKey5, charactersKey6, charactersKey7, charactersKey8, charactersKey9 };
//#if tmp.useDynamicCharset
public static String[] CHARACTERS_UPPER = new String[]{ charactersKey0, charactersKey1, charactersKey2, charactersKey3, charactersKey4, charactersKey5, charactersKey6, charactersKey7, charactersKey8, charactersKey9 };
public static boolean usesDynamicCharset;
//#endif
private static final String[] EMAIL_CHARACTERS = new String[]{ VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS + "0", VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS + "1", "abc2", "def3", "ghi4", "jkl5", "mno6", "pqrs7", "tuv8", "wxyz9" };
private String[] characters;
private boolean isNumeric;
private boolean isDecimal;
private boolean isEmail;
private boolean isUrl;
private int rowHeight;
//#if polish.TextField.includeInputInfo
//#define tmp.includeInputInfo
//#define tmp.useInputInfo
protected StringItem infoItem;
//#elif polish.TextField.showInputInfo != false
//#define tmp.useInputInfo
//#endif
protected final Object lock = new Object();
private long deleteKeyRepeatCount;
//#endif
protected char emailSeparatorChar = ';';
//#if polish.android
private AndroidTextField _androidTextField;
//#endif
//#if polish.blackberry
private PolishTextField editField;
//#if polish.Bugs.ItemStateListenerCalledTooEarly
private long lastFieldChangedEvent;
//#endif
private int bbLastCursorPosition;
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
private TextEditor series40sdk20Field;
//#endif
//#if polish.midp && !(polish.blackberry || polish.android || polish.api.windows) && !polish.TextField.useVirtualKeyboard
//#define tmp.useNativeTextBox
private de.enough.polish.midp.ui.TextBox midpTextBox;
//#if polish.TextField.passCharacterToNativeEditor
//Variable passedChar used as container for char which is passed to native TextBox.
//So when key is pressed (e.g. '2') view goes to native mode and 'a' character is appended to the current text
private char passedChar;
//Timer responsible for checking delay between two, subsequent presses
private final Timer keyDelayTimer = new Timer();
private TimerTask keyDelayTimerTask = null;
//last time when button was pressed
private long lastTimeKeyPressed;
//number of presses of one phone button
private int keyPressCounter = 0;
//latest key pressed keyCode
private int latestKey;
//maximum delay between subseqent key presses. If exceeded, will timer will call native editor.
private int delayBetweenKeys =
//#if polish.nativeEditor.delayBetweenKeys:defined
//#= ${polish.nativeEditor.delayBetweenKeys};
//#else
200;
//#endif
//#endif
private boolean skipKeyReleasedEvent = false;
//#endif
private boolean cskOpensNativeEditor = true;
//#if tmp.usePredictiveInput
long lastTimePressed = -1;
boolean predictiveInput = false;
private PredictiveAccess predictiveAccess;
boolean nextMode = this.predictiveInput;
static final int SWITCH_DELAY = 1000;
//#endif
protected boolean flashCaret = true;
protected boolean isUneditable;
private boolean isShowInputInfo = true;
private boolean suppressCommands = false;
//#if polish.TextField.showHelpText
private StringItem helpItem;
//#endif
//#if polish.key.maybeSupportsAsciiKeyMap
private static boolean useAsciiKeyMap = false;
//#endif
//#if polish.key.supportsAsciiKeyMap || polish.key.maybeSupportsAsciiKeyMap
//#define tmp.supportsAsciiKeyMap
//#endif
private boolean isKeyPressedHandled;
private int numberOfDecimalFractions = 2;
//#if polish.TextField.useVirtualKeyboard
static IntHashMap keyboardViews = new IntHashMap();
//#endif
//#if tmp.useDynamicCharset
/**
* Reads the .properties files for lowercase
* and uppercase letters and maps the values of the predefined keys
* to the character maps. Uses UTF-8 as encoding.
* @param lowercaseUrl the properties file for lower case
* @param uppercaseUrl the properties file for upper case
*/
public static void loadCharacterSets(String lowercaseUrl,String uppercaseUrl)
{
loadCharacterSets(lowercaseUrl, uppercaseUrl,"UTF8");
}
/**
* Reads the .properties files for lowercase
* and uppercase letters and maps the values of the predefined keys
* to the character maps. Uses UTF-8 as encoding.
* @param lowercaseStream the input stream of properties for lower case
* @param uppercaseStream the input stream of properties for upper case
*/
public static void loadCharacterSets(InputStream lowercaseStream, InputStream uppercaseStream)
{
loadCharacterSets(lowercaseStream, uppercaseStream,"UTF8");
}
/**
* Reads the .properties files for lowercase
* and uppercase letters and maps the values of the predefined keys
* to the character maps.
* @param lowercaseUrl the properties file for lower case
* @param uppercaseUrl the properties file for upper case
* @param encoding the encoding to use
*/
public static void loadCharacterSets(String lowercaseUrl,String uppercaseUrl, String encoding)
{
loadCharacterSets(CHARACTERS,lowercaseUrl, encoding);
loadCharacterSets(CHARACTERS_UPPER,uppercaseUrl, encoding);
try
{
validateSets();
usesDynamicCharset = true;
}catch(IllegalArgumentException e)
{
//#debug error
System.out.println("unable to load dynamic character sets : " + e.getMessage());
}
}
/**
* Reads the .properties files for lowercase
* and uppercase letters and maps the values of the predefined keys
* to the character maps.
* @param lowercaseStream the properties file for lower case
* @param uppercaseStream the properties file for upper case
* @param encoding the encoding to use
*/
public static void loadCharacterSets(InputStream lowercaseStream,InputStream uppercaseStream, String encoding)
{
loadCharacterSets(CHARACTERS,lowercaseStream, encoding);
loadCharacterSets(CHARACTERS_UPPER,uppercaseStream, encoding);
try
{
validateSets();
usesDynamicCharset = true;
}catch(IllegalArgumentException e)
{
//#debug error
System.out.println("unable to load dynamic character sets : " + e.getMessage());
}
}
/**
* Validates the character sets for lowercase and uppercase by
* comparing the number of entries for a key
* @throws IllegalArgumentException
*/
static void validateSets() throws IllegalArgumentException
{
for (int i = 0; i < CHARACTERS.length; i++) {
if(CHARACTERS[i].length() != CHARACTERS_UPPER[i].length())
{
throw new IllegalArgumentException("the dynamic charsets have a different number of entries at index " + i);
}
}
}
/**
* Reads a .properties file and maps
* the values of the predefined keys
* to the specified character maps
* @param target the character map
* @param url the properties file
* @param encoding the encoding
*/
static void loadCharacterSets(String[] target, String url, String encoding)
{
Properties properties;
try {
properties = new Properties(url,encoding);
loadCharacterSets(target,properties);
} catch (IOException e) {
//#debug error
System.out.println("unable to load character set : " + url);
}
}
/**
* Reads a .properties file and maps
* the values of the predefined keys
* to the specified character maps
* @param target the character map
* @param stream the properties file
* @param encoding the encoding
*/
static void loadCharacterSets(String[] target, InputStream stream, String encoding)
{
Properties properties;
try {
properties = new Properties();
properties.load(stream, encoding, false);
loadCharacterSets(target,properties);
} catch (IOException e) {
//#debug error
System.out.println("unable to load character set : " + stream.toString());
}
}
/**
* Reads a .properties file and maps
* the values of the predefined keys
* to the character maps
* @param target the character map
* @param properties the properties file
*/
static void loadCharacterSets(String[] target, Properties properties)
{
//#if tmp.directInput
Object[] keys = properties.keys();
for (int i = 0; i < keys.length; i++) {
String key = (String)keys[i];
try
{
int index = Integer.parseInt(key);
target[index] = properties.getProperty(key);
}catch(NumberFormatException e)
{
//#debug error
System.out.println("key " + key + " has wrong format, must be 0 - 9" );
}
}
//#endif
}
//#endif
/**
* Creates a new <code>TextField</code> object with the given label, initial
* contents, maximum size in characters, and constraints.
* If the text parameter is <code>null</code>, the
* <code>TextField</code> is created empty.
* The <code>maxSize</code> parameter must be greater than zero.
* An <code>IllegalArgumentException</code> is thrown if the
* length of the initial contents string exceeds <code>maxSize</code>.
* However,
* the implementation may assign a maximum size smaller than the
* application had requested. If this occurs, and if the length of the
* contents exceeds the newly assigned maximum size, the contents are
* truncated from the end in order to fit, and no exception is thrown.
*
* @param label item label
* @param text the initial contents, or null if the TextField is to be empty
* @param maxSize the maximum capacity in characters
* @param constraints see input constraints
* @throws IllegalArgumentException if maxSize is zero or less
* or if the value of the constraints parameter is invalid
* or if text is illegal for the specified constraints
* or if the length of the string exceeds the requested maximum capacity
*/
public TextField( String label, String text, int maxSize, int constraints)
{
this( label, text, maxSize, constraints, null );
}
/**
* Creates a new <code>TextField</code> object with the given label, initial
* contents, maximum size in characters, and constraints.
* If the text parameter is <code>null</code>, the
* <code>TextField</code> is created empty.
* The <code>maxSize</code> parameter must be greater than zero.
* An <code>IllegalArgumentException</code> is thrown if the
* length of the initial contents string exceeds <code>maxSize</code>.
* However,
* the implementation may assign a maximum size smaller than the
* application had requested. If this occurs, and if the length of the
* contents exceeds the newly assigned maximum size, the contents are
* truncated from the end in order to fit, and no exception is thrown.
*
* @param label item label
* @param text the initial contents, or null if the TextField is to be empty
* @param maxSize the maximum capacity in characters
* @param constraints see input constraints
* @param style the CSS style for this field
* @throws IllegalArgumentException if maxSize is zero or less
* or if the value of the constraints parameter is invalid
* or if text is illegal for the specified constraints
* or if the length of the string exceeds the requested maximum capacity
*/
public TextField( String label, String text, int maxSize, int constraints, Style style)
{
super( label, null, INTERACTIVE, style );
//#if polish.vendor == Generic && tmp.directInput
int spaceKey = DeviceInfo.getKeySpace();
if (spaceKey == Canvas.KEY_POUND) {
charactersKey0 = "0";
charactersKeyPound = " ";
}
//#endif
this.maxSize = maxSize;
if (label != null) {
this.title = label;
} else {
//#ifdef polish.title.input:defined
//#= this.title = "${polish.title.input}";
//#else
this.title = "Input";
//#endif
}
if ((constraints & PASSWORD) == PASSWORD) {
this.isPassword = true;
}
//#ifndef polish.hasPointerEvents
int fieldType = constraints & 0xffff;
if (fieldType == NUMERIC) {
this.enableDirectInput = true;
}
//#endif
//#if tmp.forceDirectInput
this.enableDirectInput = true;
//#endif
setConstraints(constraints);
//#if tmp.usePredictiveInput
this.predictiveAccess = new PredictiveAccess();
this.predictiveAccess.init(this);
//#endif
//#if polish.TextField.showHelpText
//#style help?
this.helpItem = new StringItem(null,null);
/* if (style != null && this.helpItem.style != null && this.helpItem.style.font == null) {
this.helpItem.style.font = style.font;
}*/
/*Font font = this.helpItem.getFont();
Font newFont = Font.getFont(font.getFace(), font.getStyle(), this.getFont().getSize());
this.helpItem.setFont(newFont);*/
//#ifdef polish.TextField.help:defined
//#= this.helpItem.setText("${polish.TextField.help}");
//#else
this.helpItem.setText("type text here");
//#endif
//#endif
//#if polish.key.maybeSupportsAsciiKeyMap
//#if polish.api.windows
if (Keyboard.needsQwertzAndNumericSupport()) {
addCommand(SWITCH_KEYBOARD_CMD);
}
useAsciiKeyMap = true;
//#endif
//#endif
//#if polish.TextField.noNewLine
this.noNewLine = true;
//#endif
setString(text);
}
//#if tmp.useNativeTextBox
/**
* Creates the TextBox used for the actual input mode.
*/
private void createTextBox() {
String currentText = this.isPassword ? this.passwordText : this.text;
this.midpTextBox = new de.enough.polish.midp.ui.TextBox( this.title, currentText, this.maxSize, getMidpConstraints() );
this.midpTextBox.addCommand(StyleSheet.OK_CMD);
if (!this.isUneditable) {
this.midpTextBox.addCommand(StyleSheet.CANCEL_CMD);
}
this.midpTextBox.setCommandListener( this );
//#if polish.midp2
if ((this.constraints & TextField.INITIAL_CAPS_NEVER) == TextField.INITIAL_CAPS_NEVER){
this.midpTextBox.setInitialInputMode("MIDP_LOWERCASE_LATIN");
}
//#endif
}
//#endif
/**
* Converts the current constraints into MIDP compatible ones
* @return MIDP compatible constraints
*/
public int getMidpConstraints() {
int cont = this.constraints;
if ((cont & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL) {
cont = cont & ~FIXED_POINT_DECIMAL | DECIMAL;
}
return cont;
}
/**
* Gets the contents of the <code>TextField</code> as a string value.
*
* @return the current contents, an empty string when the current value is null.
* @see #setString(java.lang.String)
*/
public String getString()
{
//#if polish.blackberry
if ( this.editField != null ) {
return this.editField.getText();
}
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null ) {
return this.series40sdk20Field.getContent();
}
//#endif
if ( this.isPassword ) {
if (this.passwordText == null) {
return "";
}
return this.passwordText;
} else {
if (this.text == null) {
return "";
}
return this.text;
}
}
/**
* Retrieves the decimal value entered with a dot as the decimal mark.
* <ul>
* <li>When the value has no decimal places it will be returned as it is: 12</li>
* <li>When the value is null, null will be returned: null</li>
* <li>When the value has decimal places, a dot will be used: 12.3</li>
* </ul>
* @return either the formatted value or null, when there was no input.
* @throws IllegalStateException when the TextField is not DECIMAL constrained
*/
public String getDotSeparatedDecimalString() {
//#if tmp.directInput
//#if tmp.allowDirectInput
if (this.enableDirectInput) {
//#endif
if (!this.isDecimal) {
throw new IllegalStateException();
}
String value = getString();
if ((this.constraints & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL) {
// remove grouping separator:
StringBuffer buffer = new StringBuffer(value.length());
for (int i=0; i<value.length(); i++) {
char c = value.charAt(i);
if (c == Locale.DECIMAL_SEPARATOR) {
buffer.append('.');
} else if (c != Locale.GROUPING_SEPARATOR) {
buffer.append(c);
}
}
return buffer.toString();
}
if ( Locale.DECIMAL_SEPARATOR == '.' || value == null) {
return value;
} else {
return value.replace( Locale.DECIMAL_SEPARATOR, '.');
}
//#if tmp.allowDirectInput
}
//#endif
//#endif
//#if !tmp.forceDirectInput
if (( getConstraints() & DECIMAL)!= DECIMAL) {
throw new IllegalStateException();
}
String value = getString();
if (value == null) {
return null;
}
return value.replace(',', '.');
//#endif
}
/**
* Sets the contents of the <code>TextField</code> as a string
* value, replacing the previous contents.
*
* @param text the new value of the TextField, or null if the TextField is to be made empty
* @throws IllegalArgumentException if text is illegal for the current input constraints
* or if the text would exceed the current maximum capacity
* @see #getString()
*/
public void setString( String text)
{
//#debug
System.out.println("setString [" + text + "] for " + this);
//#if polish.android
int cursorAdjustment = 0;
//#endif
if (text != null && text.length() > 0) {
int fieldType = this.constraints & 0xffff;
if (fieldType == FIXED_POINT_DECIMAL) {
int lengthBefore = text.length();
text = convertToFixedPointDecimal(text, true);
int lengthAfter = text.length();
//#if polish.android
if (lengthAfter > lengthBefore) {
cursorAdjustment = lengthAfter - lengthBefore;
} else if (this.text != null && this.text.length() > 0 && this.text.charAt(0) == '0') {
cursorAdjustment = 1;
}
//#elif !polish.blackberry
if (lengthAfter > lengthBefore) {
setCaretPosition( getCaretPosition() + lengthAfter - lengthBefore);
}
//#endif
}
}
//#if tmp.useNativeTextBox
if (this.midpTextBox != null) {
this.midpTextBox.setString( text );
}
//#endif
//#if polish.android
if (this._androidTextField != null) {
if (text == null) {
text = "";
}
String currentText = this._androidTextField.getText().toString();
if (!currentText.equals(text)) {
this._androidTextField.setTextKeepState(text);
if (cursorAdjustment != 0) {
this._androidTextField.moveCursor( cursorAdjustment );
}
}
}
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null && !this.series40sdk20Field.getContent().equals(text)) {
this.series40sdk20Field.setContent(text);
}
//#endif
//#if polish.blackberry
if (this.editField != null && !this.editField.getText().equals(text) ) {
Object bbLock = UiApplication.getEventLock();
if (this.screen == null) {
this.screen = getScreen();
}
synchronized (bbLock) {
if (this.isFocused && this.isShown) {
// don't want to have endless loops of change events:
this.screen.notifyFocusSet(null);
}
if (text != null) {
this.editField.setText(text);
} else {
this.editField.setText(""); // setting null triggers an IllegalArgumentException
}
if (this.isFocused && this.isShown) {
this.screen.notifyFocusSet(this);
}
}
}
//#endif
if (this.isPassword) {
this.passwordText = text;
if (text != null) {
int length = text.length();
StringBuffer buffer = new StringBuffer( length );
for (int i = 0; i < length; i++) {
buffer.append('*');
}
text = buffer.toString();
}
}
//#ifdef tmp.directInput
if (text == null) {
this.caretPosition = 0;
this.caretRow = 0;
this.caretColumn = 0;
this.caretX = 0;
this.caretY = 0;
} else if (
(this.caretPosition == 0 && (this.text == null || this.text.length() == 0) )
|| ( this.caretPosition > text.length())
|| (this.text != null && text != null && text.length() > (this.text.length()+1))
)
{
this.caretPosition = text.length();
}
//#endif
//#if tmp.updateDeleteCommand
if (this.isFocused) {
updateDeleteCommand( text );
}
//#endif
setText(text);
//#ifdef tmp.directInput
if ((text == null || text.length() == 0) && this.inputMode == MODE_FIRST_UPPERCASE) {
this.nextCharUppercase = true;
}
//#if polish.css.textfield-show-length && tmp.useInputInfo
if (this.isFocused && this.showLength) {
updateInfo();
}
//#endif
//#endif
//#if tmp.usePredictiveInput
if(this.predictiveInput) {
this.predictiveAccess.synchronize();
}
//#endif
}
/**
* Sets the number of decimal fractions that are allowed for FIXED_POINT_DECIMAL constrained TextFields
* @param number the number (defaults to 2)
* @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL
* @see #FIXED_POINT_DECIMAL
*/
public void setNumberOfDecimalFractions(int number) {
this.numberOfDecimalFractions = number;
}
/**
* Retrieves the number of decimal fractions that are allowed for FIXED_POINT_DECIMAL constrained TextFields
* @return the number (defaults to 2)
* @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL
* @see #FIXED_POINT_DECIMAL
*/
public int getNumberOfDecimalFractions() {
return this.numberOfDecimalFractions;
}
/**
* Converts the given entry into cash format without grouping separator.
* Subclasses may override this to implement their own behavior.
* @param original the original text, e.g. "1"
* @return the processed text, e.g. "0.01"
* @see #FIXED_POINT_DECIMAL
* @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL
* @see #getNumberOfDecimalFractions()
* @see #setNumberOfDecimalFractions(int)
* @see #convertToFixedPointDecimal(String, boolean)
*/
protected String convertToFixedPointDecimal(String original) {
return convertToFixedPointDecimal(original, false);
}
/**
* Converts the given entry into cash format.
* Subclasses may override this to implement their own behavior.
* @param original the original text, e.g. "1"
* @param addGroupingSeparator true when a grouping separator should be added like "1,000.00"
* @return the processed text, e.g. "0.01"
* @see #FIXED_POINT_DECIMAL
* @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL
* @see #getNumberOfDecimalFractions()
* @see #setNumberOfDecimalFractions(int)
*/
protected String convertToFixedPointDecimal(String original, boolean addGroupingSeparator) {
int fractions = this.numberOfDecimalFractions;
StringBuffer buffer = new StringBuffer( original.length() + 3 );
int added = 0;
for (int i=original.length(); --i >= 0; ) {
char c = original.charAt(i);
if (c >= '0' && c <= '9') {
buffer.insert(0, c);
added++;
if (added == fractions) {
buffer.insert(0, Locale.DECIMAL_SEPARATOR);
}
}
}
fractions++;
while (added > fractions) {
char c = buffer.charAt(0);
if (c == '0') {
buffer.deleteCharAt(0);
added--;
} else {
break;
}
}
while (added < fractions) {
buffer.insert(0, '0');
added++;
if (added == fractions-1) {
buffer.insert(0, Locale.DECIMAL_SEPARATOR);
}
}
if (addGroupingSeparator) {
int numberBeforeDecimalSeparator = buffer.length() - fractions - 1;
if (numberBeforeDecimalSeparator >= 3) {
for (int i = 3; i<=numberBeforeDecimalSeparator; i+=3) {
int pos = numberBeforeDecimalSeparator - i + 1;
buffer.insert(pos, Locale.GROUPING_SEPARATOR);
}
}
}
original = buffer.toString();
return original;
}
protected void updateDeleteCommand(String newText) {
//#if tmp.updateDeleteCommand
// remove delete command when the caret is before the first character,
// add it when it is after the first character:
// #debug
//System.out.println("updateDeleteCommand: newText=[" + newText + "]");
if ( !this.isUneditable ) {
if ( newText == null
//#ifdef tmp.directInput
|| (this.caretPosition == 0 && this.caretChar == this.editingCaretChar)
//#else
|| newText.length() == 0
//#endif
) {
removeCommand( DELETE_CMD );
} else if ((this.text == null || this.text.length() == 0)
//#if tmp.directInput
// needed for native input as the string is passed as a whole
// and thus skips caretPosition == 1
|| this.caretPosition > 0
//#endif
) {
addCommand( DELETE_CMD );
}
}
//#endif
}
/**
* Copies the contents of the <code>TextField</code> into a character array starting at index zero.
* Array elements beyond the characters copied are left
* unchanged.
*
* @param data the character array to receive the value
* @return the number of characters copied
* @throws ArrayIndexOutOfBoundsException if the array is too short for the contents
* @throws NullPointerException if data is null
* @see #setChars(char[], int, int)
*/
public int getChars(char[] data)
{
if (this.text == null) {
return 0;
}
String txt = this.text;
if (this.isPassword) {
txt = this.passwordText;
}
char[] textArray = txt.toCharArray();
System.arraycopy(textArray, 0, data, 0, textArray.length );
return textArray.length;
}
/**
* Sets the contents of the <code>TextField</code> from a character array,
* replacing the previous contents.
* Characters are copied from the region of the
* <code>data</code> array
* starting at array index <code>offset</code> and running for
* <code>length</code> characters.
* If the data array is <code>null</code>, the <code>TextField</code>
* is set to be empty and the other parameters are ignored.
*
* <p>The <code>offset</code> and <code>length</code> parameters must
* specify a valid range of characters within
* the character array <code>data</code>.
* The <code>offset</code> parameter must be within the
* range <code>[0..(data.length)]</code>, inclusive.
* The <code>length</code> parameter
* must be a non-negative integer such that
* <code>(offset + length) <= data.length</code>.</p>
*
* @param data the source of the character data
* @param offset the beginning of the region of characters to copy
* @param length the number of characters to copy
* @throws ArrayIndexOutOfBoundsException - if offset and length do not specify a valid range within the data array
* @throws IllegalArgumentException - if data is illegal for the current input constraints
* or if the text would exceed the current maximum capacity
* @see #getChars(char[])
*/
public void setChars(char[] data, int offset, int length)
{
char[] copy = new char[ length ];
System.arraycopy(data, offset, copy, 0, length );
setString( new String( copy ));
}
/**
* Inserts a string into the contents of the
* <code>TextField</code>. The string is
* inserted just prior to the character indicated by the
* <code>position</code> parameter, where zero specifies the first
* character of the contents of the <code>TextField</code>. If
* <code>position</code> is
* less than or equal to zero, the insertion occurs at the beginning of
* the contents, thus effecting a prepend operation. If
* <code>position</code> is greater than or equal to the current size of
* the contents, the insertion occurs immediately after the end of the
* contents, thus effecting an append operation. For example,
* <code>text.insert(s, text.size())</code> always appends the string
* <code>s</code> to the current contents.
*
* <p>The current size of the contents is increased by the number of
* inserted characters. The resulting string must fit within the current
* maximum capacity. </p>
*
* <p>If the application needs to simulate typing of characters it can
* determining the location of the current insertion point
* ("caret")
* using the with <CODE>getCaretPosition()</CODE> method.
* For example,
* <code>text.insert(s, text.getCaretPosition())</code> inserts the string
* <code>s</code> at the current caret position.</p>
*
* @param src the String to be inserted
* @param position the position at which insertion is to occur
* @throws IllegalArgumentException if the resulting contents would be illegal for the current input constraints
* or if the insertion would exceed the current maximum capacity
* @throws NullPointerException if src is null
*/
public void insert( String src, int position)
{
String txt = getString(); // cannot be null
String start = txt.substring( 0, position );
String end = txt.substring( position );
setString( start + src + end );
//#if tmp.directInput
if (position == this.caretPosition) {
this.caretPosition += src.length();
}
//#else
setCaretPosition( getCaretPosition() + src.length() );
//#endif
//#if tmp.usePredictiveInput
if(this.predictiveInput)
this.predictiveAccess.synchronize();
//#endif
}
/**
* Inserts a subrange of an array of characters into the contents of
* the <code>TextField</code>. The <code>offset</code> and
* <code>length</code> parameters indicate the subrange
* of the data array to be used for insertion. Behavior is otherwise
* identical to <A HREF="../../../javax/microedition/lcdui/TextField.html#insert(java.lang.String, int)"><CODE>insert(String, int)</CODE></A>.
*
* <p>The <code>offset</code> and <code>length</code> parameters must
* specify a valid range of characters within
* the character array <code>data</code>.
* The <code>offset</code> parameter must be within the
* range <code>[0..(data.length)]</code>, inclusive.
* The <code>length</code> parameter
* must be a non-negative integer such that
* <code>(offset + length) <= data.length</code>.</p>
*
* @param data - the source of the character data
* @param offset - the beginning of the region of characters to copy
* @param length - the number of characters to copy
* @param position - the position at which insertion is to occur
* @throws ArrayIndexOutOfBoundsException - if offset and length do not specify a valid range within the data array
* @throws IllegalArgumentException - if the resulting contents would be illegal for the current input constraints
* or if the insertion would exceed the current maximum capacity
* @throws NullPointerException - if data is null
*/
public void insert(char[] data, int offset, int length, int position)
{
char[] copy = new char[ length ];
System.arraycopy( data, offset, copy, 0, length);
insert( new String( copy ), position );
}
/**
* Deletes characters from the <code>TextField</code>.
*
* <p>The <code>offset</code> and <code>length</code> parameters must
* specify a valid range of characters within
* the contents of the <code>TextField</code>.
* The <code>offset</code> parameter must be within the
* range <code>[0..(size())]</code>, inclusive.
* The <code>length</code> parameter
* must be a non-negative integer such that
* <code>(offset + length) <= size()</code>.</p>
*
* @param offset the beginning of the region to be deleted
* @param length the number of characters to be deleted
* @throws IllegalArgumentException if the resulting contents would be illegal for the current input constraints
* @throws StringIndexOutOfBoundsException if offset and length do not specify a valid range within the contents of the TextField
*/
public void delete(int offset, int length)
{
String txt = getString();
String start = txt.substring(0, offset );
String end = txt.substring( offset + length );
setString( start + end );
}
/**
* Returns the maximum size (number of characters) that can be
* stored in this <code>TextField</code>.
*
* @return the maximum size in characters
* @see #setMaxSize(int)
*/
public int getMaxSize()
{
return this.maxSize;
}
/**
* Sets the maximum size (number of characters) that can be contained
* in this
* <code>TextField</code>. If the current contents of the
* <code>TextField</code> are larger than
* <code>maxSize</code>, the contents are truncated to fit.
*
* @param maxSize the new maximum size
* @return assigned maximum capacity may be smaller than requested.
* @throws IllegalArgumentException if maxSize is zero or less.
* or if the contents after truncation would be illegal for the current input constraints
* @see #getMaxSize()
*/
public int setMaxSize(int maxSize)
{
if ((this.text != null && maxSize < this.text.length()) || (maxSize < 1)) {
throw new IllegalArgumentException();
}
//#if tmp.useNativeTextBox
if (this.midpTextBox != null) {
this.maxSize = this.midpTextBox.setMaxSize(maxSize);
return this.maxSize;
} else {
//#endif
this.maxSize = maxSize;
return maxSize;
//#if tmp.useNativeTextBox
}
//#endif
}
/**
* Gets the number of characters that are currently stored in this
* <code>TextField</code>.
*
* @return number of characters in the TextField
*/
public int size()
{
if (this.text == null) {
return 0;
} else {
return this.text.length();
}
}
/**
* Gets the current input position. For some UIs this may block and ask
* the user for the intended caret position, and on other UIs this may
* simply return the current caret position.
* When the direct input mode is used, this method simply returns the current cursor position (= non blocking).
*
* @return the current caret position, 0 if at the beginning
*/
public int getCaretPosition()
{
int curPos = 0;
//#if polish.android
curPos = this._androidTextField.getCursorPosition();
//#elif tmp.allowDirectInput
if (this.enableDirectInput) {
curPos = this.caretPosition;
//#if tmp.useNativeTextBox
} else if (this.midpTextBox != null) {
curPos = this.midpTextBox.getCaretPosition();
//#endif
}
//#elif polish.blackberry
curPos = this.editField.getInsertPositionOffset();
//#elif tmp.forceDirectInput
curPos = this.caretPosition;
//#elif polish.series40sdk20 || polish.series40sdk11
curPos = this.series40sdk20Field.getCaretPosition();
//#else
//#ifdef tmp.useNativeTextBox
if (this.midpTextBox != null) {
curPos = this.midpTextBox.getCaretPosition();
}
//#endif
//#endif
return curPos;
}
/**
* Sets the caret position.
* Please note that this operation requires the direct input mode to work.
*
* @param position the new caret position, 0 puts the caret at the start of the line, getString().length moves the caret to the end of the input.
*/
public void setCaretPosition(int position) {
//#if polish.android
try {
AndroidTextField nativeField = this._androidTextField;
if (nativeField == null) {
this.caretPosition = position;
} else {
this.caretPosition = -1;
nativeField.setCursorPosition(position);
}
} catch (IndexOutOfBoundsException e) {
// ignore
}
//#elif polish.blackberry
Object bbLock = Application.getEventLock();
synchronized ( bbLock )
{
this.editField.setCursorPosition(position);
}
//#elif polish.series40sdk20 || polish.series40sdk11
synchronized ( this.series40sdk20Field) {
this.series40sdk20Field.setCaret(position);
}
//#elif tmp.allowDirectInput || tmp.forceDirectInput
this.caretPosition = position;
if ( this.isInitialized && this.realTextLines != null ){
int row = 0;
int col = 0;
int passedCharacters = 0;
String textLine = null;
for (int i = 0; i < this.textLines.size(); i++) {
textLine = this.realTextLines[i]; //this.textLines[i];
passedCharacters += textLine.length();
//System.out.println("passedCharacters=" + passedCharacters + ", line=" + textLine );
if (passedCharacters >= position ) {
row = i;
col = textLine.length() - (passedCharacters - position);
break;
}
}
//#debug
System.out.println("setCaretPosition, position=" + position + ", row=" + row + ", col=" + col );
this.caretRow = row;
this.caretColumn = col;
textLine = this.textLines.getLine( row );
String firstPart;
if (this.caretColumn < textLine.length()) {
firstPart = textLine.substring(0, this.caretColumn);
} else {
firstPart = textLine;
}
if (this.isPassword) {
this.caretX = stringWidth( "*" ) * firstPart.length();
} else {
this.caretX = stringWidth( firstPart );
}
this.internalY = this.caretRow * this.rowHeight;
this.caretY = this.internalY;
repaint();
}
//#endif
}
//#if polish.android
/**
* Creates the native Android implementation for the text input.
* Subclasses may override this is to use custom classes. Note that the <code>polish.android</code> preprocessing symbol needs to be checked: <code>//#if polish.android</code>.
* @return new AndroidTextFieldImpl(TextField.this) by default.
*/
protected AndroidTextField createNativeAndroidTextField() {
return new AndroidTextFieldImpl(TextField.this);
}
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
protected TextEditor createNativeNokiaTextField() {
TextEditor editor = TextEditor.createTextEditor(
9999, TextField.ANY, 50, 50);
editor.setVisible(true);
editor.setTouchEnabled(true);
editor.setSize(1, 1);
editor.setMultiline(true);
return editor;
}
//#endif
/**
* Sets the input constraints of the <code>TextField</code>. If
* the the current contents
* of the <code>TextField</code> do not match the new
* <code>constraints</code>, the contents are
* set to empty.
*
* @param constraints see input constraints
* @throws IllegalArgumentException if constraints is not any of the ones specified in input constraints
* @see #getConstraints()
*/
public void setConstraints(int constraints)
{
if (constraints == this.constraints) {
// ignore
return;
}
this.constraints = constraints;
int fieldType = constraints & 0xffff;
this.isUneditable = (constraints & UNEDITABLE) == UNEDITABLE;
//#if polish.css.text-wrap
this.animateTextWrap = this.isUneditable;
//#endif
//#if polish.android
MidletBridge.getInstance().runOnUiThread( new Runnable() {
public void run() {
if ( (TextField.this.isShown) && (TextField.this._androidView != null) ) {
// remove existing view first:
AndroidDisplay.getInstance().onHide(TextField.this._androidView, TextField.this);
}
AndroidTextField nativeField = createNativeAndroidTextField();
TextField.this._androidTextField = nativeField;
TextField.this._androidView = (View) nativeField;
if (TextField.this.isShown) {
AndroidDisplay.getInstance().onShow(TextField.this._androidView, TextField.this);
}
int caretPos = TextField.this.caretPosition;
if (caretPos != -1) {
TextField.this._androidTextField.setCursorPosition(caretPos);
TextField.this.caretPosition = -1;
}
}
});
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field == null ) {
this.series40sdk20Field = createNativeNokiaTextField();
//#= this.series40sdk20Field.setTextEditorListener(this);
inputAction(this.series40sdk20Field, 0);
}
this.enableDirectInput = true;
//#endif
//#if polish.blackberry
int filterType = TextFilter.DEFAULT;
long bbStyle = Field.FOCUSABLE;
if (this.isUneditable) {
bbStyle |= Field.READONLY;
} else {
bbStyle |= Field.EDITABLE;
}
if ( fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) {
bbStyle |= BasicEditField.FILTER_REAL_NUMERIC;
filterType = TextFilter.REAL_NUMERIC;
} else if (fieldType == NUMERIC) {
bbStyle |= BasicEditField.FILTER_INTEGER;
filterType = TextFilter.INTEGER;
} else if (fieldType == PHONENUMBER) {
bbStyle |= BasicEditField.FILTER_PHONE;
filterType = TextFilter.PHONE;
} else if (fieldType == EMAILADDR ) {
bbStyle |= BasicEditField.FILTER_EMAIL;
filterType = TextFilter.EMAIL;
} else if ( fieldType == URL ) {
bbStyle |= BasicEditField.FILTER_URL;
filterType = TextFilter.URL;
}
if ((constraints & SENSITIVE) == SENSITIVE) {
bbStyle |= BasicEditField.NO_LEARNING;
}
if ((constraints & NON_PREDICTIVE) == NON_PREDICTIVE) {
bbStyle |= BasicEditField.NO_LEARNING;
}
if(this.noNewLine){
bbStyle |= BasicEditField.NO_NEWLINE;
}
if(this.noComplexInput){
bbStyle |= BasicEditField.NO_COMPLEX_INPUT;
}
if (this.editField != null) {
// remove the old edit field from the blackberry screen:
Object bbLock = Application.getEventLock();
synchronized ( bbLock ) {
Manager manager = this._bbField.getManager();
if (manager != null) {
manager.delete(this._bbField);
}
if (this.isFocused) {
getScreen().notifyFocusSet(this);
}
}
}
int max = this.maxSize;
if (fieldType == FIXED_POINT_DECIMAL) {
int possibleGroupingSeparators = (max - this.numberOfDecimalFractions) / 3;
max = max + 1 + possibleGroupingSeparators; // this is for the dot and the grouping separator
}
this.isPassword = false;
if ((constraints & PASSWORD) == PASSWORD) {
this.isPassword = true;
this.editField = new PolishPasswordEditField( null, getString(), max, bbStyle );
}else if((bbStyle & BasicEditField.FILTER_EMAIL) == BasicEditField.FILTER_EMAIL) {
this.editField = new PolishEmailAddressEditField( null, getString(), max, bbStyle );
} else {
Style fieldStyle = getStyle();
if ( (fieldStyle != null)
&& (fieldStyle.getBooleanProperty("text-wrap") != null)
&& (fieldStyle.getBooleanProperty("text-wrap").booleanValue() == false)
) {
this.editField = new PolishOneLineField( null, getString(), max, bbStyle );
//#if polish.css.max-lines
fieldStyle.addAttribute("max-lines", new Integer(1));
//#endif
//#if polish.css.max-height
if (fieldStyle.getFont() != null) {
fieldStyle.addAttribute("max-height", new Dimension(fieldStyle.getFont().getHeight()));
}
//#endif
}
else
{
this.editField = new PolishEditField(null, getString(), max, bbStyle);
}
}
if ( fieldType == FIXED_POINT_DECIMAL) {
this.editField.setFilter( new FixedPointDecimalTextFilter());
} else {
this.editField.setFilter(TextFilter.get(filterType));
}
if (this.style != null) {
this.editField.setStyle( this.style );
}
//# this.editField.setChangeListener( this );
this._bbField = (Field) this.editField;
//#elif tmp.useNativeTextBox
if (this.midpTextBox != null) {
this.midpTextBox.setConstraints(constraints);
}
if ((constraints & PASSWORD) == PASSWORD) {
this.isPassword = true;
}
//#endif
//#ifdef tmp.directInput
this.characters = CHARACTERS;
this.isEmail = false;
this.isUrl = false;
if ((constraints & PASSWORD) == PASSWORD) {
this.isPassword = true;
}
if (fieldType == NUMERIC || fieldType == PHONENUMBER) {
this.isNumeric = true;
this.inputMode = MODE_NUMBERS;
//#ifndef polish.hasPointerEvents
this.enableDirectInput = true;
//#endif
} else {
this.isNumeric = false;
}
if (fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) {
this.isNumeric = true;
this.isDecimal = true;
this.inputMode = MODE_NUMBERS;
} else {
this.isDecimal = false;
}
if (fieldType == EMAILADDR) {
this.isEmail = true;
this.characters = EMAIL_CHARACTERS;
}
if (fieldType == URL) {
this.isUrl = true;
}
if ((constraints & INITIAL_CAPS_WORD) == INITIAL_CAPS_WORD) {
this.inputMode = MODE_FIRST_UPPERCASE;
this.nextCharUppercase = true;
}
//#if tmp.useInputInfo
updateInfo();
//#endif
//#endif
//#if !tmp.suppressCommands
//#if (polish.TextField.suppressDeleteCommand != true)
removeCommand( DELETE_CMD );
//#endif
//#if polish.TextField.suppressClearCommand != true
removeCommand( CLEAR_CMD );
//#endif
//#if tmp.directInput && tmp.supportsSymbolEntry && polish.TextField.suppressAddSymbolCommand != true
removeCommand( ENTER_SYMBOL_CMD );
//#endif
//#endif
// set item commands:
//#if !tmp.suppressCommands
if(!this.suppressCommands)
{
if (this.isFocused) {
getScreen().removeItemCommands( this );
}
// add default text field item-commands:
//#if (polish.TextField.suppressDeleteCommand != true) && !polish.blackberry
if (!this.isUneditable) {
//#ifdef polish.i18n.useDynamicTranslations
String delLabel = Locale.get("polish.command.delete");
if ( delLabel != DELETE_CMD.getLabel()) {
DELETE_CMD = new Command( delLabel, Command.CANCEL, DELETE_PRIORITY );
}
//#endif
this.addCommand(DELETE_CMD);
}
//#endif
//#if polish.TextField.suppressClearCommand != true
if (!this.isUneditable) {
//#ifdef polish.i18n.useDynamicTranslations
String clearLabel = Locale.get("polish.command.clear");
if ( clearLabel != CLEAR_CMD.getLabel()) {
CLEAR_CMD = new Command( clearLabel, Command.ITEM, CLEAR_PRIORITY );
}
//#endif
this.addCommand(CLEAR_CMD);
}
//#endif
//#if tmp.directInput && tmp.supportsSymbolEntry && polish.TextField.suppressAddSymbolCommand != true
if (!this.isNumeric) {
if (!this.isUneditable) {
//#ifdef polish.i18n.useDynamicTranslations
String enterSymbolLabel = Locale.get("polish.command.entersymbol");
if ( enterSymbolLabel != ENTER_SYMBOL_CMD.getLabel()) {
ENTER_SYMBOL_CMD = new Command( enterSymbolLabel, Command.ITEM, ENTER_SYMBOL_PRIORITY );
}
//#endif
this.addCommand(ENTER_SYMBOL_CMD);
}
}
//#endif
}
this.itemCommandListener = this;
if (this.isFocused) {
showCommands();
}
// end of if !tmp.suppressCommands:
//#endif
// if ( (constraints & UNEDITABLE) == UNEDITABLE) {
// // deactivate this field:
// super.setAppearanceMode( Item.PLAIN );
// if (this.isInitialised && this.isFocused && this.parent instanceof Container) {
// ((Container)this.parent).requestDefocus( this );
// }
// } else {
// super.setAppearanceMode( Item.INTERACTIVE );
// }
}
/**
* Sets a blackberry field to selectable.
* Used to prevent fields to be selectable if they should not be shown.
* You should check for the 'polish.blackberry' preprocessing symbol when using this method:
* <pre>
* //#if polish.blackberry
* </pre>
*
* @param editable true, if the textfield should be selectable, otherwise false
*/
public void activate(boolean editable)
{
//#if polish.blackberry
Object bbLock = Application.getEventLock();
synchronized (bbLock) {
if (editable) {
if(this._bbField == null) {
setConstraints(this.constraints);
}
if (this.isFocused) {
Display.getInstance().notifyFocusSet(this);
}
} else {
if (this._bbField != null) {
Manager manager = this._bbField.getManager();
manager.delete(this._bbField);
this.editField = null;
this._bbField = null;
}
}
}
//#endif
}
/**
* Allows to set a BlackBerry textfield to be editable
* You should check for the 'polish.blackberry' preprocessing symbol when using this method:
* <pre>
* //#if polish.blackberry
* </pre>
*
* @param editable true when this field should be editable (the default behavior).
*/
public void setEditable(boolean editable)
{
//#if polish.blackberry
this._bbField.setEditable(editable);
//#endif
}
/**
* Gets the current input constraints of the <code>TextField</code>.
*
* @return the current constraints value (see input constraints)
* @see #setConstraints(int)
*/
public int getConstraints()
{
return this.constraints;
}
/**
* Sets a hint to the implementation as to the input mode that should be
* used when the user initiates editing of this <code>TextField</code>. The
* <code>characterSubset</code> parameter names a subset of Unicode
* characters that is used by the implementation to choose an initial
* input mode. If <code>null</code> is passed, the implementation should
* choose a default input mode.
*
*
* <p>When the direct input mode is used, J2ME Polish will ignore this call completely.</p>
*
* @param characterSubset a string naming a Unicode character subset, or null
* @since MIDP 2.0
*/
public void setInitialInputMode( String characterSubset)
{
//#if tmp.useNativeTextBox
if (this.midpTextBox == null) {
createTextBox();
}
//#if !polish.midp1
this.midpTextBox.setInitialInputMode( characterSubset );
//#endif
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintContent(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
public void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) {
String myText = this.text;
//#if polish.blackberry
if (this.isFocused && getScreen().isNativeUiShownFor(this)) {
x--; // blackberry paints a border around the text that is one pixel wide
this.editField.setPaintPosition( x + g.getTranslateX(), y + g.getTranslateY() );
} else {
if (this.isUneditable || !this.isFocused) {
//#if polish.TextField.showHelpText
if(myText == null || myText.length() == 0)
{
this.helpItem.paint(x, y, leftBorder, rightBorder, g);
} else
//#endif
super.paintContent(x, y, leftBorder, rightBorder, g);
return;
}else{
super.paintContent(x, y, leftBorder, rightBorder, g);
}
}
//#elif polish.android
// //#if polish.TextField.showHelpText
// if(myText == null || myText.length() == 0)
// {
// this.helpItem.paint(x, y, leftBorder, rightBorder, g);
// }
// //#endif
//#if polish.css.repaint-previous-screen
// native views are not painted in screens that lie underneath a popup screen:
Screen scr = getScreen();
if (scr != null && !scr.isShown()) {
WrappedText wrappedText = getWrappedText();
if (myText != null && wrappedText.size() == 0) {
int cw = this.contentWidth;
TextUtil.wrap(myText, this.font, cw, cw, 0, null, 0, wrappedText );
}
super.paintContent(x, y, leftBorder, rightBorder, g);
}
//#endif
//#elif polish.series40sdk20 || polish.series40sdk11
//#if polish.TextField.showHelpText
if(myText == null || myText.length() == 0)
{
this.helpItem.paint(x, y, leftBorder, rightBorder, g);
}
//#endif
if ( ! isFocused() || this.isUneditable ) {
super.paintContent(x, y, leftBorder, rightBorder, g);
} else {
if ( this.series40sdk20Field != null ) {
Object object = Display.getInstance();
int textFieldHeight = getItemAreaHeight() - getPaddingBottom() - getPaddingTop() ;
this.series40sdk20Field.setVisible(true);
this.series40sdk20Field.setParent(object);
this.series40sdk20Field.setPosition(x, y);
this.series40sdk20Field.setSize(this.getAvailableContentWidth(), textFieldHeight);
}
}
//#else
if (this.isUneditable || !this.isFocused) {
//#if polish.TextField.showHelpText
if(myText == null || myText.length() == 0)
{
this.helpItem.paint(x, y, leftBorder, rightBorder, g);
} else
//#endif
super.paintContent(x, y, leftBorder, rightBorder, g);
return;
}
int availWidth = rightBorder-leftBorder;
int availHeight = this.availableHeight;
//#ifdef tmp.directInput
//#ifdef tmp.allowDirectInput
if ( this.enableDirectInput ) {
//#endif
// adjust text-start for input info abc|Abc|ABC|123 if it should be shown on the same line:
//#if tmp.includeInputInfo && !polish.TextField.useExternalInfo
if (this.isFocused && this.infoItem != null && this.isShowInputInfo) {
int infoWidth = this.infoItem.getItemWidth( availWidth, availWidth, availHeight);
if (this.infoItem.isLayoutRight) {
int newRightBorder = rightBorder - infoWidth;
this.infoItem.paint( newRightBorder, y, newRightBorder, rightBorder, g);
rightBorder = newRightBorder;
} else {
// left aligned (center is not supported)
this.infoItem.paint( x, y, leftBorder, rightBorder, g);
x += infoWidth;
leftBorder += infoWidth;
}
}
//#endif
//#if polish.TextField.showHelpText
if(myText == null || myText.length() == 0)
{
this.helpItem.paint(x, y, leftBorder, rightBorder, g);
} else
//#endif
if (this.isPassword && !(this.showCaret || this.isNumeric || this.caretChar == this.editingCaretChar)) {
int cX = getCaretXPosition(x, rightBorder, availWidth);
int cY = y + this.caretY;
int clipX = g.getClipX();
int clipY = g.getClipY();
int clipWidth = g.getClipWidth();
int clipHeight = g.getClipHeight();
g.clipRect( x, y, cX - x, clipHeight );
super.paintContent(x, y, leftBorder, rightBorder, g);
g.setClip( clipX, clipY, clipWidth, clipHeight );
int w = this.caretWidth;
int starWidth = charWidth('*');
if (starWidth > w) {
w = starWidth;
}
if (this.caretX + w < this.contentWidth) {
g.clipRect( cX + w, y, clipWidth, clipHeight );
super.paintContent(x, y, leftBorder, rightBorder, g);
g.setClip( clipX, clipY, clipWidth, clipHeight );
}
if (cY > y) {
g.clipRect( clipX, clipY, clipWidth, cY - clipY );
super.paintContent(x, y, leftBorder, rightBorder, g);
g.setClip( clipX, clipY, clipWidth, clipHeight );
}
int h = getFontHeight();
if (this.caretY + h < this.contentHeight) {
g.clipRect( x, cY + h, clipWidth, clipHeight );
super.paintContent(x, y, leftBorder, rightBorder, g);
g.setClip( clipX, clipY, clipWidth, clipHeight );
}
g.setColor( this.textColor);
int anchor = Graphics.TOP | Graphics.LEFT;
//#if polish.Bugs.needsBottomOrientiationForStringDrawing
cY += h;
anchor = Graphics.BOTTOM | Graphics.LEFT;
//#endif
//#if polish.css.text-effect
if (this.textEffect != null) {
this.textEffect.drawChar( this.caretChar, cX, cY, anchor, g);
} else {
//#endif
g.drawChar( this.caretChar, cX, cY, anchor );
//#if polish.css.text-effect
}
//#endif
} else {
super.paintContent(x, y, leftBorder, rightBorder, g);
}
//#ifdef polish.css.text-wrap
if (this.useSingleLine) {
x += this.xOffset;
}
//#endif
if (this.showCaret) {
//#ifdef polish.css.textfield-caret-color
g.setColor( this.caretColor );
//#else
g.setColor( this.textColor );
//#endif
int cX = getCaretXPosition(x, rightBorder, availWidth);
int cY = y + this.caretY;
if (this.caretChar != this.editingCaretChar) {
// draw background rectangle
int w = this.caretWidth;
if (this.isPassword) {
int starWidth = charWidth('*');
if (starWidth > w) {
w = starWidth;
}
}
int h = getFontHeight();
g.fillRect( cX, cY, w, h);
//display highlighted text in white color
g.setColor( DrawUtil.getComplementaryColor(g.getColor()) );
int anchor = Graphics.TOP | Graphics.LEFT;
//#if polish.Bugs.needsBottomOrientiationForStringDrawing
cY += h;
anchor = Graphics.BOTTOM | Graphics.LEFT;
//#endif
//#if polish.css.text-effect
if (this.textEffect != null) {
this.textEffect.drawChar( this.caretChar, cX, cY, anchor, g);
} else {
//#endif
g.drawChar( this.caretChar, cX, cY, anchor );
//#if polish.css.text-effect
}
//#endif
} else {
g.drawLine( cX, cY, cX, cY + getFontHeight() - 2);
}
}
//#if tmp.usePredictiveInput
this.predictiveAccess.paintChoices(x, y, this.caretX, this.caretY, leftBorder, rightBorder, g);
//#endif
// g.setColor( 0xffffff );
// g.fillRect( x, y, 10, getFontHeight() );
// g.setColor( 0xff0000 );
// g.drawChar( this.caretChar, x, y, Graphics.LEFT | Graphics.TOP );
return;
//#ifdef tmp.allowDirectInput
} else {
super.paintContent(x, y, leftBorder, rightBorder, g);
}
//#endif
//#else
super.paintContent(x, y, leftBorder, rightBorder, g);
// no direct input possible, but paint caret
if (this.showCaret && this.isFocused ) {
//#ifndef polish.css.textfield-caret-color
g.setColor( this.textColor );
//#else
g.setColor( this.caretColor );
//#endif
if (this.isLayoutCenter) {
x = leftBorder
+ ((availWidth) >> 1)
+ (this.contentWidth >> 1)
+ 2;
} else if (this.isLayoutRight){
x = rightBorder;
} else {
x += this.contentWidth + 2;
}
g.drawLine( x, y, x, y + getFontHeight() );
}
//#endif
// end of non-blackberry/android block
//#endif
}
//#ifdef tmp.directInput
/**
* Calculates the exact horizontal caret position.
* @param x the x position of this field
* @param rightBorder the right border
* @param availWidth the available width
* @return the caret position
*/
private int getCaretXPosition(int x, int rightBorder, int availWidth) {
int cX;
//#if polish.i18n.rightToLeft
if (this.isLayoutRight) {
cX = rightBorder - this.caretX;
} else
//#endif
{
cX = x + this.caretX;
}
return cX;
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initItem()
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight) {
this.screen = getScreen();
//#if tmp.includeInputInfo
if (this.infoItem != null && this.isFocused && this.isShowInputInfo) {
int infoWidth = this.infoItem.getItemWidth(firstLineWidth, availWidth, availHeight);
firstLineWidth -= infoWidth;
availWidth -= infoWidth;
}
//#endif
//#if polish.blackberry && polish.css.text-wrap
if (this.isFocused) {
this.useSingleLine = false;
}
//#endif
//#if polish.android
View nativeView = this._androidView;
if (nativeView == null) {
this.contentWidth = availWidth;
this.contentHeight = getFontHeight();
} else {
nativeView.requestLayout();
nativeView.measure(
MeasureSpec.makeMeasureSpec(availWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(availHeight, MeasureSpec.AT_MOST)
);
this.contentWidth = nativeView.getMeasuredWidth();
this.contentHeight = nativeView.getMeasuredHeight();
}
//#else
super.initContent(firstLineWidth, availWidth, availHeight);
//#if polish.TextField.showHelpText
UiAccess.init(this.helpItem, firstLineWidth, availWidth, availHeight);
//#endif
//#if tmp.includeInputInfo
if (this.infoItem != null && this.isFocused && this.isShowInputInfo) {
this.contentWidth += this.infoItem.itemWidth;
if (this.contentHeight < this.infoItem.itemHeight) {
this.contentHeight = this.infoItem.itemHeight;
}
}
//#endif
if (this.font == null) {
this.font = Font.getDefaultFont();
}
if (this.contentHeight < getFontHeight()) {
this.contentHeight = getFontHeight();
}
//#if polish.blackberry
if (!this.isFocused) {
return;
}
if(this.editField != null)
{
if (this.style != null) {
this.editField.setStyle( this.style );
}
// allowing native field to expand to the fully available width,
// the content size does not need to be changed as the same font is being
// used.
this.editField.doLayout( availWidth, this.contentHeight );
// On some devices, like the 9000, after layout() the native EditField
// grows larger than the maximum specified height, but only by a few
// pixels. When that happens, we have to increase the content height accordingly.
if ( this.editField.getExtent().height > this.contentHeight )
{
this.contentHeight = this.editField.getExtent().height;
}
updateInternalArea();
}
//#elif polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null && this.contentWidth > 0 && this.contentHeight > 0 ) {
inputAction(this.series40sdk20Field, 0);
}
//#elif tmp.directInput
this.rowHeight = getFontHeight() + this.paddingVertical;
if (this.textLines == null || this.text == null || this.text.length() == 0) {
this.caretX = 0;
this.caretY = 0;
this.caretPosition = 0;
this.caretColumn = 0;
this.caretRow = 0;
this.originalRowText = "";
this.realTextLines = null;
//#if polish.css.text-wrap
if (this.useSingleLine) {
this.xOffset = 0;
}
//#endif
} else {
// init the original text-lines with spaces and line-breaks:
//System.out.println("TextField.initContent(): text=[" + this.text + "], (this.realTextLines == null): " + (this.realTextLines == null) + ", this.caretPosition=" + this.caretPosition + ", caretColumn=" + this.caretColumn + ", doSetCaretPos=" + this.doSetCaretPosition + ", hasBeenSet=" + this.caretPositionHasBeenSet);
int length = this.textLines.size();
int textLength = this.text.length();
String[] realLines = this.realTextLines;
if (realLines == null || realLines.length != length) {
realLines = new String[ length ];
}
boolean caretPositionHasBeenSet = false;
int cp = this.caretPosition;
// if (this.caretChar != this.editingCaretChar) {
// cp++;
// }
int endOfLinePos = 0;
for (int i = 0; i < length; i++) {
String line = this.textLines.getLine(i);
endOfLinePos += line.length();
if (endOfLinePos < textLength) {
char c = this.text.charAt( endOfLinePos );
if (c == ' ' || c == '\t' || c == '\n') {
line += c;
endOfLinePos++;
}
}
realLines[i] = line;
if (!caretPositionHasBeenSet && ((endOfLinePos > cp) || (endOfLinePos == cp && i == length -1 )) ) {
//System.out.println("TextField: caretPos=" + this.caretPosition + ", line=" + line + ", endOfLinePos=" + endOfLinePos );
this.caretRow = i;
setCaretRow(line, line.length() - (endOfLinePos - cp) );
this.caretY = this.caretRow * this.rowHeight;
caretPositionHasBeenSet = true;
}
} // for each line
this.realTextLines = realLines;
if (!caretPositionHasBeenSet) {
//System.out.println("caret position has not been set before");
//this.caretPosition = this.text.length();
this.caretRow = 0; //this.realTextLines.length - 1;
String caretRowText = this.realTextLines[ this.caretRow ];
int caretRowLength = caretRowText.length();
if (caretRowLength > 0 && caretRowText.charAt( caretRowLength-1) == '\n' ) {
caretRowText = caretRowText.substring(0, caretRowLength-1);
}
setCaretRow( caretRowText, caretRowLength );
this.caretPosition = this.caretColumn;
this.caretY = 0; // this.rowHeight * (this.realTextLines.length - 1);
//System.out.println(this + ".initContent()/font3: caretX=" + this.caretX);
//this.textLines[ this.textLines.length -1 ] += " ";
this.textLines.setLine( 0, this.textLines.getLine(0) + " " );
}
}
// set the internal information so that big TextBoxes can still be scrolled
// correctly:
this.internalX = 0;
this.internalY = this.caretY;
this.internalWidth = this.contentWidth;
this.internalHeight = this.rowHeight;
this.screen = getScreen();
if (this.isFocused && this.parent instanceof Container ) {
// ensure that the visible area of this TextField is shown:
((Container)this.parent).scroll(0, this, true); // problem: itemHeight is not yet set
}
// end if !polish.android
//#endif
//#endif
}
//#if tmp.directInput
/**
* Sets the caret row.
* The fields originalRowText, caretColumn, caretRowFirstPart, caretX, caretRowLastPart and caretRowLastPartWidth
* are being set. Note that the field caretRowLastPartWidth is only set whent the
* layout is either center or right.
*
* @param line the new caret row text
* @param column the column position of the caret
*/
private void setCaretRow( String line, int column ) {
//#debug
System.out.println("setCaretRow( line=\"" + line + "\", column=" + column + ")");
this.originalRowText = line;
int length = line.length();
if (column > length ) {
column = length;
}
this.caretColumn = column;
boolean endsInLineBreak = (length >= 1) && (line.charAt(length-1) == '\n');
String caretRowFirstPart;
if (column == length || ( endsInLineBreak && column == length -1 )) {
if ( endsInLineBreak ) {
caretRowFirstPart = line.substring( 0, length - 1);
} else {
caretRowFirstPart = line;
}
} else {
caretRowFirstPart = line.substring( 0, column );
//this.caretRowLastPartWidth = this.font.stringWidth(this.caretRowLastPart);;
}
if (this.isPassword) {
this.caretX = stringWidth( "*" ) * caretRowFirstPart.length();
} else {
this.caretX = stringWidth(caretRowFirstPart);
}
//System.out.println("caretRowWidth=" + this.caretRowWidth + " for line=" + line);
//#if polish.css.text-wrap
if (this.useSingleLine) {
if (this.caretX > this.availableTextWidth) {
this.xOffset = this.availableTextWidth - this.caretX - this.caretWidth - 5;
} else {
this.xOffset = 0;
}
}
//#endif
//#debug
System.out.println("setCaretRow() result: endsInLineBreak=" + endsInLineBreak + ", firstPart=[" + caretRowFirstPart + "].");
}
//#endif
//#ifdef polish.useDynamicStyles
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getCssSelector()
*/
protected String createCssSelector() {
return "textfield";
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style)
*/
public void setStyle(Style style) {
super.setStyle(style);
if (this.font == null) {
this.font = Font.getDefaultFont();
}
//#ifdef polish.css.textfield-direct-input
Boolean useDirectInputBool = style.getBooleanProperty("textfield-direct-input");
if (useDirectInputBool != null) {
this.enableDirectInput = useDirectInputBool.booleanValue();
}
//#endif
//#if polish.css.textfield-show-length && tmp.directInput
Boolean showBool = style.getBooleanProperty("textfield-show-length");
if (showBool != null) {
this.showLength = showBool.booleanValue();
}
//#endif
//#ifdef polish.css.textfield-caret-flash
Boolean flashCursorBool = style.getBooleanProperty( "textfield-caret-flash" );
if ( flashCursorBool != null ) {
this.flashCaret = flashCursorBool.booleanValue();
if (!this.flashCaret) {
this.showCaret = true;
}
}
//#endif
//#if tmp.usePredictiveInput
//#if polish.css.predictive-containerstyle
Style containerstyle = (Style) style.getObjectProperty("predictive-containerstyle");
if (containerstyle != null) {
this.predictiveAccess.choicesContainer.setStyle( containerstyle );
}
//#endif
//#if polish.css.predictive-choicestyle
Style choicestyle = (Style) style.getObjectProperty("predictive-choicestyle");
if (choicestyle != null) {
this.predictiveAccess.choiceItemStyle = choicestyle;
}
//#endif
//#if polish.css.predictive-choice-orientation
Integer choiceorientation = style.getIntProperty("predictive-choice-orientation");
if (choiceorientation != null) {
this.predictiveAccess.choiceOrientation = choiceorientation.intValue();
}
//#endif
//#endif
//#if polish.android
if (this._androidTextField != null) {
this._androidTextField.setStyle(style);
}
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null ) {
this.series40sdk20Field.setFont(this.font);
Color color = style.getColorProperty("font-color");
if ( color != null ) {
this.series40sdk20Field.setForegroundColor(0xFF000000 | color.getColor());
}
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.StringItem#setStyle(de.enough.polish.ui.Style, boolean)
*/
public void setStyle(Style style, boolean resetStyle)
{
super.setStyle(style, resetStyle);
//#ifdef polish.css.textfield-caret-color
Color colorInt = style.getColorProperty("textfield-caret-color");
if (colorInt != null) {
this.caretColor = colorInt.getColor();
} else if (this.caretColor == -1) {
this.caretColor = this.textColor;
}
//#endif
}
//#ifdef tmp.directInput
protected boolean isValidInput( char insertChar, int position, String myText ) {
if (!this.isEmail) {
return true;
}
// check valid input for email addresses:
char lowerCaseInsertChar = Character.toLowerCase( insertChar );
boolean isValidInput = (insertChar >= '0' && insertChar <= '9') || ( lowerCaseInsertChar >= 'a' && lowerCaseInsertChar <= 'z' ) ;
if (!isValidInput) {
boolean isInLocalPart = true; // are we in the first/local part before the '@' in the address?
String emailAddressText = myText;
int atPosition = -1;
int relativeCaretPosition = this.caretPosition;
if (emailAddressText != null) {
// extract single email address part when there are several email addresses (this can
// only happen when a ChoiceTextField is used)
int separatorPosition;
while ( (separatorPosition = emailAddressText.indexOf(this.emailSeparatorChar)) != -1 ) {
if (separatorPosition < this.caretPosition) {
emailAddressText = emailAddressText.substring( separatorPosition + 1);
relativeCaretPosition -= separatorPosition;
} else {
emailAddressText = emailAddressText.substring( 0, separatorPosition );
break;
}
}
// check for the '@' sign as the separator between local part and domain name:
atPosition = emailAddressText.indexOf('@');
isInLocalPart = ( atPosition == -1 ) || ( atPosition >= this.caretPosition );
}
if (isInLocalPart) {
boolean isAtFirstChar = (emailAddressText == null || relativeCaretPosition == 0);
isValidInput = ( VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS.indexOf( insertChar ) != -1 )
&& !( (insertChar == '.') && isAtFirstChar) // the first char must not be a dot.
&& !(atPosition != -1 && insertChar == '@' && atPosition != position) // it's not allowed to enter two @ characters
&& !(insertChar == '@' && isAtFirstChar ); // the first character must not be the '@' sign
} else {
isValidInput = VALID_DOMAIN_CHARACTERS.indexOf( insertChar ) != -1;
}
if (!isValidInput) {
//#debug
System.out.println("email: invalid input!");
}
}
return isValidInput;
}
protected void commitCurrentCharacter() {
//#debug
System.out.println("comitting current character: " + this.caretChar);
String myText;
if (this.isPassword) {
myText = this.passwordText;
} else {
myText = this.text;
}
char insertChar = this.caretChar;
if (!isValidInput( insertChar, this.caretPosition, myText )) {
return;
}
this.caretChar = this.editingCaretChar;
// increase caret position after notifying itemstatelisteners in case they want to know the current caret position...
this.caretPosition++;
this.caretColumn++;
if (this.isPassword) {
this.caretX += stringWidth("*");
} else {
this.caretX += this.caretWidth;
}
boolean nextCharInputHasChanged = false;
//#if polish.TextField.suppressAutoInputModeChange
if ( this.inputMode == MODE_FIRST_UPPERCASE
&& (insertChar == ' ' || ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)) ))
{
this.nextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
//#else
nextCharInputHasChanged = this.nextCharUppercase;
if ( ( (this.inputMode == MODE_FIRST_UPPERCASE || this.nextCharUppercase || this.prepareNextCharUppercase)
&& insertChar == ' ')
//|| ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)))
){
this.nextCharUppercase = true;
this.prepareNextCharUppercase = false;
} else if ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)) {
this.prepareNextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
nextCharInputHasChanged = (this.nextCharUppercase != nextCharInputHasChanged);
if ( this.inputMode == MODE_FIRST_UPPERCASE ) {
this.inputMode = MODE_LOWERCASE;
}
//#endif
//#if polish.css.textfield-show-length && tmp.useInputInfo
if (this.showLength || nextCharInputHasChanged) {
updateInfo();
}
//#elif tmp.useInputInfo
if (nextCharInputHasChanged) {
updateInfo();
}
//#endif
notifyStateChanged();
//#ifdef polish.css.textfield-caret-flash
if (!this.flashCaret) {
repaint();
}
//#endif
}
protected void insertCharacter( char insertChar, boolean append, boolean commit ) {
if (append && this.text != null && this.text.length() >= this.maxSize ) {
return;
}
//#debug
System.out.println( "insertCharacter " + insertChar); // + ", append=" + append + ", commit=" + commit +", caretPos=" + this.caretPosition );
String myText = getString();
int cp = this.caretPosition;
if (!isValidInput( insertChar, cp, myText )) {
return;
}
if (myText == null || myText.length() == 0) {
myText = "" + insertChar;
} else if (append) {
StringBuffer buffer = new StringBuffer( myText.length() + 1 );
buffer.append( myText.substring( 0, cp ) )
.append( insertChar );
if (cp < myText.length() ) {
buffer.append( myText.substring( cp ) );
}
myText = buffer.toString();
} else {
// replace current caret char:
StringBuffer buffer = new StringBuffer(myText.length());
buffer.append(myText.substring( 0, cp ) ).append( insertChar );
if (cp < myText.length() - 1) {
buffer.append( myText.substring( this.caretPosition + 1 ) );
}
myText = buffer.toString();
}
//System.out.println("new text=[" + myText + "]" );
boolean nextCharInputHasChanged = false;
if (commit) {
this.caretPosition++;
this.caretColumn++;
//#if polish.TextField.suppressAutoInputModeChange
if ( this.inputMode == MODE_FIRST_UPPERCASE
&& (insertChar == ' ' ))
{
this.nextCharUppercase = true;
} else if ( insertChar == '.' && !(this.isEmail || this.isUrl)) {
this.prepareNextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
//#else
nextCharInputHasChanged = this.nextCharUppercase;
if ( ( (this.inputMode == MODE_FIRST_UPPERCASE || this.nextCharUppercase || this.prepareNextCharUppercase)
&& insertChar == ' ')
){
this.nextCharUppercase = true;
this.prepareNextCharUppercase = false;
} else if ( insertChar == '.' && !(this.isEmail || this.isUrl)) {
this.prepareNextCharUppercase = true;
} else {
this.nextCharUppercase = false;
this.prepareNextCharUppercase = false;
}
nextCharInputHasChanged = (this.nextCharUppercase != nextCharInputHasChanged);
if ( this.inputMode == MODE_FIRST_UPPERCASE ) {
this.inputMode = MODE_LOWERCASE;
}
//#endif
this.caretChar = this.editingCaretChar;
}
setString( myText );
if (!commit) {
if (myText.length() == 1) {
this.caretPosition = 0;
}
} else {
notifyStateChanged();
}
}
//#endif
//#if tmp.directInput && tmp.useInputInfo
/**
* Updates the information text
*/
public void updateInfo() {
if (this.isUneditable || !this.isShowInputInfo) {
// don't show info when this field is not editable
return;
}
// # debug
// System.out.println("update info: " + this.text );
String modeStr;
switch (this.inputMode) {
case MODE_LOWERCASE:
if (this.nextCharUppercase) {
modeStr = "Abc";
} else {
modeStr = "abc";
}
break;
case MODE_FIRST_UPPERCASE:
modeStr = "Abc";
break;
case MODE_UPPERCASE:
modeStr = "ABC";
break;
case MODE_NATIVE:
modeStr = "Nat.";
break;
default:
modeStr = "123";
break;
}
//#if tmp.usePredictiveInput
if(this.predictiveInput)
{
if(this.predictiveAccess.getInfo() != null)
{
modeStr = this.predictiveAccess.getInfo();
}
//#if polish.TextField.includeInputInfo
if(this.infoItem != null && this.infoItem.getStyle().layout == Graphics.RIGHT)
{
modeStr = PredictiveAccess.INDICATOR + modeStr;
}
else
{
modeStr = modeStr + PredictiveAccess.INDICATOR;
}
//#else
modeStr = PredictiveAccess.INDICATOR + modeStr;
//#endif
}
//#endif
//#ifdef polish.css.textfield-show-length
if (this.showLength) {
int length = (this.text == null) ? 0 : this.text.length();
modeStr = length + " | " + modeStr;
}
//#endif
//#if tmp.includeInputInfo
if (this.infoItem == null) {
//#if !polish.TextField.useExternalInfo
//#style info, default
this.infoItem = new StringItem( null, modeStr );
this.infoItem.screen = getScreen();
this.infoItem.parent = this;
repaint();
//#endif
} else {
this.infoItem.setText(modeStr);
}
//System.out.println("setting info to [" + modeStr + "]");
//#else
if (this.screen == null) {
this.screen = getScreen();
}
if (this.screen != null) {
this.screen.setInfo( modeStr );
}
//#endif
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.StringItem#animate(long, de.enough.polish.ui.ClippingRegion)
*/
public void animate(long currentTime, ClippingRegion repaintRegion)
{
//#if tmp.usePredictiveInput
this.predictiveAccess.animateChoices(currentTime, repaintRegion );
//#endif
//#if polish.useNativeGui
if (this.nativeItem != null) {
this.nativeItem.animate(currentTime, repaintRegion);
}
//#endif
super.animate(currentTime, repaintRegion);
}
//#if !polish.android
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#animate()
*/
public boolean animate() {
if (!this.isFocused) {
return false;
}
long currentTime = System.currentTimeMillis();
//#if polish.blackberry
//#if polish.Bugs.ItemStateListenerCalledTooEarly
if (this.lastFieldChangedEvent != 0 && currentTime - this.lastFieldChangedEvent > 500) {
this.lastFieldChangedEvent = 0;
setString( this.editField.getText() );
notifyStateChanged();
getScreen().repaint();
return true;
}
//#endif
//# return false;
//#else
//#if tmp.directInput
synchronized ( this.lock ) {
if (this.caretChar != this.editingCaretChar) {
if ( !this.isKeyDown && (currentTime - this.lastInputTime) >= INPUT_TIMEOUT ) {
commitCurrentCharacter();
}
} else if (this.isKeyDown &&
this.deleteKeyRepeatCount != 0 &&
(this.deleteKeyRepeatCount % 3) == 0 &&
this.text != null &&
this.caretPosition > 0
)
{
if (this.deleteKeyRepeatCount >= 9) {
String myText = this.text;
if (myText != null && myText.length() > 0) {
setString(null);
notifyStateChanged();
}
} else if (this.caretPosition > 0){
String myText = getString();
int nextStop = this.caretPosition - 1;
while (myText.charAt(nextStop) != ' ' && nextStop > 0) {
nextStop--;
}
//System.out.println("next stop=" + nextStop + ", caretPosition=" + this.caretPosition);
setString(myText.substring( 0, nextStop) + myText.substring( this.caretPosition ) );
notifyStateChanged();
}
}
}
//#endif
if (!this.flashCaret || this.isUneditable) {
//System.out.println("TextField.animate(): flashCaret==false");
return false;
}
if ( currentTime - this.lastCaretSwitch > 500 ) {
this.lastCaretSwitch = currentTime;
this.showCaret = ! this.showCaret;
return true;
} else {
return false;
}
//#endif
}
//#endif
//#if !(polish.blackberry || polish.android)
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyPressed(int, int)
*/
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyPressed " + keyCode );
//#if tmp.useNativeTextBox
//#if polish.TextField.passCharacterToNativeEditor
if (keyCode >0)
{
String alphabet = null;
if (keyCode == Canvas.KEY_POUND) {
alphabet = charactersKeyPound;
} else if (keyCode == Canvas.KEY_STAR) {
alphabet = charactersKeyStar;
} else {
int index = keyCode - Canvas.KEY_NUM0;
if (index >= 0 && index <= CHARACTERS.length) {
alphabet = CHARACTERS[ index ];
}
}
if (alphabet != null && (alphabet.length() >= 0)) {
if(this.keyDelayTimerTask==null || this.latestKey != keyCode){
this.keyPressCounter=0;
this.passedChar = alphabet.charAt(this.keyPressCounter++);
this.latestKey = keyCode;
}
else {
this.passedChar = alphabet.charAt(this.keyPressCounter++);
this.latestKey = keyCode;
if (this.keyPressCounter == alphabet.length()){
this.keyPressCounter=0;
}
}
if ((this.constraints & NUMERIC) == NUMERIC){
this.passedChar = (char)keyCode;
}
}
}
//#endif
//#endif
this.isKeyPressedHandled = false;
//#ifndef tmp.directInput
if (keyCode < 32 || keyCode > 126) {
//#if polish.bugs.inversedGameActions
if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM8)
|| (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM2)
|| (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM6)
|| (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM4)
|| (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5)
|| (this.screen.isSoftKey(keyCode, gameAction))
)
{
return false;
}
//#else
if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2)
|| (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8)
|| (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4)
|| (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6)
|| (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5)
|| (this.screen.isSoftKey(keyCode, gameAction))
)
{
return false;
}
//#endif
}
//#elif !polish.blackberry
if (this.inputMode == MODE_NATIVE) {
if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2)
|| (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8)
|| (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4)
|| (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6)
|| (!(gameAction == Canvas.FIRE && this.cskOpensNativeEditor) && this.screen.isSoftKey(keyCode, gameAction))
)
{
return false;
}
}
this.isKeyDown = true;
//#endif
//#if tmp.allowDirectInput
if (this.enableDirectInput) {
//#endif
//#ifdef tmp.directInput
//#if !polish.blackberry
if ((this.inputMode == MODE_NATIVE)
&& (keyCode != KEY_CHANGE_MODE)
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
//#= && keyCode != ${polish.key.ChangeNumericalAlphaInputModeKey}
//#endif
) {
//#if tmp.useNativeTextBox
//#if polish.TextField.passCharacterToNativeEditor
this.lastTimeKeyPressed = System.currentTimeMillis();
if (this.keyDelayTimerTask==null && !((this.constraints & UNEDITABLE) == UNEDITABLE)){
final int localGameAction = gameAction;
final int localKeyCode = keyCode;
this.keyDelayTimerTask = new TimerTask(){
public void run() {
if(System.currentTimeMillis()-TextField.this.lastTimeKeyPressed < (TextField.this.delayBetweenKeys+20) ) return;
showTextBox();
if (TextField.this.midpTextBox!=null && (localGameAction != Canvas.FIRE || localKeyCode == Canvas.KEY_NUM5)){
String oldText =TextField.this.midpTextBox.getString();
if (oldText.length()==0 && !((TextField.this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)){
TextField.this.passedChar = Character.toUpperCase(TextField.this.passedChar);
}
TextField.this.midpTextBox.insert(String.valueOf(TextField.this.passedChar), TextField.this.getCaretPosition());
}
TextField.this.keyDelayTimerTask.cancel();
TextField.this.keyDelayTimerTask = null;
}
};
this.keyDelayTimer.schedule(this.keyDelayTimerTask, 0,this.delayBetweenKeys);
}
//#else
showTextBox();
//#endif
return true;
//#endif
}
//#endif
synchronized ( this.lock ) {
// if (this.text == null) { // in that case no mode change can be done with an empty textfield
// return false;
// }
// else
if (this.isUneditable) {
return false;
}
boolean handled = false;
//#if tmp.usePredictiveInput && !polish.key.ChangeNumericalAlphaInputModeKey:defined
if ( (keyCode == KEY_CHANGE_MODE) && (!this.isNumeric) && (!this.isUneditable))
{
if(this.lastTimePressed == -1)
{
this.nextMode = !this.predictiveInput;
this.lastTimePressed = System.currentTimeMillis();
}
else
{
if((System.currentTimeMillis() - this.lastTimePressed) > SWITCH_DELAY && TrieProvider.isPredictiveInstalled())
{
if(this.nextMode != this.predictiveInput)
{
this.predictiveInput = !this.predictiveInput;
this.nextMode = this.predictiveInput;
updateInfo();
this.predictiveInput = !this.predictiveInput;
}
}
}
handled = true;
}
//#endif
// Backspace
//#ifdef polish.key.ClearKey:defined
//#= if (keyCode == ${polish.key.ClearKey}
//#else
if ( keyCode == -8 || keyCode == 8
//#endif
//#if polish.key.backspace:defined
//#= || keyCode == ${polish.key.backspace}
//#endif
&& !handled)
{
handled = handleKeyClear(keyCode, gameAction);
}
//#if polish.key.Menu:defined
int menuKey = 0;
//#= menuKey = ${polish.key.Menu};
if (keyCode == menuKey) {
return false;
}
//#endif
//#ifdef polish.key.ChangeNumericalAlphaInputModeKey:defined
int changeNumericalAlphaInputModeKey = 0;
//#= changeNumericalAlphaInputModeKey = ${polish.key.ChangeNumericalAlphaInputModeKey};
//#endif
if (!handled
&& ((keyCode != KEY_CHANGE_MODE)
//#if polish.key.maybeSupportsAsciiKeyMap
|| useAsciiKeyMap
//#endif
)
//#ifdef polish.key.ChangeNumericalAlphaInputModeKey:defined
&& !(keyCode == KEY_CHANGE_MODE && !this.isNumeric
&& !(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS))
&& !(keyCode == changeNumericalAlphaInputModeKey && !this.isNumeric)
//#endif
){
handled = handleKeyInsert(keyCode, gameAction);
}
// Navigate the caret
if ( !handled &&
(gameAction == Canvas.UP ||
gameAction == Canvas.DOWN ||
gameAction == Canvas.LEFT ||
gameAction == Canvas.RIGHT ||
gameAction == Canvas.FIRE
)
) {
handled = handleKeyNavigation(keyCode, gameAction);
if (!handled && gameAction == Canvas.FIRE && this.defaultCommand != null) {
notifyItemPressedStart();
handled = true;
}
}
if(true)
{
this.isKeyPressedHandled = handled;
return handled;
}
}
//#endif
//#if tmp.allowDirectInput
}
//#endif
//#ifndef polish.hasPointerEvents
String currentText = this.isPassword ? this.passwordText : this.text;
if (this.enableDirectInput) {
int currentLength = (this.text == null ? 0 : this.text.length());
if ( keyCode >= Canvas.KEY_NUM0 &&
keyCode <= Canvas.KEY_NUM9)
{
if (currentLength >= this.maxSize) {
// in numeric mode ignore 2,4,6 and 8 keys, so that they are not processed
// by a parent component:
this.isKeyPressedHandled = true;
return true;
}
String newText = (currentText == null ? "" : currentText ) + (keyCode - 48);
setString( newText );
notifyStateChanged();
this.isKeyPressedHandled = true;
return true;
}
//#ifdef polish.key.ClearKey:defined
//#= if ((keyCode == ${polish.key.ClearKey}) || (gameAction == Canvas.LEFT)) {
//#else
if (keyCode == -8 || gameAction == Canvas.LEFT) {
//#endif
if (currentLength > 0) {
setString( currentText.substring(0, currentLength - 1) );
notifyStateChanged();
}
this.isKeyPressedHandled = true;
return true;
}
return false;
}
//#endif
if ( keyCode >= 32
//#ifdef polish.key.ClearKey:defined
//#= || (keyCode == ${polish.key.ClearKey})
//#else
|| (keyCode == -8 || keyCode == 8)
//#endif
//#if ${ isOS( Windows ) }
|| (gameAction != Canvas.DOWN && gameAction != Canvas.UP && gameAction != Canvas.LEFT && gameAction != Canvas.RIGHT)
//#endif
|| (gameAction == Canvas.FIRE ) )
{
//#if tmp.useNativeTextBox
showTextBox();
//#endif
return true;
} else {
return false;
}
}
//#endif
/**
* Tries to interpret a key pressed event for inserting a character into this TextField.
* @param keyCode the key code of the event
* @param gameAction the associated game action
* @return true when the key could be interpreted as a character
*/
protected boolean handleKeyInsert(int keyCode, int gameAction)
{
//#if tmp.directInput
//#if tmp.usePredictiveInput
if (this.predictiveInput) {
return this.predictiveAccess.keyInsert(keyCode, gameAction);
}
//#endif
int currentLength = (this.text == null ? 0 : this.text.length());
char insertChar = (char) (' ' + (keyCode - 32));
//#if tmp.supportsAsciiKeyMap
try {
String name = this.screen.getKeyName( keyCode );
if (name != null && name.length() == 1) {
insertChar = name.charAt(0);
}
} catch (IllegalArgumentException e) {
// ignore
}
//#if polish.key.maybeSupportsAsciiKeyMap
if (!useAsciiKeyMap) {
if (keyCode >= 32
&& (keyCode < Canvas.KEY_NUM0 || keyCode > Canvas.KEY_NUM9)
&& (keyCode != Canvas.KEY_POUND && keyCode != Canvas.KEY_STAR)
&& (keyCode <= 126) // only allow ascii characters for the initial input...
&& ( !getScreen().isSoftKey(keyCode, gameAction) )
) {
useAsciiKeyMap = true;
//#if tmp.usePredictiveInput
this.predictiveInput = false;
//#endif
}
}
//#endif
if (keyCode >= 32
//#if polish.key.maybeSupportsAsciiKeyMap
&& useAsciiKeyMap
//#endif
&& this.inputMode != MODE_NUMBERS
&& !this.isNumeric
&& this.screen.isKeyboardAccessible()
&& !( (insertChar < 'a' || insertChar > 'z')
&&
( (gameAction == Canvas.UP && insertChar != '2' && keyCode == this.screen.getKeyCode(Canvas.UP) )
|| (gameAction == Canvas.DOWN && insertChar != '8' && keyCode == this.screen.getKeyCode(Canvas.DOWN) )
|| (gameAction == Canvas.LEFT && insertChar != '4' && keyCode == this.screen.getKeyCode(Canvas.LEFT) )
|| (gameAction == Canvas.RIGHT && insertChar != '6' && keyCode == this.screen.getKeyCode(Canvas.RIGHT))
)
//|| (gameAction == Canvas.FIRE && keyCode == this.screen.getKeyCode(Canvas.FIRE) )
)
)
{
if (this.nextCharUppercase || this.inputMode == MODE_UPPERCASE) {
insertChar = Character.toUpperCase(insertChar);
}
insertCharacter( insertChar, true, true );
return true;
}
//#if polish.key.enter:defined
//#= if ( keyCode == ${polish.key.enter} ) {
//this.caretChar = '\n';
insertCharacter('\n', true, true );
//# return true;
//# }
//#endif
//#endif
if (this.inputMode == MODE_NUMBERS && !this.isUneditable) {
if ( keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9 )
{
if (currentLength >= this.maxSize) {
// ignore this key event - also don't forward it to the parent component:
return true;
}
insertChar = Integer.toString( keyCode - Canvas.KEY_NUM0 ).charAt( 0 );
insertCharacter(insertChar, true, true );
return true;
}
//#if polish.TextField.numerickeys.1:defined
String numericKeyStr = "";
int foundNumber = -1;
//#= numericKeyStr = "${polish.TextField.numerickeys.1}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 1;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.2}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 2;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.3}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 3;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.4}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 4;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.5}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 5;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.6}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 6;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.7}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 7;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.8}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 8;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.9}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 9;
}
//#= numericKeyStr = "${polish.TextField.numerickeys.0}";
if (numericKeyStr.indexOf(insertChar) != -1) {
foundNumber = 0;
}
if (foundNumber != -1) {
if (currentLength >= this.maxSize) {
// ignore this key event - also don't forward it to the parent component:
return true;
}
insertChar = Integer.toString( foundNumber ).charAt( 0 );
insertCharacter(insertChar, true, true );
return true;
}
//#endif
if ( this.isDecimal ) {
//System.out.println("handling key for DECIMAL TextField");
if (this.text == null ||
(currentLength < this.maxSize
&& ( keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR )
&& this.text.indexOf( Locale.DECIMAL_SEPARATOR) == -1)
)
{
insertChar = Locale.DECIMAL_SEPARATOR;
insertCharacter(insertChar, true, true );
return true;
}
}
}
if ( (!this.isNumeric) //this.inputMode != MODE_NUMBERS
&& !this.isUneditable
&& ((currentLength < this.maxSize) || ( currentLength == this.maxSize && this.caretChar != this.editingCaretChar && keyCode == this.lastKey))
&& ( (keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9)
|| (keyCode == Canvas.KEY_POUND )
|| (keyCode == Canvas.KEY_STAR )
//#if tmp.supportsSymbolEntry && polish.key.AddSymbolKey:defined
//#= || (keyCode == ${polish.key.AddSymbolKey} )
//#endif
//#if tmp.supportsSymbolEntry && polish.key.AddSymbolKey2:defined
//#= || (keyCode == ${polish.key.AddSymbolKey2} )
//#endif
))
{
//#if tmp.supportsSymbolEntry && (polish.key.AddSymbolKey:defined || polish.key.AddSymbolKey2:defined)
boolean showSymbolList = false;
//#if polish.key.AddSymbolKey:defined
//#= showSymbolList = (keyCode == ${polish.key.AddSymbolKey});
//#endif
//#if polish.key.AddSymbolKey2:defined
//#= showSymbolList = showSymbolList || (keyCode == ${polish.key.AddSymbolKey2});
//#endif
if ( showSymbolList ) {
showSymbolsList();
return true;
}
//#endif
String alphabet;
if (keyCode == Canvas.KEY_POUND) {
alphabet = charactersKeyPound;
} else if (keyCode == Canvas.KEY_STAR) {
alphabet = charactersKeyStar;
} else {
alphabet = this.characters[ keyCode - Canvas.KEY_NUM0 ];
}
if (alphabet == null || (alphabet.length() == 0)) {
return false;
}
this.lastInputTime = System.currentTimeMillis();
char newCharacter;
int alphabetLength = alphabet.length();
boolean appendNewCharacter = false;
if (keyCode == this.lastKey && (this.caretChar != this.editingCaretChar)) {
this.characterIndex++;
if (this.characterIndex >= alphabetLength) {
this.characterIndex = 0;
}
} else {
// insert the last character into the text:
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
if (currentLength + 1 > this.maxSize) {
return true;
}
}
appendNewCharacter = true;
this.characterIndex = 0;
this.lastKey = keyCode;
}
newCharacter = alphabet.charAt( this.characterIndex );
//System.out.println("TextField.handleKeyPressed(): newCharacter=" + newCharacter + ", currentLength=" + currentLength + ", maxSize=" + this.maxSize + ", text.length()=" + this.text.length() );
if ( this.inputMode == MODE_UPPERCASE
|| this.nextCharUppercase )
{
//#if polish.TextField.useDynamicCharset
if(usesDynamicCharset && keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9)
{
alphabet = CHARACTERS_UPPER[ keyCode - Canvas.KEY_NUM0 ];
newCharacter = alphabet.charAt(this.characterIndex);
}
else
//#endif
{
newCharacter = Character.toUpperCase(newCharacter);
}
}
this.caretWidth = charWidth( newCharacter );
this.caretChar = newCharacter;
if (alphabetLength == 1) {
insertCharacter( newCharacter, true, true );
} else {
insertCharacter( newCharacter, appendNewCharacter, false );
}
return true;
}
//#endif
return false;
}
protected boolean handleKeyClear(int keyCode, int gameAction)
{
//#if tmp.directInput
if (this.isUneditable) {
return false;
}
//#if tmp.usePredictiveInput
if (this.predictiveInput) {
return this.predictiveAccess.keyClear(keyCode, gameAction);
}
//#endif
if ( this.text != null && this.text.length() > 0) {
return deleteCurrentChar();
}
//#endif
return false;
}
protected boolean handleKeyMode(int keyCode, int gameAction)
{
//#if tmp.directInput
//#if tmp.usePredictiveInput
if (this.predictiveInput) {
return this.predictiveAccess.keyMode(keyCode, gameAction);
}
//#endif
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
int changeNumericalAlphaInputModeKey = 0;
//#= changeNumericalAlphaInputModeKey = ${polish.key.ChangeNumericalAlphaInputModeKey};
if (keyCode ==changeNumericalAlphaInputModeKey && !this.isNumeric && !this.isUneditable) {
if (this.inputMode == MODE_NUMBERS) {
this.inputMode = MODE_LOWERCASE;
} else {
this.inputMode = MODE_NUMBERS;
}
//#if tmp.useInputInfo
updateInfo();
//#endif
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
}
if (this.inputMode == MODE_FIRST_UPPERCASE) {
this.nextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
return true;
}
//#endif
//#if polish.key.supportsAsciiKeyMap.condition:defined && polish.key.shift:defined
// there is a shift key responsible for switching the input mode which
// is only used when the device is opened up - example includes the Nokia/E70.
if (!this.screen.isKeyboardAccessible()) {
//#endif
if ( keyCode == KEY_CHANGE_MODE && !this.isNumeric && !this.isUneditable
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
&& (!(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS))
//#endif
) {
if (this.nextCharUppercase && this.inputMode == MODE_LOWERCASE) {
this.nextCharUppercase = false;
} else {
this.inputMode++;
}
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
if (this.inputMode > MODE_UPPERCASE) {
//#if polish.TextField.allowNativeModeSwitch
if (this.inputMode > MODE_NATIVE) {
this.inputMode = MODE_LOWERCASE;
} else {
this.inputMode = MODE_NATIVE;
}
//#else
this.inputMode = MODE_LOWERCASE;
//#endif
}
//#elif polish.TextField.allowNativeModeSwitch
if (this.inputMode > MODE_NATIVE) {
this.inputMode = MODE_LOWERCASE;
}
//#else
if (this.inputMode > MODE_NUMBERS) {
this.inputMode = MODE_LOWERCASE;
}
//#endif
//#if tmp.useInputInfo
updateInfo();
//#endif
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
}
if (this.inputMode == MODE_FIRST_UPPERCASE) {
this.nextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
return true;
}
//#if polish.key.supportsAsciiKeyMap.condition:defined && polish.key.shift:defined
}
//#endif
//#if polish.key.shift:defined
if ( keyCode == KEY_SHIFT && !this.isNumeric && !this.isUneditable) {
if (this.nextCharUppercase && this.inputMode == MODE_LOWERCASE) {
this.nextCharUppercase = false;
} else {
int mode = this.inputMode + 1;
if (mode >= MODE_NUMBERS) {
mode = MODE_LOWERCASE;
}
if (mode == MODE_FIRST_UPPERCASE) {
this.nextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
this.inputMode = mode;
}
//#if tmp.useInputInfo
updateInfo();
//#endif
return true;
}
//#endif
//#endif
return false;
}
protected boolean handleKeyNavigation(int keyCode, int gameAction)
{
//#if tmp.directInput
if (this.realTextLines == null) {
return false;
}
//#if tmp.usePredictiveInput
if(this.predictiveInput && this.predictiveAccess.keyNavigation(keyCode, gameAction)) {
return true;
}
//#endif
char character = this.caretChar;
boolean characterInserted = character != this.editingCaretChar;
if (characterInserted) {
commitCurrentCharacter();
}
if (gameAction == Canvas.FIRE
&& this.defaultCommand != null
&& this.itemCommandListener != null)
{
this.itemCommandListener.commandAction(this.defaultCommand, this);
return true;
}
else if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
if (this.caretRow == 0) {
return false;
}
// restore the text-line:
this.caretRow--;
this.caretY -= this.rowHeight;
this.internalY = this.caretY;
String fullLine = this.realTextLines[ this.caretRow ];
int previousCaretRowFirstLength = this.caretColumn;
setCaretRow(fullLine, this.caretColumn );
this.caretPosition -= previousCaretRowFirstLength + (this.originalRowText.length() - this.caretColumn);
this.internalX = 0;
this.internalY = this.caretRow * this.rowHeight;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
} else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) {
if (this.textLines == null || this.caretRow >= this.textLines.size() - 1) {
return false;
}
String lastLine = this.originalRowText;
int lastLineLength = lastLine.length();
this.caretRow++;
this.caretY += this.rowHeight;
this.internalY = this.caretY;
int lastCaretRowLastPartLength = lastLineLength - this.caretColumn;
String nextLine = this.realTextLines[ this.caretRow ];
setCaretRow( nextLine, this.caretColumn );
this.caretPosition += (lastCaretRowLastPartLength + this.caretColumn );
this.internalY = this.caretRow * this.rowHeight;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
//#if polish.i18n.rightToLeft
} else if (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) {
//#else
} else if (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) {
//#endif
int column = this.caretColumn;
if (column > 0) {
this.caretPosition--;
column--;
setCaretRow( this.originalRowText, column );
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
} else if ( this.caretRow > 0) {
// this is just a visual line-break:
//this.caretPosition--;
this.caretRow--;
String prevLine = this.realTextLines[ this.caretRow ];
int carColumn = prevLine.length();
boolean isOnNewlineChar = prevLine.charAt( carColumn - 1 ) == '\n';
if (isOnNewlineChar) {
this.caretPosition--;
carColumn--;
}
setCaretRow(prevLine, carColumn );
//System.out.println(this + ".handleKeyPressed()/font4: caretX=" + this.caretX);
this.caretY -= this.rowHeight;
this.internalY = this.caretY;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
}
//#if polish.i18n.rightToLeft
} else if (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) {
//#else
} else if ( gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) {
//#endif
//#ifdef polish.debug.debug
if (this.isPassword) {
//#debug
System.out.println("originalRowText=" + this.originalRowText );
}
//#endif
if (characterInserted) {
//System.out.println("right but character inserted");
return true;
}
boolean isOnNewlineChar = this.caretColumn < this.originalRowText.length()
&& this.originalRowText.charAt( this.caretColumn ) == '\n';
if (this.caretColumn < this.originalRowText.length() && !isOnNewlineChar ) {
//System.out.println("right not in last column");
this.caretColumn++;
this.caretPosition++;
setCaretRow( this.originalRowText, this.caretColumn );
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
} else if (this.caretRow < this.realTextLines.length - 1) {
//System.out.println("right in not the last row");
this.caretRow++;
if (isOnNewlineChar) {
this.caretPosition++;
}
this.originalRowText = this.realTextLines[ this.caretRow ];
if (characterInserted) {
if (this.isPassword) {
this.caretX = stringWidth("*");
} else {
this.caretX = stringWidth( String.valueOf( character ) );
}
//System.out.println(this + ".handleKeyPressed()/font6: caretX=" + this.caretX);
this.caretColumn = 1;
} else {
setCaretRow( this.originalRowText, 0 );
}
this.caretY += this.rowHeight;
this.internalY = this.caretY;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
} else if (characterInserted) {
//System.out.println("right after character insertion");
// a character has been inserted at the last column of the last row:
if (this.isPassword) {
this.caretX += stringWidth("*");
} else {
this.caretX += this.caretWidth;
}
this.caretColumn++;
this.caretPosition++;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
return true;
}
}
//#endif
return false;
}
//#if !(polish.blackberry || polish.android) && tmp.directInput
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyRepeated(int, int)
*/
protected boolean handleKeyRepeated(int keyCode, int gameAction) {
//#debug
System.out.println("TextField.handleKeyRepeated( " + keyCode + ")");
if (keyCode >= Canvas.KEY_NUM0
&& keyCode <= Canvas.KEY_NUM9 )
{
// ignore repeat events when the current input mode is numbers:
if ( this.isNumeric || this.inputMode == MODE_NUMBERS ) {
if (keyCode == Canvas.KEY_NUM0 && this.inputMode == PHONENUMBER) {
if (this.caretPosition == 1 && this.text.charAt(0) == '0') {
String str = getString();
if (str.length() > 0 && str.charAt(0) == '0') {
str = str.substring(1);
}
setString( "+" + str );
return true;
}
}
return false;
}
int currentLength = (this.text == null ? 0 : this.text.length());
if ( !this.isUneditable && currentLength <= this.maxSize )
{
// enter number character:
this.lastInputTime = System.currentTimeMillis();
char newCharacter = Integer.toString(keyCode - 48).charAt(0);
this.caretWidth = charWidth( newCharacter );
if (newCharacter != this.caretChar) {
//#if tmp.usePredictiveInput
if (this.predictiveInput)
{
TextBuilder builder = this.predictiveAccess.getBuilder();
try
{
builder.keyClear();
this.predictiveAccess.openChoices(false);
builder.addString("" + newCharacter);
}catch(Exception e)
{
//#debug error
System.out.println("unable to clear " + e);
}
setText(builder.getText().toString());
setCaretPosition(builder.getCaretPosition());
}
else
//#endif
{
this.caretChar = newCharacter;
insertCharacter( newCharacter, false, false );
}
}
return true;
}
}
//#ifdef polish.key.ClearKey:defined
//#= if ( (keyCode == ${polish.key.ClearKey}
//#else
if ( (keyCode == -8
//#endif
//#if polish.key.backspace:defined
//#= || keyCode == ${polish.key.backspace}
//#endif
) && this.caretPosition > 0
&& this.text != null
)
{
this.deleteKeyRepeatCount++;
}
return false;
//return super.handleKeyRepeated(keyCode, gameAction);
}
//#endif
//#if !(polish.blackberry || polish.android) && tmp.directInput
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyReleased(int, int)
*/
protected boolean handleKeyReleased( int keyCode, int gameAction ) {
//#debug
System.out.println("handleKeyReleased " + keyCode );
if (!this.enableDirectInput) {
return super.handleKeyReleased(keyCode, gameAction);
}
//#if tmp.useNativeTextBox && !(polish.Vendor == Samsung)
if (this.skipKeyReleasedEvent) {
this.skipKeyReleasedEvent = false;
return true;
}
//#endif
this.isKeyDown = false;
this.deleteKeyRepeatCount = 0;
//#if tmp.usePredictiveInput
if (this.predictiveAccess.handleKeyReleased( keyCode, gameAction )) {
return true;
}
//#endif
int clearKey =
//#if polish.key.ClearKey:defined
//#= ${polish.key.ClearKey};
//#else
-8;
//#endif
boolean clearKeyPressed = (keyCode == clearKey);
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
int changeNumericalAlphaInputModeKey = 0;
//#= changeNumericalAlphaInputModeKey = polish.key.ChangeNumericalAlphaInputModeKey;
//#endif
if ( (keyCode == KEY_CHANGE_MODE && !this.isNumeric && !this.isUneditable)
//#if polish.key.maybeSupportsAsciiKeyMap
&& (!useAsciiKeyMap)
//#endif
//#if polish.key.ChangeNumericalAlphaInputModeKey:defined
|| (keyCode == changeNumericalAlphaInputModeKey && !this.isNumeric && !this.isUneditable)
&& (!(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS) || keyCode == changeNumericalAlphaInputModeKey)
//#endif
){
//#if tmp.usePredictiveInput && !polish.key.ChangeNumericalAlphaInputModeKey:defined
if((System.currentTimeMillis() - this.lastTimePressed) > SWITCH_DELAY && TrieProvider.isPredictiveInstalled())
{
this.lastTimePressed = -1;
if(this.predictiveInput)
{
getPredictiveAccess().disablePredictiveInput();
}
else
{
getPredictiveAccess().enablePredictiveInput();
}
updateInfo();
return true;
}
//#endif
//#if tmp.usePredictiveInput
this.lastTimePressed = -1;
//#endif
return handleKeyMode(keyCode, gameAction) || clearKeyPressed;
}
return this.isKeyPressedHandled || clearKeyPressed || super.handleKeyReleased( keyCode, gameAction );
}
//#endif
//#if polish.hasPointerEvents && (!tmp.forceDirectInput || polish.javaplatform >= Android/1.5)
/**
* Handles the event when a pointer has been pressed at the specified position.
* The default method translates the pointer-event into an artificial
* pressing of the FIRE game-action, which is subsequently handled
* bu the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param x the x position of the pointer pressing
* @param y the y position of the pointer pressing
* @return true when the pressing of the pointer was actually handled by this item.
*/
protected boolean handlePointerPressed( int x, int y ) {
if (isInItemArea(x, y)) {
//#if !tmp.forceDirectInput
return notifyItemPressedStart();
//#endif
}
return super.handlePointerPressed(x, y);
}
//#endif
//#if polish.hasPointerEvents
/**
* Handles the event when a pointer has been pressed at the specified position.
* The default method translates the pointer-event into an artificial
* pressing of the FIRE game-action, which is subsequently handled
* bu the handleKeyPressed(-1, Canvas.FIRE) method.
* This method needs should be overwritten only when the "polish.hasPointerEvents"
* preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents".
*
* @param x the x position of the pointer pressing
* @param y the y position of the pointer pressing
* @return true when the pressing of the pointer was actually handled by this item.
*/
protected boolean handlePointerReleased( int x, int y ) {
repaint();
if (isInItemArea(x, y)) {
//#if tmp.useNativeTextBox
int fieldType = this.constraints & 0xffff;
if (fieldType != FIXED_POINT_DECIMAL) {
notifyItemPressedEnd();
//#if !polish.series40sdk20 && !polish.series40sdk11
showTextBox();
//#endif
return true;
}
//#elif polish.TextField.useVirtualKeyboard
Form keyboardView = KeyboardView.getInstance(getLabel(), this, getScreen());
Display.getInstance().setCurrent(keyboardView);
return true;
//#endif
}
return super.handlePointerReleased(x, y);
}
//#endif
//#if polish.hasPointerEvents && (polish.showSoftKeyboardOnShowNotify != false)
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleOnFocusSoftKeyboardDisplayBehavior()
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
//#if !polish.android
DeviceControl.showSoftKeyboard();
//#endif
}
//#endif
//#ifdef tmp.directInput
/**
* Removes the current character.
*
* @return true when a character could be deleted.
*/
private synchronized boolean deleteCurrentChar() {
//#debug
System.out.println("deleteCurrentChar: caretColumn=" + this.caretColumn + ", caretPosition=" + this.caretPosition + ", caretChar=" + this.caretChar );
String myText;
if (this.isPassword) {
myText = this.passwordText;
} else {
myText = this.text;
}
int position = this.caretPosition;
if (this.caretChar != this.editingCaretChar) {
myText = myText.substring( 0, position )
+ myText.substring( position + 1);
this.caretChar = this.editingCaretChar;
this.caretPosition = position;
setString( myText );
return true;
}
if (position > 0) {
position--;
myText = myText.substring( 0, position )
+ myText.substring( position + 1);
this.caretPosition = position;
setString( myText );
//#if polish.css.textfield-show-length && tmp.useInputInfo
if (this.showLength) {
updateInfo();
}
//#endif
notifyStateChanged();
return true;
} else {
return false;
}
}
//#endif
//#if tmp.useNativeTextBox
/**
* Shows the TextBox for entering texts.
*/
protected void showTextBox() {
//TODO: drubin better handling of textfield events.
//(Currently this is the easiest method to overload if you want to tie into
//"is editing mode" events.) that is triggered by both touch and commands
if (this.midpTextBox == null) {
createTextBox();
}
if (StyleSheet.currentScreen != null) {
this.screen = StyleSheet.currentScreen;
} else if (this.screen == null) {
this.screen = getScreen();
}
StyleSheet.display.setCurrent( this.midpTextBox );
}
//#endif
//#if tmp.implementsCommandListener
/* (non-Javadoc)
* @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)
*/
public void commandAction(Command cmd, Displayable box) {
//#if tmp.usePredictiveInput
if (this.predictiveAccess.commandAction(cmd, box)) {
return;
}
//#endif
//#if tmp.supportsSymbolEntry
if (box instanceof List) {
if (cmd != StyleSheet.CANCEL_CMD) {
int index = symbolsList.getSelectedIndex();
insert(definedSymbols[index],this.caretPosition);
//insertCharacter( definedSymbols.charAt(index), true, true );
StyleSheet.currentScreen = this.screen;
//#if tmp.updateDeleteCommand
updateDeleteCommand( this.text );
//#endif
} else {
StyleSheet.currentScreen = this.screen;
}
StyleSheet.display.setCurrent( this.screen );
notifyStateChanged();
return;
}
//#endif
//#if tmp.useNativeTextBox
if (cmd == StyleSheet.CANCEL_CMD) {
this.midpTextBox.setString( this.text );
this.skipKeyReleasedEvent = true;
} else if (!this.isUneditable) {
setString( this.midpTextBox.getString() );
setCaretPosition( size() );
notifyStateChanged();
this.skipKeyReleasedEvent = true;
}
StyleSheet.display.setCurrent( this.screen );
//#endif
}
//#endif
//#if (!tmp.suppressCommands && !tmp.supportsSymbolEntry) || tmp.supportsSymbolEntry
public void setItemCommandListener(ItemCommandListener l) {
this.additionalItemCommandListener = l;
}
public ItemCommandListener getItemCommandListener()
{
return this.additionalItemCommandListener;
}
//#endif
//#if tmp.supportsSymbolEntry
public static void initSymbolsList() {
if (symbolsList == null) {
//#style textFieldSymbolList?, textFieldSymbolTable?
symbolsList = new List( ENTER_SYMBOL_CMD.getLabel(), Choice.IMPLICIT );
for (int i = 0; i < definedSymbols.length; i++) {
//#style textFieldSymbolItem?
symbolsList.append( definedSymbols[i], null );
}
//TODO check localization when using dynamic localization
symbolsList.addCommand( StyleSheet.CANCEL_CMD );
}
}
private void showSymbolsList() {
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
}
initSymbolsList();
symbolsList.setCommandListener( this );
StyleSheet.display.setCurrent( symbolsList );
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.ItemCommandListener#commandAction(javax.microedition.lcdui.Command, de.enough.polish.ui.Item)
*/
public void commandAction(Command cmd, Item item) {
//#debug
System.out.println("TextField.commandAction( " + cmd.getLabel() + ", " + this + " )");
//#if tmp.usePredictiveInput
if (this.predictiveAccess.commandAction(cmd, item)) {
return;
}
//#endif
if (cmd.commandAction(this, null)) {
return;
}
//#if tmp.implementsItemCommandListener
//#if tmp.supportsSymbolEntry
if (cmd == ENTER_SYMBOL_CMD ) {
//#if polish.TextField.ignoreSymbolCommand
Screen scr = getScreen();
if (scr != null & scr.getCommandListener() != null) {
scr.getCommandListener().commandAction(cmd, scr);
}
//#else
showSymbolsList();
//#endif
return;
}
//#endif
//#ifndef tmp.suppressCommands
if ( cmd == DELETE_CMD ) {
if (this.text != null && this.text.length() > 0) {
//#ifdef tmp.directInput
//#ifdef tmp.allowDirectInput
if (this.enableDirectInput) {
//#endif
//#ifdef polish.key.ClearKey:defined
//#= handleKeyClear(${polish.key.ClearKey},0);
//#else
handleKeyClear(-8,0);
//#endif
//#ifdef tmp.allowDirectInput
} else {
String myText = getString();
setString( myText.substring(0, myText.length() - 1));
notifyStateChanged();
}
//#endif
//#else
String myText = getString();
setString( myText.substring(0, myText.length() - 1));
notifyStateChanged();
//#endif
return;
}
} else if ( cmd == CLEAR_CMD ) {
setString( null );
notifyStateChanged();
} else if ( this.additionalItemCommandListener != null ) {
this.additionalItemCommandListener.commandAction(cmd, item);
} else {
// forward command to the screen's orginal command listener:
Screen scr = getScreen();
if (scr != null) {
CommandListener listener = scr.getCommandListener();
if (listener != null) {
listener.commandAction(cmd, scr);
}
}
}
//#endif
//#if polish.key.maybeSupportsAsciiKeyMap
if (cmd == SWITCH_KEYBOARD_CMD) {
useAsciiKeyMap = !useAsciiKeyMap;
}
//#endif
//#endif
}
//#if (tmp.directInput && (polish.TextField.showInputInfo != false)) || polish.series40sdk20 || polish.series40sdk11 || polish.blackberry || polish.TextField.activateUneditableWithFire || polish.javaplatform >= Android/1.5
protected void defocus(Style originalStyle) {
super.defocus(originalStyle);
//#if polish.series40sdk20 || polish.series40sdk11
if (this.series40sdk20Field != null) {
this.series40sdk20Field.setFocus(false);
this.series40sdk20Field.setParent(null);
String newText = this.series40sdk20Field.getContent();
String oldText = this.isPassword ? this.passwordText : this.text;
setString( newText );
setInitialized(false);
repaint();
notifyStateChanged();
}
//#endif
//#if polish.blackberry
//#if polish.Bugs.ItemStateListenerCalledTooEarly
String newText = this.editField.getText();
String oldText = this.isPassword ? this.passwordText : this.text;
if (( this.lastFieldChangedEvent != 0) || (!newText.equals(oldText ) && !(oldText == null && newText.length()==0) )) {
this.lastFieldChangedEvent = 0;
setString( newText );
notifyStateChanged();
}
//#endif
Object bbLock = UiApplication.getEventLock();
synchronized (bbLock) {
this.editField.focusRemove();
}
//#if polish.hasPointerEvents && polish.TextField.hideSoftKeyboardOnDefocus
DeviceControl.hideSoftKeyboard();
//#endif
//#elif polish.TextField.showInputInfo != false && !tmp.includeInputInfo
if (this.screen != null) {
this.screen.setInfo((Item)null);
}
//#endif
//#if tmp.directInput
if (this.editingCaretChar != this.caretChar) {
commitCurrentCharacter();
notifyStateChanged();
}
//#endif
}
//#endif
//#if tmp.directInput || !polish.TextField.suppressDeleteCommand || (polish.android && polish.android.autoFocus)
protected Style focus(Style focStyle, int direction) {
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null ) {
this.series40sdk20Field.setFocus(true);
}
//#endif
//#if polish.android
if (this.isShown) {
DeviceControl.showSoftKeyboard();
}
//#if !polish.TextField.keepCaretPosition
setCaretPosition( getString().length() );
//#endif
//#elif tmp.directInput || polish.blackberry || polish.series40sdk20 || polish.series40sdk11
//#ifdef tmp.allowDirectInput
if (this.enableDirectInput) {
//#endif
//#if tmp.useInputInfo
updateInfo();
//#endif
//#if polish.TextField.jumpToStartOnFocus
//#if !polish.blackberry
if (this.caretPosition != 0) {
//#endif
setCaretPosition( 0 );
//#if !polish.blackberry
}
//#endif
//#elif !polish.TextField.keepCaretPosition
setCaretPosition( getString().length() );
//#endif
//#ifdef tmp.allowDirectInput
}
//#endif
//#endif
Style unfocusedStyle = super.focus(focStyle, direction);
//#if tmp.updateDeleteCommand && !(polish.blackberry || polish.android)
updateDeleteCommand( this.text );
//#endif
return unfocusedStyle;
}
//#endif
//#if polish.blackberry
/**
* Notifies the TextField about changes in its native BlackBerry component.
* @param field the native field
* @param context the context of the change
*/
public void fieldChanged(Field field, int context) {
if (context != FieldChangeListener.PROGRAMMATIC && this.isInitialized ) {
//#if polish.Bugs.ItemStateListenerCalledTooEarly
int fieldType = this.constraints & 0xffff;
if (fieldType == NUMERIC || fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) {
setString( this.editField.getText() );
notifyStateChanged();
} else {
long currentTime = System.currentTimeMillis();
this.lastFieldChangedEvent = currentTime;
Screen scr = getScreen();
if (scr != null) {
scr.lastInteractionTime = currentTime;
}
}
//#else
setString( this.editField.getText() );
notifyStateChanged();
//#endif
}
}
//#endif
//#if polish.series40sdk11
public void multilineToggleFix(TextEditor textEditor) {
Object parent = textEditor.getParent();
textEditor.setParent(null);
textEditor.setParent(parent);
}
//#endif
//#if polish.series40sdk20 || polish.series40sdk11
public void inputAction(TextEditor textEditor, int actions) {
if (textEditor == null ) {
return;
}
// If the text changes, make sure to update the Polish item as needed
setText(textEditor.getContent());
notifyStateChanged();
// Switching from multi to single-line and vice-versa in SDK 1.1 does not work as expected.
// As such, for now we only do this on SDK 2.0 devices.
if ( getNumberOfLines() > 1 && textEditor.isMultiline() == false ) {
textEditor.setMultiline(true);
//#if polish.series40sdk11
multilineToggleFix(textEditor);
//#endif
} else if ( getNumberOfLines() <= 1 && textEditor.isMultiline() ) {
textEditor.setMultiline(false);
//#if polish.series40sdk11
multilineToggleFix(textEditor);
//#endif
}
}
//#endif
/**
* Sets the input mode for this TextField.
* Is ignored when no direct input mode is used.
*
* @param inputMode the input mode
*/
public void setInputMode(int inputMode) {
this.inputMode = inputMode;
//#if tmp.directInput
//#if tmp.useInputInfo
if (this.isFocused) {
updateInfo();
}
//#endif
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
}
if (inputMode == MODE_FIRST_UPPERCASE) {
this.nextCharUppercase = true;
} else {
this.nextCharUppercase = false;
}
//#endif
}
/**
* Returns the current input mode.
*
* @return the current input mode
*/
public int getInputMode() {
return this.inputMode;
}
/**
* (De)activates the input info element for this TextField.
* Note that the input info cannot be shown when it is deactivated by setting the "polish.TextField.includeInputInfo"
* preprocessing variable to "false".
*
* @param show true when the input info should be shown
*/
public void setShowInputInfo(boolean show) {
this.isShowInputInfo = show;
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.StringItem#showNotify()
*/
protected void showNotify() {
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null && this.isFocused) {
this.series40sdk20Field.setVisible(true);
this.series40sdk20Field.setFocus(true);
}
//#endif
//#if tmp.updateDeleteCommand
updateDeleteCommand(this.text);
//#endif
//#if polish.TextField.useExternalInfo && !polish.blackberry
if(this.isFocused && this.infoItem != null)
{
updateInfo();
}
//#endif
//#if polish.blackberry && polish.hasPointerEvents
//#if polish.showSoftKeyboardOnShowNotify != false
if (this.isFocused) {
DeviceControl.showSoftKeyboard();
}
//#endif
//#endif
super.showNotify();
}
//#if (!polish.blackberry && tmp.directInput) || polish.series40sdk20 || polish.series40sdk11
/* (non-Javadoc)
* @see de.enough.polish.ui.StringItem#hideNotify()
*/
protected void hideNotify() {
//#if polish.series40sdk20 || polish.series40sdk11
if ( this.series40sdk20Field != null ) {
this.series40sdk20Field.setVisible(false);
this.series40sdk20Field.setFocus(false);
}
//#else
if (this.caretChar != this.editingCaretChar) {
commitCurrentCharacter();
}
//#endif
super.hideNotify();
}
//#endif
//#if tmp.usePredictiveInput
public PredictiveAccess getPredictiveAccess() {
return this.predictiveAccess;
}
public void setPredictiveAccess(PredictiveAccess predictive) {
this.predictiveAccess = predictive;
}
//#endif
/**
* Checks if commands are currently suppressed by this TextField.
* @return true when commands are suppressed
*/
public boolean isSuppressCommands() {
return this.suppressCommands;
}
/**
* Toggles the surpressing of commands for this TextField
* This has no effect when commands are globally suppressed by settting
* the preprocessing variable "polish.TextField.suppressCommands" to "true".
*
* @param suppressCommands true when commands should be suppressed
*/
public void setSuppressCommands(boolean suppressCommands) {
this.suppressCommands = suppressCommands;
setConstraints( this.constraints );
}
//#if polish.TextField.showHelpText
/**
* Sets a help text for this TextField. The help text
* appears when a TextField has no input yet and is
* used to inform the user about the desired content
* (e.g. "Insert name here ...")
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* @param text the help text
* @see #setHelpStyle()
* @see #setHelpStyle(Style)
* @see #setHelpText(String,Style)
*/
public void setHelpText(String text)
{
this.helpItem.setText(text);
}
//#endif
//#if polish.TextField.showHelpText
/**
* Sets a help text for this TextField and its style. The help text
* appears when a TextField has no input yet and is
* used to inform the user about the desired content
* (e.g. "Insert name here ...")
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* This method can be used with preprocessing:
* <pre>
* //#style inputHelp
* myTextField.setHelpText("Enter your Name...");
* </pre>
* @param text the help text
* @see #setHelpStyle()
* @see #setHelpStyle(Style)
* @see #setHelpText(String)
*/
public void setHelpText(String text, Style helpStyle)
{
this.helpItem.setText(text);
if (helpStyle != null) {
this.helpItem.setStyle(helpStyle);
}
//#if polish.android
MidletBridge.getInstance().runOnUiThread( new Runnable() {
public void run() {
TextField.this._androidTextField.applyTextField();
}
});
//#endif
}
//#endif
//#if polish.TextField.showHelpText
/**
* Sets the help style for this TextField
* with the use of style preprocessing e.g.:
* <pre>
* //#style myStyle
* setHelpStyle();
* </pre>
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* @see #setHelpText(String)
* @see #setHelpStyle(Style)
*/
public void setHelpStyle() {
// nothing here
}
/**
* Sets the style of the help text
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* @param style the style
* @see #setHelpText(String)
* @see #setHelpStyle()
*/
public void setHelpStyle(Style style)
{
if (this.helpItem != null)
{
this.helpItem.setStyle(style);
//#if polish.android
MidletBridge.getInstance().runOnUiThread( new Runnable() {
public void run() {
TextField.this._androidTextField.applyTextField();
}
});
//#endif
}
}
//#endif
//#if polish.TextField.showHelpText
/**
* Retrieves the help text for this TextField.
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* @return the help text
* @see #setHelpText(String)
* @see #setHelpText(String,Style)
*/
public String getHelpText()
{
String text = null;
if (this.helpItem != null) {
text = this.helpItem.getText();
}
return text;
}
//#endif
//#if polish.TextField.showHelpText
/**
* Retrieves the help text for this TextField.
* This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code>
* in the build.xml.
* @return the help text
* @see #setHelpText(String)
* @see #setHelpText(String,Style)
*/
public Color getHelpTextColor()
{
if (!this.isStyleInitialized && this.style != null)
{
setStyle(this.style);
}
Style helpStyle = this.helpItem.getStyle();
if (helpStyle == null)
{
helpStyle = this.style;
}
if (helpStyle != null)
{
Color color = helpStyle.getColorProperty("font-color");
return color;
}
return new Color( 0x0 );
}
//#endif
//#if polish.TextField.useExternalInfo && !polish.blackberry
/**
* Returns the StringItem which is displaying the input info
* @return the StringItem displaying the input info
* @see #getInfoItem()
*/
public StringItem getInfoItem() {
return this.infoItem;
}
/**
* Sets the StringItem which should display the input info
* @param infoItem the StringItem to display the input info
* @see #setInfoItem(StringItem)
*/
public void setInfoItem(StringItem infoItem) {
this.infoItem = infoItem;
}
//#endif
//#if !polish.blackberry && tmp.supportsSymbolEntry
/**
* Returns the defined symbols as a String array
* @return the string array
*/
public static String[] getDefinedSymbols() {
return definedSymbols;
}
//#endif
//#if polish.blackberry
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#updateInternalArea()
*/
public void updateInternalArea() {
int cursorPosition = this.editField.getCursorPosition();
// check if cursor is in visible area:
int lineHeight = getLineHeight();
if (this.text != null) {
this.internalX = 0;
int size = this.textLines.size();
this.internalHeight = lineHeight;
this.internalWidth = this.itemWidth;
// assume last row by default:
this.internalY = this.contentHeight - lineHeight;
if (cursorPosition < this.text.length() - this.textLines.getLine(size-1).length()) {
// cursor might not be in the last row:
int endOfLinePos = 0;
int textLength = this.text.length();
for (int i = 0; i < size; i++) {
String line = this.textLines.getLine(i);
endOfLinePos += line.length();
if (endOfLinePos < textLength) {
char c = this.text.charAt( endOfLinePos );
if (c == ' ' || c == '\t' || c == '\n') {
line += c;
endOfLinePos++;
}
}
if (cursorPosition <= endOfLinePos) {
this.internalY = lineHeight * i;
break;
}
}
}
if (this.parent instanceof Container) {
int direction = Canvas.DOWN;
if (cursorPosition > this.bbLastCursorPosition) {
direction = Canvas.UP;
}
this.bbLastCursorPosition = cursorPosition;
boolean scrolled = ((Container)this.parent).scroll(direction, this, true);
if(scrolled) {
repaintFully();
}
}
} else {
this.internalX = NO_POSITION_SET;
}
}
//#endif
/**
* Retrieves matching words for the specified textfield.
* Note that you need to enable the predictive input mode using the preprocessing variable
* <code>polish.TextField.usePredictiveInputMode</code>.
*
* @return ArrayList<String> of allowed words - null when no predictive mode is used
*/
public ArrayList getPredictiveMatchingWords() {
//#if tmp.usePredictiveInput
PredictiveAccess predictive = getPredictiveAccess();
return predictive.getResults();
//#else
//# return null;
//#endif
}
/**
* Allows the given words for the specified textfield.
* Note that you need to enable the predictive input mode using the preprocessing variable
* <code>polish.TextField.usePredictiveInputMode</code>.
*
* @param words array of allowed words - use null to reset the allowed words to the default RMS dictionary
*/
public void setPredictiveDictionary(String[] words) {
//#if tmp.usePredictiveInput
PredictiveAccess predictive = getPredictiveAccess();
predictive.initPredictiveInput(words);
setString("");
predictive.synchronize();
if(words == null)
{
predictive.setPredictiveType(PredictiveAccess.TRIE);
}
else
{
predictive.setPredictiveType(PredictiveAccess.ARRAY);
}
//#endif
}
//TODO andre: document
public void setPredictiveInfo(String info) {
//#if tmp.usePredictiveInput
PredictiveAccess predictive = getPredictiveAccess();
predictive.setInfo(info);
//#endif
}
/**
* Set the word-not-found box in the textfield
*
* @param alert the alert
*/
public void setPredictiveWordNotFoundAlert(Alert alert) {
//#if tmp.usePredictiveInput
getPredictiveAccess().setAlert(alert);
//#endif
}
/**
* Returns true if the flag to open the native editor on CenterSoftKey press is set to true
* @return true when the native editor is opened when FIRE is pressed
*/
public boolean isCskOpensNativeEditor() {
return this.cskOpensNativeEditor;
}
/**
* Sets the flag to open the native editor on CenterSoftKey press
* @param cskOpensNativeEditor true when the native editor should be opened when FIRE is pressed
*/
public void setCskOpensNativeEditor(boolean cskOpensNativeEditor) {
this.cskOpensNativeEditor = cskOpensNativeEditor;
}
/**
* Sets the title to be displayed in the native textbox
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Set if the textfield should accept only simple input.
*
* @param noComplexInput set if the textfield should accept only simple input
*/
public void setNoComplexInput(boolean noComplexInput){
this.noComplexInput= noComplexInput;
this.setConstraints(this.constraints);
}
/**
* Set if the textfield should accept the enter key as an input which results in a new line.
*
* @param noNewLine set if new lines should be ignored
*/
public void setNoNewLine(boolean noNewLine) {
this.noNewLine = noNewLine;
//#if polish.blackberry
this.setConstraints(this.constraints);
//#endif
}
/**
* Checks if the textfield should accept the enter key as an input which results in a new line.
*
* @return true if new lines should be ignored
*/
public boolean isNoNewLine() {
return this.noNewLine;
}
/**
* Checks if this textfield is edtiable.
* @return true when this field is editable
*/
public boolean isEditable() {
return ((this.constraints & TextField.UNEDITABLE) != TextField.UNEDITABLE);
}
public boolean isConstraintsPhoneNumber() {
return ((this.constraints & PHONENUMBER) == PHONENUMBER);
}
public boolean isConstraintsEmail() {
return ((this.constraints & EMAILADDR) == EMAILADDR);
}
public boolean isConstraintsNumeric() {
return ((this.constraints & NUMERIC) == NUMERIC);
}
public boolean isConstraintsDecimal() {
return ((this.constraints & DECIMAL) == DECIMAL) || ((this.constraints & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL);
}
public boolean isConstraintsPassword() {
return ((this.constraints & PASSWORD) == PASSWORD);
}
//#ifdef polish.TextField.additionalMethods:defined
//#include ${polish.TextField.additionalMethods}
//#endif
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
d3f30ecc8d9d5e8ca257a2b43add0110421eba6c | 8eaf88146f7d3eb3f82d43ccac8177d58b229ff0 | /Topicos_Plugin.java | 34041ba180c2bd6465bddf8362f5d5e3f3953880 | [] | no_license | LucasFreitasRocha/pluginsImageJ | 2371510eb78959fc8e9952e27b1b113388ca0044 | d9c0f8fd8ae2027de23606dc03bb0949b540f819 | refs/heads/master | 2021-10-28T09:41:09.718441 | 2021-10-25T01:43:04 | 2021-10-25T01:43:04 | 214,248,965 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 284 | java |
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.plugin.PlugIn;
import ij.process.ImageProcessor;
public class Topicos_Plugin implements PlugIn {
public void run(String arg) {
ImagePlus read = WindowManager.getImage("READ");
read.show();
}
}
| [
"rochadefreitaslucas@gmail.com"
] | rochadefreitaslucas@gmail.com |
d45940b6ee0c96b29c466b024779a008c97cbcb3 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/google--j2objc/97be5e92b907bf452731a01306c40193e2374173/after/Options.java | bfcdff2a03aa6d11de90ef8186d7a1883ceefa10 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,985 | java | /*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* The set of tool properties, initialized by the command-line arguments.
* This class was extracted from the main class, to make it easier for
* other classes to access options.
*
* @author Tom Ball
*/
public class Options {
private static List<String> sourcePathEntries = Lists.newArrayList(".");
private static List<String> classPathEntries = Lists.newArrayList(".");
private static List<String> pluginPathEntries = Lists.newArrayList();
private static String pluginOptionString = "";
private static List<Plugin> plugins = new ArrayList<Plugin>();
private static File outputDirectory = new File(".");
private static OutputStyleOption outputStyle = OutputStyleOption.PACKAGE;
private static String implementationSuffix = ".m";
private static MemoryManagementOption memoryManagementOption = null;
private static boolean emitLineDirectives = false;
private static boolean warningsAsErrors = false;
private static boolean deprecatedDeclarations = false;
// Keys are class names, values are header paths (with a .h).
private static Map<String, String> headerMappings = Maps.newLinkedHashMap();
private static File outputHeaderMappingFile = null;
private static Map<String, String> classMappings = Maps.newLinkedHashMap();
private static Map<String, String> methodMappings = Maps.newLinkedHashMap();
private static boolean stripGwtIncompatible = false;
private static boolean segmentedHeaders = false;
private static String fileEncoding = System.getProperty("file.encoding", "UTF-8");
private static boolean jsniWarnings = true;
private static boolean buildClosure = false;
private static boolean stripReflection = false;
private static boolean extractUnsequencedModifications = true;
private static boolean docCommentsEnabled = false;
private static boolean finalMethodsAsFunctions = true;
private static boolean removeClassMethods = false;
private static boolean hidePrivateMembers = true;
private static int batchTranslateMaximum = 0;
private static File proGuardUsageFile = null;
static final String DEFAULT_HEADER_MAPPING_FILE = "mappings.j2objc";
// Null if not set (means we use the default). Can be empty also (means we use no mapping files).
private static List<String> headerMappingFiles = null;
private static final String JRE_MAPPINGS_FILE = "JRE.mappings";
private static String fileHeader;
private static final String FILE_HEADER_KEY = "file-header";
private static String usageMessage;
private static String helpMessage;
private static final String USAGE_MSG_KEY = "usage-message";
private static final String HELP_MSG_KEY = "help-message";
private static String temporaryDirectory;
private static final String XBOOTCLASSPATH = "-Xbootclasspath:";
private static String bootclasspath = System.getProperty("sun.boot.class.path");
private static Map<String, String> packagePrefixes = Maps.newHashMap();
private static final String BATCH_PROCESSING_MAX_FLAG = "--batch-translate-max=";
static {
// Load string resources.
URL propertiesUrl = Resources.getResource(J2ObjC.class, "J2ObjC.properties");
Properties properties = new Properties();
try {
properties.load(propertiesUrl.openStream());
} catch (IOException e) {
System.err.println("unable to access tool properties: " + e);
System.exit(1);
}
fileHeader = properties.getProperty(FILE_HEADER_KEY);
Preconditions.checkNotNull(fileHeader);
usageMessage = properties.getProperty(USAGE_MSG_KEY);
Preconditions.checkNotNull(usageMessage);
helpMessage = properties.getProperty(HELP_MSG_KEY);
Preconditions.checkNotNull(helpMessage);
}
/**
* Types of memory management to be used by translated code.
*/
public static enum MemoryManagementOption { REFERENCE_COUNTING, ARC }
private static final MemoryManagementOption DEFAULT_MEMORY_MANAGEMENT_OPTION =
MemoryManagementOption.REFERENCE_COUNTING;
/**
* Types of output file generation. Output files are generated in
* the specified output directory in an optional sub-directory.
*/
public static enum OutputStyleOption {
/** Use the class's package, like javac.*/
PACKAGE,
/** Use the relative directory of the input file. */
SOURCE,
/** Don't use a relative directory. */
NONE
}
public static final OutputStyleOption DEFAULT_OUTPUT_STYLE_OPTION =
OutputStyleOption.PACKAGE;
/**
* Set all log handlers in this package with a common level.
*/
private static void setLogLevel(Level level) {
Logger.getLogger("com.google.devtools.j2objc").setLevel(level);
}
public static boolean isVerbose() {
return Logger.getLogger("com.google.devtools.j2objc").getLevel() == Level.FINEST;
}
/**
* Load the options from a command-line, returning the arguments that were
* not option-related (usually files). If help is requested or an error is
* detected, the appropriate status method is invoked and the app terminates.
* @throws IOException
*/
public static String[] load(String[] args) throws IOException {
setLogLevel(Level.INFO);
addJreMappings();
// Create a temporary directory as the sourcepath's first entry, so that
// modified sources will take precedence over regular files.
sourcePathEntries = Lists.newArrayList();
int nArg = 0;
String[] noFiles = new String[0];
while (nArg < args.length) {
String arg = args[nArg];
if (arg.isEmpty()) {
++nArg;
continue;
}
if (arg.equals("-classpath")) {
if (++nArg == args.length) {
return noFiles;
}
classPathEntries = getPathArgument(args[nArg]);
} else if (arg.equals("-sourcepath")) {
if (++nArg == args.length) {
usage("-sourcepath requires an argument");
}
sourcePathEntries.addAll(getPathArgument(args[nArg]));
} else if (arg.equals("-pluginpath")) {
if (++nArg == args.length) {
usage("-pluginpath requires an argument");
}
pluginPathEntries = getPathArgument(args[nArg]);
} else if (arg.equals("-pluginoptions")) {
if (++nArg == args.length){
usage("-pluginoptions requires an argument");
}
pluginOptionString = args[nArg];
} else if (arg.equals("-d")) {
if (++nArg == args.length) {
usage("-d requires an argument");
}
outputDirectory = new File(args[nArg]);
} else if (arg.equals("--mapping")) {
if (++nArg == args.length) {
usage("--mapping requires an argument");
}
addMappingsFiles(args[nArg].split(","));
} else if (arg.equals("--header-mapping")) {
if (++nArg == args.length) {
usage("--header-mapping requires an argument");
}
if (args[nArg].isEmpty()) {
// For when user supplies an empty mapping files list. Otherwise the default will be used.
headerMappingFiles = Collections.<String>emptyList();
} else {
headerMappingFiles = Lists.newArrayList(args[nArg].split(","));
}
} else if (arg.equals("--output-header-mapping")) {
if (++nArg == args.length) {
usage("--output-header-mapping requires an argument");
}
outputHeaderMappingFile = new File(args[nArg]);
} else if (arg.equals("--dead-code-report")) {
if (++nArg == args.length) {
usage("--dead-code-report requires an argument");
}
proGuardUsageFile = new File(args[nArg]);
} else if (arg.equals("--prefix")) {
if (++nArg == args.length) {
usage("--prefix requires an argument");
}
addPrefixOption(args[nArg]);
} else if (arg.equals("--prefixes")) {
if (++nArg == args.length) {
usage("--prefixes requires an argument");
}
addPrefixesFile(args[nArg]);
} else if (arg.equals("-x")) {
if (++nArg == args.length) {
usage("-x requires an argument");
}
String s = args[nArg];
if (s.equals("objective-c")) {
implementationSuffix = ".m";
} else if (s.equals("objective-c++")) {
implementationSuffix = ".mm";
} else {
usage("unsupported language: " + s);
}
} else if (arg.equals("--ignore-missing-imports")) {
ErrorUtil.error("--ignore-missing-imports is no longer supported");
} else if (arg.equals("-use-reference-counting")) {
checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING);
} else if (arg.equals("--no-package-directories")) {
outputStyle = OutputStyleOption.NONE;
} else if (arg.equals("--preserve-full-paths")) {
outputStyle = OutputStyleOption.SOURCE;
} else if (arg.equals("-use-arc")) {
checkMemoryManagementOption(MemoryManagementOption.ARC);
} else if (arg.equals("-g")) {
emitLineDirectives = true;
} else if (arg.equals("-Werror")) {
warningsAsErrors = true;
} else if (arg.equals("--generate-deprecated")) {
deprecatedDeclarations = true;
} else if (arg.equals("-q") || arg.equals("--quiet")) {
setLogLevel(Level.WARNING);
} else if (arg.equals("-t") || arg.equals("--timing-info")) {
setLogLevel(Level.FINE);
} else if (arg.equals("-v") || arg.equals("--verbose")) {
setLogLevel(Level.FINEST);
} else if (arg.startsWith(XBOOTCLASSPATH)) {
bootclasspath = arg.substring(XBOOTCLASSPATH.length());
} else if (arg.equals("-Xno-jsni-delimiters")) {
// TODO(tball): remove flag when all client builds stop using it.
} else if (arg.equals("-Xno-jsni-warnings")) {
jsniWarnings = false;
} else if (arg.equals("-encoding")) {
if (++nArg == args.length) {
usage("-encoding requires an argument");
}
fileEncoding = args[nArg];
try {
// Verify encoding has a supported charset.
Charset.forName(fileEncoding);
} catch (UnsupportedCharsetException e) {
ErrorUtil.warning(e.getMessage());
}
} else if (arg.equals("--strip-gwt-incompatible")) {
stripGwtIncompatible = true;
} else if (arg.equals("--strip-reflection")) {
stripReflection = true;
} else if (arg.equals("--segmented-headers")) {
segmentedHeaders = true;
} else if (arg.equals("--build-closure")) {
buildClosure = true;
} else if (arg.equals("--extract-unsequenced")) {
extractUnsequencedModifications = true;
} else if (arg.equals("--no-extract-unsequenced")) {
extractUnsequencedModifications = false;
} else if (arg.equals("--doc-comments")) {
docCommentsEnabled = true;
} else if (arg.startsWith(BATCH_PROCESSING_MAX_FLAG)) {
batchTranslateMaximum =
Integer.parseInt(arg.substring(BATCH_PROCESSING_MAX_FLAG.length()));
// TODO(tball): remove obsolete flag once projects stop using it.
} else if (arg.equals("--final-methods-as-functions")) {
finalMethodsAsFunctions = true;
} else if (arg.equals("--no-final-methods-functions")) {
finalMethodsAsFunctions = false;
} else if (arg.equals("--no-class-methods")) {
removeClassMethods = true;
// TODO(tball): remove obsolete flag once projects stop using it.
} else if (arg.equals("--hide-private-members")) {
hidePrivateMembers = true;
} else if (arg.equals("--no-hide-private-members")) {
hidePrivateMembers = false;
} else if (arg.startsWith("-h") || arg.equals("--help")) {
help(false);
} else if (arg.startsWith("-")) {
usage("invalid flag: " + arg);
} else {
break;
}
++nArg;
}
if (memoryManagementOption == null) {
memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING;
}
int nFiles = args.length - nArg;
String[] files = new String[nFiles];
for (int i = 0; i < nFiles; i++) {
String path = args[i + nArg];
if (path.endsWith(".jar")) {
appendSourcePath(path);
}
files[i] = path;
}
return files;
}
/**
* Add prefix option, which has a format of "<package>=<prefix>".
*/
private static void addPrefixOption(String arg) {
int i = arg.indexOf('=');
// Make sure key and value are at least 1 character.
if (i < 1 || i >= arg.length() - 1) {
usage("invalid prefix format");
}
String pkg = arg.substring(0, i);
String prefix = arg.substring(i + 1);
addPackagePrefix(pkg, prefix);
}
/**
* Add a file map of packages to their respective prefixes, using the
* Properties file format.
*/
private static void addPrefixesFile(String filename) throws IOException {
Properties props = new Properties();
FileInputStream fis = new FileInputStream(filename);
props.load(fis);
fis.close();
addPrefixProperties(props);
}
@VisibleForTesting
static void addPrefixProperties(Properties props) {
for (String pkg : props.stringPropertyNames()) {
addPackagePrefix(pkg, props.getProperty(pkg).trim());
}
}
private static void addMappingsFiles(String[] filenames) throws IOException {
for (String filename : filenames) {
if (!filename.isEmpty()) {
addMappingsProperties(FileUtil.loadProperties(filename));
}
}
}
private static void addJreMappings() throws IOException {
InputStream stream = J2ObjC.class.getResourceAsStream(JRE_MAPPINGS_FILE);
addMappingsProperties(FileUtil.loadProperties(stream));
}
private static void addMappingsProperties(Properties mappings) {
Enumeration<?> keyIterator = mappings.propertyNames();
while (keyIterator.hasMoreElements()) {
String key = (String) keyIterator.nextElement();
if (key.indexOf('(') > 0) {
// All method mappings have parentheses characters, classes don't.
String iosMethod = mappings.getProperty(key);
methodMappings.put(key, iosMethod);
} else {
String iosClass = mappings.getProperty(key);
classMappings.put(key, iosClass);
}
}
}
/**
* Check that the memory management option wasn't previously set to a
* different value. If okay, then set the option.
*/
private static void checkMemoryManagementOption(MemoryManagementOption option) {
if (memoryManagementOption != null && memoryManagementOption != option) {
usage("Multiple memory management options cannot be set.");
}
setMemoryManagementOption(option);
}
public static void usage(String invalidUseMsg) {
System.err.println("j2objc: " + invalidUseMsg);
System.err.println(usageMessage);
System.exit(1);
}
public static void help(boolean errorExit) {
System.err.println(helpMessage);
// javac exits with 2, but any non-zero value works.
System.exit(errorExit ? 2 : 0);
}
private static List<String> getPathArgument(String argument) {
List<String> entries = Lists.newArrayList();
for (String entry : Splitter.on(File.pathSeparatorChar).split(argument)) {
if (new File(entry).exists()) { // JDT fails with bad path entries.
entries.add(entry);
} else if (entry.startsWith("~/")) {
// Expand bash/csh tildes, which don't get expanded by the shell
// first if in the middle of a path string.
String expanded = System.getProperty("user.home") + entry.substring(1);
if (new File(expanded).exists()) {
entries.add(expanded);
}
}
}
return entries;
}
public static boolean docCommentsEnabled() {
return docCommentsEnabled;
}
@VisibleForTesting
public static void setDocCommentsEnabled(boolean value) {
docCommentsEnabled = value;
}
@VisibleForTesting
public static void resetDocComments() {
docCommentsEnabled = false;
}
public static List<String> getSourcePathEntries() {
return sourcePathEntries;
}
public static void appendSourcePath(String entry) {
sourcePathEntries.add(entry);
}
public static void insertSourcePath(int index, String entry) {
sourcePathEntries.add(index, entry);
}
public static List<String> getClassPathEntries() {
return classPathEntries;
}
public static String[] getPluginPathEntries() {
return pluginPathEntries.toArray(new String[pluginPathEntries.size()]);
}
public static String getPluginOptionString() {
return pluginOptionString;
}
public static List<Plugin> getPlugins() {
return plugins;
}
public static File getOutputDirectory() {
return outputDirectory;
}
/**
* If true, put output files in sub-directories defined by
* package declaration (like javac does).
*/
public static boolean usePackageDirectories() {
return outputStyle == OutputStyleOption.PACKAGE;
}
/**
* If true, put output files in the same directories from
* which the input files were read.
*/
public static boolean useSourceDirectories() {
return outputStyle == OutputStyleOption.SOURCE;
}
public static void setPackageDirectories(OutputStyleOption style) {
outputStyle = style;
}
public static String getImplementationFileSuffix() {
return implementationSuffix;
}
public static boolean useReferenceCounting() {
return memoryManagementOption == MemoryManagementOption.REFERENCE_COUNTING;
}
public static boolean useARC() {
return memoryManagementOption == MemoryManagementOption.ARC;
}
public static MemoryManagementOption getMemoryManagementOption() {
return memoryManagementOption;
}
// Used by tests.
public static void setMemoryManagementOption(MemoryManagementOption option) {
memoryManagementOption = option;
}
public static void resetMemoryManagementOption() {
memoryManagementOption = DEFAULT_MEMORY_MANAGEMENT_OPTION;
}
public static boolean emitLineDirectives() {
return emitLineDirectives;
}
public static void setEmitLineDirectives(boolean b) {
emitLineDirectives = b;
}
public static boolean treatWarningsAsErrors() {
return warningsAsErrors;
}
@VisibleForTesting
public static void enableDeprecatedDeclarations() {
deprecatedDeclarations = true;
}
@VisibleForTesting
public static void resetDeprecatedDeclarations() {
deprecatedDeclarations = false;
}
public static boolean generateDeprecatedDeclarations() {
return deprecatedDeclarations;
}
public static Map<String, String> getClassMappings() {
return classMappings;
}
public static Map<String, String> getMethodMappings() {
return methodMappings;
}
public static Map<String, String> getHeaderMappings() {
return headerMappings;
}
@Nullable
public static List<String> getHeaderMappingFiles() {
return headerMappingFiles;
}
public static void setHeaderMappingFiles(List<String> headerMappingFiles) {
Options.headerMappingFiles = headerMappingFiles;
}
public static String getUsageMessage() {
return usageMessage;
}
public static String getHelpMessage() {
return helpMessage;
}
public static String getFileHeader() {
return fileHeader;
}
public static File getProGuardUsageFile() {
return proGuardUsageFile;
}
public static File getOutputHeaderMappingFile() {
return outputHeaderMappingFile;
}
@VisibleForTesting
public static void setOutputHeaderMappingFile(File outputHeaderMappingFile) {
Options.outputHeaderMappingFile = outputHeaderMappingFile;
}
public static List<String> getBootClasspath() {
return getPathArgument(bootclasspath);
}
public static Map<String, String> getPackagePrefixes() {
return packagePrefixes;
}
public static String addPackagePrefix(String pkg, String prefix) {
return packagePrefixes.put(pkg, prefix);
}
@VisibleForTesting
public static void clearPackagePrefixes() {
packagePrefixes.clear();
}
public static String getTemporaryDirectory() throws IOException {
if (temporaryDirectory != null) {
return temporaryDirectory;
}
File tmpfile = File.createTempFile("j2objc", Long.toString(System.nanoTime()));
if (!tmpfile.delete()) {
throw new IOException("Could not delete temp file: " + tmpfile.getAbsolutePath());
}
if (!tmpfile.mkdir()) {
throw new IOException("Could not create temp directory: " + tmpfile.getAbsolutePath());
}
temporaryDirectory = tmpfile.getAbsolutePath();
return temporaryDirectory;
}
// Called on exit. This is done here rather than using File.deleteOnExit(),
// so the package directories created by the dead-code-eliminator don't have
// to be tracked.
public static void deleteTemporaryDirectory() {
if (temporaryDirectory != null) {
deleteDir(new File(temporaryDirectory));
temporaryDirectory = null;
}
}
static void deleteDir(File dir) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
deleteDir(f);
} else if (f.getName().endsWith(".java")) {
// Only delete Java files, as other temporary files (like hsperfdata)
// may also be in tmpdir.
// TODO(kstanger): It doesn't make sense that hsperfdata would show up in our tempdir.
// Consider deleting this method and using FileUtil#deleteTempDir() instead.
f.delete();
}
}
dir.delete(); // Will fail if other files in dir, which is fine.
}
public static String fileEncoding() {
return fileEncoding;
}
public static Charset getCharset() {
return Charset.forName(fileEncoding);
}
public static boolean stripGwtIncompatibleMethods() {
return stripGwtIncompatible;
}
@VisibleForTesting
public static void setStripGwtIncompatibleMethods(boolean b) {
stripGwtIncompatible = b;
}
public static boolean generateSegmentedHeaders() {
return segmentedHeaders;
}
@VisibleForTesting
public static void enableSegmentedHeaders() {
segmentedHeaders = true;
}
@VisibleForTesting
public static void resetSegmentedHeaders() {
segmentedHeaders = false;
}
public static boolean jsniWarnings() {
return jsniWarnings;
}
public static void setJsniWarnings(boolean b) {
jsniWarnings = b;
}
public static boolean buildClosure() {
return buildClosure;
}
@VisibleForTesting
public static void setBuildClosure(boolean b) {
buildClosure = b;
}
@VisibleForTesting
public static void resetBuildClosure() {
buildClosure = false;
}
public static boolean stripReflection() {
return stripReflection;
}
@VisibleForTesting
public static void setStripReflection(boolean b) {
stripReflection = b;
}
public static boolean extractUnsequencedModifications() {
return extractUnsequencedModifications;
}
@VisibleForTesting
public static void enableExtractUnsequencedModifications() {
extractUnsequencedModifications = true;
}
@VisibleForTesting
public static void resetExtractUnsequencedModifications() {
extractUnsequencedModifications = false;
}
public static int batchTranslateMaximum() {
return batchTranslateMaximum;
}
@VisibleForTesting
public static void setBatchTranslateMaximum(int max) {
batchTranslateMaximum = max;
}
@VisibleForTesting
public static void resetBatchTranslateMaximum() {
batchTranslateMaximum = 0;
}
public static boolean finalMethodsAsFunctions() {
return finalMethodsAsFunctions;
}
@VisibleForTesting
public static void enableFinalMethodsAsFunctions() {
finalMethodsAsFunctions = true;
}
@VisibleForTesting
public static void resetFinalMethodsAsFunctions() {
finalMethodsAsFunctions = false;
}
public static boolean removeClassMethods() {
return removeClassMethods;
}
@VisibleForTesting
public static void setRemoveClassMethods(boolean b) {
removeClassMethods = b;
}
@VisibleForTesting
public static void resetRemoveClassMethods() {
removeClassMethods = false;
}
public static boolean hidePrivateMembers() {
return hidePrivateMembers;
}
@VisibleForTesting
public static void enableHidePrivateMembers() {
hidePrivateMembers = true;
}
@VisibleForTesting
public static void resetHidePrivateMembers() {
hidePrivateMembers = false;
}
public static boolean shouldPreProcess() {
return Options.getHeaderMappingFiles() != null && Options.useSourceDirectories();
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
511188504b8614d2e6bd729ed52870eadf2a70c1 | 8a85d5987d859e96d382b754b72e39be8feaaf40 | /src/main/java/com/strangeman/classmates/bean/MessageExample.java | 907de01ad557768d2613ecd036cc2e7fd48280d6 | [] | no_license | chapter7ofnight/classmates | 34e07ffbe389c96651c9c4c1df1b775c2c9cb973 | 42ff6d44076c254557e1d4598de10285f08e6d6c | refs/heads/master | 2020-03-07T17:11:17.737496 | 2018-05-10T03:05:58 | 2018-05-10T03:05:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,192 | java | package com.strangeman.classmates.bean;
import java.util.ArrayList;
import java.util.List;
public class MessageExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public MessageExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(String value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(String value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(String value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(String value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(String value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(String value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdLike(String value) {
addCriterion("id like", value, "id");
return (Criteria) this;
}
public Criteria andIdNotLike(String value) {
addCriterion("id not like", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<String> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<String> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(String value1, String value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(String value1, String value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andFromIsNull() {
addCriterion("from is null");
return (Criteria) this;
}
public Criteria andFromIsNotNull() {
addCriterion("from is not null");
return (Criteria) this;
}
public Criteria andFromEqualTo(String value) {
addCriterion("from =", value, "from");
return (Criteria) this;
}
public Criteria andFromNotEqualTo(String value) {
addCriterion("from <>", value, "from");
return (Criteria) this;
}
public Criteria andFromGreaterThan(String value) {
addCriterion("from >", value, "from");
return (Criteria) this;
}
public Criteria andFromGreaterThanOrEqualTo(String value) {
addCriterion("from >=", value, "from");
return (Criteria) this;
}
public Criteria andFromLessThan(String value) {
addCriterion("from <", value, "from");
return (Criteria) this;
}
public Criteria andFromLessThanOrEqualTo(String value) {
addCriterion("from <=", value, "from");
return (Criteria) this;
}
public Criteria andFromLike(String value) {
addCriterion("from like", value, "from");
return (Criteria) this;
}
public Criteria andFromNotLike(String value) {
addCriterion("from not like", value, "from");
return (Criteria) this;
}
public Criteria andFromIn(List<String> values) {
addCriterion("from in", values, "from");
return (Criteria) this;
}
public Criteria andFromNotIn(List<String> values) {
addCriterion("from not in", values, "from");
return (Criteria) this;
}
public Criteria andFromBetween(String value1, String value2) {
addCriterion("from between", value1, value2, "from");
return (Criteria) this;
}
public Criteria andFromNotBetween(String value1, String value2) {
addCriterion("from not between", value1, value2, "from");
return (Criteria) this;
}
public Criteria andToIsNull() {
addCriterion("to is null");
return (Criteria) this;
}
public Criteria andToIsNotNull() {
addCriterion("to is not null");
return (Criteria) this;
}
public Criteria andToEqualTo(String value) {
addCriterion("to =", value, "to");
return (Criteria) this;
}
public Criteria andToNotEqualTo(String value) {
addCriterion("to <>", value, "to");
return (Criteria) this;
}
public Criteria andToGreaterThan(String value) {
addCriterion("to >", value, "to");
return (Criteria) this;
}
public Criteria andToGreaterThanOrEqualTo(String value) {
addCriterion("to >=", value, "to");
return (Criteria) this;
}
public Criteria andToLessThan(String value) {
addCriterion("to <", value, "to");
return (Criteria) this;
}
public Criteria andToLessThanOrEqualTo(String value) {
addCriterion("to <=", value, "to");
return (Criteria) this;
}
public Criteria andToLike(String value) {
addCriterion("to like", value, "to");
return (Criteria) this;
}
public Criteria andToNotLike(String value) {
addCriterion("to not like", value, "to");
return (Criteria) this;
}
public Criteria andToIn(List<String> values) {
addCriterion("to in", values, "to");
return (Criteria) this;
}
public Criteria andToNotIn(List<String> values) {
addCriterion("to not in", values, "to");
return (Criteria) this;
}
public Criteria andToBetween(String value1, String value2) {
addCriterion("to between", value1, value2, "to");
return (Criteria) this;
}
public Criteria andToNotBetween(String value1, String value2) {
addCriterion("to not between", value1, value2, "to");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(String value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(String value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(String value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(String value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(String value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(String value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLike(String value) {
addCriterion("create_time like", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotLike(String value) {
addCriterion("create_time not like", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<String> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<String> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(String value1, String value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(String value1, String value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andReadFlagIsNull() {
addCriterion("read_flag is null");
return (Criteria) this;
}
public Criteria andReadFlagIsNotNull() {
addCriterion("read_flag is not null");
return (Criteria) this;
}
public Criteria andReadFlagEqualTo(Integer value) {
addCriterion("read_flag =", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagNotEqualTo(Integer value) {
addCriterion("read_flag <>", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagGreaterThan(Integer value) {
addCriterion("read_flag >", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagGreaterThanOrEqualTo(Integer value) {
addCriterion("read_flag >=", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagLessThan(Integer value) {
addCriterion("read_flag <", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagLessThanOrEqualTo(Integer value) {
addCriterion("read_flag <=", value, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagIn(List<Integer> values) {
addCriterion("read_flag in", values, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagNotIn(List<Integer> values) {
addCriterion("read_flag not in", values, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagBetween(Integer value1, Integer value2) {
addCriterion("read_flag between", value1, value2, "readFlag");
return (Criteria) this;
}
public Criteria andReadFlagNotBetween(Integer value1, Integer value2) {
addCriterion("read_flag not between", value1, value2, "readFlag");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | [
"312764843@qq.com"
] | 312764843@qq.com |
36f1b2614ce638a90ab1386f40346b50ed9a7e1a | 46f2a4d17fb83ddf8f28facc7a02e0af7feb8357 | /app/src/main/java/com/example/phompang/thermalfeedback/adapter/ContactAdapter.java | 0a856d6c7355d24af020d984a8c00ab3a556223d | [] | no_license | PhompAng/ThermalFeedback | f204e6ee8f120f0025e6db0b1bbd71365d635787 | 9804a34748746be11b5c6255a7f5c56eb7a158f1 | refs/heads/master | 2021-03-27T16:11:01.551705 | 2018-01-11T07:03:27 | 2018-01-11T07:03:27 | 78,106,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,601 | java | package com.example.phompang.thermalfeedback.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.phompang.thermalfeedback.R;
import com.example.phompang.thermalfeedback.model.Contact;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by phompang on 12/29/2016 AD.
*/
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
private Context context;
private List<Contact> contacts;
private ViewHolder.OnContactDeleteListener listener;
public ContactAdapter(Context context, List<Contact> contacts, ViewHolder.OnContactDeleteListener listener) {
this.context = context;
this.contacts = contacts;
this.listener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_contact, parent, false);
return new ViewHolder(v, listener);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Contact contact = contacts.get(position);
holder.name.setText(contact.getName());
holder.phone.setText(contact.getPhone());
}
@Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
}
@Override
public int getItemCount() {
return contacts.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.img)
CircularImageView img;
@BindView(R.id.name)
TextView name;
@BindView(R.id.phone)
TextView phone;
@BindView(R.id.delete)
ImageView delete;
OnContactDeleteListener listener;
ViewHolder(View itemView, OnContactDeleteListener listener) {
super(itemView);
ButterKnife.bind(this, itemView);
this.listener = listener;
delete.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (listener != null) {
listener.onContactDelete(getAdapterPosition());
}
}
public interface OnContactDeleteListener {
void onContactDelete(int position);
}
}
}
| [
"tingtong003tomy@gmail.com"
] | tingtong003tomy@gmail.com |
1bb839034ca7fb64724514d9f14ce10a00875949 | 8ae4facdbd06a3116c22b009820e1f9daea6799a | /discovery/src/test/java/com/example/basics/DiscoveryApplicationTests.java | 3683808ee69fb66cd9995c9d07be58ef73eea3b2 | [] | no_license | sivanandapanda/spring-cloud-gateway | 96e29305397daacf565367fee5fa996d8ea958d6 | 783fcba564e0e092fa42f02ead66180d9c90b48e | refs/heads/main | 2023-03-12T15:46:49.597568 | 2021-02-27T13:27:16 | 2021-02-27T13:27:16 | 341,947,894 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 213 | java | package com.example.basics;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DiscoveryApplicationTests {
@Test
void contextLoads() {
}
}
| [
"sivanandpanda@gmail.com"
] | sivanandpanda@gmail.com |
1ddcb618deb8b9f27bc64a1f1e2054d01b9cc9fe | 0b673f0187ab1d169972c35265d98579ac0115e7 | /CDRD/src/br/com/contos/jdbc/JDBCNotificacaoDAO.java | 123bd7b5a1aa6bcdc1485cea6a3c42ec31332bd1 | [] | no_license | confoosed/Contos-De-Reinos-Distantes | 860fad4ea1f39674988dc6f3b51353f184a2a8be | d7760b20d10cbe37b977a5e7d089301fcda01684 | refs/heads/master | 2020-03-27T22:30:53.109500 | 2018-09-03T17:46:27 | 2018-09-03T17:46:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,558 | java | package br.com.contos.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import br.com.contos.classes.Notificacao;
import br.com.contos.jdbcinterfaces.NotificacaoDAO;
public class JDBCNotificacaoDAO implements NotificacaoDAO{
private Connection conexao;
public JDBCNotificacaoDAO(Connection conexao) {
this.conexao = conexao;
}
public boolean inserir(Notificacao notificacao){
String comando = "INSERT INTO notificacacoes (notificacao, data_criacao, usuario_id) VALUES (?,?,?)";
PreparedStatement p;
try{
p = this.conexao.prepareStatement(comando);
p.setString(1, notificacao.getNotificacao());
p.setString(2, notificacao.getDataCriacao());
p.setString(3, notificacao.getUsuarioId());
p.execute();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean atualizar(Notificacao notificacao){
String comando = "UPDATE notificacoes SET notificacao=?";
comando += " WHERE id=?";
PreparedStatement p;
try {
p = this.conexao.prepareStatement(comando);
p.setString(1, notificacao.getNotificacao());
p.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean deletar(Notificacao notificacao) {
String comando = "DELETE FROM notificacoes WHERE notificacao = '" + notificacao +"'";
Statement p;
try {
p = this.conexao.createStatement();
p.execute(comando);
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public List<Notificacao> buscar(String busca) {
String comando = "SELECT * FROM notificacoes";
System.out.println(comando);
List<Notificacao> listNotificacao = new ArrayList<Notificacao>();
Notificacao notificacao = null;
try {
Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(comando);
while (rs.next()) {
notificacao = new Notificacao();
String notif = rs.getString("notificacao");
String datacriacao = notificacao.converteNascimentoParaFrontend(rs.getString("dataCriacao"));
String usuarioid = rs.getString("usuarioId");
notificacao.setNotificacao(notif);
notificacao.setDataCriacao(datacriacao);
notificacao.setUsuarioId(usuarioid);
listNotificacao.add(notificacao);
}
} catch (Exception e) {
e.printStackTrace();
}
return listNotificacao;
}
}
| [
"kalylhenings@gmail.com"
] | kalylhenings@gmail.com |
0ef243c5c066b19a60dabdf0cc9fd40aa06da4f6 | ad7497c62b6bf9e40e241de1044a4bef63a34aa7 | /skysail.server/src/de/twenty11/skysail/server/um/domain/PasswordsMatchValidator.java | cd9c638b4ac3c0fcf097ccb1d725241516671c24 | [
"Apache-2.0"
] | permissive | evandor/skysail-framework | f99dbaceb6383ce899077cdf0acd40787acbca03 | 480df6f043ab85328ecc6cc38958c501edbc2374 | refs/heads/master | 2021-01-17T08:40:00.758281 | 2016-11-21T07:50:38 | 2016-11-21T07:50:38 | 28,823,015 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 651 | java | package de.twenty11.skysail.server.um.domain;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, Registration> {
@Override
public void initialize(PasswordsMatch passwordParameters) {
}
@Override
public boolean isValid(Registration registration, ConstraintValidatorContext arg1) {
if (registration.getPassword() == null && registration.getPwdRepeated() == null) {
return true;
}
return registration.getPassword().equals(registration.getPwdRepeated());
}
}
| [
"evandor@gmail.com"
] | evandor@gmail.com |
19778fa81690f994961fe9edb5dec81a02d7f0b4 | 09683aaffcd781992f89746f5be5bebcf8cf864b | /src/main/java/com/github/dwladdimiroc/stormMonitor/util/Metrics.java | b2026a6a38d8f916a551e5282862e561adea1a1e | [] | no_license | dwladdimiroc/storm-monitor | 3740465ef6608e85b01f09e6a75d3cbf39b36236 | a6a155b3fdacb07e752b53943ec9ef813cfc0fce | refs/heads/master | 2021-03-08T05:20:27.705797 | 2020-09-28T08:10:32 | 2020-09-28T08:10:32 | 246,320,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,709 | java | package com.github.dwladdimiroc.stormMonitor.util;
import com.github.dwladdimiroc.stormMonitor.StormAdaptative;
import com.github.dwladdimiroc.stormMonitor.eda.Stats;
import com.github.dwladdimiroc.stormMonitor.eda.TopologyApp;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class Metrics {
private final static Logger logger = LoggerFactory.getLogger(Metrics.class);
private final boolean showLogger = false;
static final MetricRegistry metricsRegistry = new MetricRegistry();
private Map<String, Long> input;
private Map<String, Long> throughput;
private Map<String, Long> queue;
private Map<String, Double> latency;
private Map<String, Double> utilization;
private Map<String, Integer> replication;
private CsvReporter reporter;
private Config confMape;
public Metrics(String pathFolder, Config confMape) {
new File(pathFolder).mkdir();
this.input = new HashMap<String, Long>();
this.throughput = new HashMap<String, Long>();
this.queue = new HashMap<String, Long>();
this.latency = new HashMap<String, Double>();
this.utilization = new HashMap<String, Double>();
this.replication = new HashMap<String, Integer>();
this.confMape = confMape;
this.reporter = CsvReporter.forRegistry(metricsRegistry).formatFor(Locale.US).convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.SECONDS).build(new File(pathFolder));
}
public void start() {
// try {
// Thread.sleep(1000);
this.reporter.start(this.confMape.getWindowMonitor(), TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
public void createStatsBolt(final String nameBolt) {
this.throughput.put(nameBolt, Long.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@throughput"),
new Gauge<Long>() {
@Override
public Long getValue() {
return throughput.get(nameBolt);
}
});
this.queue.put(nameBolt, Long.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@queue"),
new Gauge<Long>() {
@Override
public Long getValue() {
return queue.get(nameBolt);
}
});
this.latency.put(nameBolt, Double.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@latency"),
new Gauge<Double>() {
@Override
public Double getValue() {
return latency.get(nameBolt);
}
});
this.utilization.put(nameBolt, Double.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@utilization"),
new Gauge<Double>() {
@Override
public Double getValue() {
return utilization.get(nameBolt);
}
});
this.replication.put(nameBolt, Integer.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@replication"),
new Gauge<Integer>() {
@Override
public Integer getValue() {
return replication.get(nameBolt);
}
});
}
public void createStatsSpout(final String nameSpout) {
this.input.put(nameSpout, Long.valueOf(0));
Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameSpout + "@input"),
new Gauge<Long>() {
@Override
public Long getValue() {
return input.get(nameSpout);
}
});
}
public void sendStats(TopologyApp topologyApp) {
for (String bolt : topologyApp.keySet()) {
sendStatsBolt(bolt, topologyApp.getStats(bolt));
}
for (String spout : topologyApp.getInputStats().keyInput()) {
sendStatsSpout(spout, topologyApp.getInputStats().getStreamInput(spout));
}
topologyApp.getInputStats().clear();
}
private void sendStatsSpout(String spout, long input) {
if (showLogger)
logger.info("[Spout={}],[Input={}]", spout, input);
this.input.put(spout, input);
}
private void sendStatsBolt(String bolt, Stats statsBolt) {
if (showLogger)
logger.info("[Bolt={}],[Executed={}],[LastSimple={}],[Queue={}],[Raw={},{}]", bolt, statsBolt.getThroughput(),
statsBolt.getLastSample(), statsBolt.getQueue(), statsBolt.getTimeAvg(), statsBolt.getExecutedTotal());
this.throughput.put(bolt, statsBolt.getThroughput());
this.queue.put(bolt, statsBolt.getQueue());
this.latency.put(bolt, statsBolt.getTimeAvg());
this.utilization.put(bolt, statsBolt.getLastSample());
this.replication.put(bolt, statsBolt.getReplicas());
}
}
| [
"daniel.wladdimiro@lip6.fr"
] | daniel.wladdimiro@lip6.fr |
3ad5a5139d807e16e1d2653dd702981387538171 | 06f700275881d252d5994cfb2d6f51316e1a2ab1 | /build/generated-sources/jax-ws/com/ilient/api/ApiServiceRequestAttachment.java | 48d7566514ee58f14b092b4b2c450c7021cdd18f | [] | no_license | danielshsp/sqlConn | 6418aed765c3d94f8b53fc6b981db0ed699cdeac | 9ec1eaed8618af400e1e5cc55e1a63d3bcd00818 | refs/heads/master | 2020-04-27T22:05:53.686993 | 2019-03-09T17:13:22 | 2019-03-09T17:13:22 | 174,723,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,805 | java |
package com.ilient.api;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for apiServiceRequestAttachment complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="apiServiceRequestAttachment">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fileContent" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
* <element name="fileDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="fileId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="fileName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="srId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "apiServiceRequestAttachment", propOrder = {
"fileContent",
"fileDate",
"fileId",
"fileName",
"srId"
})
public class ApiServiceRequestAttachment {
protected byte[] fileContent;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar fileDate;
protected String fileId;
protected String fileName;
protected int srId;
/**
* Gets the value of the fileContent property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getFileContent() {
return fileContent;
}
/**
* Sets the value of the fileContent property.
*
* @param value
* allowed object is
* byte[]
*/
public void setFileContent(byte[] value) {
this.fileContent = value;
}
/**
* Gets the value of the fileDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFileDate() {
return fileDate;
}
/**
* Sets the value of the fileDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFileDate(XMLGregorianCalendar value) {
this.fileDate = value;
}
/**
* Gets the value of the fileId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFileId() {
return fileId;
}
/**
* Sets the value of the fileId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFileId(String value) {
this.fileId = value;
}
/**
* Gets the value of the fileName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFileName() {
return fileName;
}
/**
* Sets the value of the fileName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFileName(String value) {
this.fileName = value;
}
/**
* Gets the value of the srId property.
*
*/
public int getSrId() {
return srId;
}
/**
* Sets the value of the srId property.
*
*/
public void setSrId(int value) {
this.srId = value;
}
}
| [
"gkx638"
] | gkx638 |
b83d806306faa1bfbb0428e76cc08084e2f68e77 | 7e3dee96374e6c5316b937196a7e2036307a9059 | /android-sdk/src/main/java/com/sensorberg/sdk/model/realm/RealmScan.java | 975b468c4f0caee8c63525e2a75b0bfa3e5e15a2 | [
"MIT"
] | permissive | passavent7/android-sdk | d43ba27ac678166697b534de94b7fe81a27af119 | e5b322ace12544434901d3a1fa9f292c160d577a | refs/heads/master | 2020-12-26T04:37:35.772802 | 2015-06-04T09:39:15 | 2015-06-04T09:39:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,291 | java | package com.sensorberg.sdk.model.realm;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.sensorberg.sdk.model.ISO8601TypeAdapter;
import com.sensorberg.sdk.scanner.ScanEvent;
import com.sensorberg.sdk.scanner.ScanEventType;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.RealmResults;
public class RealmScan extends RealmObject {
private long eventTime;
private boolean isEntry;
private String proximityUUID;
private int proximityMajor;
private int proximityMinor;
private long sentToServerTimestamp;
private long createdAt;
public static RealmScan from(ScanEvent scanEvent, Realm realm, long now) {
RealmScan value = realm.createObject(RealmScan.class);
value.setEventTime(scanEvent.getEventTime());
value.setEntry(scanEvent.getEventMask() == ScanEventType.ENTRY.getMask());
value.setProximityUUID(scanEvent.getBeaconId().getUuid().toString());
value.setProximityMajor(scanEvent.getBeaconId().getMajorId());
value.setProximityMinor(scanEvent.getBeaconId().getMinorId());
value.setSentToServerTimestamp(RealmFields.Scan.NO_DATE);
value.setCreatedAt(now);
return value;
}
public boolean isEntry() {
return isEntry;
}
public void setEntry(boolean isEntry) {
this.isEntry = isEntry;
}
public String getProximityUUID() {
return proximityUUID;
}
public void setProximityUUID(String proximityUUID) {
this.proximityUUID = proximityUUID;
}
public int getProximityMajor() {
return proximityMajor;
}
public void setProximityMajor(int proximityMajor) {
this.proximityMajor = proximityMajor;
}
public int getProximityMinor() {
return proximityMinor;
}
public void setProximityMinor(int proximityMinor) {
this.proximityMinor = proximityMinor;
}
public long getEventTime() {
return eventTime;
}
public void setEventTime(long eventTime) {
this.eventTime = eventTime;
}
public long getSentToServerTimestamp() {
return sentToServerTimestamp;
}
public void setSentToServerTimestamp(long sentToServerTimestamp) {
this.sentToServerTimestamp = sentToServerTimestamp;
}
public String getPid(){
return this.getProximityUUID().replace("-", "") + String.format("%1$05d%2$05d", this.getProximityMajor() , this.getProximityMinor());
}
public int getTrigger(){
return isEntry() ? ScanEventType.ENTRY.getMask() : ScanEventType.EXIT.getMask();
}
public static Type ADAPTER_TYPE() {
try {
return Class.forName("io.realm.RealmScanRealmProxy");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("io.realm.RealmScanRealmProxy was not found");
}
}
public static RealmResults<RealmScan> notSentScans(Realm realm){
RealmQuery<RealmScan> scans = realm.where(RealmScan.class)
.equalTo(RealmFields.Scan.sentToServerTimestamp, RealmFields.Scan.NO_DATE);
return scans.findAll();
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public static void maskAsSent(List<RealmScan> scans, Realm realm, long now, long cacheTtl) {
if (scans.size() > 0) {
realm.beginTransaction();
for (int i = scans.size() - 1; i >= 0; i--) {
scans.get(i).setSentToServerTimestamp(now);
}
realm.commitTransaction();
}
removeAllOlderThan(realm, now, cacheTtl);
}
public static void removeAllOlderThan(Realm realm, long now, long cacheTtl) {
RealmResults<?> actionsToDelete = realm.where(RealmScan.class)
.lessThan(RealmFields.Scan.createdAt, now - cacheTtl)
.not().equalTo(RealmFields.Scan.sentToServerTimestamp, RealmFields.Action.NO_DATE)
.findAll();
if (actionsToDelete.size() > 0){
realm.beginTransaction();
for (int i = actionsToDelete.size() - 1; i >= 0; i--) {
actionsToDelete.get(i).removeFromRealm();
}
realm.commitTransaction();
}
}
public static class RealmScanObjectTypeAdapter extends TypeAdapter<RealmScan> {
@Override
public void write(JsonWriter out, RealmScan value) throws IOException {
out.beginObject();
out.name("pid").value(value.getPid());
out.name("trigger").value(value.getTrigger());
out.name("dt");
ISO8601TypeAdapter.DATE_ADAPTER.write(out, new Date(value.getEventTime()));
out.endObject();
}
@Override
public RealmScan read(JsonReader in) throws IOException {
throw new IllegalArgumentException("you must not use this to read a RealmScanObject");
}
}
}
| [
"falko@briefhansa.de"
] | falko@briefhansa.de |
21cd33d1923b75c991a41641cc6b734dc5459baa | 2deeed0d4f5d78aafe0b1174529326b8d3fb1ab2 | /android/app/src/main/java/thevolt/flutter_screen/MainActivity.java | 6531384496c2a3a6725773d9c1bf87da33bdf109 | [] | no_license | Ranshikha/flutter_delivery_screen | 7077a423a7a9d6e1fc92505ef48c6abbd0f38084 | 9bd157f9dec4a3a3845c7d7be67c78d53dde30d4 | refs/heads/master | 2020-12-14T00:51:22.357795 | 2020-01-21T16:30:24 | 2020-01-21T16:30:24 | 234,582,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 432 | java | package thevolt.flutter_screen;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
}
| [
"ranshikha404@gmail.com"
] | ranshikha404@gmail.com |
64231840e7e0bd50e1f3bedb1ff51261893b2b67 | 6a59e5bd764735c86eeaac4225e6705a07e5e8d0 | /app/src/main/java/com/app/cellular/mobile/Navigation_main/Address_Ontrack.java | 40da554adc4499cd8b8b1d4da832d97d1bc5c9ea | [] | no_license | priyankagiri14/cellular_mobile | 4290720b42fcd710e271fb049b442b27c5f02d4b | 64088000aefe836383517713dae4bb719c8e2c3b | refs/heads/master | 2020-09-25T14:02:56.788142 | 2020-02-18T12:00:34 | 2020-02-18T12:00:34 | 226,018,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,589 | java | package com.app.cellular.mobile.Navigation_main;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
import com.app.cellular.mobile.AboutActivity;
import com.app.cellular.mobile.R;
public class Address_Ontrack extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
/**
* This method is initializing all the design components which will be used further for some functionalty.
* @param savedInstanceState
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.address_ontrack);
DrawerLayout drawer = findViewById(R.id.address_drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
toolbar=findViewById(R.id.toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
/**
* This function will return the boolean value for the menu item to performm some functionality according to the code written in the conditions.
* @param item
* @return this function returns the boolean value (true or false)
*/
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_login) {
// Handle the camera action
Intent i=new Intent(this, Navigation_Main.class);
startActivity(i);
} else if (id == R.id.nav_contacts) {
Intent i1=new Intent(this, Contact_Ontrack.class);
startActivity(i1);
} else if (id == R.id.nav_address) {
}else if (id == R.id.aboutdrawer) {
Intent i1=new Intent(this, AboutActivity.class);
startActivity(i1);
}
DrawerLayout drawer = findViewById(R.id.address_drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| [
"priyanka@ontrackis.com"
] | priyanka@ontrackis.com |
f99ee953719ad246ac3be3c7fec4c8a0e5c428ec | b239ac53ff301239a8838ad2c0424f23bec9a6f0 | /jgrzesiak_mod4/deitelfig16_15/StaticCharMethods.java | 0a0c784b73ca0c51d8e887ac98f5016de8f6ccb9 | [] | no_license | jhgrz/itp120 | 8e4a00589621f0f80b4af8f5f494b19341d7e8d4 | 3aff341b5bdfc70158d9083d1046da188273496b | refs/heads/master | 2021-01-16T23:17:23.404018 | 2017-02-22T16:50:13 | 2017-02-22T16:50:13 | 82,817,285 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,564 | java | package deitelfig16_15;
// Fig. 16.15: StaticCharMethods.java
// Character static methods for testing characters and converting case.
import java.util.Scanner;
public class StaticCharMethods
{
public static void main( String[] args )
{
Scanner scanner = new Scanner( System.in ); // create scanner
System.out.println( "Enter a character and press Enter" );
String input = scanner.next();
char c = input.charAt( 0 ); // get input character
// display character info
System.out.printf( "is defined: %b\n", Character.isDefined( c ) );
System.out.printf( "is digit: %b\n", Character.isDigit( c ) );
System.out.printf( "is first character in a Java identifier: %b\n",
Character.isJavaIdentifierStart( c ) );
System.out.printf( "is part of a Java identifier: %b\n",
Character.isJavaIdentifierPart( c ) );
System.out.printf( "is letter: %b\n", Character.isLetter( c ) );
System.out.printf(
"is letter or digit: %b\n", Character.isLetterOrDigit( c ) );
System.out.printf(
"is lower case: %b\n", Character.isLowerCase( c ) );
System.out.printf(
"is upper case: %b\n", Character.isUpperCase( c ) );
System.out.printf(
"to upper case: %s\n", Character.toUpperCase( c ) );
System.out.printf(
"to lower case: %s\n", Character.toLowerCase( c ) );
} // end main
} // end class StaticCharMethods
/**************************************************************************
* (C) Copyright 1992-2012 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| [
"root@Johns-MacBook-Pro.local"
] | root@Johns-MacBook-Pro.local |
15aed1133ab774bf2df501f8f1a24f891c2bb301 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-large-project/src/test/java/org/gradle/test/performancenull_28/Testnull_2771.java | ebe4449eea62503e167992945f7434d21d3decbf | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 304 | java | package org.gradle.test.performancenull_28;
import static org.junit.Assert.*;
public class Testnull_2771 {
private final Productionnull_2771 production = new Productionnull_2771("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
a9b1a07c6fd3456015391a0a794103a7c9683b85 | c28d079399340f12b9655868113d641bc8b89209 | /src/main/java/model/WeatherReportResponse.java | bc7c504f2e6c2446deda8db38498b5dd5693bfbb | [] | no_license | chiragNarkhede/Weather-Reporting-Comparator | 9c6655a14f87cd6a60ac463aa1acb9d96abad6c5 | a581a42e3958d76f43d2a3989100fc4a90b7cd05 | refs/heads/master | 2022-12-11T20:26:10.098497 | 2020-08-13T14:19:29 | 2020-08-13T14:19:29 | 286,822,677 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 843 | java | package model;
import java.util.List;
import model.WeatherDetails;
import model.WindDetails;
import model.MainDetails;
/* Create Object for JSON response
* which received from API
*/
public class WeatherReportResponse {
public List<WeatherDetails> weather ;
public MainDetails main;
public WindDetails wind;
public String name;
public MainDetails getMain() {
return main;
}
public void setMain(MainDetails main) {
this.main = main;
}
public WindDetails getWind() {
return wind;
}
public void setWind(WindDetails wind) {
this.wind = wind;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<WeatherDetails> getWeather() {
return weather;
}
public void setWeather(List<WeatherDetails> weather) {
this.weather = weather;
}
}
| [
"chiragnarkhede178@gmail.com"
] | chiragnarkhede178@gmail.com |
dc33b569a19994003c3bd125019504fcbf22ac10 | b080e60bf6e61a75d40d9f7644ae34418861de70 | /src/mc/alk/arena/controllers/messaging/MatchMessager.java | 0cd89bb70498b1b91d3d80e013a7dd8790f87f43 | [] | no_license | Kirill20/BattleArena | 4e3de390d8c4fa36507a77c371435dd5f23d652c | 79d6c5d166ad8fa6bcb513e2008961ef46b4a0cc | refs/heads/master | 2021-01-18T10:42:44.622387 | 2013-08-08T05:38:25 | 2013-08-08T05:38:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,139 | java | package mc.alk.arena.controllers.messaging;
import java.util.Collection;
import java.util.List;
import mc.alk.arena.competition.match.Match;
import mc.alk.arena.objects.ArenaPlayer;
import mc.alk.arena.objects.MatchState;
import mc.alk.arena.objects.messaging.AnnouncementOptions;
import mc.alk.arena.objects.messaging.Channel;
import mc.alk.arena.objects.teams.ArenaTeam;
public class MatchMessager {
MatchMessageHandler impl;
final AnnouncementOptions bos;
boolean silent = false;
public MatchMessager(Match match){
this.impl = new MatchMessageImpl(match);
this.bos = match.getParams().getAnnouncementOptions();
}
private Channel getChannel(MatchState state) {
if (silent) return Channel.NullChannel;
return bos != null && bos.hasOption(true,state) ? bos.getChannel(true,state) : AnnouncementOptions.getDefaultChannel(true,state);
}
public void sendOnBeginMsg(List<ArenaTeam> teams) {
try{impl.sendOnBeginMsg(getChannel(MatchState.ONBEGIN), teams);}catch(Exception e){e.printStackTrace();}
}
public void sendOnPreStartMsg(List<ArenaTeam> teams) {
sendOnPreStartMsg(teams, getChannel(MatchState.ONPRESTART));
}
public void sendOnPreStartMsg(List<ArenaTeam> teams, Channel serverChannel) {
try{impl.sendOnPreStartMsg(serverChannel, teams);}catch(Exception e){e.printStackTrace();}
}
public void sendOnStartMsg(List<ArenaTeam> teams) {
try{impl.sendOnStartMsg(getChannel(MatchState.ONSTART), teams);}catch(Exception e){e.printStackTrace();}
}
public void sendOnVictoryMsg(Collection<ArenaTeam> winners, Collection<ArenaTeam> losers) {
try{impl.sendOnVictoryMsg(getChannel(MatchState.ONVICTORY), winners,losers);}catch(Exception e){e.printStackTrace();}
}
public void sendOnDrawMessage(Collection<ArenaTeam> drawers, Collection<ArenaTeam> losers) {
try{impl.sendOnDrawMsg(getChannel(MatchState.ONVICTORY), drawers, losers);}catch(Exception e){e.printStackTrace();}
}
public void sendYourTeamNotReadyMsg(ArenaTeam t1) {
try{impl.sendYourTeamNotReadyMsg(t1);}catch(Exception e){e.printStackTrace();}
}
public void sendOtherTeamNotReadyMsg(ArenaTeam t1) {
try{impl.sendOtherTeamNotReadyMsg(t1);}catch(Exception e){e.printStackTrace();}
}
public void sendOnIntervalMsg(int remaining, Collection<ArenaTeam> currentLeaders) {
try{impl.sendOnIntervalMsg(getChannel(MatchState.ONMATCHINTERVAL), currentLeaders, remaining);}catch(Exception e){e.printStackTrace();}
}
public void sendTimeExpired() {
try{impl.sendTimeExpired(getChannel(MatchState.ONMATCHTIMEEXPIRED));}catch(Exception e){e.printStackTrace();}
}
public void setMessageHandler(MatchMessageHandler mc) {
this.impl = mc;
}
public MatchMessageHandler getMessageHandler() {
return impl;
}
public void setSilent(boolean silent){
this.silent = silent;
}
public void sendAddedToTeam(ArenaTeam team, ArenaPlayer player) {
try{impl.sendAddedToTeam(team,player);}catch(Exception e){e.printStackTrace();}
}
public void sendCountdownTillPrestart(int remaining) {
try{impl.sendCountdownTillPrestart(getChannel(MatchState.ONCOUNTDOWNTOEVENT), remaining);}
catch(Exception e){e.printStackTrace();}
}
}
| [
"alkarin.v@gmail.com"
] | alkarin.v@gmail.com |
56b7d912d1dc37c38eaad76337a80d60f34dafee | 089469c624662b3598ca264ef5564cd96656105d | /app/src/main/java/com/android/github/souravbera/e_commerce/ConfirmFinalOrderActivity.java | 1f97cf6566203c3e05c991df502e0b4d9ff55842 | [] | no_license | nano-research-labs/E-Commerce-Clothes-App | 065b10664e03d23af50ec7408cc14b27d958a3c2 | 7221b08e0193c43f09ab4abfe1f987226de2fca8 | refs/heads/master | 2023-02-05T06:57:36.748563 | 2020-12-23T13:24:13 | 2020-12-23T13:24:13 | 296,399,881 | 0 | 1 | null | 2020-12-23T13:24:15 | 2020-09-17T17:44:04 | Java | UTF-8 | Java | false | false | 5,130 | java | package com.android.github.souravbera.e_commerce;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.android.github.souravbera.e_commerce.Prevalent.Prevalent;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rey.material.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ConfirmFinalOrderActivity extends AppCompatActivity {
private EditText nameEditText, phoneEditText, addressEditText, cityEditText;
private Button confirmOrderbtn;
private String totalAmount= "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_final_order);
totalAmount= getIntent().getStringExtra("Total Price");
Toast.makeText(this,"Total Price= Rs."+totalAmount,Toast.LENGTH_SHORT).show();
confirmOrderbtn= findViewById(R.id.confirm_final_btn);
nameEditText= findViewById(R.id.shippment_name);
addressEditText= findViewById(R.id.shippment_address);
cityEditText= findViewById(R.id.shippment_city);
phoneEditText= findViewById(R.id.shippment_phone);
confirmOrderbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Check();
}
});
}
private void Check()
{
if(TextUtils.isEmpty(nameEditText.getText().toString()))
{
Toast.makeText(this, "Please Provide your full Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(addressEditText.getText().toString()))
{
Toast.makeText(this, "Please Provide your Address", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(cityEditText.getText().toString()))
{
Toast.makeText(this, "Please Provide your City Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phoneEditText.getText().toString()))
{
Toast.makeText(this, "Please Confirm your Phone Number", Toast.LENGTH_SHORT).show();
}
else{
ConfirmOrder();
}
}
private void ConfirmOrder()
{
final String saveCurrentDate, saveCurrentTime;
Calendar calForData= Calendar.getInstance();
SimpleDateFormat currentDate= new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate= currentDate.format(calForData.getTime());
SimpleDateFormat currentTime= new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime= currentTime.format(calForData.getTime());
final DatabaseReference ordersRef= FirebaseDatabase.getInstance().getReference()
.child("Orders")
.child(Prevalent.currentOnlineUser.getPhone());
HashMap<String, Object> orderMap= new HashMap<>();
orderMap.put("totalAmount", totalAmount);
orderMap.put("name",nameEditText.getText().toString());
orderMap.put("phone",phoneEditText.getText().toString());
orderMap.put("address",addressEditText.getText().toString());
orderMap.put("city",cityEditText.getText().toString());
orderMap.put("date",saveCurrentDate);
orderMap.put("time",saveCurrentTime);
orderMap.put("state","not shipped");
ordersRef.updateChildren(orderMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful())
{
FirebaseDatabase.getInstance().getReference()
.child("Cart List")
.child("User View")
.child(Prevalent.currentOnlineUser.getPhone())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(ConfirmFinalOrderActivity.this, "your final Order has been placed successfully",Toast.LENGTH_SHORT).show();
Intent intent= new Intent(ConfirmFinalOrderActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
}
}
});
}
}
| [
"sauravberaiit@gmail.com"
] | sauravberaiit@gmail.com |
a3a7900f392ea38ecc0ba3f21aee4119d586446c | f18fcc1981d16bc49a9c171b4b13a5a83aa055d1 | /src/au/com/billingbuddy/business/objects/ProcessSubscriptionsMDTR.java | 1e5966833922c6f33665139e1e66cf930d539408 | [] | no_license | edicsonm/BillingBuddyServer | ec7477770c026dcb37b5049f0bc29eed0fa832f1 | f6a0afa8e4dc865e46ce14ae6c06644ec38bdb24 | refs/heads/master | 2021-01-02T09:43:46.834643 | 2015-05-29T11:46:53 | 2015-05-29T11:46:53 | 28,280,646 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 39,489 | java | package au.com.billingbuddy.business.objects;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import au.com.billigbuddy.utils.ErrorManager;
import au.com.billingbuddy.common.objects.ConfigurationSystem;
import au.com.billingbuddy.common.objects.Utilities;
import au.com.billingbuddy.connection.objects.MySQLTransaction;
import au.com.billingbuddy.dao.objects.SubscriptionsToProcessDAO;
import au.com.billingbuddy.dao.objects.ErrorLogDAO;
import au.com.billingbuddy.dao.objects.SubmittedProcessLogDAO;
import au.com.billingbuddy.exceptions.objects.SubscriptionsToProcessDAOException;
import au.com.billingbuddy.exceptions.objects.ErrorLogDAOException;
import au.com.billingbuddy.exceptions.objects.MySQLConnectionException;
import au.com.billingbuddy.exceptions.objects.MySQLTransactionException;
import au.com.billingbuddy.exceptions.objects.SubmittedProcessLogDAOException;
import au.com.billingbuddy.exceptions.objects.SubscriptionsMDTRException;
import au.com.billingbuddy.loggers.LoggerDeclined;
import au.com.billingbuddy.loggers.LoggerProcessed;
import au.com.billingbuddy.vo.objects.SubscriptionsToProcessVO;
import au.com.billingbuddy.vo.objects.ErrorLogVO;
import au.com.billingbuddy.vo.objects.SubmittedProcessLogVO;
import com.stripe.Stripe;
import com.stripe.exception.APIConnectionException;
import com.stripe.exception.APIException;
import com.stripe.exception.AuthenticationException;
import com.stripe.exception.CardException;
import com.stripe.exception.InvalidRequestException;
import com.stripe.model.Charge;
public class ProcessSubscriptionsMDTR {
private static ProcessSubscriptionsMDTR instance = null;
private HashMap<String, ProcessSubscription> hashThreadsProcessSubscription = new HashMap<String, ProcessSubscription>();
private SubmittedProcessLogVO submittedProcessLogVO = new SubmittedProcessLogVO();
private MySQLTransaction mySQLTransaction = null;
private String processName = "ProcessSubscriptions";
private long initialTime;
private long finalTime;
private long initialTimeThreadsCreation;
private long finalTimeThreadsCreation;
private boolean writeInErrorLog = false;
private String logFileName;
private boolean answer = true;
private boolean unpaids = false;
private boolean noUpdated = false;
private int numberUnpaids = 0;
private int numberNoUpdated = 0;
private int numberUpdated = 0;
private int numberCharged = 0;
private int numberSent = 0;
private int numberTransactionsToProcess = 0;
private boolean swErrorOnlevel1 = false;
private boolean errorFileExist = false;
private ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess = null;
/*"trace", "debug", "info", "warn", "error" and "fatal"*/
private static final Logger logger = LogManager.getLogger(ProcessSubscriptionsMDTR.class);
private static final Logger loggerProcessed = LoggerProcessed.logger;
private static final Logger loggerDeclined = LoggerDeclined.logger;
public static synchronized ProcessSubscriptionsMDTR getInstance() {
if (instance == null) {
instance = new ProcessSubscriptionsMDTR();
}
return instance;
}
private ProcessSubscriptionsMDTR() {
Stripe.apiKey = ConfigurationSystem.getKey("apiKey");
}
public HashMap<String,String> executeSubscriptionsToProcess() throws SubscriptionsMDTRException {
HashMap<String,String> resp = null;
initVariables();
try {
SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO();
logger.info("/*****************************************************************************************************/");
logger.info("/**********************INICIANDO EL PROCESO DE PROC_EXECUTE_SUBSCRIPTIONS_PROCESS *********************/");
logger.info("/******************************************************************************************************/");
resp = subscriptionsToProcessDAO.execute();
if(resp != null){
Set<String> set = resp.keySet();
for (String key : set) {
logger.info(key+" --> "+resp.get(key));
}
logger.info("/*****************************************************************************************************/");
logger.info("/************************TERMINA EL PROCESO DE PROC_EXECUTE_SUBSCRIPTIONS_PROCESS*********************/");
logger.info("/*****************************************************************************************************/");
if(resp.get("P_ERROR_CODE").equalsIgnoreCase("000")){
try {
boolean respuesta = instance.proccesSubscriptions();
if (!respuesta){//Se presento algun error
if(instance.isWriteInErrorLog()){
logger.info("Se presentaron errores, la informacion se encuentra almacenada en el archivo " + instance.getLogFileName());
logger.info("Verifique las causas de los errores y ejecute el proceso de recuperacion de errores.");
}
}
} catch (SubscriptionsMDTRException e) {
logger.info(e.getMessage());
logger.error(e);
}
}else{
try {
JSONObject informationDetails = new JSONObject();
informationDetails.putAll(resp);
submittedProcessLogVO.setProcessName(processName);
submittedProcessLogVO.setStartTime(Calendar.getInstance().getTime().toString());
submittedProcessLogVO.setStatusProcess("Error");
submittedProcessLogVO.setInformation(informationDetails.toJSONString());
SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO();
submittedProcessLogDAO.insert(submittedProcessLogVO);
} catch (SubmittedProcessLogDAOException e) {
throw new SubscriptionsMDTRException(e);
}
logger.info("Se presentaron errores");
logger.info(resp.get("P_ERROR_TEXT"));
}
}else{
logger.info("/*****************************************************************************************************/");
logger.info("/**************************TERMINA EL PROCESO DE EXECUTESUBSCRIPTIONSTOPROCESS************************/");
logger.info("/*****************************************************************************************************/");
}
} catch (SubscriptionsToProcessDAOException e) {
logger.info(e.getMessage());
logger.error(e);
} catch (MySQLConnectionException e) {
logger.info(e.getMessage());
logger.error(e);
}
return resp;
}
private void initVariables() {
numberUnpaids = 0;
numberNoUpdated = 0;
numberUpdated = 0;
numberCharged = 0;
numberSent = 0;
numberTransactionsToProcess = 0;
swErrorOnlevel1 = false;
errorFileExist = false;
}
public synchronized boolean proccesSubscriptions() throws SubscriptionsMDTRException {
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************INICIANDO EL PROCESO DE SUBSCRIPCIONES******************************/");
logger.info("/*****************************************************************************************************/");
setLogFileName(ConfigurationSystem.getKey("urlSaveErrorFilesSaveInformationSubscriptions") + processName + " - "+ Calendar.getInstance().getTime());
loggerProcessed.info("Iniciando trazas sobre el procesamiento " + getLogFileName());
loggerDeclined.info("Iniciando trazas sobre el procesamiento " + getLogFileName());
try {
initialTime = Calendar.getInstance().getTimeInMillis();
mySQLTransaction = new MySQLTransaction();
submittedProcessLogVO.setProcessName(processName);
submittedProcessLogVO.setStartTime(Calendar.getInstance().getTime().toString());
submittedProcessLogVO.setStatusProcess("OnExecution");
SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO();
submittedProcessLogDAO.insert(submittedProcessLogVO);
SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(mySQLTransaction);
listSubscriptionsToProcess = subscriptionsToProcessDAO.search();
if(listSubscriptionsToProcess != null && listSubscriptionsToProcess.size() > 0) {
numberTransactionsToProcess = listSubscriptionsToProcess.size();
initialTimeThreadsCreation = Calendar.getInstance().getTimeInMillis();
for (int position = 0; position<listSubscriptionsToProcess.size(); position++) {
SubscriptionsToProcessVO subscriptionsToProcessVO = listSubscriptionsToProcess.get(position);
int first = listSubscriptionsToProcess.indexOf(subscriptionsToProcessVO);
int last = listSubscriptionsToProcess.lastIndexOf(subscriptionsToProcessVO);
logger.trace(position+" "+subscriptionsToProcessVO.getSubscriptionId() + " first: " + first+" "+subscriptionsToProcessVO.getSubscriptionId() + " last: " + last);
ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcessAUX = new ArrayList<SubscriptionsToProcessVO>(listSubscriptionsToProcess.subList(first, last + 1));
position = last;
ProcessSubscription processSubscription = new ProcessSubscription(listSubscriptionsToProcessAUX, subscriptionsToProcessDAO, mySQLTransaction);
processSubscription.setName(subscriptionsToProcessVO.getSubscriptionId());
processSubscription.start();
hashThreadsProcessSubscription.put(processSubscription.getName(), processSubscription);
//
// finalTimeIndividual = Calendar.getInstance().getTimeInMillis();
// System.out.println("Tiempo total para procesar una subscripcion: " + (finalTimeIndividual-initialTimeIndividual) + " ms.");
}
finalTimeThreadsCreation = Calendar.getInstance().getTimeInMillis();
logger.info("Todos los hilos fueron creados en "+(finalTimeThreadsCreation-initialTimeThreadsCreation) + " ms. Se llama al proceso de monitoreo de los hilos creados");
MonitorProcessSubscription monitorProcessSubscription = new MonitorProcessSubscription(hashThreadsProcessSubscription);
monitorProcessSubscription.start();
} else {
finalTime = Calendar.getInstance().getTimeInMillis();
logger.info("No se encontraron subscripciones para procesar, el tiempo de ejecucion fue de " + (finalTime-initialTime) + " ms.");
try {
submittedProcessLogDAO = new SubmittedProcessLogDAO();
submittedProcessLogVO.setEndTime(Calendar.getInstance().getTime().toString());
if(answer) submittedProcessLogVO.setStatusProcess("Success");
else submittedProcessLogVO.setStatusProcess("Error");
JSONObject informationDetails = new JSONObject();
JSONObject information = new JSONObject();
information.put("unpaids", unpaids);
if(unpaids){
information.put("Recomendation","Run the \"Reprocess Process\" to resend the transactions to our processor.");
information.put("Information", "There are subscripcions that our procesor could not charge to some card holders. The uncharged transactions information are available in the tables Reprocess_X ");
informationDetails.put("InformationUnpaids", information);
informationDetails.put("ReprocessUnpaids", unpaids);
}
information = new JSONObject();
information.put("noUpdated", noUpdated);
if(noUpdated){
information.put("InformationNoUpdated", "There are subscripcions that were charged by our processor but the information was not updated in our systems.");
information.put("Recomendation","Check system logs to determine the causes of the error.");
informationDetails.put("InformationNoUpdated", information);
}
information = new JSONObject();
information.put("errorFileExist", errorFileExist);
if(errorFileExist){
information.put("Information", "Was created a file that content information about the subscripcions that could not Update.");
information.put("Recomendation","Execute the recovery process to update the correct field in our data base.");
information.put("FileLocation",getLogFileName());
informationDetails.put("ReprocessErrorFile", errorFileExist);
informationDetails.put("InformationErrorFileExist", information);
}
information = new JSONObject();
information.put("Total Time", ((finalTime-initialTime) + " ms."));
information.put("Total Transactions to process", numberTransactionsToProcess);
information.put("Total Transactions no updates on Data Base", numberNoUpdated);
information.put("Total Transactions updates on Data Base", numberUpdated);
information.put("Total Transactions unpaids", numberUnpaids);
information.put("Total Transactions chargeds", numberCharged);
information.put("Total Transactions sent to our procesor", numberSent);
information.put("Total Transactions keeped on file ", numberSent);
informationDetails.put("Resume ProcessExecution", information);
logger.info("Imprimiendo resumen de las transacciones procesadas cuando no se encuentra ninguna");
logger.info( "Total de numberNoUpdated: " + numberNoUpdated);
logger.info( "Total de numberUpdated: " + numberUpdated);
logger.info( "Total de numberUnpaids: " + numberUnpaids);
logger.info( "Total de numberCharged: " + numberCharged);
submittedProcessLogVO.setInformation(informationDetails.toJSONString());
submittedProcessLogDAO.update(submittedProcessLogVO);
mySQLTransaction.commit();
} catch (MySQLConnectionException e) {
e.printStackTrace();
} catch (MySQLTransactionException e) {
e.printStackTrace();
} catch (SubmittedProcessLogDAOException e) {
e.printStackTrace();
} finally{
try {
if(mySQLTransaction != null){
mySQLTransaction.close();
}
} catch (MySQLTransactionException e) {
e.printStackTrace();
}
}
}
} catch (MySQLConnectionException e) {
logger.error(e);
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/");
logger.info("/*****************************************************************************************************/");
throw new SubscriptionsMDTRException(e);
} catch (SubscriptionsToProcessDAOException e) {
logger.error(e);
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/");
logger.info("/*****************************************************************************************************/");
SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e);
subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.proccesDailySubscriptions.DailySubscriptionDAOException");
throw subscriptionsMDTRException;
} catch (MySQLTransactionException e) {
logger.error(e);
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/");
logger.info("/*****************************************************************************************************/");
SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e);
subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.proccesDailySubscriptions.MySQLTransactionException");
throw subscriptionsMDTRException;
} catch (SubmittedProcessLogDAOException e) {
logger.error(e);
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/");
logger.info("/*****************************************************************************************************/");
throw new SubscriptionsMDTRException(e);
}
return answer;
}
public ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess() throws SubscriptionsMDTRException{
ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess = null;
try {
SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO();
listSubscriptionsToProcess = subscriptionsToProcessDAO.search();
} catch (MySQLConnectionException e) {
e.printStackTrace();
SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e);
subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.listSubscriptionsToProcess.MySQLConnectionException");
throw subscriptionsMDTRException;
} catch (SubscriptionsToProcessDAOException e) {
e.printStackTrace();
SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e);
subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.listSubscriptionsToProcess.SubscriptionsToProcessDAOException e");
throw subscriptionsMDTRException;
}
return listSubscriptionsToProcess;
}
public synchronized void writeError(JSONObject errorDetails){
try{
writeInErrorLog = true;
File file = new File(getLogFileName());
if(!file.exists()){
file.createNewFile();
}
FileWriter fstream = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(errorDetails.toJSONString());
out.newLine();
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
public JSONObject reprocessFile(JSONObject jSONObjectParameters) throws SubscriptionsMDTRException {
logger.info("/*****************************************************************************************************/");
logger.info("/**********************INICIANDO PROCESO DE REPROCESAMIENTO DE ARCHIVO********************************/");
logger.info("/*****************************************************************************************************/");
MySQLTransaction mySQLTransaction = null;
File archivo = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
SubscriptionsToProcessVO subscriptionsToProcessVO = null;
int unProcessed = 0;
int processed = 0;
int totalRegistries = 0;
try {
mySQLTransaction = new MySQLTransaction();
mySQLTransaction.start();
SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(mySQLTransaction);
archivo = new File(jSONObjectParameters.get("fileName").toString());
fileReader = new FileReader(archivo);
bufferedReader = new BufferedReader(fileReader);
String linea;
while ((linea = bufferedReader.readLine()) != null) {
totalRegistries ++ ;
System.out.println(linea);
Object obj = JSONValue.parse(linea);
JSONObject jSONObject = (JSONObject) obj;
subscriptionsToProcessVO = new SubscriptionsToProcessVO();
subscriptionsToProcessVO.setStatus(jSONObject.get("Supr_Status").toString());
subscriptionsToProcessVO.setAuthorizerCode(jSONObject.get("Supr_AuthorizerCode")!= null? jSONObject.get("Supr_AuthorizerCode").toString():null);
subscriptionsToProcessVO.setAuthorizerReason(jSONObject.get("Supr_AuthorizerReason") != null ? jSONObject.get("Supr_AuthorizerReason").toString():null);
subscriptionsToProcessVO.setProcessAttempt(Integer.parseInt(jSONObject.get("Supr_ProcessAttempt").toString()));
subscriptionsToProcessVO.setId(jSONObject.get("Supr_ID").toString());
if(jSONObject.get("ReprocessTRX") != null && jSONObject.get("ReprocessTRX").toString().equalsIgnoreCase("true")){
try {
processed ++;
int resp = subscriptionsToProcessDAO.update(subscriptionsToProcessVO);
logger.debug("Reprocesando la subscripcion " + subscriptionsToProcessVO.getId()+",la respuesta obtenida es " + resp);
} catch (SubscriptionsToProcessDAOException e) {
mySQLTransaction.rollback();
throw new SubscriptionsMDTRException(e);
}
}else{
unProcessed ++;
}
}
if(totalRegistries == processed) {
SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO(mySQLTransaction);
submittedProcessLogVO.setId(jSONObjectParameters.get("idSubmittedProcessLog").toString());
submittedProcessLogVO = submittedProcessLogDAO.searchByID(submittedProcessLogVO);
Object obj = JSONValue.parse(submittedProcessLogVO.getInformation());
JSONObject jSONObjectInitial = (JSONObject) obj;
jSONObjectInitial.remove("ReprocessErrorFile");
JSONObject jSONObjectFinal = new JSONObject();
jSONObjectFinal.put("Total number of registries", totalRegistries);
jSONObjectFinal.put("Number of processed", processed);
jSONObjectFinal.put("Number of unProcessed", unProcessed);
jSONObjectFinal.put("Reprocessing date", Calendar.getInstance().getTime().toString());
JSONObject information = new JSONObject();
information.put("Initial Information", jSONObjectInitial);
information.put("Final Information", jSONObjectFinal);
submittedProcessLogVO.setInformation(information.toJSONString());
submittedProcessLogVO.setStatusProcess("Success");
submittedProcessLogDAO.update(submittedProcessLogVO);
jSONObjectParameters.put("answer", true);
}else {
if(processed == 0) jSONObjectParameters.put("errorType", "noRegistriesUpdated");
jSONObjectParameters.put("answer", false);
}
mySQLTransaction.commit();
// System.out.println("Termina el proceso satisfactoriamente");
jSONObjectParameters.put("unProcessed", unProcessed);
jSONObjectParameters.put("processed", processed);
jSONObjectParameters.put("totalRegistries", totalRegistries);
/*System.out.println("unProcessed: " + unProcessed);
System.out.println("processed: " + processed);
System.out.println("totalRegistries: " + totalRegistries);*/
logger.info("/*****************************************************************************************************/");
logger.info("/**********************TERMINANDO PROCESO DE REPROCESAMIENTO DE ARCHIVO*******************************/");
logger.info("/*****************************************************************************************************/");
return jSONObjectParameters;
} catch (MySQLTransactionException e) {
/*e.printStackTrace();*/
throw new SubscriptionsMDTRException(e);
} catch (MySQLConnectionException e) {
/*e.printStackTrace();*/
throw new SubscriptionsMDTRException(e);
} catch (FileNotFoundException e) {
/*e.printStackTrace();*/
throw new SubscriptionsMDTRException(e);
} catch (IOException e) {
/*e.printStackTrace();*/
throw new SubscriptionsMDTRException(e);
} catch (SubmittedProcessLogDAOException e) {
throw new SubscriptionsMDTRException(e);
} finally {
try {
if (null != fileReader) {
fileReader.close();
}
} catch (Exception e2) {
throw new SubscriptionsMDTRException(e2);
}
try {
if(mySQLTransaction != null){
mySQLTransaction.close();
}
} catch (MySQLTransactionException e) {
e.printStackTrace();
}
}
}
public void manageError(JSONObject jSONObject,String processName, String fileName) {
try {
ErrorLogDAO errorLogDAO = new ErrorLogDAO();
ErrorLogVO errorLogVO = new ErrorLogVO();
errorLogVO.setProcessName(processName);
errorLogVO.setInformation(jSONObject.toJSONString());
if(errorLogDAO.insert(errorLogVO) == 0){
ErrorManager.logDailySubscriptionErrorFile(fileName, jSONObject);
}
} catch (MySQLConnectionException e) {
e.printStackTrace();
} catch (ErrorLogDAOException e) {
e.printStackTrace();
}
}
public boolean isWriteInErrorLog() {
return writeInErrorLog;
}
public void setWriteInErrorLog(boolean writeInErrorLog) {
this.writeInErrorLog = writeInErrorLog;
}
public String getLogFileName() {
return logFileName;
}
public void setLogFileName(String logFileName) {
this.logFileName = logFileName;
}
class MonitorProcessSubscription extends Thread {
HashMap<String, ProcessSubscription> hashProcessSubscription = new HashMap<String, ProcessSubscription>();
public MonitorProcessSubscription(HashMap<String, ProcessSubscription> hashProcessSubscription){
this.hashProcessSubscription = hashProcessSubscription;
}
@Override
public void run() {
while (!hashProcessSubscription.isEmpty()) {
logger.info("Esperando la finalizacion de " + hashProcessSubscription.size() + " hilos ... " + "(numberSent: " + numberSent + ") (numberCharged: " +numberCharged+") (numberUnpaids: " + numberUnpaids+")");
try {
this.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
finalTime = Calendar.getInstance().getTimeInMillis();
logger.info("Termina el monitoreo de los hilos creados para procesar todas las subscripciones en " + (finalTime-initialTime) + " ms.");
}
}
class ProcessSubscription extends Thread {
private Map<String, Object> hashMapCharge = new HashMap<String, Object>();
private ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess;
private SubscriptionsToProcessDAO subscriptionsToProcessDAO;
private SubmittedProcessLogDAO submittedProcessLogDAO;
private MySQLTransaction mySQLTransaction;
private int level = 0;
private boolean unpaidSubGroup = false;
private boolean executeThread = true;
public ProcessSubscription(ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess, SubscriptionsToProcessDAO subscriptionsToProcessDAO, MySQLTransaction mySQLTransaction){
this.listSubscriptionsToProcess = listSubscriptionsToProcess;
this.subscriptionsToProcessDAO = subscriptionsToProcessDAO;
this.mySQLTransaction = mySQLTransaction;
}
@Override
public void run() {
logger.trace("El hilo " + this.getName() + " tiene " + listSubscriptionsToProcess.size() + " elementos para procesar");
while(executeThread){
try {
for (SubscriptionsToProcessVO subscriptionsToProcessVO : listSubscriptionsToProcess) {
logger.trace("Ejecutando " + subscriptionsToProcessVO.getId() + " de la subscripcion " + this.getName());
hashMapCharge.put("amount", Utilities.currencyToStripe(subscriptionsToProcessVO.getAmount(), subscriptionsToProcessVO.getCurrency()));
hashMapCharge.put("currency", subscriptionsToProcessVO.getCurrency());
hashMapCharge.put("description", "Charge for test@example.com");
Map<String, Object> hashMapCard = new HashMap<String, Object>();
hashMapCard.put("number", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getNumber());
hashMapCard.put("exp_month", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getExpMonth());
hashMapCard.put("exp_year", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getExpYear());
hashMapCard.put("cvc", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getCvv());
hashMapCard.put("name", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getName());
hashMapCharge.put("card", hashMapCard);
try {
subscriptionsToProcessVO.setStatus("Sending");
subscriptionsToProcessVO.setAuthorizerCode(null);
subscriptionsToProcessVO.setAuthorizerReason(null);
if (subscriptionsToProcessDAO.update(subscriptionsToProcessVO) != 0) {
logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXX Envia la subscripcion numero "+subscriptionsToProcessVO.getId());
level = 1;
try {
sent();
Charge charge = Charge.create(hashMapCharge);
subscriptionsToProcessVO.setStatus("Charged");
subscriptionsToProcessVO.setAuthorizerCode(charge.getId());
subscriptionsToProcessVO.setAuthorizerReason(null);
charged();
logger.debug("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged.");
// LoggerProcessed.logger.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged.");
loggerProcessed.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged.");
} catch (CardException e) {
unpaid();
unpaids = true;
unpaidSubGroup = true;
subscriptionsToProcessVO.setProcessAttempt(subscriptionsToProcessVO.getProcessAttempt() + 1);
subscriptionsToProcessVO.setStatus("Unpaid");
subscriptionsToProcessVO.setAuthorizerCode(null);
subscriptionsToProcessVO.setAuthorizerReason(e.getMessage());
logger.debug("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue decline.");
loggerDeclined.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue decline.");
}
subscriptionsToProcessVO.setErrorCode("1");//User esta variable para simular errores, Con este valor no actualiza
// subscriptionsToProcessVO.setErrorCode("2");//User esta variable para simular errores, con este valor lanza una exception
if(subscriptionsToProcessDAO.update(subscriptionsToProcessVO) == 0) {
// System.out.println("No fue posible actualizar la informacion del pago. Suspender todo el proceso. " + "Generar informe con la informacion del error");
JSONObject errorDetails = new JSONObject();
errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus());
errorDetails.put("Supr_AuthorizerCode", subscriptionsToProcessVO.getAuthorizerCode());
errorDetails.put("Supr_AuthorizerReason", subscriptionsToProcessVO.getAuthorizerReason());
errorDetails.put("Supr_ProcessAttempt", subscriptionsToProcessVO.getProcessAttempt());
errorDetails.put("Supr_ID", subscriptionsToProcessVO.getId());
errorDetails.put("Subs_ID", subscriptionsToProcessVO.getSubscriptionId());
errorDetails.put("AutorizationID", subscriptionsToProcessVO.getAuthorizerCode());
errorDetails.put("CALL_DailySubscriptionDAO", subscriptionsToProcessDAO.getCallString());
errorDetails.put("ReprocessTRX",true);
writeError(errorDetails);
answer = false;
noUpdated = true;
noUpdated();
setSwErrorOnlevel1(true);
errorFileExist = true;
}else{
updated();
}
if(unpaidSubGroup) break; //Rompe el ciclo despues de que consigue una subscripcion que no fue aprobada y es actualizada en las tablas de las subscripciones
}else{
logger.debug("No actualiza el registro para la subscripcion "+subscriptionsToProcessVO.getId()+ ".");
}
} catch (SubscriptionsToProcessDAOException e) {
logger.debug("No fue posible actualizar la informacion del pago. Suspender todo el proceso. " + "Generar informe con la informacion del error " + subscriptionsToProcessDAO.getCallString());
JSONObject errorDetails = new JSONObject();
errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus());
errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus());
errorDetails.put("Supr_AuthorizerCode", subscriptionsToProcessVO.getAuthorizerCode());
errorDetails.put("Supr_AuthorizerReason", subscriptionsToProcessVO.getAuthorizerReason());
errorDetails.put("Supr_ProcessAttempt", subscriptionsToProcessVO.getProcessAttempt());
errorDetails.put("Supr_ID", subscriptionsToProcessVO.getId());
errorDetails.put("Subs_ID", subscriptionsToProcessVO.getSubscriptionId());
errorDetails.put("AutorizationID", subscriptionsToProcessVO.getAuthorizerCode());
errorDetails.put("CALL_DailySubscriptionDAO", subscriptionsToProcessDAO.getCallString());
if(level == 1) {
/*Esto es para verificar que el archivo de errores contiene transacciones que deben ser cargadas en la BD.
*Esto es porque el error ocurre antes de enviar la transaccion, por lo que el registro no se debe modificar para que
*pueda ser reenviado como si fuese la primera vez*/
setSwErrorOnlevel1(true);
errorDetails.put("ReprocessTRX",true);
}else{
errorDetails.put("ReprocessTRX",false);
}
noUpdated();
writeError(errorDetails);
answer = false;
errorFileExist = true;
new SubscriptionsMDTRException(e, subscriptionsToProcessDAO.getCallString());
break;
}
}
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (APIConnectionException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
} catch (InvalidRequestException e) {
e.printStackTrace();
}
executeThread = false;
}
hashThreadsProcessSubscription.remove(this.getName());
if (hashThreadsProcessSubscription.isEmpty()) {
finalTime = Calendar.getInstance().getTimeInMillis();
logger.info("A Tiempo total para procesar todas las subscripciones: " + (finalTime-initialTime) + " ms.");
System.out.println("Tiempo total para procesar todas las subscripciones: " + (finalTime-initialTime) + " ms.");
try {
submittedProcessLogDAO = new SubmittedProcessLogDAO();
submittedProcessLogVO.setEndTime(Calendar.getInstance().getTime().toString());
if(answer) submittedProcessLogVO.setStatusProcess("Success");
else submittedProcessLogVO.setStatusProcess("Error");
JSONObject informationDetails = new JSONObject();
JSONObject information = new JSONObject();
// information.put("unpaids", unpaids);
// if(unpaids){
// information.put("Recomendation","Run the \"Reprocess Process\" to resend the transactions to our processor.");
// information.put("Information", "There are subscripcions that our procesor could not charge to some card holders. The uncharges transactions information are available in the tables Reprocess_X ");
// informationDetails.put("InformationUnpaids", information);
// informationDetails.put("ReprocessUnpaids", unpaids);
// }
information = new JSONObject();
information.put("noUpdated", noUpdated);
if(noUpdated && swErrorOnlevel1){
information.put("InformationNoUpdated", "There are subscripcions that were charged by our processor but the information was not updated in our systems.");
information.put("Recomendation","Check system logs to determine the causes of the error.");
informationDetails.put("InformationNoUpdated", information);
}
information = new JSONObject();
information.put("errorFileExist", errorFileExist);
if(errorFileExist && swErrorOnlevel1){
information.put("Information", "Was created a file that content information about the subscripcions that could not Update.");
information.put("Recomendation","Execute the recovery process to update the correct field in our data base.");
information.put("FileLocation",getLogFileName());
informationDetails.put("ReprocessErrorFile", errorFileExist);
informationDetails.put("InformationErrorFileExist", information);
}else if(errorFileExist && !swErrorOnlevel1){
information.put("Information", "Was created a file that content information about the subscripcions that could not be sent to out processor.");
information.put("FileLocation",getLogFileName());
informationDetails.put("ReprocessErrorFile", false);
informationDetails.put("InformationErrorFileExist", information);
}
information = new JSONObject();
information.put("Total Time", ((finalTime-initialTime) + " ms."));
information.put("Total Transactions to process", numberTransactionsToProcess);
information.put("Total Transactions no updates on Data Base", numberNoUpdated);
information.put("Total Transactions updates on Data Base", numberUpdated);
information.put("Total Transactions keeped on file ", numberNoUpdated);
information.put("Total Transactions unpaids", numberUnpaids);
information.put("Total Transactions chargeds", numberCharged);
information.put("Total Transactions sent to our procesor", numberSent);
informationDetails.put("Resume ProcessExecution", information);
logger.info("Imprimiendo resumen FINAL ... ");
logger.info("Total Time " + ((finalTime-initialTime) + " ms."));
logger.info("Total Transactions to process " + numberTransactionsToProcess);
logger.info("Total Transactions no updates on Data Base "+ numberNoUpdated);
logger.info("Total Transactions updates on Data Base "+ numberUpdated);
logger.info("Total Transactions keeped on file "+ numberNoUpdated);
logger.info("Total Transactions unpaids "+ numberUnpaids);
logger.info("Total Transactions chargeds "+ numberCharged);
logger.info("Total Transactions sent to our procesor "+ numberSent);
submittedProcessLogVO.setInformation(informationDetails.toJSONString());
submittedProcessLogDAO.update(submittedProcessLogVO);
mySQLTransaction.commit();
} catch (MySQLConnectionException e) {
e.printStackTrace();
} catch (MySQLTransactionException e) {
e.printStackTrace();
} catch (SubmittedProcessLogDAOException e) {
e.printStackTrace();
} finally{
try {
if(mySQLTransaction != null){
mySQLTransaction.close();
}
} catch (MySQLTransactionException e) {
e.printStackTrace();
}
}
logger.info("/*****************************************************************************************************/");
logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/");
logger.info("/*****************************************************************************************************/");
}
}
public void cancel() {
executeThread = false;
}
}
private synchronized void sent(){
numberSent ++;
}
private synchronized void charged(){
numberCharged ++;
}
private synchronized void unpaid(){
numberUnpaids ++;
}
private synchronized void noUpdated(){
numberNoUpdated ++;
}
private synchronized void updated(){
numberUpdated ++;
}
public synchronized void setSwErrorOnlevel1(boolean swErrorOnlevel1) {
this.swErrorOnlevel1 = swErrorOnlevel1;
}
public HashMap<String, ProcessSubscription> getHashThreadsProcessSubscription() {
return hashThreadsProcessSubscription;
}
public void printThreads() {
System.out.println("Imprimiendo hilos .... ");
Set<String> set = hashThreadsProcessSubscription.keySet();
for (String key : set) {
ProcessSubscription processSubscription = hashThreadsProcessSubscription.get(key);
System.out.println("Nombre hilo " + processSubscription.getName());
}
}
public void destroyThread(String name) {
System.out.println("Intentando cancelar hijo .... " + name);
ProcessSubscription processSubscription = hashThreadsProcessSubscription.get(name);
if(processSubscription != null ) processSubscription.cancel();
else System.out.println("Hilo no encontrado ...");
}
}
| [
"edicsonm@gmail.com"
] | edicsonm@gmail.com |
dabfd04001a03ba3a52331add5fb9a5d0935bdea | 41bebb1d64f52ff5acd4d48ce91a56fa97ec0c41 | /src/test/java/seedu/address/logic/suggestions/TrieTest.java | 92fdde32ea5ca5f150400e114a3188a913a7f2b0 | [
"MIT"
] | permissive | linnnruoo/JitHub | a3eea0e6d42e3b69d38e006b182de9aff1cb6252 | c9fbd34a85929e3e494a0c89d3e59737bd4d831a | refs/heads/master | 2020-03-30T09:22:01.861211 | 2018-11-12T15:55:12 | 2018-11-12T15:55:12 | 151,073,023 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,599 | java | package seedu.address.logic.suggestions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.ClearScheduleCommand;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.ExportAllCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.HistoryCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.commands.RedoCommand;
import seedu.address.logic.commands.ScheduleCommand;
import seedu.address.logic.commands.SelectCommand;
import seedu.address.logic.commands.TodoCommand;
import seedu.address.logic.commands.UndoCommand;
public class TrieTest {
private Trie dictionary;
@Before
public void setUp() {
dictionary = new Trie();
}
@Test
public void insert() {
dictionary.insert(AddCommand.COMMAND_WORD);
}
@Test
public void searchChar() {
dictionary.insert(AddCommand.COMMAND_WORD);
// check if 'add' exists
assertTrue(dictionary.search('a'));
assertTrue(dictionary.search('d'));
assertTrue(dictionary.search('d'));
// check if 's' exists after 'add'
assertFalse(dictionary.search('s'));
}
@Test
public void searchString() {
dictionary.insert(AddCommand.COMMAND_WORD);
// check if 'add' exists
assertTrue(dictionary.search("add"));
}
@Test
public void moveUpCrawler() {
dictionary.insert(AddCommand.COMMAND_WORD);
//check if first character 'a' is valid
assertTrue(dictionary.search('a'));
dictionary.moveSearchCrawlerToParent();
//check if first character 'a' is still valid after using moveSearchCrawlerToParent
assertTrue(dictionary.search('a'));
dictionary.moveSearchCrawlerToParent();
dictionary.moveSearchCrawlerToParent();
//check if moving back to parent once after it is already at the root causes issues
assertTrue(dictionary.search('a'));
}
@Test
public void searchStringMultipleValuesInTrie() {
dictionary.insert(AddCommand.COMMAND_WORD);
dictionary.insert(HistoryCommand.COMMAND_WORD);
dictionary.insert(HelpCommand.COMMAND_WORD);
assertTrue(dictionary.search("add"));
assertTrue(dictionary.search("history"));
assertTrue(dictionary.search("help"));
}
@Test
public void searchCharMultipleValuesInTrie() {
dictionary.insert(AddCommand.COMMAND_WORD);
dictionary.insert(HistoryCommand.COMMAND_WORD);
dictionary.insert(HelpCommand.COMMAND_WORD);
assertTrue(dictionary.search('a'));
assertTrue(dictionary.search('d'));
assertFalse(dictionary.search('h'));
dictionary.moveSearchCrawlerToParent();
dictionary.moveSearchCrawlerToParent();
assertTrue(dictionary.search('h'));
assertTrue(dictionary.search('i'));
assertFalse(dictionary.search('e')); //'hie' does not exist
assertTrue(dictionary.search('s')); //'his' exists
dictionary.moveSearchCrawlerToParent(); //'hi'
dictionary.moveSearchCrawlerToParent(); //'h'
assertTrue(dictionary.search('e')); //'he' exists
}
@Test
public void getListOfWords() {
dictionary.insert(AddCommand.COMMAND_WORD);
dictionary.insert(ClearCommand.COMMAND_WORD);
dictionary.insert(DeleteCommand.COMMAND_WORD);
dictionary.insert(EditCommand.COMMAND_WORD);
dictionary.insert(ExitCommand.COMMAND_WORD);
dictionary.insert(ExportAllCommand.COMMAND_WORD);
dictionary.insert(FindCommand.COMMAND_WORD);
dictionary.insert(HelpCommand.COMMAND_WORD);
dictionary.insert(HistoryCommand.COMMAND_WORD);
dictionary.insert(ListCommand.COMMAND_WORD);
dictionary.insert(RedoCommand.COMMAND_WORD);
dictionary.insert(ScheduleCommand.COMMAND_WORD);
dictionary.insert(SelectCommand.COMMAND_WORD);
dictionary.insert(TodoCommand.COMMAND_WORD);
dictionary.insert(UndoCommand.COMMAND_WORD);
List<String> eWordList = new ArrayList<>();
eWordList.add(EditCommand.COMMAND_WORD);
eWordList.add(ExitCommand.COMMAND_WORD);
eWordList.add(ExportAllCommand.COMMAND_WORD);
assertTrue(eWordList.containsAll(dictionary.getListOfWords("e")));
assertFalse(eWordList.containsAll(dictionary.getListOfWords("a")));
List<String> exWordList = new ArrayList<>();
exWordList.add(ExitCommand.COMMAND_WORD);
exWordList.add(ExportAllCommand.COMMAND_WORD);
assertTrue(exWordList.containsAll(dictionary.getListOfWords("ex")));
assertFalse(exWordList.containsAll(dictionary.getListOfWords("e")));
}
@Test
public void withSameStartingNames_getListOfWords() {
dictionary.insert(ClearCommand.COMMAND_WORD);
dictionary.insert(ClearScheduleCommand.COMMAND_WORD);
List<String> cWordList = new ArrayList<>();
cWordList.add(ClearCommand.COMMAND_WORD);
cWordList.add(ClearScheduleCommand.COMMAND_WORD);
assertTrue(cWordList.containsAll(dictionary.getListOfWords("c")));
}
}
| [
"elston.ayx@u.nus.edu"
] | elston.ayx@u.nus.edu |
6828d9138ee6483c9ca473747a1638e7d8bf8a53 | 4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849 | /aliyun-java-sdk-viapi-regen/src/main/java/com/aliyuncs/viapi_regen/model/v20211119/CheckDatasetOssBucketCORSRequest.java | d1160f68aafd6cb2b8e672e143c6c3187c25a545 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-java-sdk | a263fa08e261f12d45586d1b3ad8a6609bba0e91 | e19239808ad2298d32dda77db29a6d809e4f7add | refs/heads/master | 2023-09-03T12:28:09.765286 | 2023-09-01T09:03:00 | 2023-09-01T09:03:00 | 39,555,898 | 1,542 | 1,317 | NOASSERTION | 2023-09-14T07:27:05 | 2015-07-23T08:41:13 | Java | UTF-8 | Java | false | false | 1,708 | java | /*
* 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.aliyuncs.viapi_regen.model.v20211119;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.viapi_regen.Endpoint;
/**
* @author auto create
* @version
*/
public class CheckDatasetOssBucketCORSRequest extends RpcAcsRequest<CheckDatasetOssBucketCORSResponse> {
private Long labelsetId;
public CheckDatasetOssBucketCORSRequest() {
super("viapi-regen", "2021-11-19", "CheckDatasetOssBucketCORS", "selflearning");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Long getLabelsetId() {
return this.labelsetId;
}
public void setLabelsetId(Long labelsetId) {
this.labelsetId = labelsetId;
if(labelsetId != null){
putBodyParameter("LabelsetId", labelsetId.toString());
}
}
@Override
public Class<CheckDatasetOssBucketCORSResponse> getResponseClass() {
return CheckDatasetOssBucketCORSResponse.class;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
f3ff394252e5a0f254633b5b0bfcb2277245aea8 | 2bd7643730a0048e0ba1e7bb663a97166c54dc54 | /EBPSv2/src/main/java/com/controller/rest/application/FrequentlyAskedQuestionRestController.java | 613c057b76a3b1f084e001d02ce66223f6f1863b | [] | no_license | bkings/BuildingPermitDynamic | 3f8b4d7fa8aaff45b43f05fc16fcb1ea54da3ad7 | bb7322f6e04b2017854a5ceebcf4b37d755d000b | refs/heads/master | 2023-02-16T20:46:37.209422 | 2021-01-17T06:40:25 | 2021-01-17T06:40:25 | 299,945,567 | 1 | 0 | null | 2020-10-21T13:30:47 | 2020-09-30T14:25:30 | Java | UTF-8 | Java | false | false | 1,419 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.controller.rest.application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.application.FrequentlyAskedQuestionService;
@RestController
@CrossOrigin
@RequestMapping("api/application/FrequentlyAskedQuestion")
public class FrequentlyAskedQuestionRestController {
@Autowired
FrequentlyAskedQuestionService service;
@GetMapping()
public Object show() {
return service.getAll();
}
@GetMapping("/{id}")
public Object showById(@PathVariable Integer id) {
return service.getById(id);
}
@PostMapping()
public Object doSave(@RequestBody String jsonData, @RequestHeader(value = "Authorization") String Authorization) {
return service.save(jsonData,Authorization);
}
}
| [
"bbikings@yahoo.com"
] | bbikings@yahoo.com |
d82b7198b03d0083f5cf47ed0b0c3e59570967b7 | a36e8b0697fbc7356f74ed6e5dfefc8ec31a0f92 | /src/net/shopxx/controller/member/PasswordController.java | 38efdc36a5f7551947191205c208bbb1304d2bf8 | [] | no_license | cwy329233832/shop | eb11fe65e96705f0c291e5f7ab2b7adb2fa01e94 | d88331f74741af1d558c079b072769b787408230 | refs/heads/master | 2021-03-01T07:00:29.606834 | 2019-01-26T09:43:25 | 2019-01-26T09:43:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,034 | java | /*
* Copyright 2005-2017 shopxx.net. All rights reserved.
* Support: http://www.shopxx.net
* License: http://www.shopxx.net/license
*/
package net.shopxx.controller.member;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import net.shopxx.entity.Member;
import net.shopxx.security.CurrentUser;
import net.shopxx.service.MemberService;
/**
* Controller密码
*
* @author SHOP++ Team
* @version 5.0
*/
@Controller("memberPasswordController")
@RequestMapping("/member/password")
public class PasswordController extends BaseController {
@Inject
private MemberService memberService;
/**
* 验证当前密码
*/
@GetMapping("/check_current_password")
public @ResponseBody boolean checkCurrentPassword(String currentPassword, @CurrentUser Member currentUser) {
return StringUtils.isNotEmpty(currentPassword) && currentUser.isValidCredentials(currentPassword);
}
/**
* 编辑
*/
@GetMapping("/edit")
public String edit() {
return "member/password/edit";
}
/**
* 更新
*/
@PostMapping("/update")
public String update(String currentPassword, String password, @CurrentUser Member currentUser, RedirectAttributes redirectAttributes) {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(currentPassword)) {
return UNPROCESSABLE_ENTITY_VIEW;
}
if (!isValid(Member.class, "password", password)) {
return UNPROCESSABLE_ENTITY_VIEW;
}
if (!currentUser.isValidCredentials(currentPassword)) {
return UNPROCESSABLE_ENTITY_VIEW;
}
currentUser.setPassword(password);
memberService.update(currentUser);
addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
return "redirect:edit";
}
} | [
"zhangwenxuan@sina.com"
] | zhangwenxuan@sina.com |
80ccb13570d83e45e0a7d71677e7eaf5b9801aaf | 0663afe07eec169dbe8a932acea6ecae52a11299 | /src/main/java/com/atguigu/crud/service/UserService.java | e59c6423d2054dcea54d0d52371c80ee0c2d69ba | [] | no_license | qiushanling-admin/ssm-crud | 139e58d7e19580afcbbbac8ca60de178134f88c6 | 36bac38bb6b006546ea9da983d0623039affd5c7 | refs/heads/master | 2020-12-04T13:26:09.406661 | 2019-03-15T03:10:00 | 2019-03-15T03:10:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,199 | java | package com.atguigu.crud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.crud.bean.User;
import com.atguigu.crud.bean.UserExample;
import com.atguigu.crud.bean.UserExample.Criteria;
import com.atguigu.crud.dao.UserMapper;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
/**
* 校验用户名
* @param username
* @return
*/
public boolean checkUserName(String username) {
UserExample userExample = new UserExample();
Criteria criteria = userExample.createCriteria();
criteria.andUsernameEqualTo(username);
long count = userMapper.countByExample(userExample);
return count==0;
}
/**
* 添加用户
* @param user
*/
public void add(User user) {
userMapper.insert(user);
}
/**
* 激活用户
* @param code
*/
public boolean active(String code) {
UserExample userExample = new UserExample();
Criteria criteria = userExample.createCriteria();
criteria.andCodeEqualTo(code);
List<User> userList = userMapper.selectByExample(userExample);
User user = userList.get(0);
user.setState(true);
int count = userMapper.updateByPrimaryKey(user);
return count!=0;
}
/**
* 登录
* @param user
* @return
*/
public User login(User user) {
UserExample userExample = new UserExample();
Criteria criteria = userExample.createCriteria();
criteria.andUsernameEqualTo(user.getUsername());
criteria.andPasswordEqualTo(user.getPassword());
criteria.andStateEqualTo(true);
List<User> userList = userMapper.selectByExample(userExample);
if(userList.size()>0){
User currentUser = userList.get(0);
return currentUser;
}else{
return null;
}
}
public User getUserByUserName(String username){
UserExample userExample = new UserExample();
Criteria criteria = userExample.createCriteria();
criteria.andUsernameEqualTo(username);
criteria.andStateEqualTo(true);
List<User> userList = userMapper.selectByExample(userExample);
if(userList.size()>0){
User currentUser = userList.get(0);
return currentUser;
}else{
return null;
}
}
}
| [
"38879101+476554858@users.noreply.github.com"
] | 38879101+476554858@users.noreply.github.com |
2274e76905261637ea0bab91d36be95442b4ecdc | 714bf80a42af65d5fe8cd3d33784f739eb87292c | /src/StartWindow.java | 33be2337bdb400fb5346c1a168cc24bbbb7f2c78 | [] | no_license | jweiler2020/Block_Game | d9cff070700e7f66741b554896103c8305270965 | 30cdb0ae445c756220e7a1d5e6f81f186f855352 | refs/heads/master | 2020-04-26T05:13:15.990625 | 2019-04-29T01:57:47 | 2019-04-29T01:57:47 | 173,327,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,394 | java | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StartWindow extends JFrame
implements ActionListener
{
private JButton playGameButton, settingsButton, quitButton;
private JButton backToMainButton;
private JPanel mainPanel, settingsPanel;
private CardLayout cl = new CardLayout();
public StartWindow(String title)
{
super(title);
// Useful objects
Font labelFont = new Font("Arial", Font.BOLD, 20);
Font buttonFont = new Font("Arial", Font.PLAIN, 15);
GridBagConstraints c = new GridBagConstraints();
//----------------------------Start Main Panel------------------------------//
JLabel mainPanelLabel = new JLabel("Block Game 2019 Edition™", JLabel.CENTER);
mainPanelLabel.setFont(labelFont);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
playGameButton = new JButton("Play");
playGameButton.addActionListener(this);
playGameButton.setFont(buttonFont);
settingsButton = new JButton("Settings");
settingsButton.addActionListener(this);
settingsButton.setFont(buttonFont);
quitButton = new JButton("Quit");
quitButton.addActionListener(this);
quitButton.setFont(buttonFont);
c.weightx = 1;
c.weighty = 1 / 3d;
c.insets = new Insets(5, 0, 5, 0);
c.gridx = 0;
c.gridy = 0;
buttonPanel.add(playGameButton, c);
c.gridy++;
buttonPanel.add(settingsButton, c);
c.gridy++;
buttonPanel.add(quitButton, c);
mainPanel = new JPanel();
mainPanel.setName("mainPanel");
mainPanel.setLayout(new GridBagLayout());
c.weightx = 1;
c.weighty = 0.5;
c.gridx = 0;
c.insets = new Insets(0, 0, 0, 0);
c.gridy = 0;
mainPanel.add(mainPanelLabel, c);
c.gridy++;
mainPanel.add(buttonPanel, c);
//----------------------------End Main Panel--------------------------------//
//----------------------------Start Settings Panel--------------------------//
JLabel settingsPanelLabel = new JLabel("Settings");
settingsPanelLabel.setFont(labelFont);
backToMainButton = new JButton("Back to Main Menu");
backToMainButton.addActionListener(this);
backToMainButton.setFont(buttonFont);
settingsPanel = new JPanel();
settingsPanel.setName("settingsPanel");
settingsPanel.setLayout(new GridBagLayout());
c.weightx = 1;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
settingsPanel.add(settingsPanelLabel, c);
c.gridy++;
settingsPanel.add(backToMainButton, c);
//---------------------------End Settings Panel-----------------------------//
Container con = getContentPane();
con.setLayout(cl);
con.add(mainPanel, mainPanel.getName());
con.add(settingsPanel, settingsPanel.getName());
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playGameButton)
{
new GameController();
dispose();
} else if (e.getSource() == settingsButton)
{
cl.show(getContentPane(), settingsPanel.getName());
} else if (e.getSource() == quitButton)
{
System.exit(0);
} else if (e.getSource() == backToMainButton)
{
cl.show(getContentPane(), mainPanel.getName());
}
}
public static void main(String[] args)
{
StartWindow win = new StartWindow("Block Game 2019 Edition™");
win.setBounds(200, 200, 400, 300);
win.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
win.setResizable(false);
win.setVisible(true);
}
}
| [
"jweiler2020@cusd.claremont.edu"
] | jweiler2020@cusd.claremont.edu |
9308501d1bfaf2ec9c57abd63792596b54b98b38 | 19106d337d6d26387b514ed0e1cdcf3816f7e979 | /src/main/java/vsdl/wrepo/cql/query/ColumnInfo.java | f96be6aac9edaa70db6a8158af4e3da5451527c4 | [] | no_license | VectorShadow/WickedRepository | e74a7242b0dad2cfb5878f9f9518315b409d53d9 | c776b70bad647cd4bf8871444e845cbff460d526 | refs/heads/master | 2023-07-05T18:25:55.304420 | 2021-08-14T20:51:31 | 2021-08-14T20:51:31 | 392,843,643 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package vsdl.wrepo.cql.query;
public class ColumnInfo {
private final String NAME;
private final String DATA_TYPE;
public ColumnInfo(String name, String dataType) {
NAME = name;
DATA_TYPE = dataType;
}
public String getName() {
return NAME;
}
public String getDataType() {
return DATA_TYPE;
}
}
| [
"ncbrayshaw@hotmail.com"
] | ncbrayshaw@hotmail.com |
414c4d6349fdc90188fab39bcd135a4f0503171c | 6763f0f021b47582538987d4ba0a29c506bab3b7 | /src/main/java/com/raitichan/MCTweet/config/MCTweetConfigGuiFactory.java | 49f6cb8942d60a89a21d7c9360d6ed3b4bd8b59e | [] | no_license | raiti-chan/MCTweet | 78dd254fd9929b24e6c8dec5f13bc4f002e63527 | 18f24d2bd7c1421a914dab7f04a57441f0ff4d7b | refs/heads/master | 2020-12-30T13:28:56.085944 | 2017-05-28T02:19:20 | 2017-05-28T02:19:20 | 90,355,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,622 | java | package com.raitichan.MCTweet.config;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.IModGuiFactory;
/**
* MCTweet config gui factory.
* <br>Created by Raiti-chan on 2017/05/13.
*
* @author Raiti-chan
* @version 1.0.0
* @since 1.0.0
*/
@SuppressWarnings("unused")
public class MCTweetConfigGuiFactory implements IModGuiFactory {
/**
* Called when instantiated to initialize with the active minecraft instance.
*
* @param minecraftInstance the instance
*/
@Override
public void initialize (Minecraft minecraftInstance) {
}
/**
* Return the name of a class extending {@link GuiScreen}. This class will
* be instantiated when the "config" button is pressed in the mod list. It will
* have a single argument constructor - the "parent" screen, the same as all
* Minecraft GUIs. The expected behaviour is that this screen will replace the
* "mod list" screen completely, and will return to the mod list screen through
* the parent link, once the appropriate action is taken from the config screen.
* <p>
* A null from this method indicates that the mod does not provide a "config"
* button GUI screen, and the config button will be hidden/disabled.
* <p>
* This config GUI is anticipated to provide configuration to the mod in a friendly
* visual way. It should not be abused to set internals such as IDs (they're gonna
* keep disappearing anyway), but rather, interesting behaviours. This config GUI
* is never run when a server game is running, and should be used to configure
* desired behaviours that affect server state. Costs, mod game modes, stuff like that
* can be changed here.
*
* @return A class that will be instantiated on clicks on the config button
* or null if no GUI is desired.
*/
@Override
public Class<? extends GuiScreen> mainConfigGuiClass () {
return MCTweetConfigGuiScreen.class;
}
/**
* Return a list of the "runtime" categories this mod wishes to populate with
* GUI elements.
* <p>
* Runtime categories are created on demand and organized in a 'lite' tree format.
* The parent represents the parent node in the tree. There is one special parent
* 'Help' that will always list first, and is generally meant to provide Help type
* content for mods. The remaining parents will sort alphabetically, though
* this may change if there is a lot of alphabetic abuse. "AAA" is probably never a valid
* category parent.
* <p>
* Runtime configuration itself falls into two flavours: in-game help, which is
* generally non interactive except for the text it wishes to show, and client-only
* affecting behaviours. This would include things like toggling minimaps, or cheat modes
* or anything NOT affecting the behaviour of the server. Please don't abuse this to
* change the state of the server in any way, this is intended to behave identically
* when the server is local or remote.
*
* @return the set of options this mod wishes to have available, or empty if none
*/
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories () {
return null;
}
/**
* Return an instance of a {@link RuntimeOptionGuiHandler} that handles painting the
* right hand side option screen for the specified {@link RuntimeOptionCategoryElement}.
*
* @param element The element we wish to paint for
* @return The Handler for painting it
*/
@SuppressWarnings("deprecation")
@Override
public RuntimeOptionGuiHandler getHandlerFor (RuntimeOptionCategoryElement element) {
return null;
}
}
| [
"rusuke@t-net.ne.jp"
] | rusuke@t-net.ne.jp |
ca05cc53c4319fde39ad3b866d1d2decb47e1bfb | 202b67a83f0558b4db7e570d8daf73517d319f4f | /app/src/main/java/com/lorem/simpledictionary/LoaderActivity.java | 9cc8425badae2eaf90418045104f0cc3931b91dc | [] | no_license | ravimahfunda/SimpleDictionary | 53b2d9fa4fd29855c387a28750639d5bf3efffa5 | 8f75eb63ad0aa2f8973291de679bd2ddc0aa961f | refs/heads/master | 2020-03-26T11:26:52.737391 | 2018-08-15T11:12:50 | 2018-08-15T11:12:50 | 144,843,108 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,247 | java | package com.lorem.simpledictionary;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import com.lorem.simpledictionary.db.DatabaseContract;
import com.lorem.simpledictionary.db.OperationHelper;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
public class LoaderActivity extends AppCompatActivity {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader);
progressBar = (ProgressBar) findViewById(R.id.pb_load);
new LoadData().execute();
}
private class LoadData extends AsyncTask<Void, Integer, Void> {
final String TAG = LoadData.class.getSimpleName();
OperationHelper operationHelper;
OperationHelper operationID;
double progress;
double maxprogress = 100;
@Override
protected void onPreExecute() {
operationHelper = new OperationHelper(LoaderActivity.this);
}
@Override
protected Void doInBackground(Void... params) {
SharedPreferences preferences = getSharedPreferences("LOADER", Context.MODE_PRIVATE);
Boolean firstRun = preferences.getBoolean("LOADED", true);
if (firstRun) {
ArrayList<Word> enWords = preLoadRaw(R.raw.english_indonesia);
ArrayList<Word> idWords = preLoadRaw(R.raw.indonesia_english);
progress = 10;
publishProgress((int) progress);
Double progressMaxInsert = 100.0;
Double progressDiff = (progressMaxInsert - progress) / (enWords.size() + idWords.size());
try {
operationHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
operationHelper.beginTransaction();
try {
for (Word model : enWords) {
Log.d("INSRETION EN", "Inserting word " + model.getWord());
operationHelper.insertTransaction(DatabaseContract.TABLE_EN,model);
progress += progressDiff;
publishProgress((int) progress);
}
for (Word model : idWords) {
Log.d("INSRETION ID", "Inserting word " + model.getWord());
operationHelper.insertTransaction(DatabaseContract.TABLE_ID,model);
progress += progressDiff;
publishProgress((int) progress);
}
// Jika semua proses telah di set success maka akan di commit ke database
operationHelper.setTransactionSuccess();
} catch (Exception e) {
// Jika gagal maka do nothing
Log.e(TAG, "doInBackground: Exception");
}
operationHelper.endTransaction();
operationHelper.close();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("LOADED", false);
editor.apply();
publishProgress((int) maxprogress);
} else {
try {
synchronized (this) {
this.wait(1000);
publishProgress(50);
this.wait(1000);
publishProgress((int) maxprogress);
}
} catch (Exception e) {
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
}
@Override
protected void onPostExecute(Void result) {
Intent i = new Intent(LoaderActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
public ArrayList<Word> preLoadRaw(int fileId) {
ArrayList<Word> mahasiswaModels = new ArrayList<>();
String line = null;
BufferedReader reader;
try {
Resources res = getResources();
InputStream raw_dict = res.openRawResource(fileId);
reader = new BufferedReader(new InputStreamReader(raw_dict));
int count = 0;
do {
line = reader.readLine();
String[] splitstr = line.split("\t");
Word mahasiswaModel;
mahasiswaModel = new Word(splitstr[0], splitstr[1]);
mahasiswaModels.add(mahasiswaModel);
count++;
} while (line != null);
} catch (Exception e) {
e.printStackTrace();
}
return mahasiswaModels;
}
} | [
"ravimahfunda@gmail.com"
] | ravimahfunda@gmail.com |
c4b0b055bbb31a11bdf7f0cb37a55e730559ed79 | 3b50b3b55a9fd4f6bc90315d2bda9c07ec599116 | /app/src/main/java/com/d/httprequest/model/WpTerm.java | fea8fd5e0c073f305260783effd6bcb96c80a6ce | [] | no_license | huuhuybn/HttpRequest3 | c0a0359c7dd759a8fc9df97706025de43c890f02 | 79beb0d59a3dad1a93bfcf29edcf1dbe22239d6b | refs/heads/master | 2020-06-21T01:39:11.865132 | 2019-07-17T04:03:26 | 2019-07-17T04:03:26 | 197,312,450 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 824 | java |
package com.d.httprequest.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WpTerm {
@SerializedName("taxonomy")
@Expose
private String taxonomy;
@SerializedName("embeddable")
@Expose
private Boolean embeddable;
@SerializedName("href")
@Expose
private String href;
public String getTaxonomy() {
return taxonomy;
}
public void setTaxonomy(String taxonomy) {
this.taxonomy = taxonomy;
}
public Boolean getEmbeddable() {
return embeddable;
}
public void setEmbeddable(Boolean embeddable) {
this.embeddable = embeddable;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
| [
"huuhuybn@gmail.com"
] | huuhuybn@gmail.com |
5506dbd686fe0af2c55f7d287237448cda28a4bf | 429499b7d25bab3d74daec5064afeb2dc26dc607 | /src/main/java/com/Project/ESB/IService/FillAttenteIService.java | 6eb3ac12f32b148e20b4d2d43d5dfc60b96a1704 | [] | no_license | HajlaouiAmine/esb_pfe | 1f0c1a3ef3422ceb68765cf527b91eecbaec562a | 7c6661841ad6e2f21ac003ace5bf78e16fbb07d1 | refs/heads/main | 2023-04-29T07:49:54.041038 | 2021-05-18T12:19:30 | 2021-05-18T12:19:30 | 368,510,163 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 166 | java | package com.Project.ESB.IService;
import com.Project.ESB.Model.FillAttente;
public interface FillAttenteIService {
FillAttente créer(FillAttente fillAttente);
}
| [
"amine.hajlaoui.77@gmail.com"
] | amine.hajlaoui.77@gmail.com |
021f43182ac840a822bb8412242fca229c95546f | 9b832ed4de8a20e3eb3165cfd86dfcf2fa5affcd | /src/HttpServer/HttpEnum.java | e9c9fd6304597d6ff293fb97346f4ed53f715c27 | [] | no_license | HugoDanielson/NovoNordisk | f52b85b2063f1ff1e0b3542bad4afdfd1cb62a02 | f2918a338e15231b7b0c58d732388684f7cd1ea8 | refs/heads/master | 2023-01-06T04:01:51.799368 | 2020-10-22T03:12:06 | 2020-10-22T03:12:06 | 306,209,015 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 599 | java | package HttpServer;
public class HttpEnum {
public enum eHttpPath {
COM1("/iiwa_com1"), COM2("/iiwa_com2"), COM3("/iiwa_com3"), COM4("/iiwa_com4"),COM5("/iiwa_com5");
private String path;
private eHttpPath(String path) {
this.path = path;
}
public String getValue() {
return this.path;
}
// public static eHttpPath valueOf(String value) {
// for (eHttpPath path : eHttpPath.values()) {
// if (path.getValue().contentEquals(value)){
// return path;
// }
// }
// return null;
// }
};
}
| [
"danielbilik@DANIELBILIK4939"
] | danielbilik@DANIELBILIK4939 |
71dc72d8b8b7cc2fc32e6ff6bd31ab4d5ee85cce | 33c8113d1b55222ec16ca382284de234bdfc4616 | /app/src/main/java/com/example/restaurantsdemoapp/contract/MainActivityContract.java | 6bd9f2ae614f665fcaa36ac5996aa79cf7196b5f | [] | no_license | yogeshMarutiPatil/RestaurantDemoApp | ede4308f3ff2b50b5c9011119b7b9d715e5f3b60 | 35cd056338981f3e3aeb1cca89be18f072edfbbd | refs/heads/master | 2020-09-26T07:41:09.977449 | 2019-12-11T12:06:27 | 2019-12-11T12:06:27 | 226,206,220 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 930 | java | package com.example.restaurantsdemoapp.contract;
import android.content.Context;
import com.example.restaurantsdemoapp.model.adapter.RestaurantRecyclerViewAdapter;
import com.example.restaurantsdemoapp.model.pojo.Restaurant;
import java.util.List;
public interface MainActivityContract {
interface Model {
public List<Restaurant> getRestaurantData(Context context, List<Restaurant> restaurantList);
public boolean sortingOption(int id, Context context, List<Restaurant> restaurantList, RestaurantRecyclerViewAdapter mAdapter);
}
interface View {
public void setupUI();
public void getRestaurantData();
}
interface Presenter {
public List<Restaurant> getRestaurantData(Context context, List<Restaurant> restaurantList);
public boolean sortingOption(int id, Context context, List<Restaurant> restaurantList, RestaurantRecyclerViewAdapter mAdapter);
}
}
| [
"yogeshnxt@gmail.com"
] | yogeshnxt@gmail.com |
f107968883cddcfdc89a8fb9572cd040997dffb6 | ba1c4635e8ca406241300cffc5a5ae16d8047c1f | /src/es/workast/utils/WorkastException.java | 48a96540c523cf30aba523e7b48c9af00b763838 | [] | no_license | ncornag/workast | 686dd1ae0d46c4753e8e79cb62aef88d229a47b3 | 9a5f1b46d34a73f331747dd881822a7986d517c4 | refs/heads/master | 2021-01-22T12:13:08.830627 | 2008-09-25T22:20:01 | 2015-12-02T15:04:02 | 32,228,769 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 1,606 | java | package es.workast.utils;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.AbstractMessageSource;
/**
* TODO Documentar
*
* @author Nicolás Cornaglia
*/
public class WorkastException extends RuntimeException {
private static final long serialVersionUID = 1L;
protected WorkastException() {
super();
}
public WorkastException(String messageKey, Object... messageArgs) {
super(resolveMessage(messageKey, messageArgs));
}
public WorkastException(Throwable cause) {
super(cause);
}
public WorkastException(Throwable cause, String messageKey, Object... messageArgs) {
super(resolveMessage(messageKey, messageArgs), cause);
}
private static String resolveMessage(String messageKey, Object[] messageArgs) {
AbstractMessageSource ms = MessageUtils.getMessageSource();
String resolved = null;
if (ms != null) {
try {
resolved = ms.getMessage(messageKey, messageArgs, MessageUtils.DEFAULT_LOCALE);
} catch (NoSuchMessageException e) {
resolved = copyArgs(messageKey, messageArgs);
}
} else {
resolved = copyArgs(messageKey, messageArgs);
}
return resolved;
}
private static String copyArgs(String messageKey, Object[] messageArgs) {
String resolved = messageKey + (messageArgs.length > 0 ? ":" : "");
for (Object arg : messageArgs) {
resolved = resolved + ", " + arg;
}
return resolved;
}
}
| [
"ncornag@gmail.com"
] | ncornag@gmail.com |
dd19f611261b0f44a36b6431dd2ba94155bc93f2 | e96ae2301d33421d08b6413fdc2f35a6b4c5df5c | /src/com/windows3/po/ProductDetail.java | 1ff3a1350feb1a4f8bd0e990d8e3b10f937d80cf | [] | no_license | windows3/spring_mybatis_2_mvc | 938f7efb2b10ecd9e14b66c74c053d5859a5e977 | dfc86b20149e2854d912c29e2bf8e98e651ae74b | refs/heads/master | 2020-04-05T02:57:36.163408 | 2018-11-07T05:46:34 | 2018-11-07T05:46:34 | 156,490,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,480 | java | package com.windows3.po;
import java.io.Serializable;
/**
* Created by 3 on 2018/1/20.
*/
public class ProductDetail implements Serializable {
private Integer id;
private Integer productId;
private String smallImage;
private String bigImage;
private String productCaption;
public ProductDetail() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getSmallImage() {
return smallImage;
}
public void setSmallImage(String smallImage) {
this.smallImage = smallImage;
}
public String getBigImage() {
return bigImage;
}
public void setBigImage(String bigImage) {
this.bigImage = bigImage;
}
public String getProductCaption() {
return productCaption;
}
public void setProductCaption(String productCaption) {
this.productCaption = productCaption;
}
@Override
public String toString() {
return "ProductDetailDao{" +
"id=" + id +
", productId=" + productId +
", smallImage='" + smallImage + '\'' +
", bigImage='" + bigImage + '\'' +
", productCaption='" + productCaption + '\'' +
'}';
}
}
| [
"416400304@qq.com"
] | 416400304@qq.com |
9f55e01d625ce20df8c5c4d8a8fef9bf0439f13a | 4ddff7c87688a7b6ec2ea6d0e4d699c91ef73fd2 | /src/main/java/com/zzc/modules/sysmgr/user/base/entity/UserOrgPositionRelation.java | 342daf3ee5c7ad3a43808482db4c081af646a82f | [] | no_license | 1033132510/SCM | 56146e99e840c912d1a17f763250d9ab170e7d3c | 6a4b8d4bc8685bb5167bd14021f3129a9f5bab91 | refs/heads/master | 2021-01-21T12:15:23.021648 | 2017-05-19T08:14:45 | 2017-05-19T08:14:45 | 91,782,654 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 786 | java | package com.zzc.modules.sysmgr.user.base.entity;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Created by wufan on 2015/11/12.
*/
@Entity
@Table(name = "SYS_USER_ORG_POSITION")
public class UserOrgPositionRelation {
@EmbeddedId
private UserOrgPositionRelationPK id;
@Column(name = "DESCRIPTION", length = 200)
private String description;
public UserOrgPositionRelationPK getId() {
return id;
}
public void setId(UserOrgPositionRelationPK id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| [
"lenovo"
] | lenovo |
c7120a7c6cb61b812535116d442f10f241bae63c | b1db7cf979aaed9a60e376fe2a61e020b66f84e0 | /src/java/com/jilit/irp/persistence/dto/HobbiesMasterId.java | 76838550152fbe0b86ff219f3ff747cd8b011944 | [] | no_license | livcoding/CLXRegistration_OLD | c2a569c0c05c46b9fbb6e176ffc1fd9ca3ebd7e1 | a167f29d20d9c9f1de0e4e78bfca6317f837bc4d | refs/heads/master | 2023-06-21T11:14:20.595579 | 2021-07-23T07:26:29 | 2021-07-23T07:26:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 899 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jilit.irp.persistence.dto;
/**
*
* @author ashok.singh
*/
public class HobbiesMasterId implements java.io.Serializable {
private String clientid;
private String hobbyname;
public HobbiesMasterId() {
}
public HobbiesMasterId(String clientid, String hobbyname) {
this.clientid = clientid;
this.hobbyname = hobbyname;
}
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getHobbyname() {
return hobbyname;
}
public void setHobbyname(String hobbyname) {
this.hobbyname = hobbyname;
}
}
| [
"uvsir001@gmail.com"
] | uvsir001@gmail.com |
7657972bb3e025a17e5c55a176303cf644ca6a3d | f03081503b10bfd96216cb564b1050120c66aa70 | /app/src/androidTest/java/com/example/sam/randommusichttp/ExampleInstrumentedTest.java | 34d8b9031ef68feb6f9aa9f5170afc180fedce96 | [] | no_license | ntv168/RandomChannelHttp | a3da3f43a1133ee12a3da085e48c8a6c945e8c0b | dd71769f61b6f70246f4326cd3ef2621df3a0f6d | refs/heads/master | 2021-07-08T18:12:18.934192 | 2017-10-08T16:06:43 | 2017-10-08T16:06:43 | 106,122,511 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package com.example.sam.randommusichttp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.sam.randommusichttp", appContext.getPackageName());
}
}
| [
"yolovelee"
] | yolovelee |
0c8a664754ced5e001617ba0d630d64c9069f414 | 2d7433ffc30c3a320bd46faae52aacf5b05216f3 | /app/src/main/java/com/sam_chordas/android/stockhawk/widget/DetailWidgetProvider.java | 43aea57847843f70aa91cb35d75539f851438abb | [] | no_license | nvh0412/StockHawk | af8c070cc4f389762a56130af939b0dbaeb4f9b9 | 111dca766b279dc8ea2b9de1be26a67bb70559d8 | refs/heads/master | 2020-04-06T03:47:54.017811 | 2016-09-14T17:02:07 | 2016-09-14T17:02:07 | 67,299,730 | 0 | 0 | null | 2016-09-03T16:18:44 | 2016-09-03T16:18:44 | null | UTF-8 | Java | false | false | 2,379 | java | package com.sam_chordas.android.stockhawk.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.TaskStackBuilder;
import android.widget.RemoteViews;
import com.sam_chordas.android.stockhawk.R;
import com.sam_chordas.android.stockhawk.service.StockTaskService;
import com.sam_chordas.android.stockhawk.ui.MyStocksActivity;
/**
* Created by HoaNV on 9/13/16.
*/
public class DetailWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_detail);
Intent intent = new Intent(context, MyStocksActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
// Set up the collection
setRemoteAdapter(context, views);
Intent clickIntentTemplate = new Intent(context, MyStocksActivity.class);
PendingIntent clickPendingIntent = TaskStackBuilder.create(context)
.addNextIntentWithParentStack(clickIntentTemplate)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(R.id.widget_list, clickPendingIntent);
views.setEmptyView(R.id.widget_list, R.id.widget_empty);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (StockTaskService.ACTION_DATE_UPDATED.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
new ComponentName(context, getClass()));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);
}
}
private void setRemoteAdapter(Context context, @NonNull final RemoteViews views) {
views.setRemoteAdapter(R.id.widget_list,
new Intent(context, DetailWidgetRemoteViewsService.class));
}
}
| [
"nvh0412@gmail.com"
] | nvh0412@gmail.com |
17afc7ad83d60e577c93697b844090655bf69b01 | a04a8bb40cb6682a26d4f43b5de2f8410fb6d269 | /src/main/java/cz/fit/dpo/mvcshooter/designPatterns/controller/commandPattern/concreteCommands/MoveCannonDownCommand.java | 94834044f1dd0bcbc48546410524e463d984ef3c | [] | no_license | RANJEL/DesignPatternsSeminarJob-MVC_Shooter_Game | 5e179c252f39a91749125378ddc1e37c7cd0eacb | e55a469069ded0c139f427d08211668d938b425d | refs/heads/master | 2020-03-27T16:23:37.179032 | 2018-08-31T10:19:01 | 2018-08-31T10:19:01 | 146,778,735 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | package cz.fit.dpo.mvcshooter.designPatterns.controller.commandPattern.concreteCommands;
import cz.fit.dpo.mvcshooter.designPatterns.controller.commandPattern.AbstractCommand;
import cz.fit.dpo.mvcshooter.model.Model;
public class MoveCannonDownCommand extends AbstractCommand {
public MoveCannonDownCommand(Model itsReceiver) {
super(itsReceiver);
}
@Override
public void execute() {
itsReceiver.moveCannonDown();
}
}
| [
"lejnajan@fit.cvut.cz"
] | lejnajan@fit.cvut.cz |
44d5c33243402e32a2ab1de91178cfb38dc78eb1 | a86ef8b64b11209173fd1123fa387b4ae6194905 | /src/com/linmalu/library/api/LinmaluBossbar.java | 3506225e111e2c3e4461b4d14abd6227035ed035 | [] | no_license | Linmalu/LinmaluLibrary_v1.7.9 | 2a9b4e424ccdc5fbbdf651a628eb235bef791511 | 12172799d1c41951d7427cd130b2bab37c58a864 | refs/heads/master | 2020-03-18T11:25:11.992714 | 2018-07-24T12:02:14 | 2018-07-24T12:02:14 | 134,670,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,199 | java | package com.linmalu.library.api;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.linmalu.library.LinmaluLibrary;
public class LinmaluBossbar implements Runnable
{
private static int bossbarID = 0;
private static HashMap<Integer, Integer> schedule = new HashMap<>();
public static void sendMessage(String message)
{
for(Player player : Bukkit.getOnlinePlayers())
{
new LinmaluBossbar(player, message, 100);
}
}
public static void sendMessage(String message, float health)
{
for(Player player : Bukkit.getOnlinePlayers())
{
new LinmaluBossbar(player, message, health);
}
}
public static void sendMessage(Player player, String message)
{
new LinmaluBossbar(player, message, 100);
}
public static void sendMessage(Player player, String message, float health)
{
new LinmaluBossbar(player, message, health);
}
private Player player;
private int taskId;
@SuppressWarnings("deprecation")
private LinmaluBossbar(Player player, String message, float health)
{
this.player = player;
if(bossbarID == 0)
{
Zombie zombie = player.getWorld().spawn(new Location(player.getWorld(), 0, -100, 0), Zombie.class);
bossbarID = zombie.getEntityId();
zombie.remove();
}
health = health / 100 * 200;
health = health > 200 ? 200 : health <= 0 ? 1 : health;
ProtocolManager pm = ProtocolLibrary.getProtocolManager();
PacketContainer pc = pm.createPacket(PacketType.Play.Server.SPAWN_ENTITY_LIVING);
StructureModifier<Integer> ints = pc.getIntegers();
ints.writeDefaults();
ints.write(0, bossbarID);
ints.write(1, (int)EntityType.ENDER_DRAGON.getTypeId());
ints.write(2, player.getLocation().getBlockX() * 32);
ints.write(3, (player.getLocation().getBlockY() - 300) * 32);
ints.write(4, player.getLocation().getBlockZ() * 32);
WrappedDataWatcher watcher = new WrappedDataWatcher();
watcher.setObject(0, (byte)0);
watcher.setObject(6, health);
watcher.setObject(10, message);
pc.getDataWatcherModifier().writeDefaults();
pc.getDataWatcherModifier().write(0, watcher);
try
{
pm.sendServerPacket(player, pc);
}
catch(Exception e)
{
e.printStackTrace();
}
taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(LinmaluLibrary.getMain(), this, 20L);
schedule.put(player.getEntityId(), taskId);
}
public void run()
{
int id = player.getEntityId();
if(schedule.containsKey(id) && schedule.get(id) != taskId)
{
return;
}
ProtocolManager pm = ProtocolLibrary.getProtocolManager();
PacketContainer pc = pm.createPacket(PacketType.Play.Server.ENTITY_DESTROY);
pc.getIntegerArrays().write(0, new int[]{bossbarID});
try
{
pm.sendServerPacket(player, pc);
}
catch(Exception e)
{
e.printStackTrace();
}
schedule.remove(id);
}
}
| [
"gkdwns0103@naver.com"
] | gkdwns0103@naver.com |
934f5acd4198edf04eebf7c9e2834b9736bc7fdb | d340ca98ec67ca00f44d52dd222ff1bfce45a23b | /VariantDriftPrototype/src/main/java/de/hub/mse/variantsync/variantdrift/experiments/algorithms/nwm/alg/merge/Merger.java | 2c5662349f4b2e872077d709940b695c0073f16b | [] | no_license | AlexanderSchultheiss/variant-drift | e6f45dc027dd6a9d922ca98825afd60e54fcd3c5 | 4dba0cbd373adcb485dd45437e95447eaa7957ff | refs/heads/master | 2023-02-06T19:38:28.409815 | 2020-09-24T09:09:30 | 2020-09-24T09:09:30 | 298,225,102 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,217 | java | package de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.alg.merge;
import java.util.ArrayList;
import java.util.HashSet;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.common.AlgoUtil;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Element;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Tuple;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.alg.Matchable;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Model;
import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.execution.RunResult;
public abstract class Merger {
protected ArrayList<Model> models;
private Model mergedModel = null;
private ArrayList<Tuple> mergedTuples;
public Merger(ArrayList<Model> models) {
this.models = models;
}
public Merger(){
this.models = new ArrayList<Model>();
}
protected abstract Matchable getMatch();
public abstract RunResult getRunResult(int numOfModels);
private ArrayList<Element> makeElementsFromMatchTuples(ArrayList<Tuple> match){
ArrayList<Element> retVal = new ArrayList<Element>();
for(Tuple t:match){
retVal.add(new Element(t));
}
return retVal;
}
private ArrayList<Element> getNotMatchedElementsFromModel(Model m, HashSet<Element> ignoreList){
ArrayList<Element> nonIgnored = new ArrayList<Element>();
for(Element elem:m.getElements()){
boolean canBeAdded = true;
for(Element bue:elem.getBasedUponElements()){
if(ignoreList.contains(bue)) {
canBeAdded = false;
break;
}
}
if(canBeAdded)
nonIgnored.add(elem);
}
return nonIgnored;
}
private ArrayList<Element> getNonMatchedElements(){
ArrayList<Tuple> match = getMatch().getTuplesInMatch();
ArrayList<Element> retVal = new ArrayList<Element>();
HashSet<Element> matchedElements = new HashSet<Element>();
for(Tuple t:match){
for(Element elem:t.sortedElements())
matchedElements.add(elem);
}
for(Model m: getMatch().getModels()){
retVal.addAll(getNotMatchedElementsFromModel(m, matchedElements));
}
return retVal;
}
public void refreshResultTuplesWeight(Model merged) {
// int numOfSourceModels = 0;
ArrayList<Model> srcModels = getMatch().getModels();
// for(Model m: getMatch().getModels()){
// numOfSourceModels += m.getMergedFrom();
// }
Tuple t = null;
for(Element e:merged.getElements()){
if(e.getBasedUponElements().size() > 1){
t = e.getContaingTuple();
t.setWeight(t.calcWeight(srcModels));
}
}
}
public Model mergeMatchedModels(){
//System.out.println("distro before:");
//RunResult rr = new RunResult(0, null, null, getMatch().getTuplesInMatch());
//System.out.println(rr);
if(this.mergedModel != null)
return this.mergedModel ;
ArrayList<Tuple> matchTuples = getMatch().getTuplesInMatch();
ArrayList<Element> elements = makeElementsFromMatchTuples(matchTuples);
elements.addAll(getNonMatchedElements());
// Collections.sort(elements, new Comparator<Element>() {
// @Override
// public int compare(Element e1, Element e2) {
// // TODO Auto-generated method stub
// return e1.toPrint().compareTo(e2.toPrint());
// }
// });
StringBuilder sb = new StringBuilder();
sb.append("merged models: ");
String modelId = "";
int numOfSourceModels = 0;
for(Model m: getMatch().getModels()){
modelId = modelId+m.getId();
sb.append(m.getId()).append(",");
numOfSourceModels += m.getMergedFrom();
}
//System.out.println(sb.toString());
Model merged = new Model(modelId,elements);
for(Element e:elements){
e.setModelId(modelId);
}
merged.setMergedFrom(numOfSourceModels);
//refreshResultTuplesWeight(numOfSourceModels, merged);
this.mergedModel = merged;
return merged;
}
public ArrayList<Tuple> extractMerge(){
if(this.mergedTuples != null)
return this.mergedTuples;
ArrayList<Tuple> tpls = new ArrayList<Tuple>();
Model m = mergeMatchedModels();
for(Element e:m.getElements()){
if(e.getBasedUponElements().size() > 1 || AlgoUtil.COMPUTE_RESULTS_CLASSICALLY){
tpls.add(e.getContaingTuple());
}
}
this.mergedTuples = tpls;
return tpls;
}
}
| [
"alexander.schultheiss@informatik.hu-berlin.de"
] | alexander.schultheiss@informatik.hu-berlin.de |
7e4734dc25d83cb71af4b8e7d9abda1c73a453a9 | 0403b0ed061eb22ac185f3981952c67b771551be | /CucumberLatestFramework/src/main/java/com/Pages/HotelsPage.java | df2e179df3fa3967234522bb07f676365f195496 | [] | no_license | lileshbansal/Cucumberframework | 395abef20297e18df27957e1508702528bf47304 | 1cb65dbba076ea1887866fc100e9da5c6168cbbf | refs/heads/master | 2020-04-16T03:07:46.543762 | 2019-01-14T10:55:56 | 2019-01-14T10:55:56 | 165,221,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,166 | java | package com.Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.TestBase.TestBase;
public class HotelsPage extends TestBase{
@FindBy(id = "hp-widget__sDest")
WebElement city_dropdown;
@FindBy(id = "hp-widget__chkIn")
WebElement checkin;
@FindBy(id = "hp-widget__chkOut")
WebElement checkout;
@FindBy(id = "hp-widget__paxCounter")
WebElement rooms;
@FindBy(id = "searchBtn")
WebElement searchBtn;
public HotelsPage() {
PageFactory.initElements(driver, this);
}
public void enter_city() {
city_dropdown.click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.id("//ul[@id='ui-id-1']//span[text()='Mumbai, India']")).click();
}
public void clickonSubmit() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
searchBtn.click();
}
}
| [
"lilbansa1@WKWIN3438802.global.publicisgroupe.net"
] | lilbansa1@WKWIN3438802.global.publicisgroupe.net |
cefed1884d836c6cbea0d44f4f431f0e5ab9cb01 | 2cbb913f97b7b918d16015b1aca459a32b8e594f | /src/main/java/latmod/ftbu/mod/FTBUFinals.java | 47715b00e81964a00af92a86dcf545bc4a0a7035 | [] | no_license | labolet/FTBUtilities | 6a1c4f48530fec6e38185b0035a5165f77b5e528 | 4b9d4b12de7e35ecd33584da042d9d75c9fce7a3 | refs/heads/1.7.10 | 2021-01-18T04:59:33.423572 | 2015-10-29T03:50:36 | 2015-10-29T03:50:36 | 45,157,748 | 0 | 0 | null | 2015-10-29T03:24:29 | 2015-10-29T03:24:29 | null | UTF-8 | Java | false | false | 427 | java | package latmod.ftbu.mod;
import ftb.lib.mod.FTBLibFinals;
public class FTBUFinals // FTBU
{
public static final String MOD_ID = "FTBU";
public static final String MOD_VERSION = "@VERSION@";
public static final String MOD_NAME = "FTBUtilities";
public static final String MOD_DEP = "required-after:FTBL;after:Baubles;after:Waila";
public static final String MOD_VERSION_DISPLAY = FTBLibFinals.DEV ? "Dev" : MOD_VERSION;
} | [
"latvianmodder@gmail.com"
] | latvianmodder@gmail.com |
71404a2b0201bafb1179321c648d20ea08093b82 | 244a5ccba8b06d930d90f88584aca488f4a307e4 | /tracker/src/main/java/com/all/tracker/service/VersionService.java | 877fcfa3d15560b3f1b3e7fc69cf3ad7336f7ba8 | [
"Apache-2.0"
] | permissive | josdem/client-backend | 31513adef063fcf7eaeb4633077c69ddbd21e3e9 | cfa2bfbba258406f23714480ff1d061103b5450c | refs/heads/master | 2020-12-24T13:17:51.994904 | 2013-02-13T22:03:01 | 2013-02-13T22:03:01 | 2,869,206 | 1 | 1 | null | 2016-03-10T00:23:04 | 2011-11-28T18:34:54 | Java | UTF-8 | Java | false | false | 15,346 | java | /**
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2011 Eric Haddad Koenig
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.all.tracker.service;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Properties;
import javax.annotation.PostConstruct;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import com.all.commons.Md5FileGenerator;
import com.all.tracker.model.Version;
@Service
public class VersionService {
public static final String QUERY_VERSION = "from Version where artifactId = ?";
private static final Log log = LogFactory.getLog(VersionService.class);
private static final String EXTENSION = ".zip";
private static final String UNDERSCORE = "_";
public static final String UPDATE_FILE_PATH = "version.update.base.file.path";
@Autowired
private HibernateTemplate ht;
@Autowired
private Properties settings;
private Md5FileGenerator md5FileGenerator = new Md5FileGenerator();
private String updatePath;
@PostConstruct
public void initialize() {
updatePath = settings.getProperty(UPDATE_FILE_PATH);
if (updatePath == null) {
throw new IllegalStateException("Property not found in settings.properties file: " + UPDATE_FILE_PATH);
}
}
@SuppressWarnings("unchecked")
public Version getUpdatedVersion(String clientArtifactId, String clientVersion, String os) throws NoUpdateException, FileNotFoundException {
List<Version> allVersions = ht.find(QUERY_VERSION, clientArtifactId);
if (allVersions.isEmpty()) {
throw new NoUpdateException("Artifact ID not found", new IllegalArgumentException("Could not find the artifactId: " + clientArtifactId));
}
Version latestUpdateVersion = findLatestVersion(allVersions, new Version(clientArtifactId, clientVersion));
if (latestUpdateVersion == null) {
throw new NoUpdateException("No new updates found for artifact ID: " + clientArtifactId);
}
String artifactId = latestUpdateVersion.getArtifactId();
String latestVersion = latestUpdateVersion.getVersion();
String updateFilePath = getUpdateFilePath(artifactId, latestVersion, os);
File updateFile = new File(updateFilePath);
log.debug("update file path: " + updateFilePath);
if (!updateFile.exists()) {
throw new NoUpdateException("Cannot find update file", new FileNotFoundException(updateFilePath));
}
latestUpdateVersion.setUpdateFile(updateFile);
latestUpdateVersion.setMd5Checksum(calculateMd5Checksum(updateFile));
return latestUpdateVersion;
}
private Version findLatestVersion(List<Version> versions, Version clientVersion) {
Version latestVersion = null;
for (Version version : versions) {
if (version.compareTo(clientVersion) > 0) {
latestVersion = version;
clientVersion = version;
}
}
return latestVersion;
}
// TODO cache the md5 checksum so it gets only calculated once
private String calculateMd5Checksum(File updateFile) {
byte[] calculatedMd5Checksum = md5FileGenerator.calculateMd5Checksum(updateFile);
return md5FileGenerator.getByteToBase64String(calculatedMd5Checksum);
}
private String getUpdateFilePath(String artifactId, String version, String os) {
StringBuilder sb = new StringBuilder(updatePath);
sb.append(File.separator);
sb.append(artifactId.toUpperCase());
sb.append(File.separator);
sb.append(version.toUpperCase());
sb.append(File.separator);
sb.append(artifactId.toUpperCase());
sb.append(UNDERSCORE);
sb.append(version.toUpperCase());
sb.append(UNDERSCORE);
sb.append(os.toUpperCase());
sb.append(EXTENSION);
return sb.toString();
}
}
| [
"joseluis.delacruz@gmail.com"
] | joseluis.delacruz@gmail.com |
ebadb4ff76490c28586a52bab2eaa2742b3ba5fb | 159f75d12bb51bff89497499c2dbc2971ad8dc3e | /edelta.parent/edelta/old/EdeltaEObjectAtOffsetHelper.java | a700098cb6dc9cb74735558929cbdb7e629da1d9 | [] | no_license | LorenzoBettini/edelta | f406a305b99bdf30e373cb26d097df8ae256da6c | b011c66859f7751bd8434e91d87ace681978f1c1 | refs/heads/master | 2023-07-02T10:07:46.624753 | 2023-06-08T11:36:36 | 2023-06-08T11:36:36 | 97,230,480 | 8 | 7 | null | 2023-06-08T10:02:02 | 2017-07-14T12:13:27 | Java | UTF-8 | Java | false | false | 1,720 | java | package edelta.resource;
import org.eclipse.emf.ecore.ENamedElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.xbase.XExpression;
import org.eclipse.xtext.xbase.linking.BrokenConstructorCallAwareEObjectAtOffsetHelper;
import com.google.inject.Inject;
import edelta.edelta.EdeltaEcoreReference;
import edelta.edelta.EdeltaEcoreReferenceExpression;
import edelta.resource.derivedstate.EdeltaDerivedStateHelper;
/**
* Customization for ecoreref references, using the original enamed element.
*
* @author Lorenzo Bettini
*/
public class EdeltaEObjectAtOffsetHelper extends BrokenConstructorCallAwareEObjectAtOffsetHelper {
@Inject
private EdeltaDerivedStateHelper edeltaDerivedStateHelper;
@Override
protected EObject resolveCrossReferencedElement(final INode node) {
final EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node);
if (referenceOwner instanceof EdeltaEcoreReference) {
final EdeltaEcoreReference ecoreReference = (EdeltaEcoreReference) referenceOwner;
final ENamedElement original = edeltaDerivedStateHelper
.getEcoreReferenceState(ecoreReference)
.getOriginalEnamedelement();
if (original != null)
return original;
XExpression expression = edeltaDerivedStateHelper
.getEcoreReferenceExpressionState(
EcoreUtil2.getContainerOfType(ecoreReference, EdeltaEcoreReferenceExpression.class))
.getEnamedElementXExpressionMap()
.get(ecoreReference.getEnamedelement());
if (expression != null)
return expression;
}
return super.resolveCrossReferencedElement(node);
}
}
| [
"lorenzo.bettini@gmail.com"
] | lorenzo.bettini@gmail.com |
b0bc8a815e355b07e1556605b9d0003be1fc6663 | 5d5d989ddcc8b16b09c8884569f96941d4b4c3bd | /src/doodledrop/db/UserNotExistException.java | c8510c4dc6340118fae0af6c1e2c8018fbe56a70 | [] | no_license | robinbach/DoodleDropJavaGame | 5bc712e3f1af4eb25d8576178fcc5a45c3826282 | 04d1504f86c6f0f491094d532b27753d82e47491 | refs/heads/master | 2021-01-15T20:29:22.506946 | 2014-12-01T19:33:37 | 2014-12-01T19:33:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 140 | java | package doodledrop.db;
public class UserNotExistException extends Exception
{
UserNotExistException(String str){
super(str);
}
}
| [
"dianazh@umich.edu"
] | dianazh@umich.edu |
c2e877c85e4d8ae9a06be653e86158ec7eaea33a | 32f0659b89082607d271d05e95718698b44fab64 | /15_Quiz/4팀_신동오_권연주_이민용_이수진/QuizGui/Game.java | b1952f41f65c5d7ed3e79d2d21ca59622e24823b | [] | no_license | lzhxxn/ToyProject | fbd753fd2d1d37a0d45c3a474161aaf3fb6037e3 | 31e7d61b880d831b5180af447040c8f73df1d658 | refs/heads/main | 2023-03-09T00:24:53.929978 | 2021-02-28T07:54:01 | 2021-02-28T07:54:01 | 341,750,233 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 4,190 | java | import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
class Game extends JFrame{
Container c;
JPanel pN,pS,pC;
JPanel pN1,pN2;
JLabel laName, laScore, laT;
JButton bRe, bPass, bExit;
JButton bSB, bCC;
JButton qB[] = new JButton[20];
int timeI; String timeS;
int scoreI; String scoreS;
Color bgc = new Color(59, 89, 182);
Color pbgc = new Color(237,239,236);
Color txtc = new Color(45,48,54);
//JButton text;
Game(String nameG){ //컴포넌트 컨테이너 생성
c = getContentPane();
pN = new JPanel(new GridLayout(1,2));
pN1 = new JPanel(new GridLayout(1,2));
laName = new JLabel("<html>Player<br>"+nameG+"</html>");
scoreI = 0;
scoreS = Integer.toString(scoreI);
laScore = new JLabel("<html>Score<br>"+scoreS+"</html>");
pN2 = new JPanel(new GridLayout(1,2));
bSB = new JButton("Board");
timeI = 15;
timeS = Integer.toString(timeI);
laT = new JLabel(timeS);
pC = new JPanel(new CardLayout());
makeButton(); // 문제버튼 얹기
pS = new JPanel(new BorderLayout());
ImageIcon normalIcon1 = new ImageIcon("img\\Restart.png");
bRe = new JButton(null,normalIcon1);
bPass = new JButton("Pass");
ImageIcon normalIcon2 = new ImageIcon("img\\exit.png");
bExit = new JButton(null,normalIcon2);
pN.add(pN1);
pN.add(pN2);
pN1.add(laName);pN1.add(laScore);
pN2.add(laT);
pN2.add(bSB);
pS.add(bRe, BorderLayout.WEST);
pS.add(bExit, BorderLayout.EAST);
pS.add(bPass);
c.add(pN, BorderLayout.NORTH);
c.add(pS, BorderLayout.SOUTH);
c.add(pC);
designC();
listenerSet();
setUI();
new IntTime().start();
}
void makeButton(){ //#1 문제버튼 만들기(현재 배열로 햇는데, 컬렉션으로 바꿔야할듯)
for(int i=0;i<qB.length;i++){
qB[i] = new JButton(Integer.toString(i));
qB[i].setBackground(bgc);
qB[i].setForeground(Color.WHITE);
qB[i].setFocusPainted(false);
qB[i].setFont(new Font("굴림체", Font.BOLD, 20));
pC.add(qB[i]);
}
}
void designC(){ //여기서 컴포넌트 꾸며주세요~~
pN.setBackground(bgc);
pN1.setBackground(pbgc);
Border oBN = laName.getBorder();
Border eBorder = new EmptyBorder(20, 10, 20, 10);
CompoundBorder cBN = new CompoundBorder(oBN, eBorder);
laName.setBorder(cBN);
laName.setFont(new Font("Tahoma", Font.BOLD, 15));
laName.setBackground(pbgc);
laName.setForeground(txtc);
laName.setOpaque(true);
Border oBS = laScore.getBorder();
CompoundBorder cBS = new CompoundBorder(oBS, eBorder);
laScore.setBorder(cBS);
laScore.setFont(new Font("Tahoma", Font.BOLD, 15));
laScore.setBackground(pbgc);
laScore.setForeground(txtc);
laScore.setOpaque(true);
pN2.setBackground(pbgc);
laT.setFont(new Font("Tahoma", Font.BOLD, 25));
laT.setHorizontalAlignment(JLabel.CENTER);
bSB.setFont(new Font("Tahoma", Font.BOLD, 15));
bSB.setBackground(pbgc);
bSB.setForeground(txtc);
pC.setBackground(bgc);
bRe.setBackground(pbgc);
bPass.setFont(new Font("Tahoma", Font.BOLD, 30));
bPass.setBackground(pbgc);
bPass.setForeground(txtc);
bExit.setBackground(pbgc);
}
void listenerSet(){
ActionListener gameH = new GameHandler(this);
bSB.addActionListener(gameH);
bPass.addActionListener(gameH);
bRe.addActionListener(gameH);
bExit.addActionListener(gameH);
for(int i=0;i<qB.length;i++){
qB[i].addActionListener(gameH);
}
}
class IntTime extends Thread{
public void run(){
while(true){
try{
Thread.sleep(1000);
timeI -= 1;
timeS = Integer.toString(timeI);
//System.out.println(timeS);
if(timeI == 10) laT.setFont(new Font("Tahoma", Font.BOLD, 45));
laT.setText(timeS);
if(timeI == 0) break;
}catch(InterruptedException iie){
}
}
//text = new JButton("Time Out");
laT.setFont(new Font("Tahoma", Font.BOLD, 18));
laT.setText("Time Over");
validate();
}
}
void setUI(){
setTitle("PLAY");
setSize(400, 400);
setVisible(true);
//setLocation(350, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
}
public static void main(String[] args) {
//new Game("신동오");
}
}
| [
"75344302+lzhxxn@users.noreply.github.com"
] | 75344302+lzhxxn@users.noreply.github.com |
1979db8189d65a77e15ccca91b3da95a82fd793e | c87176ed15135df616111f8de3e8b836ab32d91a | /Dialog1/app/src/main/java/com/example/cglin/dialog1/MainActivity.java | fc556dd17530d97bca4c0ddbf760ad3325ea1d2a | [] | no_license | CGLingit/Android | 8759247d79015804bb8280892102929902a550ea | ce1e979a9aa4d13994fbf16b16dd7ee8828a8013 | refs/heads/master | 2021-01-22T17:52:30.234660 | 2017-04-25T13:03:14 | 2017-04-25T13:03:14 | 85,038,791 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,227 | java | package com.example.cglin.dialog1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(android.R.drawable.ic_dialog_info);
dialog.setTitle("Welcome");
dialog.setMessage("欢迎使用本程序");
dialog.setPositiveButton("肯定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//确定完成的事情
}
});
dialog.setNegativeButton("否定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//否定的事情
}
});
dialog.create();
dialog.show();
}
}
| [
"1542102449@qq.com"
] | 1542102449@qq.com |
bc0e5725b683ca76eb58d3594790d2ab3eabb400 | 772d3e6ac425b1e6fa13ef3858adecf4eb51e8dc | /test/NullPointerExceptionExam.java | f373a26322b0544b73b1a5d04ebd9c4288aee7c6 | [] | no_license | go88hoontops/java | 2723a13decbf5eaf7a4928476a76e94341f5c58c | ea7c4f2f577874dc1ec8ab5d5f7f910432ab3f37 | refs/heads/master | 2023-04-06T09:10:10.373247 | 2021-04-06T01:09:46 | 2021-04-06T01:09:46 | 355,005,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package com.jh.test;
public class NullPointerExceptionExam {
public static void main(String[] args) {
String data =null;
//전처리
//에러가 생기지않게 처리.
System.out.println("asdasdasd");
}
}
| [
"go88.hoon@gmail.com"
] | go88.hoon@gmail.com |
a6eaa8496059559dabbd9797c72deb8867eb8ace | 08542aed048e8cc31c1f111c7c002a070264f900 | /src/com/android/settings/ConfirmLockPassword.java | 0e802dc81982fb6381d4833b52ea894fd180cbf4 | [] | no_license | thehacker911/LG_Launcher | f2922ccf435e0f7c6d616cfbb68735d51c4efd6a | 91696e501e9d56f1941137dd685539e0a5b5743d | refs/heads/master | 2020-05-18T03:41:01.096277 | 2014-02-26T15:39:52 | 2014-02-26T15:39:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,794 | java | package com.android.settings;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.PasswordEntryKeyboardHelper;
import com.android.internal.widget.PasswordEntryKeyboardView;
public class ConfirmLockPassword extends PreferenceActivity
{
public Intent getIntent()
{
Intent localIntent = new Intent(super.getIntent());
localIntent.putExtra(":android:show_fragment", ConfirmLockPasswordFragment.class.getName());
localIntent.putExtra(":android:no_headers", true);
return localIntent;
}
protected boolean isValidFragment(String paramString)
{
return ConfirmLockPasswordFragment.class.getName().equals(paramString);
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
CharSequence localCharSequence = getText(2131428314);
showBreadCrumbs(localCharSequence, localCharSequence);
}
public static class ConfirmLockPasswordFragment extends Fragment
implements TextWatcher, View.OnClickListener, TextView.OnEditorActionListener
{
private Button mContinueButton;
private Handler mHandler = new Handler();
private TextView mHeaderText;
private PasswordEntryKeyboardHelper mKeyboardHelper;
private PasswordEntryKeyboardView mKeyboardView;
private LockPatternUtils mLockPatternUtils;
private TextView mPasswordEntry;
private void handleNext()
{
String str = this.mPasswordEntry.getText().toString();
if (this.mLockPatternUtils.checkPassword(str))
{
Intent localIntent = new Intent();
localIntent.putExtra("password", str);
getActivity().setResult(-1, localIntent);
getActivity().finish();
return;
}
showError(2131428328);
}
private void showError(int paramInt)
{
this.mHeaderText.setText(paramInt);
this.mHeaderText.announceForAccessibility(this.mHeaderText.getText());
this.mPasswordEntry.setText(null);
this.mHandler.postDelayed(new Runnable()
{
public void run()
{
ConfirmLockPassword.ConfirmLockPasswordFragment.this.mHeaderText.setText(2131428314);
}
}
, 3000L);
}
public void afterTextChanged(Editable paramEditable)
{
Button localButton = this.mContinueButton;
if (this.mPasswordEntry.getText().length() > 0);
for (boolean bool = true; ; bool = false)
{
localButton.setEnabled(bool);
return;
}
}
public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3)
{
}
public void onClick(View paramView)
{
switch (paramView.getId())
{
default:
return;
case 2131230763:
handleNext();
return;
case 2131230762:
}
getActivity().setResult(0);
getActivity().finish();
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
this.mLockPatternUtils = new LockPatternUtils(getActivity());
}
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
int i = this.mLockPatternUtils.getKeyguardStoredPasswordQuality();
View localView = paramLayoutInflater.inflate(2130968600, null);
localView.findViewById(2131230762).setOnClickListener(this);
this.mContinueButton = ((Button)localView.findViewById(2131230763));
this.mContinueButton.setOnClickListener(this);
this.mContinueButton.setEnabled(false);
this.mPasswordEntry = ((TextView)localView.findViewById(2131230761));
this.mPasswordEntry.setOnEditorActionListener(this);
this.mPasswordEntry.addTextChangedListener(this);
this.mKeyboardView = ((PasswordEntryKeyboardView)localView.findViewById(2131230764));
this.mHeaderText = ((TextView)localView.findViewById(2131230759));
int j;
int k;
label156: int m;
label204: int n;
label239: PreferenceActivity localPreferenceActivity;
if ((262144 == i) || (327680 == i) || (393216 == i))
{
j = 1;
TextView localTextView1 = this.mHeaderText;
if (j == 0)
break label296;
k = 2131428314;
localTextView1.setText(k);
Activity localActivity = getActivity();
this.mKeyboardHelper = new PasswordEntryKeyboardHelper(localActivity, this.mKeyboardView, this.mPasswordEntry);
PasswordEntryKeyboardHelper localPasswordEntryKeyboardHelper = this.mKeyboardHelper;
if (j == 0)
break label303;
m = 0;
localPasswordEntryKeyboardHelper.setKeyboardMode(m);
this.mKeyboardView.requestFocus();
n = this.mPasswordEntry.getInputType();
TextView localTextView2 = this.mPasswordEntry;
if (j == 0)
break label309;
localTextView2.setInputType(n);
if ((localActivity instanceof PreferenceActivity))
{
localPreferenceActivity = (PreferenceActivity)localActivity;
if (j == 0)
break label316;
}
}
label296: label303: label309: label316: for (int i1 = 2131428314; ; i1 = 2131428316)
{
CharSequence localCharSequence = getText(i1);
localPreferenceActivity.showBreadCrumbs(localCharSequence, localCharSequence);
return localView;
j = 0;
break;
k = 2131428316;
break label156;
m = 1;
break label204;
n = 18;
break label239;
}
}
public boolean onEditorAction(TextView paramTextView, int paramInt, KeyEvent paramKeyEvent)
{
if ((paramInt == 0) || (paramInt == 6) || (paramInt == 5))
{
handleNext();
return true;
}
return false;
}
public void onPause()
{
super.onPause();
this.mKeyboardView.requestFocus();
}
public void onResume()
{
super.onResume();
this.mKeyboardView.requestFocus();
}
public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3)
{
}
}
}
/* Location: C:\dex 2 jar\classes-dex2jar.jar
* Qualified Name: com.android.settings.ConfirmLockPassword
* JD-Core Version: 0.6.2
*/ | [
"maikdiebenkorn@outlook.com"
] | maikdiebenkorn@outlook.com |
9a6f70e759e336c264ca0b3d3d8214bcbc6b65eb | 4c80a78ea7dd17a81b3beeafc2510452431a756a | /src/main/java/com/hcl/ing/hungerbox/dto/ItemResponseDto.java | 053617df4cf2b9cdfb76383da6badb7c62def755 | [] | no_license | bojjasrirajesh/HungerBox | 2f5ad59d11007b8d6030fe9b996e4c4ab8421182 | b2e8cf47db60cee890a573b2b5b22aa92bed3d2d | refs/heads/master | 2020-12-28T14:54:56.892606 | 2020-02-06T10:26:35 | 2020-02-06T10:26:35 | 238,378,330 | 0 | 1 | null | 2020-02-05T08:46:16 | 2020-02-05T05:52:36 | Java | UTF-8 | Java | false | false | 847 | java | package com.hcl.ing.hungerbox.dto;
import java.io.Serializable;
import java.util.List;
import com.hcl.ing.hungerbox.entity.Items;
public class ItemResponseDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String message;
private Integer statusCode;
private List<Items> items;
private Items item;
public Items getItem() {
return item;
}
public void setItem(Items item) {
this.item = item;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
| [
"bojja.r@HCL.COM"
] | bojja.r@HCL.COM |
ebf13310d6f113b218ec610cfe6328c69fdbfd01 | f2e493bf3fe8398128742c57ad088adca4a7efd2 | /baselibrary/src/main/java/com/fastaoe/baselibrary/permission/PermissionUtils.java | a73ea69ad0e8333b835e0b36053e1373d13c0cc7 | [] | no_license | jsntjinjin/android-proficient | 8f6744f97c95cb1ca92938285666de60684e0dc6 | 3dd341c4736d95932550d64a3c40dd8b2f12e049 | refs/heads/master | 2020-12-03T00:10:39.645770 | 2017-07-07T09:50:55 | 2017-07-07T09:50:55 | 95,995,504 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,732 | java | package com.fastaoe.baselibrary.permission;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jinjin on 2017/6/11.
*/
public class PermissionUtils {
private PermissionUtils() {
throw new UnsupportedOperationException("can not instantiated!");
}
public static boolean isOverM() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return true;
} else {
return false;
}
}
// 执行授权成功方法
public static void executeSuccessMethod(Object object, int requestCode) {
Method[] methods = object.getClass().getDeclaredMethods();
for (Method method : methods) {
PermissionSuccess success = method.getAnnotation(PermissionSuccess.class);
if (success != null && success.requestCode() == requestCode) {
executeMethod(method, object);
}
}
}
private static void executeMethod(Method method, Object object) {
try {
method.setAccessible(true);
method.invoke(object);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取没有授权的权限
public static List<String> getDeniedPermission(Object object, String[] requestPermissions) {
List<String> deniedPermissions = new ArrayList<>();
for (String requestPermission : requestPermissions) {
// 遍历获取到没有授权的权限
if (ContextCompat.checkSelfPermission(getActivity(object), requestPermission)
== PackageManager.PERMISSION_DENIED) {
deniedPermissions.add(requestPermission);
}
}
return deniedPermissions;
}
public static Activity getActivity(Object object) {
if (object instanceof Activity) {
return (Activity) object;
} else {
return ((Fragment) object).getActivity();
}
}
// 执行授权拒绝方法
public static void executeFailureMethod(Object object, int requestCode) {
Method[] methods = object.getClass().getDeclaredMethods();
for (Method method : methods) {
PermissionFailure success = method.getAnnotation(PermissionFailure.class);
if (success != null && success.requestCode() == requestCode) {
executeMethod(method, object);
}
}
}
}
| [
"313919790@qq.com"
] | 313919790@qq.com |
ce3e15d39770b5146ce72697146addecbd8a40a1 | 22967aea1664d9bb13a096888031217920024334 | /src/main/java/com/example/demo/config/WebSecurityConfiguration.java | f93281e4bec1f261b1101ee8fdba2a8360ac4bdf | [] | no_license | dileepkeeppalli/backend | ae2fb2edb1c850e7320377275d08cbae8bb68db8 | ea1b3c9dd0b2a8e96995bd608a9eb9de07c3a95e | refs/heads/master | 2021-05-21T21:52:37.484285 | 2020-04-03T19:28:13 | 2020-04-03T19:28:13 | 252,817,636 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 694 | java | package com.example.demo.config;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
}
| [
"dileepkeeppalli@gmail.com"
] | dileepkeeppalli@gmail.com |
253c992930bdedfb9788c24451237c50bcb16c34 | 857a1fda631712321b78ae9b9f9ca6482365a657 | /src/HomeWork16/myThread.java | 941acd0cfed7629f4f88eef70584c33b2e41fe6e | [] | no_license | fekdas/CSvorob_JHomeWork | f7b8bb05b80d4e700ba91ca37f3f9dd27534698d | 90ef418b2122b602b9fb7bc7af769256aa7011bb | refs/heads/master | 2021-01-10T11:28:20.143800 | 2016-03-14T15:53:26 | 2016-03-14T15:53:26 | 51,298,930 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 372 | java | package HomeWork16;
public class myThread extends Thread {
public void run() {
for (int i = 0; i<11;i++) {
HomeWork16task2task3.print10();
try {
Thread.sleep(505);
}
catch (InterruptedException e)
{
System.out.println("sleep не отработал как надо" + e.getMessage());
}
}
}
}
| [
"constantine.svorob@gmail.com"
] | constantine.svorob@gmail.com |
475d642b56480de71e0f367b83394eec457b0e44 | fca7ff6789824ac9af76794de6df23f8b1d50158 | /Online_Charity_Website_SpringBoot_Project/src/main/java/com/capgemini/exception/NoSuchEventFoundException.java | 783154914492e2b4593591d61e8914e5fa33fb2c | [] | no_license | wefouryou143/wefouryou143-Online_Charity_Website | d3d3a0cf3a0049a6b863bb938f107ecedd89fb34 | 8fd159ac9ae10d8e2d207e5a49cce6427fa832b7 | refs/heads/master | 2023-07-02T03:00:41.716140 | 2021-08-05T14:02:22 | 2021-08-05T14:02:22 | 393,053,517 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 233 | java | package com.capgemini.exception;
public class NoSuchEventFoundException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public NoSuchEventFoundException(String message) {
super(message);
}
}
| [
"wefouryou.143@gmail.com"
] | wefouryou.143@gmail.com |
73f743f85b3e136c9b42cddc802cb7856029c2c8 | 9673e33e34e5d7607458bf4867b836f66e659cfe | /src/testing/java/org/msyu/reinforce/target/testing/junit/JUnitTarget.java | 0229e06d62f48ad256308095aa6b90aaf82e0dc9 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | ypoluektovich/reinforce | 32a2ea05ca9bb130e68429ddc8c11eb2ea27def1 | 99530276ed51f5e6202a95bde3bc32b6b269efd2 | refs/heads/master | 2021-01-10T20:13:39.028353 | 2013-10-09T12:13:55 | 2013-10-09T12:13:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,887 | java | package org.msyu.reinforce.target.testing.junit;
import org.hamcrest.Matcher;
import org.junit.runner.JUnitCore;
import org.msyu.reinforce.Build;
import org.msyu.reinforce.ExecutionException;
import org.msyu.reinforce.Log;
import org.msyu.reinforce.TargetInitializationException;
import org.msyu.reinforce.TargetInvocation;
import org.msyu.reinforce.target.ActionOnEmptySource;
import org.msyu.reinforce.target.testing.AJavaBasedTestingTarget;
import org.msyu.reinforce.util.definition.SettingParserUtil;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JUnitTarget extends AJavaBasedTestingTarget<TestDescription> {
public JUnitTarget(TargetInvocation invocation) {
super(invocation);
}
@Override
protected final Set<Class<?>> getRequiredClassesForRunner() {
return new HashSet<>(Arrays.asList(JUnitRunner.class, JUnitCore.class, Matcher.class));
}
@Override
protected final TestDescription newTestDescription(ActionOnEmptySource onMissing, Map testMap) throws TargetInitializationException {
TestDescription testDescription = new TestDescription(onMissing);
try {
SettingParserUtil.parseSingle(
testMap,
Arrays.asList(new AllInCollectionTestParser(testDescription))
);
} catch (TargetInitializationException e) {
throw new TargetInitializationException("could not determine what tests to run", e);
}
return testDescription;
}
@Override
protected void run(TestDescription testDescription, int index, Path workingDir) throws ExecutionException {
Path testDescFile = prepareDescriptionFile(workingDir, index, testDescription);
executeRunner(testDescFile);
}
private Path prepareDescriptionFile(Path workingDir, int testIndex, TestDescription testDescription) throws ExecutionException {
Path testDescriptionFile = workingDir.resolve("tests." + testIndex + ".dat");
try (ObjectOutput output = new ObjectOutputStream(Files.newOutputStream(testDescriptionFile))) {
testDescription.serialize(output);
} catch (IOException e) {
throw new ExecutionException("error while writing test description file");
}
return testDescriptionFile;
}
private void executeRunner(Path testDescFile) throws ExecutionException {
int exitCode;
try {
List<String> commandLine = getCommandLineArray(testDescFile);
Log.debug("Command line arguments: %s", commandLine);
Log.verbose("Starting external process...");
Process process = new ProcessBuilder(commandLine)
.directory(Build.getCurrent().getBasePath().toFile())
.inheritIO()
.start();
while (true) {
try {
exitCode = process.waitFor();
break;
} catch (InterruptedException e) {
Log.debug("The thread waiting for the JUnit runner got interrupted. Ignoring...");
}
}
} catch (IOException e) {
throw new ExecutionException("exception during JUnit invocation", e);
}
Log.verbose("Process exited with code %d", exitCode);
if (exitCode != 0) {
throw new ExecutionException("JUnit runner exited with status code: " + exitCode);
}
}
private List<String> getCommandLineArray(Path testDescFile) {
List<String> commandArgs = new ArrayList<>();
commandArgs.add(getJavaExecutable());
commandArgs.add("-cp");
commandArgs.add(getRunnerClasspathString());
commandArgs.add(JUnitRunner.class.getName());
commandArgs.add(testDescFile.toString());
return commandArgs;
}
private String getRunnerClasspathString() {
StringBuilder sb = new StringBuilder();
for (String entry : myRunnerClasspath) {
if (sb.length() > 0) {
sb.append(System.getProperty("path.separator"));
}
sb.append(entry);
}
return sb.toString();
}
}
| [
"ypoluektovich@gmail.com"
] | ypoluektovich@gmail.com |
34509f7cfa4ee5eb1f3d150cffd1e5fc28f301cb | 5a896a60704b137fdc5cea77f1848edd53562b00 | /app/src/main/java/com/example/my/fragmentSG.java | 017ec06d18557bb13663401b847d5aaeeaec1540 | [] | no_license | weiwangqiang/-jianmi | 06a7df015af3e5a9038baa9d93fd6e5af63b00fe | 4ae9a92ea5f89e5b003176b043b910e029e4b2c6 | refs/heads/master | 2021-01-21T11:18:34.418229 | 2017-11-12T03:34:51 | 2017-11-12T03:34:51 | 83,548,036 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,092 | java | package com.example.my;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.adapter.baomingAdapter;
import com.example.object.Orders;
import com.example.wangqiang.jianmi1.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wangqiang on 2016/7/10.
* 上岗
*/
public class fragmentSG extends Fragment{
private ListView listview;
private List<Orders> list = new ArrayList<>();
private baomingAdapter adapter;
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.main_my_apply_list,container,false);
init();
return view;
}
public void init(){
listview = (ListView)view.findViewById(R.id.my_apply_list);
adapter = new baomingAdapter(getActivity(),list,
R.layout.main_my_apply_worklistitem,
new String[]{"image","title","time","money","location"},
new int[]{R.id.my_apply_listItem_image,
R.id.my_apply_listItem_title,
R.id.my_apply_listItem_time,
R.id.my_apply_listItem_money,
R.id.my_apply_listItem_location,
R.id.my_apply_listItem_connect,
R.id.my_apply_listItem_cancel
});
listview.setAdapter(adapter);
}
@Override
public void onStart() {
// TODO Auto-generated method stub
Log.e("HJJ", "fragmentSG **** onStart...");
super.onStart();
}
@Override
public void onResume() {
Log.e("HJJ", "fragmentSG **** onResume...");
// TODO Auto-generated method stub
super.onResume();
}
/**
* 打开另一个activity,退出程序,调用onPause,onStop
*/
@Override
public void onPause() {
Log.e("HJJ", "fragmentSG **** onPause...");
// TODO Auto-generated method stub
super.onPause();
}
@Override
public void onStop() {
Log.e("HJJ", "fragmentSG **** onStop...");
// TODO Auto-generated method stub
super.onStop();
}
@Override
public void onDestroyView() {
Log.e("HJJ", "fragmentSG **** onDestroyView...");
// TODO Auto-generated method stub
super.onDestroyView();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.e("HJJ", "fragmentSG **** onDestroy...");
super.onDestroy();
}
@Override
public void onDetach() {
Log.e("HJJ", "fragmentSG **** onDetach...");
// TODO Auto-generated method stub
super.onDetach();
}
//fragment 是否被隐藏,解决viewPager 有白画面的情况
@Override
public void onHiddenChanged (boolean hidden){
Log.e("fragmentSG is ",""+hidden);
}
}
| [
"1198039102@qq.com"
] | 1198039102@qq.com |
81f853d92f6df605be56ef33a72e36eac3f3ae79 | 400bbe1f189d1a91ef43bd87110908d8a4f3da7e | /src/main/java/com/example/demo/persistence/model/Author.java | 5e3568a5542759b96d3e8051aab7f584de84dc72 | [] | no_license | anushghazaryan261/authors_books | 7fcfd8070a56e869e42c4d9b2a0dc64a1971c7f0 | b8d30e391a44d1fbc8bc604d15a11d2ddff6401f | refs/heads/master | 2021-04-14T18:35:14.587281 | 2020-03-22T19:17:26 | 2020-03-22T19:17:26 | 249,248,669 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,642 | java | package com.example.demo.persistence.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "authors")
public class Author extends AbstractBaseEntity {
private String name;
private String surname;
public Author() {
}
@ManyToMany(fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE},mappedBy = "authors")
private Set<Book> books=new HashSet<>();
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Author author = (Author) o;
return Objects.equals(name, author.name) &&
Objects.equals(surname, author.surname) &&
Objects.equals(books, author.books);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name, surname, books);
}
@Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", surname='" + surname + '\'' +
", books=" + books +
'}';
}
}
| [
"anushik.ghazaryan@gmail.com"
] | anushik.ghazaryan@gmail.com |
a0ba48d978f52cab84c463a26b38fbf934f52519 | dc6fa886881d6dce63564fabc956b2867897ef91 | /src/main/java/school/lemon/changerequest/java/FractionNumber.java | 70a6b2a141970c3ac5b4c7038ee9cb59ec83a815 | [
"Apache-2.0"
] | permissive | dianasinenchenko/oop.pr1 | 3c7b504d67b0a6277eb71b8fe080211ea5f1a43a | 84d462397d43bca12bf19f962d9dd11813621a56 | refs/heads/master | 2021-01-12T08:19:49.428674 | 2017-01-06T14:14:05 | 2017-01-06T14:14:05 | 76,540,722 | 0 | 0 | null | 2016-12-15T08:40:48 | 2016-12-15T08:40:48 | null | UTF-8 | Java | false | false | 3,374 | java | package school.lemon.changerequest.java;
/**
* Created by Diana on 05.01.2017.
*/
public class FractionNumber {
private int dividend;
private int divisor;
public FractionNumber(int dividend, int divisor) {
if (divisor == 0) throw new ArithmeticException("You divisor is 0, incorrect value");
if (dividend == 0) {
this.dividend = dividend;
this.divisor = 1;
}
this.dividend = dividend;
this.divisor = divisor;
int GreatestCommonDivisor = GreatestCommonDivisor(this.dividend, this.divisor);
this.dividend = dividend / GreatestCommonDivisor;
this.divisor = divisor / GreatestCommonDivisor;
}
public int GreatestCommonDivisor(int dividend, int divisor) {
return divisor == 0 ? dividend : GreatestCommonDivisor(divisor, dividend % divisor);
}
public FractionNumber(int dividend) {
this.dividend = dividend;
this.divisor = 1;
}
public int GetDividend() {
return dividend;
}
public int GetDivisor() {
return divisor;
}
public double GetDecimalValue() {
return (double) dividend / (double) divisor;
}
public String ToString() {
return String.format("%1$d/%2$d", dividend, divisor);
}
public FractionNumber AddAnotherFractionNumber(FractionNumber anotherFractionNumber) {
int anotherDividend;
int anotherDivisor;
if (divisor == anotherFractionNumber.divisor) {
anotherDividend = divisor + anotherFractionNumber.dividend;
anotherDivisor = divisor;
} else {
anotherDivisor = anotherFractionNumber.divisor * divisor;
anotherDividend = anotherFractionNumber.dividend * divisor + dividend * anotherFractionNumber.divisor;
}
return new FractionNumber(anotherDividend, anotherDivisor);
}
public FractionNumber SubtractAnotherFractionNumber(FractionNumber anotherFractionNumber) {
int anotherDividend;
int anotherDivisor;
if (divisor == anotherFractionNumber.divisor) {
anotherDividend = divisor - anotherFractionNumber.dividend;
anotherDivisor = divisor;
} else {
anotherDivisor = anotherFractionNumber.divisor * divisor;
anotherDividend = anotherFractionNumber.dividend * divisor - dividend * anotherFractionNumber.divisor;
}
return new FractionNumber(anotherDividend, anotherDivisor);
}
public FractionNumber MultiplyAnotherFractionNumber(FractionNumber anotherFractionNumber) {
int anotherDividend;
int anotherDivisor;
anotherDivisor = anotherFractionNumber.divisor * divisor;
anotherDividend = anotherFractionNumber.dividend * dividend;
return new FractionNumber(anotherDividend, anotherDivisor);
}
public FractionNumber DivideAnotherFractionNumber(FractionNumber anotherFractionNumber) {
int anotherDividend;
int anotherDivisor;
anotherDivisor = anotherFractionNumber.divisor * dividend;
anotherDividend = anotherFractionNumber.dividend * divisor;
return new FractionNumber(anotherDividend, anotherDivisor);
}
public final static FractionNumber ONE = new FractionNumber(1, 1);
public final static FractionNumber ZERRo = new FractionNumber(0, 1);
}
| [
"diana.sinenchenko@gmail.com"
] | diana.sinenchenko@gmail.com |
bdbdd2c4da8c7b9c5e1936a007a161a8147fc044 | 99129174f5044768333f09796274b63c737c0eed | /app/src/test/java/com/anysoftkeyboard/keyboards/ExternalAnyKeyboardTest.java | bf44d7ee08aa38df5ff06b215bfef816f2ff543d | [
"Apache-2.0"
] | permissive | jannat412/AnySoftKeyboard | ed96d3dc9badbc59eedf049c68a04cedca921d74 | 58f7291ef91cafac01d88614b10c7b2e1a956484 | refs/heads/master | 2021-05-11T21:19:10.652669 | 2018-01-13T03:34:42 | 2018-01-13T03:34:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,816 | java | package com.anysoftkeyboard.keyboards;
import android.content.Context;
import android.text.TextUtils;
import com.anysoftkeyboard.AnySoftKeyboardTestRunner;
import com.anysoftkeyboard.addons.AddOn;
import com.anysoftkeyboard.addons.DefaultAddOn;
import com.anysoftkeyboard.api.KeyCodes;
import com.anysoftkeyboard.keyboards.views.KeyDrawableStateProvider;
import com.menny.android.anysoftkeyboard.AnyApplication;
import com.menny.android.anysoftkeyboard.R;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
@RunWith(AnySoftKeyboardTestRunner.class)
public class ExternalAnyKeyboardTest {
public static final KeyboardDimens SIMPLE_KeyboardDimens = new KeyboardDimens() {
@Override
public int getKeyboardMaxWidth() {
return 480;
}
@Override
public float getKeyHorizontalGap() {
return 1;
}
@Override
public float getRowVerticalGap() {
return 2;
}
@Override
public int getNormalKeyHeight() {
return 5;
}
@Override
public int getSmallKeyHeight() {
return 4;
}
@Override
public int getLargeKeyHeight() {
return 6;
}
};
private AddOn mDefaultAddOn;
private Context mContext;
@Before
public void setup() {
mContext = RuntimeEnvironment.application;
mDefaultAddOn = new DefaultAddOn(mContext, mContext);
}
@Test
public void testGeneralProperties() throws Exception {
AnyKeyboard keyboard = AnyApplication.getKeyboardFactory(RuntimeEnvironment.application).getEnabledAddOn().createKeyboard(Keyboard.KEYBOARD_ROW_MODE_NORMAL);
Assert.assertNotNull(keyboard);
Assert.assertTrue(keyboard instanceof ExternalAnyKeyboard);
Assert.assertEquals("en", keyboard.getDefaultDictionaryLocale());
Assert.assertEquals("English", keyboard.getKeyboardName());
Assert.assertEquals("c7535083-4fe6-49dc-81aa-c5438a1a343a", keyboard.getKeyboardId());
Assert.assertEquals(R.drawable.ic_stat_en, keyboard.getKeyboardIconResId());
Assert.assertEquals(1, keyboard.getKeyboardMode());
}
@Test
public void testLoadedKeyboard() throws Exception {
AnyKeyboard keyboard = AnyApplication.getKeyboardFactory(RuntimeEnvironment.application).getEnabledAddOn().createKeyboard(Keyboard.KEYBOARD_ROW_MODE_NORMAL);
Assert.assertNotNull(keyboard);
keyboard.loadKeyboard(SIMPLE_KeyboardDimens);
Assert.assertEquals(SIMPLE_KeyboardDimens.getKeyboardMaxWidth(), keyboard.getMinWidth());
Assert.assertEquals(48, keyboard.getHeight());
Assert.assertEquals(40, keyboard.getKeys().size());
Assert.assertNotNull(keyboard.getShiftKey());
Assert.assertEquals(KeyCodes.SHIFT, keyboard.getShiftKey().mCodes[0]);
}
@Test
public void testDrawableState() throws Exception {
//NOTE: this is used ONLY for the key's background drawable!
AnyKeyboard keyboard = AnyApplication.getKeyboardFactory(RuntimeEnvironment.application).getEnabledAddOn().createKeyboard(Keyboard.KEYBOARD_ROW_MODE_NORMAL);
Assert.assertNotNull(keyboard);
keyboard.loadKeyboard(SIMPLE_KeyboardDimens);
KeyDrawableStateProvider provider = new KeyDrawableStateProvider(1, 2, 3, 4, 5);
AnyKeyboard.AnyKey key = (AnyKeyboard.AnyKey) keyboard.getKeys().get(4);
Assert.assertFalse(key.isFunctional());
Assert.assertArrayEquals(provider.KEY_STATE_NORMAL, key.getCurrentDrawableState(provider));
key.onPressed();
Assert.assertArrayEquals(provider.KEY_STATE_PRESSED, key.getCurrentDrawableState(provider));
key.onReleased();
Assert.assertArrayEquals(provider.KEY_STATE_NORMAL, key.getCurrentDrawableState(provider));
AnyKeyboard.AnyKey shiftKey = (AnyKeyboard.AnyKey) keyboard.getShiftKey();
Assert.assertNotNull(shiftKey);
Assert.assertEquals(KeyCodes.SHIFT, shiftKey.getPrimaryCode());
Assert.assertTrue(shiftKey.isFunctional());
Assert.assertArrayEquals(provider.KEY_STATE_FUNCTIONAL_NORMAL, shiftKey.getCurrentDrawableState(provider));
shiftKey.onPressed();
Assert.assertArrayEquals(provider.KEY_STATE_FUNCTIONAL_PRESSED, shiftKey.getCurrentDrawableState(provider));
shiftKey.onReleased();
Assert.assertArrayEquals(provider.KEY_STATE_FUNCTIONAL_NORMAL, shiftKey.getCurrentDrawableState(provider));
//enter
AnyKeyboard.AnyKey enterKey = (AnyKeyboard.AnyKey) keyboard.getKeys().get(keyboard.getKeys().size() - 1);
Assert.assertNotNull(enterKey);
Assert.assertEquals(KeyCodes.ENTER, enterKey.getPrimaryCode());
Assert.assertTrue(enterKey.isFunctional());
Assert.assertArrayEquals(provider.KEY_STATE_ACTION_NORMAL, enterKey.getCurrentDrawableState(provider));
enterKey.onPressed();
Assert.assertArrayEquals(provider.KEY_STATE_ACTION_PRESSED, enterKey.getCurrentDrawableState(provider));
enterKey.onReleased();
Assert.assertArrayEquals(provider.KEY_STATE_ACTION_NORMAL, enterKey.getCurrentDrawableState(provider));
}
@Test
public void testCodesParsing() throws Exception {
ExternalAnyKeyboard keyboard = new ExternalAnyKeyboard(mDefaultAddOn, mContext, mContext,
R.xml.keyboard_with_codes_as_letters, R.xml.keyboard_with_codes_as_letters,
"test", R.drawable.sym_keyboard_notification_icon, 0, "en", "", "", Keyboard.KEYBOARD_ROW_MODE_NORMAL);
keyboard.loadKeyboard(SIMPLE_KeyboardDimens);
final Keyboard.Key keyZ = keyboard.getKeys().get(0);
Assert.assertNotNull(keyZ);
Assert.assertEquals((int) 'z', keyZ.getPrimaryCode());
Assert.assertEquals((int) 'z', keyZ.getCodeAtIndex(0, false));
Assert.assertEquals((int) 'Z', keyZ.getCodeAtIndex(0, true));
Assert.assertEquals("1żžź", keyZ.popupCharacters.toString());
Assert.assertEquals(R.xml.popup_one_row, keyZ.popupResId);
final Keyboard.Key keyX = keyboard.getKeys().get(1);
Assert.assertNotNull(keyX);
Assert.assertEquals((int) 'x', keyX.getPrimaryCode());
Assert.assertEquals((int) 'x', keyX.getCodeAtIndex(0, false));
Assert.assertEquals((int) 'X', keyX.getCodeAtIndex(0, true));
Assert.assertTrue(TextUtils.isEmpty(keyX.popupCharacters));
Assert.assertEquals(0, keyX.popupResId);
/*disabled due to Robolectric issue: https://github.com/robolectric/robolectric/pull/3671
final AnyKeyboard.AnyKey key3 = (AnyKeyboard.AnyKey) keyboard.getKeys().get(2);
Assert.assertNotNull(key3);
Assert.assertEquals("\'", key3.label.toString());
Assert.assertEquals((int) '\'', key3.getPrimaryCode());
Assert.assertEquals((int) '\'', key3.getCodeAtIndex(0, false));
Assert.assertEquals((int) '\"', key3.getCodeAtIndex(0, true));
Assert.assertEquals("„\"”", key3.popupCharacters.toString());
Assert.assertEquals(R.xml.popup_one_row, key3.popupResId);
Assert.assertTrue(key3.isFunctional());
*/
final AnyKeyboard.AnyKey keyMinus4 = (AnyKeyboard.AnyKey) keyboard.getKeys().get(3);
Assert.assertNotNull(keyMinus4);
Assert.assertEquals(-4, keyMinus4.getPrimaryCode());
Assert.assertEquals(-4, keyMinus4.getCodeAtIndex(0, false));
Assert.assertEquals(-4, keyMinus4.getCodeAtIndex(0, true));
Assert.assertEquals("f", keyMinus4.popupCharacters.toString());
Assert.assertEquals(R.xml.popup_one_row, keyMinus4.popupResId);
Assert.assertTrue(keyMinus4.isFunctional());
final AnyKeyboard.AnyKey keyMinus5 = (AnyKeyboard.AnyKey) keyboard.getKeys().get(4);
Assert.assertNotNull(keyMinus5);
Assert.assertEquals(-5, keyMinus5.getPrimaryCode());
Assert.assertEquals(-5, keyMinus5.getCodeAtIndex(0, false));
Assert.assertEquals(-5, keyMinus5.getCodeAtIndex(0, true));
Assert.assertTrue(TextUtils.isEmpty(keyMinus5.popupCharacters));
Assert.assertEquals(0, keyMinus5.popupResId);
Assert.assertTrue(keyMinus5.isFunctional());
final AnyKeyboard.AnyKey keyP = (AnyKeyboard.AnyKey) keyboard.getKeys().get(5);
Assert.assertNotNull(keyP);
Assert.assertEquals((int) 'p', keyP.getPrimaryCode());
Assert.assertEquals('p', keyP.getCodeAtIndex(0, false));
Assert.assertEquals('P', keyP.getCodeAtIndex(0, true));
Assert.assertEquals('a', keyP.getCodeAtIndex(1, false));
Assert.assertEquals('A', keyP.getCodeAtIndex(1, true));
Assert.assertEquals('b', keyP.getCodeAtIndex(2, false));
Assert.assertEquals('B', keyP.getCodeAtIndex(2, true));
Assert.assertTrue(TextUtils.isEmpty(keyP.popupCharacters));
Assert.assertEquals(0, keyP.popupResId);
Assert.assertFalse(keyP.isFunctional());
final AnyKeyboard.AnyKey key99 = (AnyKeyboard.AnyKey) keyboard.getKeys().get(6);
Assert.assertNotNull(keyP);
Assert.assertEquals(99, key99.getPrimaryCode());
Assert.assertEquals('c', key99.getCodeAtIndex(0, false));
Assert.assertEquals('C', key99.getCodeAtIndex(0, true));
Assert.assertEquals('d', key99.getCodeAtIndex(1, false));
Assert.assertEquals('D', key99.getCodeAtIndex(1, true));
Assert.assertEquals('e', key99.getCodeAtIndex(2, false));
Assert.assertEquals('E', key99.getCodeAtIndex(2, true));
Assert.assertEquals("ĥ", key99.popupCharacters.toString());
Assert.assertEquals(R.xml.popup_one_row, key99.popupResId);
Assert.assertFalse(key99.isFunctional());
}
} | [
"menny@evendanan.net"
] | menny@evendanan.net |
e2d9e2c9e2798b96f2b982b3d549b453fcc55e92 | 8f8cbbde08bf43879c64bcd926651d49bac981e0 | /client/app/src/main/java/com/example/taskone/activities/MainActivity.java | e84d30c2f7f4a16337909d76c4a9e47bedf2ddfc | [] | no_license | fedya2303/Task1 | 1d9938e05947c28d27776dee5d4edd0a0e46b458 | 599f8a28ce232d2b6a10432448c3f6a289914dcb | refs/heads/main | 2022-12-28T10:51:55.128653 | 2020-10-15T19:18:05 | 2020-10-15T19:18:05 | 304,004,400 | 0 | 0 | null | 2020-10-15T19:18:07 | 2020-10-14T12:13:00 | Java | UTF-8 | Java | false | false | 2,677 | java | package com.example.taskone.activities;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.taskone.viewmodel.MyViewModel;
import com.example.taskone.R;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private MyViewModel viewModel = new MyViewModel();
;
EditText hostEditText;
Button sendReqButton;
EditText portEditText;
TextView responseText;
private String mAppUnitId = "ca-app-pub-7526080045582593~7855797963";
private String mInterstitialAdUnitId = "ca-app-pub-3940256099942544/1033173712";
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendReqButton = findViewById(R.id.btn_req);
hostEditText = findViewById(R.id.host_edit_text);
portEditText = findViewById(R.id.port_edit_text);
responseText = findViewById(R.id.grpc_response_text);
mInterstitialAd = new InterstitialAd(this);
initializeInterstitialAd(mAppUnitId);
mInterstitialAd.setAdUnitId(mInterstitialAdUnitId);
loadInterstitialAd(mInterstitialAdUnitId);
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
sendReqButton.setOnClickListener(view -> {
if ("1".contentEquals(responseText.getText())) {
viewModel.downloadFile(getFilesDir(), getApplicationContext());
}
if ("3".contentEquals(responseText.getText())) {
mInterstitialAd.show();
responseText.setText("0");
} else {
viewModel.sendRequest(hostEditText.getText().toString(), portEditText.getText().toString());
}
});
viewModel.getNumber().observe(this,
number -> responseText.setText(number.toString()));
}
private void initializeInterstitialAd(String appUnitId) {
MobileAds.initialize(this, appUnitId);
}
private void loadInterstitialAd(String interstitialAdUnitId) {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
} | [
"potapchenkof@gmail.com"
] | potapchenkof@gmail.com |
5c311b3c55887f993b84edbd1da6fd02fbe4f886 | 1809d94fc23e1a971b20262581c892e328873a8e | /src/filters/FreePassFilter.java | b5aeb3f37fca5c580ecf99f80cdec5c9e3881036 | [] | no_license | pyj0807/exer02 | c4bd45d86cbac7fe83faeab2a12e42078a813630 | f8184001a4205583f14bcbf3910ec1574500464a | refs/heads/master | 2020-03-27T17:20:58.224872 | 2018-09-18T04:22:19 | 2018-09-18T04:22:19 | 146,845,877 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 949 | java | package filters;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FreePassFilter extends HttpFilter {
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpSession session = request.getSession();
Cookie[] ar = request.getCookies();
if (ar != null) {
chain.doFilter(request, response);
} else {
for (int i = 0; i < ar.length; i++) {
Cookie c = ar[i];
String name = c.getName();
String value = c.getValue();
String path = c.getPath();
String domain = c.getDomain();
int maxage = c.getMaxAge();
}
}
}
}
| [
"kgitbank@DESKTOP-U6AB831"
] | kgitbank@DESKTOP-U6AB831 |
4f87bd1974c3b2dc6852a6b7d04ee5a6f89616a1 | eaf875dc2300c5257de58f23a0be0ba6f23c224d | /src/main/java/com/nate/eddiebot/listener/EventDispatcher.java | 23255fb4a72ba74547f4ef1652f87a1ff8682e57 | [] | no_license | nsedler/EddieBot | 940688131c11df2a28099695de215b2b3cee8765 | 2564c46dc23d485b79705a8ba908cf08b7bc16b2 | refs/heads/master | 2022-11-27T16:32:56.542177 | 2020-07-24T16:49:08 | 2020-07-24T16:49:08 | 152,156,336 | 3 | 1 | null | 2018-12-09T03:20:42 | 2018-10-08T22:46:38 | Java | UTF-8 | Java | false | false | 520 | java | package com.nate.eddiebot.listener;
import com.nate.eddiebot.EddieBot;
import com.nate.eddiebot.listener.events.BetterMessageEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class EventDispatcher extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent event) {
EddieBot.sendToCommands(new BetterMessageEvent(event));
EddieBot.sendToPassives(new BetterMessageEvent(event));
}
}
| [
"nsedler1@gmail.com"
] | nsedler1@gmail.com |
df9930dc795d7eb0e8378587cd36fdbdbcdc5fe8 | 9cc385c40f6342fed3dc76e0f54b649e764bf79c | /src/adapter/BirdAdapter.java | e257dd97d191b042d48ec825d4d56189e57c3e56 | [] | no_license | SerheosMorello/patterns | 6230db549d6a1b7a205812689b9310def2c6db79 | b45d67bd6612fd22b1eb4cc7577eb55d5fde72d4 | refs/heads/master | 2021-01-03T21:12:10.303787 | 2020-02-18T13:01:26 | 2020-02-18T13:01:26 | 240,237,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 224 | java | package adapter;
public class BirdAdapter implements ToyDuck {
Bird bird;
public BirdAdapter(Bird bird) {
this.bird = bird;
}
@Override
public void squeak() {
bird.makeSound();
}
}
| [
"Sergii.Pankrashyn.9@fntsoftware.com"
] | Sergii.Pankrashyn.9@fntsoftware.com |
0b5aae8b114bf0fc55269fb2fca73feebd0548c8 | 63db96cd587c04b4f99bb1839c5feb88000aaa54 | /src/test/java/ar/edu/itba/sia/gps/eightpuzzle/E8State.java | 4da19a47a9fe2cecbe50e8c9e31d3a45656e8b69 | [] | no_license | pabloito/GenericProblemSolver | 1e65403f2e9e12cbbb4842adfb4bd14163276f1c | c09a45bc5885924375f4d328c336fbddd1110103 | refs/heads/master | 2020-05-16T21:27:51.452971 | 2019-04-24T21:18:32 | 2019-04-24T21:18:32 | 183,307,014 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,744 | java | package ar.edu.itba.sia.gps.eightpuzzle;
import ar.edu.itba.sia.gps.api.State;
import java.util.Arrays;
public class E8State implements State{
private Pair array[];
Pair blank;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof E8State)) return false;
E8State e8State = (E8State) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (array == null){
if (e8State.array != null)
return false;
} else {
for (int i = 0;i < 8; i++){
if(!array[i].equals(e8State.array[i]))
return false;
}
}
return blank.equals(e8State.blank);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(array);
result = 31 * result + blank.hashCode();
return result;
}
/*@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
E8State other = (E8State) obj;
if (blank == null) {
if (other.blank != null)
return false;
else if (array == null)
if (other.array != null)
return false;
} else if (array == null){
if (other.array != null)
return false;
} else {
for (int i = 0;i < 8; i++){
if(!array[i].equals(other.array[i]))
return false;
}
}
return true;
}*/
public Pair getBlank() {
return blank;
}
public Pair[] getArray() {
return array;
}
public E8State(Pair blank, Pair[] array){
this.blank = blank;
this.array = array;
}
private static StringBuilder stringBuilder = new StringBuilder();
@Override
public String toString() {
int strOrder[] = new int[9];
for (int i = 0; i < 8; i++) {
strOrder[array[i].getX()+array[i].getY()*3] = i+1;
}
strOrder[blank.getX()+blank.getY()*3] = -1;
int a;
stringBuilder.delete(0,stringBuilder.capacity());
for (int i = 0; i < 9; i++) {
a = strOrder[i];
if(a > 0)
stringBuilder.append(a).append(' ');
else
stringBuilder.append('B').append(' ');
if(i%3 == 2)
stringBuilder.append('\n');
}
return stringBuilder.append('\n').toString();
}
@Override
public String getRepresentation() {
return toString();
}
}
| [
"pradnic@itba.edu.ar"
] | pradnic@itba.edu.ar |
7a980b5783b75b198bbd8e6984643181f3a4beb7 | a02b5b260c1311bd1d0956943d8792c98eecaf8a | /src/eg/edu/alexu/ehr/ontology/OWLObjectVisitor.java | 8429e9ab4a9e69c3a1d8c02c75328b6b913ebc1b | [] | no_license | SamehHany/OntologyGraph | 862e6acf4ce5650027ccb42dc5a9eef9003fe10a | 5df8592cca39e0768b7a85450f88a272c832d96f | refs/heads/master | 2021-01-21T02:10:16.225564 | 2016-07-08T14:00:54 | 2016-07-08T14:00:54 | 44,068,551 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,713 | java | /**
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eg.edu.alexu.ehr.ontology;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLDataExactCardinality;
import org.semanticweb.owlapi.model.OWLDataMaxCardinality;
import org.semanticweb.owlapi.model.OWLDataMinCardinality;
import org.semanticweb.owlapi.model.OWLDataPropertyRangeAxiom;
import org.semanticweb.owlapi.model.OWLObjectExactCardinality;
import org.semanticweb.owlapi.model.OWLObjectMaxCardinality;
import org.semanticweb.owlapi.model.OWLObjectMinCardinality;
import org.semanticweb.owlapi.util.OWLObjectVisitorAdapter;
public class OWLObjectVisitor extends OWLObjectVisitorAdapter {
@Override
public void visit(OWLDataMaxCardinality desc) {
super.visit(desc);
System.out.println("Max Cardinality =[" + desc.getCardinality() + "]");
}
@Override
public void visit(OWLDataMinCardinality desc) {
super.visit(desc);
System.out.println("Min Cardinality =[" + desc.getCardinality() + "]");
}
@Override
public void visit(OWLObjectMaxCardinality desc) {
super.visit(desc);
System.out.println("Object Max Cardinality =[" + desc.getCardinality()
+ "]");
}
@Override
public void visit(OWLObjectMinCardinality desc) {
super.visit(desc);
System.out.println("Object Min Cardinality =[" + desc.getCardinality()
+ "]");
}
@Override
public void visit(OWLDataExactCardinality desc) {
super.visit(desc);
System.out.println("Exact Data Cardinality =[" + desc.getCardinality()
+ "]" + desc.getProperty());
}
@Override
public void visit(OWLObjectExactCardinality desc) {
super.visit(desc);
System.out.println("Exact Object Cardinality =[" + desc.getCardinality()
+ "]");
}
@Override
public void visit(OWLAnnotation node) {
super.visit(node);
System.out.println("visitng owlannoation node =[" + node + "]");
}
// @Override
// public void visit(OWLAnonymousIndividual individual) {
// super.visit(individual);
// System.out.println("indivual =["+individual+"]");
// }
// public void visit(OWLClass c){
// super.visit(c);
// System.out.println("*********"+c.getIRI());
// }
@Override
public void visit(OWLDataPropertyRangeAxiom owldpr) {
super.visit(owldpr);
System.out.println(owldpr);
}
}
| [
"sameh.hany90@gmail.com"
] | sameh.hany90@gmail.com |
e60da6db4f68f7dee6b5af69bb774d39115348e1 | 4873409187e29d2ff7ad8d1090a5d04767ea72b4 | /src/main/java/se/gustavkarlsson/rocketchat/models/from_rocket_chat/FromRocketChatMessage.java | 7d85df4107a3fc930d667d480ec513008d18fa48 | [
"MIT"
] | permissive | alefq/rocketchat-jira-trigger | 3796e59030e459765932dce06d9a3f07b7053c10 | 6c4fb458d85968393a1ff6793adaa29e6c561def | refs/heads/master | 2020-08-11T02:40:00.435174 | 2020-06-10T20:19:05 | 2020-06-10T20:19:05 | 214,474,175 | 1 | 0 | MIT | 2019-10-11T15:45:50 | 2019-10-11T15:45:50 | null | UTF-8 | Java | false | false | 4,380 | java | package se.gustavkarlsson.rocketchat.models.from_rocket_chat;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.Objects;
public final class FromRocketChatMessage {
@SerializedName("token")
private String token;
@SerializedName("channel_id")
private String channelId;
@SerializedName("channel_name")
private String channelName;
@SerializedName("user_id")
private String userId;
@SerializedName("user_name")
private String userName;
@SerializedName("text")
private String text;
@SerializedName("bot")
private Object bot;
@SerializedName("isEdited")
private Boolean edited;
@SerializedName("alias")
private String alias;
@SerializedName("message_id")
private String messageId;
@SerializedName("timestamp")
private Date timestamp;
@SerializedName("trigger_word")
private String triggerWord;
public FromRocketChatMessage() {
}
public FromRocketChatMessage(String token, String channelId, String channelName, String userId, String userName, String text, Object bot, Boolean edited, String alias, String messageId, Date timestamp, String triggerWord) {
this.token = token;
this.channelId = channelId;
this.channelName = channelName;
this.userId = userId;
this.userName = userName;
this.text = text;
this.bot = bot;
this.edited = edited;
this.alias = alias;
this.messageId = messageId;
this.timestamp = timestamp;
this.triggerWord = triggerWord;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Object getBot() {
return bot;
}
public void setBot(Object bot) {
this.bot = bot;
}
public Boolean isEdited() {
return edited;
}
public void setEdited(Boolean edited) {
this.edited = edited;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getTriggerWord() {
return triggerWord;
}
public void setTriggerWord(String triggerWord) {
this.triggerWord = triggerWord;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FromRocketChatMessage that = (FromRocketChatMessage) o;
return Objects.equals(token, that.token) &&
Objects.equals(channelId, that.channelId) &&
Objects.equals(channelName, that.channelName) &&
Objects.equals(userId, that.userId) &&
Objects.equals(userName, that.userName) &&
Objects.equals(text, that.text) &&
Objects.equals(bot, that.bot) &&
Objects.equals(edited, that.edited) &&
Objects.equals(alias, that.alias) &&
Objects.equals(messageId, that.messageId) &&
Objects.equals(timestamp, that.timestamp) &&
Objects.equals(triggerWord, that.triggerWord);
}
@Override
public int hashCode() {
return Objects.hash(token, channelId, channelName, userId, userName, text, bot, edited, alias, messageId, timestamp, triggerWord);
}
@Override
public String toString() {
return "FromRocketChatMessage{" +
"token='" + token + '\'' +
", channelId='" + channelId + '\'' +
", channelName='" + channelName + '\'' +
", userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", text='" + text + '\'' +
", bot=" + bot +
", isEdited=" + edited +
", alias='" + alias + '\'' +
", messageId='" + messageId + '\'' +
", timestamp=" + timestamp +
", triggerWord='" + triggerWord + '\'' +
'}';
}
}
| [
"afeltes@sodep.com.py"
] | afeltes@sodep.com.py |
ee44dfc32f7070c70c8cf72551d987e94978a0e8 | 70239077fca3aab680309a3a12c9f0c0e6a12131 | /Lab1/ChangingPeople.java | 50d8ea0e1e26caa99b13c8f20b3035411b0ee6e6 | [] | no_license | jessicagerson/Chapter5 | b4f7245d7ec9822e94c4956aea77030f16dad442 | eba4c72b3fa968daeaf4e9b0eb5a069dd8a133c9 | refs/heads/master | 2021-08-23T11:35:28.693173 | 2017-12-04T18:43:50 | 2017-12-04T18:43:50 | 111,021,251 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,546 | java |
// **********************************************************************
// ChangingPeople.java
//
// Demonstrates parameter passing -- contains a method that should
// change to Person objects.
// **********************************************************************
package Lab1;
public class ChangingPeople
{
// ---------------------------------------------------------
// Sets up two person objects, one integer, and one String
// object. These are sent to a method that should make
// some changes.
// ---------------------------------------------------------
public static void main (String[] args)
{
Person person1 = new Person ("Sally", 13);
Person person2 = new Person ("Sam", 15);
int age = 21;
String name = "Jill";
System.out.println ("\nParameter Passing... Original values...");
System.out.println ("person1: " + person1);
System.out.println ("person2: " + person2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
changePeople (person1, person2, age, name);
System.out.println ("\nValues after calling changePeople...");
System.out.println ("person1: " + person1);
System.out.println ("person2: " + person2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
}
// -------------------------------------------------------------------
// Change the first actual parameter to "Jack - Age 101" and change
// the second actual parameter to be a person with the age and
// name given in the third and fourth parameters.
// -------------------------------------------------------------------
public static void changePeople (Person p1, Person p2, int age, String name)
{
System.out.println ("\nInside changePeople... Original parameters...");
System.out.println ("person1: " + p1);
System.out.println ("person2: " + p2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
// Make changes
p2.changeName(name);
p2.changeAge(age);
Person p3 = new Person (name, age);
p2 = p3;
name = "Jack";
age = 101;
p1.changeName (name);
p1.changeAge (age);
// Print changes
System.out.println ("\nInside changePeople... Changed values...");
System.out.println ("person1: " + p1);
System.out.println ("person2: " + p2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
}
}
| [
"jessygerson123@gmail.com"
] | jessygerson123@gmail.com |
ed50957bb0f8353c18fda1a5e9fe85bc65f71129 | 3bbbd4909366c845d2f6734a575ac9542bbff2d5 | /src/main/java/com/zxtech/ess/module/base/service/impl/BaseFaultDutyParamServiceImpl.java | 45e7214fad1bf8f4bc2c546718b0ee19dbeba17e | [] | no_license | lanbohello163/hyss | 3c4e57ad5d6018a691c4ce56ffc3a27b9afa4d82 | e9c97542a443e5add8888686628b95ecdd8f8535 | refs/heads/master | 2022-12-22T03:39:43.366505 | 2019-09-02T01:29:48 | 2019-09-02T01:29:48 | 205,752,991 | 0 | 0 | null | 2022-12-16T09:56:05 | 2019-09-02T01:13:29 | Java | UTF-8 | Java | false | false | 3,150 | java | package com.zxtech.ess.module.base.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.zxtech.ess.module.base.bean.BaseFaultDutyParamSearchBean;
import com.zxtech.ess.module.base.mapper.BaseFaultDutyParamManagerMapper;
import com.zxtech.ess.module.base.service.IBaseFaultDutyParamService;
import com.zxtech.ess.module.gen.bean.CalFaultDutyParam;
import com.zxtech.ess.module.gen.mapper.CalFaultDutyParamMapper;
import com.zxtech.platform.constant.ResultConstants;
import com.zxtech.platform.utils.page.PageHandler;
import com.zxtech.platform.vo.UserBean;
@Service("baseFaultDutyParamServiceImpl")
public class BaseFaultDutyParamServiceImpl implements IBaseFaultDutyParamService {
@Autowired
private CalFaultDutyParamMapper calFaultDutyParamMapper;
@Autowired
private BaseFaultDutyParamManagerMapper baseFaultDutyParamManagerMapper;
@Override
public Map<String, Object> getListWithPaging(BaseFaultDutyParamSearchBean queryInfo) {
Page<Map<String, Object>> pageResult = PageHandler.buildPage(queryInfo)
.doSelectPage(() -> baseFaultDutyParamManagerMapper.getListWithPaging(queryInfo));
return PageHandler.wrapPageMap(pageResult);
}
//新增、编辑时判断不良分类编码是否存在重复记录
private Boolean checkRepeatColumn(CalFaultDutyParam bean){
CalFaultDutyParam calFaultDutyParam = new CalFaultDutyParam();
calFaultDutyParam.setBad_code(bean.getBad_code());
List<CalFaultDutyParam> list = calFaultDutyParamMapper.selectBySqlConditions(calFaultDutyParam);
if (list.stream().filter(javaBean ->!javaBean.getId().equals(bean.getId())).count()==0)
return false;
return true;
}
@Override
public String add(CalFaultDutyParam bean, UserBean user) {
String resStr = ResultConstants.SUCCESS;
if (checkRepeatColumn(bean))
return ResultConstants.REPEAT;
int ret = calFaultDutyParamMapper.insertSelective(bean);
if (ret == 0)
resStr = ResultConstants.ERROR;
return resStr;
}
@Override
public String update(CalFaultDutyParam bean, UserBean user) {
String resStr = ResultConstants.SUCCESS;
if (checkRepeatColumn(bean))
return ResultConstants.REPEAT;
CalFaultDutyParam calFaultDutyParam = calFaultDutyParamMapper.selectByPrimaryKey(bean.getId());
bean.setEnable_flag(calFaultDutyParam.getEnable_flag());
int ret = calFaultDutyParamMapper.updateByPrimaryKey(bean);
if(ret == 0)
resStr = ResultConstants.ERROR;
return resStr;
}
@Override
public String enable(CalFaultDutyParam bean, UserBean user) {
String resStr = ResultConstants.SUCCESS;
bean.setEnable_flag("1");
int ret = calFaultDutyParamMapper.updateByPrimaryKeySelective(bean);
if(ret == 0)
resStr = ResultConstants.ERROR;
return resStr;
}
@Override
public String disable(CalFaultDutyParam bean, UserBean user) {
String resStr = ResultConstants.SUCCESS;
bean.setEnable_flag("0");
int ret = calFaultDutyParamMapper.updateByPrimaryKeySelective(bean);
if(ret == 0)
resStr = ResultConstants.ERROR;
return resStr;
}
}
| [
"lanbohello@163.com"
] | lanbohello@163.com |
97811f699b0c5af711fb9e53abdf579f47d5b6ff | a09da10b7e2902a3fa1db09bf7e292fdb8279962 | /jk_web/src/main/java/com/xy/webservice/EpServiceService.java | 7f1781d9c8a92066e8e9cad317f17bdb4bf709a1 | [] | no_license | xieyanfds/jk_parent | ba1f371320b41456695e27202f6c7fc56d9d979d | 6e72e3c103fbb7b89d125bd72e7bb21179fa9893 | refs/heads/master | 2021-10-26T04:15:38.529618 | 2019-04-10T08:27:44 | 2019-04-10T08:27:44 | 115,376,032 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,964 | java |
package com.xy.webservice;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.4-b01
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "EpServiceService", targetNamespace = "http://webservice.xy.com/", wsdlLocation = "http://localhost/jk_ws1/ws/export?wsdl")
public class EpServiceService
extends Service
{
private final static URL EPSERVICESERVICE_WSDL_LOCATION;
private final static WebServiceException EPSERVICESERVICE_EXCEPTION;
private final static QName EPSERVICESERVICE_QNAME = new QName("http://webservice.xy.com/", "EpServiceService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost/jk_ws1/ws/export?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
EPSERVICESERVICE_WSDL_LOCATION = url;
EPSERVICESERVICE_EXCEPTION = e;
}
public EpServiceService() {
super(__getWsdlLocation(), EPSERVICESERVICE_QNAME);
}
public EpServiceService(WebServiceFeature... features) {
super(__getWsdlLocation(), EPSERVICESERVICE_QNAME, features);
}
public EpServiceService(URL wsdlLocation) {
super(wsdlLocation, EPSERVICESERVICE_QNAME);
}
public EpServiceService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, EPSERVICESERVICE_QNAME, features);
}
public EpServiceService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public EpServiceService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns EpService
*/
@WebEndpoint(name = "EpServicePort")
public EpService getEpServicePort() {
return super.getPort(new QName("http://webservice.xy.com/", "EpServicePort"), EpService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns EpService
*/
@WebEndpoint(name = "EpServicePort")
public EpService getEpServicePort(WebServiceFeature... features) {
return super.getPort(new QName("http://webservice.xy.com/", "EpServicePort"), EpService.class, features);
}
private static URL __getWsdlLocation() {
if (EPSERVICESERVICE_EXCEPTION!= null) {
throw EPSERVICESERVICE_EXCEPTION;
}
return EPSERVICESERVICE_WSDL_LOCATION;
}
}
| [
"xy_fds@163.com"
] | xy_fds@163.com |
2a1394a0a757babf1716c5805fab8dee94302c69 | 57de39b55754148c160051a4cf73117e86e630f9 | /JEM Application/Mobile/J-Application/app/src/main/java/com/example/jmora/webservicesoap/validator/AbstractValidate.java | 4564d74d5228f5721edaf8d0e542c725a0514f61 | [] | no_license | joelmora9618/J-Application | 8e9dd91ea9b6b90f3ba492f76dfc39c9db3445d4 | e46a188736577433f4b6b17c52db1b13ea126210 | refs/heads/master | 2021-05-14T13:01:53.516378 | 2018-01-05T20:51:39 | 2018-01-05T20:51:39 | 116,423,946 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 280 | java | package com.example.jmora.webservicesoap.validator;
/**
* Created by JMora on 22/05/2017.
*/
public abstract class AbstractValidate {
/**
*
* @return verdadero si todos los validadores son válidos, si no, falsa
*/
public abstract boolean isValid();
}
| [
"joelmora9618@gmail.com"
] | joelmora9618@gmail.com |
79c630153c40128a80ae7c95c2a50046f352bb68 | cd956b956e8bd1e97dde854b73b76c96449a09bc | /app/src/main/java/com/raymondqk/raymusicplayer/activity/MusicListActivity.java | 117ae8652a9a818d9e7913544c39cf08f280b5cf | [] | no_license | mason0510/RayMusicPlayer | ee361963a33c16a387bfa90407740d38b8895692 | b2a0f28e35017cf440c5d99ed9c0774e0f9f6696 | refs/heads/master | 2022-12-06T02:03:38.797412 | 2016-09-04T15:20:01 | 2016-09-04T15:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,311 | java | package com.raymondqk.raymusicplayer.activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;
import com.raymondqk.raymusicplayer.MusicMode;
import com.raymondqk.raymusicplayer.R;
import com.raymondqk.raymusicplayer.adapter.MusicListAdapter;
import com.raymondqk.raymusicplayer.service.MusicService;
import com.raymondqk.raymusicplayer.utils.ConstantUtils;
import com.raymondqk.raymusicplayer.utils.MusicUtils;
import java.util.List;
/**
* Created by 陈其康 raymondchan on 2016/8/3 0003.
*/
public class MusicListActivity extends AppCompatActivity implements View.OnClickListener {
private ListView mListView;
private MusicListAdapter mAdapter;
private ImageButton mIb_play;
private ImageButton mIb_next;
private ImageButton mIb_preview;
private ImageButton mIb_play_mode;
private ImageButton mIb_favor;
private SeekBar mProgressBar;
private List<MusicMode> mMusicList;
private Messenger mMessenger = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ConstantUtils.WHAT_REGIST_MSGER_LIST_ACTIVITY:
Bundle data = msg.getData();
data.setClassLoader(MusicMode.class.getClassLoader());
mMusicList = data.getParcelableArrayList(ConstantUtils.CURRENT_MUSIC_LIST);
// mMusicList = (List<MusicMode>) data.get(ConstantUtils.CURRENT_MUSIC_LIST);
if (mMusicList != null) {
mAdapter = new MusicListAdapter(MusicListActivity.this, mMusicList);
mListView.setAdapter(mAdapter);
}
boolean isPlaying = data.getBoolean(ConstantUtils.IS_PLAYING);
if (isPlaying) {
mIb_play.setImageResource(R.drawable.pause);
} else {
mIb_play.setImageResource(R.drawable.play);
}
break;
case ConstantUtils.WHAT_PLAY_PLAY_BTN:
break;
case ConstantUtils.WHAT_PLAY_NEXT_BTN:
break;
case ConstantUtils.WHAT_PLAY_PRE_BTN:
break;
case ConstantUtils.WHAT_PLAY_DURATION:
int position = msg.arg1;
int duration = msg.arg2;
mProgressBar.setProgress(position * 100 / duration);
break;
case ConstantUtils.WHAT_PLAYED:
setPlaying(msg);
default:
super.handleMessage(msg);
break;
}
}
private void setPlaying(Message msg) {
Bundle data = msg.getData();
//就算没用到对应的对象,也要设置class loader,否则会出错。
data.setClassLoader(MusicMode.class.getClassLoader());
boolean isPlaying = data.getBoolean(ConstantUtils.IS_PLAYING);
MusicMode musicMode = data.getParcelable(ConstantUtils.CURRENT_MUSIC);
if (isPlaying) {
mIb_play.setImageResource(R.drawable.pause);
} else {
mIb_play.setImageResource(R.drawable.play);
}
}
});
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = new Messenger(service);
if (mService != null) {
// Toast.makeText(MusicListActivity.this, "服务连接成功", Toast.LENGTH_SHORT).show();
Message msg = Message.obtain();
msg.replyTo = mMessenger;
msg.what = ConstantUtils.WHAT_REGIST_MSGER_LIST_ACTIVITY;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
private Messenger mService;
private float mPercent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_musiclist);
initView();
Intent intent = new Intent(this, MusicService.class);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
Message msg = Message.obtain();
msg.what = ConstantUtils.WHAT_UN_REGIST_MSGER_LIST_ACTIVITY;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
super.onDestroy();
}
private void initView() {
//去掉默认导航栏
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_musiclist);
//设置导航图标 左上角
toolbar.setNavigationIcon(R.drawable.nav_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
toolbar.setTitle(R.string.app_name);
toolbar.setSubtitle(R.string.menu_list);
toolbar.inflateMenu(R.menu.list_menu);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_search:
Toast.makeText(MusicListActivity.this, "search", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item_setting:
Toast.makeText(MusicListActivity.this, "setting", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
mListView = (ListView) findViewById(R.id.lv_music);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mMusicList.get(position);
Message msg = Message.obtain();
msg.what = ConstantUtils.WHAT_MUSIC_SELECTED;
msg.arg1 = position;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
mIb_play = (ImageButton) findViewById(R.id.ib_play);
mIb_next = (ImageButton) findViewById(R.id.ib_next);
mIb_preview = (ImageButton) findViewById(R.id.ib_preview);
mIb_play_mode = (ImageButton) findViewById(R.id.ib_play_mode);
mIb_favor = (ImageButton) findViewById(R.id.ib_favor);
mIb_favor.setOnClickListener(this);
mIb_next.setOnClickListener(this);
mIb_preview.setOnClickListener(this);
mIb_play.setOnClickListener(this);
mIb_play_mode.setOnClickListener(this);
mProgressBar = (SeekBar) findViewById(R.id.progressbar);
mProgressBar.setProgress(0);
mProgressBar.setMax(100);
mProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mPercent = (float) progress * 100 / (float) mProgressBar.getMax();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//当用户释放SeekBar之后,在通知service更新进度,解决拖动过程中卡顿问题
Message msg = Message.obtain();
msg.what = ConstantUtils.WHAT_CHANGE_PROGRESS;
msg.arg1 = (int) mPercent;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
unbindService(mServiceConnection);
super.onBackPressed();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ib_play_mode:
break;
case R.id.ib_play:
MusicUtils.playCurrent(mService);
break;
case R.id.ib_next:
MusicUtils.playNext(mService);
break;
case R.id.ib_preview:
MusicUtils.playPreview(mService);
break;
case R.id.ib_favor:
break;
}
}
}
| [
"raymondcqk@163.com"
] | raymondcqk@163.com |
bf52fe08dad48f8125e426144c01d27c2e3c56f7 | 15729a88912bb86c61063891385268fa9fabdd62 | /src/test/java/com/mycompany/guice/AppControllerMockitoTest.java | 9797c8a41019a5b99c47c39982b6070d8baf3414 | [] | no_license | vamsiampolu/guice-app | 93821b9cd5afc98f7f47ad48086af75b44cf8597 | 5ed239b77ec311969b7fa57e1a5de3a446a3f0f7 | refs/heads/master | 2021-04-15T06:40:23.447615 | 2018-03-22T00:00:48 | 2018-03-22T00:00:48 | 126,754,467 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,258 | java | package com.mycompany.guice;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.anyString;
import com.mycompany.guice.controllers.AppController;
import com.mycompany.guice.services.MessageService;
@RunWith(MockitoJUnitRunner.class)
public class AppControllerMockitoTest {
@Mock(name="msgSvc") private MessageService service;
private AppController subject;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void should_call_message_service_with_message_and_email() {
String recepient = "someone@somewhere.com";
String message = "Where are the awesome swiss watches?";
when(service.sendMessage(recepient, message)).thenReturn(true);
subject = new AppController(service);
boolean received = subject.doSomething();
Assert.assertEquals(true, received);
verify(service, times(1)).sendMessage(anyString(), anyString());
}
}
| [
"vamsiampolu3000@gmail.com"
] | vamsiampolu3000@gmail.com |
3f552631d58415b5add80dbd40a4ed2cdd251daf | 1dc15816590dbe49d69eed6ea579cc745cc76e08 | /src/imu/pcloud/app/model/TimeConfig.java | fb3e6e80f91aec2b987992c70b1269ad49e53a89 | [] | no_license | Zyzzz/PCloudApp | 8578a7114b7a015fdd7851758e6d6c96bebd6a37 | c96946a04857fa88c28b4ea681f0af537fc98cfb | refs/heads/master | 2020-12-24T06:53:03.816503 | 2016-09-19T08:13:18 | 2016-09-19T08:13:18 | 58,203,527 | 2 | 1 | null | 2016-06-09T18:10:52 | 2016-05-06T11:44:24 | Java | UTF-8 | Java | false | false | 1,086 | java | package imu.pcloud.app.model;
import java.util.Date;
/**
* Created by guyu on 2016/6/9.
*/
public class TimeConfig {
int planId;
int planMode;
int timeMode;
//plan mode
final public static int MODE_PERSONAL_PLAN = 0;
final public static int MODE_MULTI_PLAN = 1;
//time mode
final public static int MODE_WEEKS = 0;
final public static int MODE_DAYS = 1;
final public static int MODE_ALL = 2;
boolean []weeks = new boolean[8];
Date startDate;
Date endDate;
public int getPlanId() {
return planId;
}
public void setPlanId(int planId) {
this.planId = planId;
}
public int getPlanMode() {
return planMode;
}
public void setPlanMode(int planMode) {
this.planMode = planMode;
}
public int getTimeMode() {
return timeMode;
}
public void setTimeMode(int timeMode) {
this.timeMode = timeMode;
}
public boolean[] getWeeks() {
return weeks;
}
public void setWeeks(boolean[] weeks) {
this.weeks = weeks;
}
}
| [
"guyu@imudges.com"
] | guyu@imudges.com |
8439927d7c0e18f99ca3ebe36226b04e1f31d92d | a24dea8651d6166fe0ca209c45879cd8c1d4e2dd | /LeetCode/All_Paths_From_Source_To_Target/All_Paths_From_Source_To_Target.java | 5427a5e0d43bdf9fe1ea9973accd2b838397c211 | [] | no_license | lakshmipathyarjun6/ProgrammingChallenges | b853b7f78fd4c5c969a8a41e8360c2f53f9663dc | dbe4e35e98b0a3e940c8e8dd61c52aaae5d62e15 | refs/heads/master | 2022-01-21T17:08:35.174002 | 2022-01-15T18:40:06 | 2022-01-15T18:40:06 | 61,674,320 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 734 | java | class Solution {
Set<List<Integer>> paths;
public void dfs(List<Integer> currPath, int[][] graph, int current) {
List<Integer> currPathNew = new ArrayList<Integer>(currPath);
currPathNew.add(current);
if(current == graph.length-1) {
paths.add(currPathNew);
}
for(int i = 0; i < graph[current].length; i++) {
dfs(currPathNew, graph, graph[current][i]);
}
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
paths = new HashSet<List<Integer>>();
dfs(new LinkedList<Integer>(), graph, 0);
List<List<Integer>> allPaths = new LinkedList<List<Integer>>(paths);
return allPaths;
}
}
| [
"lakshmipathyarjun6@gmail.com"
] | lakshmipathyarjun6@gmail.com |
267588e004457a5a7003670061640243f314c1ec | 6bac1a560bf008cb2d898438050d720653ce628a | /telekom/Siebel/gensrc/com/siebel/selfservice/common/account/query/ListOfContactAlternatePhoneQuery.java | 04daf2bf3473dbadef81b9dfd58b96b4e33453c0 | [] | no_license | vkscorpio3/TelekomPOC | 8ff40774bbbfc6868b4a3f84a971d972b9dc9ab7 | c437ef7c30e93ea24c1d8acc0110b985401d049b | refs/heads/master | 2020-03-08T16:54:42.639312 | 2017-08-26T22:25:25 | 2017-08-26T22:25:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,890 | java |
package com.siebel.selfservice.common.account.query;
import java.io.Serializable;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ListOfContactAlternatePhoneQuery complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ListOfContactAlternatePhoneQuery">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ContactAlternatePhone" type="{http://www.siebel.com/SelfService/Common/Account/Query}ContactAlternatePhoneQuery" minOccurs="0"/>
* </sequence>
* <attribute name="pagesize" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="startrownum" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="recordcountneeded" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ListOfContactAlternatePhoneQuery", propOrder = {
"contactAlternatePhone"
})
public class ListOfContactAlternatePhoneQuery
implements Serializable
{
@XmlElement(name = "ContactAlternatePhone")
protected ContactAlternatePhoneQuery contactAlternatePhone;
@XmlAttribute
protected BigInteger pagesize;
@XmlAttribute
protected BigInteger startrownum;
@XmlAttribute
protected Boolean recordcountneeded;
/**
* Gets the value of the contactAlternatePhone property.
*
* @return
* possible object is
* {@link ContactAlternatePhoneQuery }
*
*/
public ContactAlternatePhoneQuery getContactAlternatePhone() {
return contactAlternatePhone;
}
/**
* Sets the value of the contactAlternatePhone property.
*
* @param value
* allowed object is
* {@link ContactAlternatePhoneQuery }
*
*/
public void setContactAlternatePhone(ContactAlternatePhoneQuery value) {
this.contactAlternatePhone = value;
}
/**
* Gets the value of the pagesize property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPagesize() {
return pagesize;
}
/**
* Sets the value of the pagesize property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPagesize(BigInteger value) {
this.pagesize = value;
}
/**
* Gets the value of the startrownum property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getStartrownum() {
return startrownum;
}
/**
* Sets the value of the startrownum property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setStartrownum(BigInteger value) {
this.startrownum = value;
}
/**
* Gets the value of the recordcountneeded property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isRecordcountneeded() {
return recordcountneeded;
}
/**
* Sets the value of the recordcountneeded property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setRecordcountneeded(Boolean value) {
this.recordcountneeded = value;
}
}
| [
"vivek.singh4@techmahindra.com"
] | vivek.singh4@techmahindra.com |
6eb4bd8ddb80cc94ff7585b8ea9fb039850d12c7 | 8b606d476da07a66a64914113c44bbdb79ef8990 | /src/test/java/Ciphers/CesarCipherTest.java | 54a83756a28d55cadf6f4953959c2fe973a47fdf | [] | no_license | Dominik166/Enigma1 | f6db134045115936d747228845d0852271878ea2 | 086acc6910ec3c9b05cc2d0001cabaf4a1da2080 | refs/heads/master | 2021-01-04T17:09:08.278996 | 2020-03-01T10:50:05 | 2020-03-01T10:50:05 | 240,678,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,971 | java |
package Ciphers;
import ciphers.impl.impl.CesarCipher;
import ciphers.impl.Cipher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class CesarCipherTest {
protected final String textWitnNoAlphabeticLetters = "12312[]][";
protected final String textWithAlphabeticLetters = "abcdd";
protected final String expectedTextForAlphabeticLetters = "defgg";
protected final String mixedText = "123ac";
protected final String expectedTextForMixedText = "123df//";
protected Cipher cesarCipher = new CesarCipher();
// @Test
// public void testOnlyAlphabeticLettersAreEncoded(){
// String encode = cesarCipher.encode(mixedText);
// Assertions.assertEquals(mixedText, encode);
// String decode = cesarCipher.decode(textWithAlphabeticLetters);
// Assertions.assertEquals(textWithAlphabeticLetters,decode);
@DisplayName("Testing correction of encoding text with no alphabetic letters")
@Test
public void testOnlyAlphabeticLettersAreEncoded() {
String encode = cesarCipher.encode(mixedText);
Assertions.assertEquals(mixedText, encode);
String decode = cesarCipher.decode(textWithAlphabeticLetters);
Assertions.assertEquals(textWithAlphabeticLetters, decode);
}
@DisplayName("Testing correction of encoding text with no alphabetic letters")
@Test
public void testIfEncodingModifyTextWithAlphabeticChars (){
String encoded = cesarCipher.encode(textWithAlphabeticLetters);
Assertions.assertEquals(expectedTextForAlphabeticLetters, encoded);
}
@DisplayName("Testing correction of encoding text with no alphabetic letters")
@Test
public void testIfDecodingModifyTextWithAlphabeticChars (){
String decoded = cesarCipher.decode(expectedTextForAlphabeticLetters);
Assertions.assertEquals(textWithAlphabeticLetters, decoded);
}
}
| [
"dymo.s@interia.pl"
] | dymo.s@interia.pl |
40824a3f9fe55b324e46bda4a9d53d5418f387cc | 7dd1ab6a4825399851feab8aff8e85cd1f5d9aaf | /src/Glav_form/Bukhgalter.java | ae2f9f8f6243e5065364f1eca6ac502c0b5cd858 | [] | no_license | RuslanMen7/realt | 0d6f05261b3e35b998d9c4165f71e2a6ae1bc044 | 0f083b96852207922cc07c3da1d8317c61ef43ad | refs/heads/master | 2020-04-09T16:07:24.794805 | 2018-12-05T01:52:20 | 2018-12-05T01:52:20 | 160,444,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,934 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Glav_form;
import Bukhdalter.sozdaniye_kvitka;
import Bukhdalter.zarplata;
import Delete_dannye.delete;
import Dopol_Form.otchet;
import Dopol_Form.otchet_sotrudnikov;
import Sotrudniki.Sotrudniki;
import java.awt.Component;
import javax.swing.JOptionPane;
/**
*
* @author Asus
*/
public class Bukhgalter extends javax.swing.JFrame {
/**
* Creates new form Bukhgalter
*/
public Bukhgalter() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Бухгалтер");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setBackground(new java.awt.Color(255, 99, 177));
jButton1.setText("Выход");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Logotip/Безымянный_1.png"))); // NOI18N
jButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton2.setText("Сотрудники");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton3.setText("Начисление зарплаты");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton4.setText("Создание квитка");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton6.setText("Отчеты");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jButton7.setText("Удаленная информация");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Добро пожаловать в систему Бухгалтера");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(35, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton7, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(35, 35, 35))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))))
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4)
.addGap(11, 11, 11)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton6)
.addContainerGap(30, Short.MAX_VALUE))
);
jMenu1.setText("Файл");
jMenuItem1.setText("Действия по сотрудникам");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem5.setText("Создание квитка");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem5);
jMenuItem6.setText("Начисление зарплаты");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem6);
jMenuItem7.setText("Удаленная информация");
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem7);
jMenuItem8.setText("Отчеты");
jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem8ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem8);
jMenuItem2.setText("Выход");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuBar1.add(jMenu1);
jMenu2.setText("Помощь");
jMenuItem3.setText("О программе");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem3);
jMenuItem4.setText("Справка");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Component frame = null;
int n = JOptionPane.showConfirmDialog(
frame,
"Выдествительно хотите покинуть форму?",
"",
JOptionPane.YES_NO_OPTION);
if (n == 0) {
dispose();
Authorization form1 = new Authorization();
form1.setVisible(true);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
}//GEN-LAST:event_formWindowClosed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
Component frame = null;
int n = JOptionPane.showConfirmDialog(
frame,
"Выдествительно хотите выйти из системы ?",
"",
JOptionPane.YES_NO_OPTION);
if (n == 0) {
dispose();
Authorization form1 = new Authorization();
form1.setVisible(true);
}
}//GEN-LAST:event_formWindowClosing
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
new Sotrudniki().setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
new delete().setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
new otchet().setVisible(true);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
new zarplata().setVisible(true);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
new sozdaniye_kvitka().setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
new Sotrudniki().setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
new sozdaniye_kvitka().setVisible(true);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
new zarplata().setVisible(true);
}//GEN-LAST:event_jMenuItem6ActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
Component frame = null;
int n = JOptionPane.showConfirmDialog(
frame,
"Выдествительно хотите покинуть форму?",
"",
JOptionPane.YES_NO_OPTION);
if (n == 0) {
dispose();
Authorization form1 = new Authorization();
form1.setVisible(true);
}
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
JOptionPane.showMessageDialog(null, "Программа СТО Бурятия \n"
+ " Разработчик:Хуснутдинов Руслан Фиргатович \n Проектировщик:Сизинцев Денис Сергевич");
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
JOptionPane.showMessageDialog(null, "Для получения информации или редоктирования\n в систеие бухгалтера не обходимо\n нажать одну из пяти кнопак. ");
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
new delete().setVisible(true);
}//GEN-LAST:event_jMenuItem7ActionPerformed
private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
new otchet().setVisible(true);
}//GEN-LAST:event_jMenuItem8ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Bukhgalter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Bukhgalter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Bukhgalter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Bukhgalter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Bukhgalter().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
| [
"ASUS@DESKTOP-2JMSBTH"
] | ASUS@DESKTOP-2JMSBTH |
e77aa506073261a476dca1027a5cd4e33a32bcc2 | 152b07644c2f7c3ebcc3831998b05eb46786d6dc | /Accurate-Parent/Accurate-Dao/src/main/java/com/jhg/marketing/dao/mapper/DiseasesTypeMapper.java | 8060b5402489fa6d229a27bdaeefc9c5f50728d1 | [
"AFL-3.0"
] | permissive | gongboGit/JhgWechatDevolepment | e24fdf6656540b20c6d8d706478e51bd99309049 | 75565786e2cdde65fc0aeb3821d39554d2b94ed4 | refs/heads/master | 2022-12-15T12:28:42.533256 | 2019-11-26T05:28:47 | 2019-11-26T05:28:47 | 224,101,251 | 0 | 0 | AFL-3.0 | 2022-12-11T20:35:36 | 2019-11-26T04:20:16 | JavaScript | UTF-8 | Java | false | false | 200 | java | package com.jhg.marketing.dao.mapper;
import com.jhg.marketing.dao.domin.DiseasesType;
import tk.mybatis.mapper.common.Mapper;
public interface DiseasesTypeMapper extends Mapper<DiseasesType> {
}
| [
"592792000@qq.com"
] | 592792000@qq.com |
139f5fff307b1f887ff8c7aed5d580a2bd5e21c9 | e6d74f0a56bfbd35664bb1345f9c75420b7f62a5 | /StreamBaseParse/src/Parser/OutputStream.java | a72074f884dda9cf078db29aaa31df46bad72ee8 | [] | no_license | gokhansa/StramBase-Eventflow-Parser-.sbapp- | 65291bd4eae7f4bd6a7c7195b11f83e8d5e11c00 | 5456675be98b3a9fe071ae919c61102966878a9e | refs/heads/master | 2021-01-10T10:50:53.292511 | 2016-02-24T16:13:39 | 2016-02-24T16:13:39 | 52,445,918 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 340 | java | package Parser;
public class OutputStream implements Elements{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "Name:"+ getName();
}
@Override
public String getType() {
return "OutputStream";
}
}
| [
"gokhansagirlar@gmail.com"
] | gokhansagirlar@gmail.com |
a04377ef22dd892bbc5f64ebdb1277524ecc25a0 | 9cbf152fcdd6540f31092e68a9dac9eab1bdd7e1 | /src/main/java/com/rfb/demo/rxjavatest/asm/Music.java | dfc94d09558ab3bdaec9513be5dcdb6433d013bf | [] | no_license | RFBGH/javaTest | 17f8eac24b89e0729fd67981934b50c5b6db4cec | f59e606a6903ed70013ffdd4d18159d94623d10c | refs/heads/master | 2022-11-26T23:29:05.501679 | 2021-03-04T14:22:37 | 2021-03-04T14:22:37 | 131,824,449 | 0 | 0 | null | 2022-11-16T08:39:13 | 2018-05-02T08:54:56 | Java | UTF-8 | Java | false | false | 414 | java | package com.rfb.demo.rxjavatest.asm;
public class Music {
public void run(){
System.out.println("this is run");
}
public int getValue(){
System.out.println("this is run");
return 1;
}
public void put(String value){
}
private void add(String value, Thread thread){
}
protected Music fake(int[] nums, String[] values){
return null;
}
}
| [
"ruanfengbing@bytedance.com"
] | ruanfengbing@bytedance.com |
b2a5222e96b5207be83b355059b64b5a4bbfe629 | 1336a1808af4575e1b3ab27f1e0c10a6ad4463d1 | /Crypto/ConstantKey-ForgeryAttack-Lean/Malicious/app/src/main/java/edu/ksu/cs/malicious/MainActivity.java | 12a646a0650bdacc37a4098863cb827b5b8a2dca | [
"BSD-3-Clause"
] | permissive | vaginessa/android-app-vulnerability-benchmarks | bda9f44fd4540d4a703531b72cd65230df6ab58e | 6289f39d394afe83f5e591dcfb01e913f7307a90 | refs/heads/master | 2020-04-20T18:19:08.362162 | 2019-01-15T18:19:59 | 2019-01-22T22:25:09 | 169,016,953 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,415 | java | package edu.ksu.cs.malicious;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
private static String TAG = "Malicious";
static final String PROVIDED_TOKEN_KEY = "generatedToken";
static final String INIT_VECTOR_KEY = "initVector";
static final byte[] SECRET_KEY = "0123456789!@#$%^".getBytes();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText emailAddrText = (EditText) findViewById(R.id.emailText);
String emailAddr = emailAddrText.getText().toString();
Intent intent = new Intent("edu.ksu.cs.benign.NEWPASS");
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/GCM/NoPadding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
Log.d(TAG, "Exception while creating cipher instance", e);
Toast.makeText(getApplicationContext(), "Cipher error",
Toast.LENGTH_LONG).show();
return;
}
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY,"AES");
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
} catch (InvalidKeyException e) {
Log.d(TAG, "Exception while initializing cipher instance", e);
Toast.makeText(getApplicationContext(), "Cipher error",
Toast.LENGTH_LONG).show();
return;
}
try {
String token = Base64.encodeToString(cipher.doFinal(emailAddr.getBytes()),
Base64.DEFAULT);
intent.putExtra(PROVIDED_TOKEN_KEY, token);
Log.d(TAG, "Token = " + token);
} catch (IllegalBlockSizeException | BadPaddingException e) {
Log.d(TAG, "Exception while encrypting data second time", e);
Toast.makeText(getApplicationContext(),
"Token was not emailed. Try again :(",
Toast.LENGTH_LONG).show();
return;
}
String initializationVector = Base64.encodeToString(cipher.getIV(),
Base64.DEFAULT);
intent.putExtra(INIT_VECTOR_KEY, initializationVector);
Log.d(TAG, "IV = " + initializationVector);
startActivity(intent);
}
});
}
}
| [
"joymitro.gmail.com"
] | joymitro.gmail.com |
aa7949a12ae13972849da60a5d0c7e04efa1e2ad | c7e094cb46600f22ca026eaa3997c2bd25c0a81e | /src/main/java/io/mercer/dp/visitor/File.java | 71ea214fad520da6aedb4860fa5949a4542a3b7e | [] | no_license | mercer/DesignPatterns | 119dd7f93b678426f16ea70d5811a7b37a3806c4 | 727bab336a97b38ed6bd78119caa966e37df5874 | refs/heads/master | 2020-05-18T17:14:23.120713 | 2014-06-04T06:02:29 | 2014-06-04T06:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,005 | java | package io.mercer.dp.visitor;
import java.util.ArrayList;
import java.util.List;
public class File implements Item {
private String name;
private boolean directory = false;
private List<File> children = new ArrayList<File>();
private int level = 0;
public File (String name, boolean isDirectory) {
this.name = name;
this.directory = isDirectory;
}
public void addChild(File file) {
this.children.add(file);
file.incrementLevel();
}
public String getName() {
return name;
}
public int getLevel() {
return level;
}
public void incrementLevel() {
this.level++;
for (File file : children) {
file.incrementLevel();
}
}
public boolean isDirectory() {
return directory;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
for (File file : children) {
file.accept(visitor);
}
}
}
| [
"mercer.traieste@gmail.com"
] | mercer.traieste@gmail.com |
898b4042e5676042e092de259f19ef670c3e8d4c | ca526552fcd6d4572e13dbb3868594563a7c8024 | /src/main/java/dyoon/innocent/lp/ILPSolver.java | d94ff07760feb9a38ec0b097f3048024d3de8b76 | [] | no_license | dongyoungy/innocent | e0e4fa45ee914a4bac4a80b9c5ca43bfb92fa076 | 09bc2b39aedcec915dea5b30d0874c278f7d6601 | refs/heads/master | 2021-07-16T19:39:29.540043 | 2019-02-06T03:12:32 | 2019-02-06T03:12:32 | 153,812,486 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,720 | java | package dyoon.innocent.lp;
import dyoon.innocent.Query;
import dyoon.innocent.data.PartitionSpace;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solution;
import org.chocosolver.solver.variables.IntVar;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Created by Dong Young Yoon on 2018-12-17. */
public class ILPSolver {
public static List<PartitionSpace> solveForBestColumnForPartition(
List<PartitionSpace> partitionSpaces, int k) {
Model m = new Model("test");
Set<String> querySet = new HashSet<>();
Map<String, List<IntVar>> qToPs = new HashMap<>();
Map<String, IntVar> qMap = new HashMap<>();
int i = 0;
IntVar[] psVar = new IntVar[partitionSpaces.size()];
for (PartitionSpace space : partitionSpaces) {
String ps = String.format("ps_%d", i);
psVar[i] = m.intVar(ps, 0, 1);
for (Query query : space.getQueries()) {
String q = String.format("q_%s", query.getId());
querySet.add(q);
if (!qToPs.containsKey(q)) {
qToPs.put(q, new ArrayList<>());
}
List<IntVar> psList = qToPs.get(q);
psList.add(psVar[i]);
}
++i;
}
// objective function
IntVar qCovered = m.intVar("qCovered", 0, 100000);
IntVar[] qVar = new IntVar[querySet.size()];
i = 0;
for (String q : querySet) {
qVar[i] = m.intVar(q, 0, 1);
qMap.put(q, qVar[i]);
++i;
}
m.sum(qVar, "=", qCovered).post();
// constraint 1: no more than k sets
IntVar numPs = m.intVar("numPs", 0, partitionSpaces.size());
m.sum(psVar, "=", numPs).post();
m.arithm(numPs, "<=", k).post();
// constraint 2: a query needs at least one ps chosen
for (String q : qToPs.keySet()) {
IntVar qVar1 = qMap.get(q);
List<IntVar> psVarList = qToPs.get(q);
IntVar[] psVars = psVarList.toArray(new IntVar[psVarList.size()]);
IntVar qSum = m.intVar(q + "_sum", 0, 100000);
m.sum(psVars, "=", qSum).post();
m.arithm(qSum, ">=", qVar1).post();
}
m.setObjective(Model.MAXIMIZE, qCovered);
m.getSolver().limitTime("30s");
Solution solution = new Solution(m);
while (m.getSolver().solve()) {
m.getSolver().printStatistics();
solution.record();
}
m.getSolver().printStatistics();
List<PartitionSpace> result = new ArrayList<>();
for (i = 0; i < psVar.length; ++i) {
System.out.println(String.format("ps_%d = %d", i, solution.getIntVal(psVar[i])));
if (solution.getIntVal(psVar[i]) == 1) {
result.add(partitionSpaces.get(i));
}
}
return result;
}
}
| [
"dongyoungy@gmail.com"
] | dongyoungy@gmail.com |
b83253eea766a98179a410882213b761cf420a00 | 444eedd67e672d46e7244308bf9b0f6559cdd994 | /app/src/main/java/android/example/com/pembimbingintern/Model/PostPutDelMhs.java | b05d94a9c9395ad30920e420cf4aaba854421f97 | [] | no_license | FahrizalAziFerdiansyah/PembimbingIntern | c69c9d39bf53de5fa55094815196214fdec2b927 | 3bfbadfd061e535e3b97faccaf11b68ca1b8249c | refs/heads/master | 2023-01-31T10:05:13.170312 | 2020-12-15T16:08:54 | 2020-12-15T16:08:54 | 308,878,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package android.example.com.pembimbingintern.Model;
import com.google.gson.annotations.SerializedName;
public class PostPutDelMhs {
@SerializedName("status")
String status;
@SerializedName("result")
Mahasiswa mMahasiswa;
@SerializedName("message")
String message;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Mahasiswa getmMahasiswa() {
return mMahasiswa;
}
public void setmMahasiswa(Mahasiswa mMahasiswa) {
this.mMahasiswa = mMahasiswa;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| [
"47998993+FahrizalAziFerdiansyah@users.noreply.github.com"
] | 47998993+FahrizalAziFerdiansyah@users.noreply.github.com |
58cc1702a3eaddcb749776ccdf2e4889c7c5f745 | 05ebb721fe64b06af0590a9fe84cd9191410ec79 | /src/main/java/com/example/virus/vo/NewSummary.java | 70473198c49c592556e5c6af1f10397eaf2aeec6 | [] | no_license | GeoIntelSolution/virsus-info | c674386186a001c06c066184139d75d907a79557 | 8a24c5bd226e382a27abbb0b878b63a166038e9f | refs/heads/master | 2020-12-19T12:48:13.552014 | 2020-01-27T03:06:45 | 2020-01-27T03:06:45 | 235,737,419 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,164 | java | package com.example.virus.vo;
import java.util.List;
public class NewSummary {
private long createTime;
private long modifyTime;
private String tags;
private int countryType;
private String provinceId;
private String provinceName;
private String provinceShortName;
private String cityName;
private int confirmedCount;
private int suspectedCount;
private int curedCount;
private int deadCount;
private String comment;
private int sort;
private String operator;
private java.util.List<CityItem> cities;
public List<CityItem> getCities() {
return cities;
}
public void setCities(List<CityItem> cities) {
this.cities = cities;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getModifyTime() {
return modifyTime;
}
public void setModifyTime(long modifyTime) {
this.modifyTime = modifyTime;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public int getCountryType() {
return countryType;
}
public void setCountryType(int countryType) {
this.countryType = countryType;
}
public String getProvinceId() {
return provinceId;
}
public void setProvinceId(String provinceId) {
this.provinceId = provinceId;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getProvinceShortName() {
return provinceShortName;
}
public void setProvinceShortName(String provinceShortName) {
this.provinceShortName = provinceShortName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getConfirmedCount() {
return confirmedCount;
}
public void setConfirmedCount(int confirmedCount) {
this.confirmedCount = confirmedCount;
}
public int getSuspectedCount() {
return suspectedCount;
}
public void setSuspectedCount(int suspectedCount) {
this.suspectedCount = suspectedCount;
}
public int getCuredCount() {
return curedCount;
}
public void setCuredCount(int curedCount) {
this.curedCount = curedCount;
}
public int getDeadCount() {
return deadCount;
}
public void setDeadCount(int deadCount) {
this.deadCount = deadCount;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
}
| [
"1501540275@qq.com"
] | 1501540275@qq.com |
b2665dd1ea7d46d31b70ad7d5f70d1e6e73fba5a | c94f888541c0c430331110818ed7f3d6b27b788a | /blockchain/java/src/main/java/com/antgroup/antchain/openapi/blockchain/models/GetContractConfigChainRequest.java | c4c633fe286ff627c451f9173f846c1e1cd242c6 | [
"MIT",
"Apache-2.0"
] | permissive | alipay/antchain-openapi-prod-sdk | 48534eb78878bd708a0c05f2fe280ba9c41d09ad | 5269b1f55f1fc19cf0584dc3ceea821d3f8f8632 | refs/heads/master | 2023-09-03T07:12:04.166131 | 2023-09-01T08:56:15 | 2023-09-01T08:56:15 | 275,521,177 | 9 | 10 | MIT | 2021-03-25T02:35:20 | 2020-06-28T06:22:14 | PHP | UTF-8 | Java | false | false | 1,076 | java | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.blockchain.models;
import com.aliyun.tea.*;
public class GetContractConfigChainRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
public static GetContractConfigChainRequest build(java.util.Map<String, ?> map) throws Exception {
GetContractConfigChainRequest self = new GetContractConfigChainRequest();
return TeaModel.build(map, self);
}
public GetContractConfigChainRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public GetContractConfigChainRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
8448c9872156aa32fad0d2b895626f766232fbf7 | 4b26b54fcd7a02c291105b6f8be1ab00a5b1b7e2 | /sunlands-study-examplan-parent/study-examplan-server/src/main/java/com/sunlands/examplan/base/entity/DataEntity.java | 2dab079853dd191d0eb67c99e2feb47af34de73f | [] | no_license | NaM0729/kekeguo | cbfa1ea26faeb207ebcf493b5560fe22c671077c | 3e0350b37a77c911f1d6940e06468c2cb09f80ea | refs/heads/master | 2020-03-30T06:37:56.919308 | 2018-12-26T02:55:13 | 2018-12-26T02:55:13 | 150,876,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,353 | java | package com.sunlands.examplan.base.entity;
import com.sunlands.examplan.constant.DeleteFlag;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
import java.util.Date;
/**
* 数据实体类
*
* @author 周宇
* @Class Name DataEntity
* @Create In 2018年08月10日14:20:40
*/
public abstract class DataEntity implements Serializable {
private static final long serialVersionUID = 1L;
protected String createBy; // 创建者
protected Date createDate; // 创建日期
protected String updateBy; // 更新者
protected Date updateDate; // 更新日期
/**
* 删除标示(0:正常,1:删除)
*/
protected Integer deleteFlag;
/**
* 插入之前执行方法,需要手动调用
*/
public void preInsert(String userId) {
if (StringUtils.isNotBlank(userId)) {
this.updateBy = userId;
this.createBy = userId;
this.deleteFlag = DeleteFlag.NORMAL.getValue();
}
this.updateDate = new Date();
this.createDate = this.updateDate;
}
/**
* 更新之前执行方法,需要手动调用
*/
public void preUpdate(String userId) {
if (StringUtils.isNotBlank(userId)) {
this.updateBy = userId;
}
this.updateDate = new Date();
}
}
| [
"zynxmy@163.com"
] | zynxmy@163.com |
cebaa50fb192674a4731fc451cf5b25c0b7eab4e | efa8f185b5c7ebfe56d425a960cb0b2fef40d5cc | /poc-concordion/src/main/java/com/examples/vo/Forecast.java | 84d5e6e449b1029b6e07758642c5cfe0cee549e8 | [] | no_license | carlosricor/poc-concordion | 55a539d48a3acc39af1b121fb203be2743f026ef | fed5bf8a8db5b543a9b38a757593b533796bfc71 | refs/heads/master | 2021-09-05T17:31:25.771833 | 2018-01-29T22:59:43 | 2018-01-29T22:59:43 | 119,452,404 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,798 | java |
package com.examples.vo;
import java.util.ArrayList;
public class Forecast {
private Integer dt;
private Temp temp;
private Double pressure;
private Integer humidity;
private java.util.List<Weather> weather = new ArrayList<>();
private Double speed;
private Integer deg;
private Integer clouds;
private Double rain;
private Double snow;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Temp getTemp() {
return temp;
}
public void setTemp(Temp temp) {
this.temp = temp;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Integer getDeg() {
return deg;
}
public void setDeg(Integer deg) {
this.deg = deg;
}
public Integer getClouds() {
return clouds;
}
public void setClouds(Integer clouds) {
this.clouds = clouds;
}
public Double getRain() {
return rain;
}
public void setRain(Double rain) {
this.rain = rain;
}
public Double getSnow() {
return snow;
}
public void setSnow(Double snow) {
this.snow = snow;
}
}
| [
"Carlos Rico@EM2014000400"
] | Carlos Rico@EM2014000400 |
6b3648548e37fb5f3480c28b1089b14f3f915e82 | 5fe0b2836fd22c3e7d1ce88b8628f226d3b727bb | /WinPointManagementSystem/src/main/java/com/winpoint/repository/PaymentModeRepository.java | 69e9aca6c811cefbddc8facf922a7fdeef1d8692 | [] | no_license | WinPointLC/WinPointDigitization-SpringBoot | 50d848abae5b6895afe95cf25b9313ba2f4b24dd | 61b57fe77b8f62f43030fab6cdca19b9945811d4 | refs/heads/master | 2023-03-09T05:57:46.962074 | 2021-03-02T06:36:31 | 2021-03-02T06:36:31 | 299,283,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 224 | java | package com.winpoint.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.winpoint.model.PaymentMode;
public interface PaymentModeRepository extends JpaRepository<PaymentMode, Integer>{
}
| [
"55729950+ak-agarwal@users.noreply.github.com"
] | 55729950+ak-agarwal@users.noreply.github.com |
b69da3c6121ffad561813e1c7e87cf0fd967bba3 | e1e5bd6b116e71a60040ec1e1642289217d527b0 | /H5/L2jMaster_org/L2jMaster_org_2019_07_02/L2JMaster_Server/src/main/java/com/l2jserver/gameserver/network/clientpackets/AnswerCoupleAction.java | 4bb0c9c63494f40f9954fab896b724b5d38b1e4c | [] | no_license | serk123/L2jOpenSource | 6d6e1988a421763a9467bba0e4ac1fe3796b34b3 | 603e784e5f58f7fd07b01f6282218e8492f7090b | refs/heads/master | 2023-03-18T01:51:23.867273 | 2020-04-23T10:44:41 | 2020-04-23T10:44:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,342 | java | /*
* Copyright (C) 2004-2019 L2J Server
*
* This file is part of L2J Server.
*
* L2J Server is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.network.clientpackets;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.ExRotation;
import com.l2jserver.gameserver.network.serverpackets.SocialAction;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.util.Util;
/**
* @author JIV
*/
public class AnswerCoupleAction extends L2GameClientPacket
{
private static final String _C__D0_7A_ANSWERCOUPLEACTION = "[C] D0:7A AnswerCoupleAction";
private int _charObjId;
private int _actionId;
private int _answer;
@Override
protected void readImpl()
{
_actionId = readD();
_answer = readD();
_charObjId = readD();
}
@Override
protected void runImpl()
{
L2PcInstance activeChar = getActiveChar();
L2PcInstance target = L2World.getInstance().getPlayer(_charObjId);
if ((activeChar == null) || (target == null))
{
return;
}
if ((target.getMultiSocialTarget() != activeChar.getObjectId()) || (target.getMultiSociaAction() != _actionId))
{
return;
}
if (_answer == 0) // cancel
{
target.sendPacket(SystemMessageId.COUPLE_ACTION_DENIED);
}
else if (_answer == 1) // approve
{
final int distance = (int) activeChar.calculateDistance(target, false, false);
if ((distance > 125) || (distance < 15) || (activeChar.getObjectId() == target.getObjectId()))
{
sendPacket(SystemMessageId.TARGET_DO_NOT_MEET_LOC_REQUIREMENTS);
target.sendPacket(SystemMessageId.TARGET_DO_NOT_MEET_LOC_REQUIREMENTS);
return;
}
int heading = Util.calculateHeadingFrom(activeChar, target);
activeChar.broadcastPacket(new ExRotation(activeChar.getObjectId(), heading));
activeChar.setHeading(heading);
heading = Util.calculateHeadingFrom(target, activeChar);
target.setHeading(heading);
target.broadcastPacket(new ExRotation(target.getObjectId(), heading));
activeChar.broadcastPacket(new SocialAction(activeChar.getObjectId(), _actionId));
target.broadcastPacket(new SocialAction(_charObjId, _actionId));
}
else if (_answer == -1) // refused
{
SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.C1_IS_SET_TO_REFUSE_COUPLE_ACTIONS);
sm.addPcName(activeChar);
target.sendPacket(sm);
}
target.setMultiSocialAction(0, 0);
}
@Override
public String getType()
{
return _C__D0_7A_ANSWERCOUPLEACTION;
}
}
| [
"64197706+L2jOpenSource@users.noreply.github.com"
] | 64197706+L2jOpenSource@users.noreply.github.com |
2803b6b99f0f2dcb4406225d12322e1d13d2ea13 | 2aa81ae67c7d6e0c52ea3c55c6b2784416a3a5be | /src/test/java/PageObject/AjaxSubmitWithLoading.java | 256499c1b15e1e9ae801e1356b1e0abf31bcec63 | [] | no_license | Patryk728/Selenium | fa9d490fa83ee21309eef66168d1f93a1f95aba5 | fdd93bf16e9928786b58aab29016d42b0b94e127 | refs/heads/master | 2020-04-25T19:56:28.203128 | 2019-02-28T12:16:04 | 2019-02-28T12:16:04 | 173,038,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,833 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
public class AjaxSubmitWithLoading extends BasePage {
private final static String Url = appUrl + "ajax-form-submit-demo.html";
public AjaxSubmitWithLoading(RemoteWebDriver webDriver) {
super(webDriver);
}
public static String getUrl() {
return Url;
}
//elements for Ajax Form
private WebElement nameBox;
private WebElement commentBox;
private WebElement submitButton;
private WebElement resultMessage;
//methods for Ajax Form
public AjaxSubmitWithLoading nameBoxClick() {
nameBox.click();
return this;
}
public AjaxSubmitWithLoading nameBoxInputText(String inputName) {
nameBox.sendKeys(inputName);
return this;
}
public AjaxSubmitWithLoading commentBoxClick() {
commentBox.click();
return this;
}
public AjaxSubmitWithLoading commentBoxInputText(String inputComment) {
commentBox.sendKeys(inputComment);
return this;
}
public AjaxSubmitWithLoading submitButtonClick() {
submitButton.click();
return this;
}
public WebElement getSubmitButton() {
return submitButton;
}
public WebElement getResultMessage() {
return resultMessage;
}
public AjaxSubmitWithLoading initializeElements(RemoteWebDriver webDriver) {
nameBox = webDriver.findElement(By.xpath("//*[@id=\"title\"]"));
commentBox = webDriver.findElement(By.xpath("//*[@id=\"description\"]"));
submitButton = webDriver.findElement(By.xpath("//*[@id=\"btn-submit\"]"));
resultMessage = webDriver.findElement(By.xpath("//*[@id=\"submit-control\"]"));
return this;
}
} | [
"patryk.dabrowski9@gmail.com"
] | patryk.dabrowski9@gmail.com |
51f6d53e88bb5c728d50eee24bb6e2ed95239be5 | 37f36fe4d46af514dda9b7585bdf535f614e5201 | /src/java/controller/ReturnController.java | d0c36efcbaaea49aa316fc955effbd3fce97a72d | [] | no_license | longg20/JourneyToTheWest | 871f77513f7be12e9cd0bd6cd6bb61bf80191d96 | b80cee7134e0384fe4a7739af8fd10d753bdc4f8 | refs/heads/master | 2023-01-23T07:05:12.187629 | 2020-12-04T05:53:26 | 2020-12-04T05:53:26 | 318,417,568 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,835 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Long
*/
public class ReturnController extends HttpServlet {
private static final String ADMIN = "admin/admin.jsp";
private static final String ACTOR = "actor/actor.jsp";
private static final String INVALID = "error.jsp";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String url = INVALID;
try {
HttpSession session = request.getSession();
String role = (String) session.getAttribute("ROLE");
if (role.equals("admin"))
url = ADMIN;
else if (role.equals("actor"))
url = ACTOR;
else {
request.setAttribute("ERROR", "Invalid role");
}
} catch (Exception e) {
log("ERROR at ReturnController: " + e.getMessage());
} finally {
request.getRequestDispatcher(url).forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"longttse140019@fpt.edu.vn"
] | longttse140019@fpt.edu.vn |
3035e005f8243974ff002e9570d1e6d06e2eca82 | 4619ef64436f410273215c4db1773d6e7c2c3b64 | /SimiCart/app/src/main/java/com/simicart/plugins/braintree/model/BrainTreeModel.java | b6708bcf71f9f6e315f02d53f3fafa3583a77a92 | [] | no_license | Simicart/Android-studio-core | ba72add5d98b6fff1895d0fc1b02441276d2963d | 44389099b7a2e2ca5c1eb1c14f6f8129713d880c | refs/heads/master | 2021-06-08T16:21:49.831387 | 2016-09-21T13:35:06 | 2016-09-21T13:35:06 | 48,149,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,112 | java | package com.simicart.plugins.braintree.model;
import com.simicart.core.base.model.SimiModel;
import com.simicart.core.base.model.collection.SimiCollection;
import org.json.JSONArray;
import org.json.JSONException;
public class BrainTreeModel extends SimiModel {
protected String message;
@Override
protected void parseData() {
try {
if (mJSON.has("message")) {
JSONArray messArr = mJSON.getJSONArray("message");
if (messArr.length() > 0) {
message = messArr.getString(0);
}
}
JSONArray js_data = this.mJSON.getJSONArray("data");
if (null == collection) {
collection = new SimiCollection();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void setUrlAction() {
mUrlAction = "simibraintree/index/update_payment";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| [
"crabby@simicart.com"
] | crabby@simicart.com |
6e6376b024a86cb37946b5a6060267ad4abc099b | 83eb940fc766c8ff515727a3fe5c15a53ac3ddde | /app/src/main/java/moe/koibito/findiction/NaviListAdapter.java | 4615d287039acb4520c417231393d8197c0aceff | [] | no_license | Astoration/FINDiction | 4f0d77dcc46d962d2e0670f92549e6b18ad51340 | 6cbeb89fc0a57a36fa1ca6bd7dae7f41ca2426a6 | refs/heads/master | 2020-07-03T09:55:56.473584 | 2017-09-04T02:47:04 | 2017-09-04T02:47:04 | 67,225,496 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,923 | java | package moe.koibito.findiction;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Astoration on 2016. 9. 3..
*/
public class NaviListAdapter extends BaseAdapter {
private ArrayList<NaviMenuItem> MenuItemlist = new ArrayList<>();
public NaviListAdapter(NaviMenuItem[] items){
MenuItemlist.addAll(Arrays.asList(items));
}
public void addMenuItem(Drawable drawable,String title){
NaviMenuItem item = new NaviMenuItem(drawable,title);
MenuItemlist.add(item);
}
@Override
public int getCount() {
return MenuItemlist.size();
}
@Override
public Object getItem(int i) {
return MenuItemlist.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final int pos = i;
Context context = viewGroup.getContext();
if(view==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navidrawer_list_item,viewGroup,false);
}
ImageView icon = (ImageView) view.findViewById(R.id.list_icon);
TextView title= (TextView) view.findViewById(R.id.list_title);
NaviMenuItem item = MenuItemlist.get(pos);
icon.setImageDrawable(item.getIconDrawable());
title.setText(item.getTitle());
return view;
}
@Override
public boolean isEmpty() {
return MenuItemlist.isEmpty();
}
}
| [
"ybdh00@naver.com"
] | ybdh00@naver.com |
b712699c62d85021d9a6c2fb934f2e55816b7d0b | 6e483845ddc79559ace7f3a69afa078d70520a99 | /src/edu/fatec/grafo/Grafo.java | 1523321b53d946e42c0fc32ad95c306108aa2d35 | [] | no_license | brunonlima/GrafoManhattanV2.0 | e0bba318b56f467a9aff470f22a0f33fd301de62 | f0a3ccc2ebca6fd0e491e392b3aab3a0ecb3cbd7 | refs/heads/master | 2021-09-07T04:52:06.995998 | 2018-02-17T19:43:26 | 2018-02-17T19:43:26 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,812 | java | package edu.fatec.grafo;
import java.util.LinkedList;
import java.util.Scanner;
//Classe G=(V,E) não-orientado.Tempo esperado de execução é proporcional à O(|V|E|)
public class Grafo {
//Atributos
private final int V;// Número de vértices,sendo uma constante.
private int E;// Número de arestas
private int adj[][];// Matriz de adjacências
private LinkedList<Integer>[] adje;// Lista de adjacências
// Construtor que inicializa o Grafo com V vértices
public Grafo(int V) {
if (V < 0) throw new IllegalArgumentException("Número de vértices não pode ser negativo");
this.V = V;
this.E = 0;
adj = new int[V][V];
adje = (LinkedList<Integer>[]) new LinkedList[V];
for (int v = 0; v < V; v++) {
adje[v] = new LinkedList<Integer>();
}
}
/* Método que adiciona E(v-w) arestas ao Grafo.
* Tempo esperado de execução é proporcional a O(V + E).
*/
public void adiciona_aresta(int E) {
if (E < 0) throw new IllegalArgumentException("Número de arestas não pode ser negativo");
int v=0,w=0,cont=0;
int u=0;
Scanner s = new Scanner(System.in);
while(cont < E){
System.out.printf("\n%d ARESTA:",cont+1);
do{
System.out.printf("\nForneça o valor da coordenada X: ");
v=s.nextInt();
}while(v > this.V);
do{
System.out.printf("Forneça o valor da coordenada Y: ");
w=s.nextInt();
} while(w > this.V);
do{
System.out.printf("\nForneça o valor de peso da aresta[%d,%d]: " , v , w);
System.out.printf("\n*Sendo 1 para Aresta horizontal ou vertical\n");
System.out.printf("*Sendo 2(RAIZ de 2) para Aresta diagonal\n");
u=s.nextInt();
}while(u > 2);
if (v != w && this.adj[v - 1][w - 1] == 0) {
this.adj[v - 1][w - 1] = u;
this.adj[w - 1][v - 1] = u;
adicionaArestaLista(v-1, w-1);
this.E++;
}
cont = cont + 1;
}
}
public void mostrarGrafo(){
int v, w;
System.out.printf("\n\n");
for (v = 0; v < this.V; v++){
System.out.printf( "%2d:", v+1);
for (w = 0; w < this.V; w++)
if (this.adj[v][w] > 0 )
System.out.printf( " %2d", w+1);
System.out.printf( "\n");
}
}
/* Método que mostra matriz de adjacências.
* Tempo esperado de execução é proporcional a O(V x V).
* Matriz simétrica.
*/
public void mostrarMatriz(){
int i , j;
System.out.printf( "\n\n** MATRIZ DE ADJACÊNCIAS**\n");
for(i = 0; i < this.V ; i++){
System.out.printf(" %d" , i + 1);
}
System.out.printf("\n --------------------------------------------------");
System.out.printf("\n");
for(i = 0; i < this.V ; i++){
System.out.printf("%d|" , i + 1);
for(j = 0; j < this.V ; j++)
System.out.printf(" %d" , this.adj[i][j]);
System.out.printf("\n");
}
}
private void adicionaArestaLista(int v, int w) {
if (v < 0 || v >= V) throw new IndexOutOfBoundsException();
if (w < 0 || w >= V) throw new IndexOutOfBoundsException();
adje[v].add(w);
adje[w].add(v);
}
public int V(){return V;}
public int E(){return E;}
public int[][] getAdj(){return adj;}
public Iterable<Integer> adje(int v) {
if (v < 0 || v >= V) throw new IndexOutOfBoundsException();
return adje[v];
}
}
| [
"brunofatecscs@gmail.com"
] | brunofatecscs@gmail.com |
fb82059fa5b3fb3dbd5a02e0ac41aebb8d969633 | 8526a444075827abccab07b2948a3269f04fefe7 | /app/src/main/java/nau/william/capstonechat/utils/Display.java | 02db1b9c30ed48669288d07fd2c32387cdc41694 | [] | no_license | WMNau/capstone-chat-app-android | 2f735033f77816ecc168a111539435649346a820 | b1ede4ca3b739659da9acea275d897dba79e2a6e | refs/heads/master | 2020-05-14T08:58:55.673650 | 2019-05-15T01:15:09 | 2019-05-15T01:15:09 | 181,732,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,059 | java | package nau.william.capstonechat.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.TextView;
import android.widget.Toast;
public class Display {
public static void toastMessage(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public static void popupMessage(Context context, String title, String message) {
toastMessage(context, message);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
TextView messageView = new TextView(context);
messageView.setText(message);
builder.setView(messageView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
| [
"="
] | = |
12e4f8bb995c2cc74284719ecb70d27c051b5858 | 471579962eb0abf949c73685353ef0098a8ad127 | /HelloGradle/src/main/java/com/kaifantech/component/timer/agv/server/YufengAgvServerTimer.java | 113d3cb3e9a7f5936fa385df2781bf12cd36b7c1 | [] | no_license | huyulin11/gradle | a727c7e31b9a42aee6decd5d6a5f5ceac84180f3 | 3cdc3b8b02e9f48af93d1cc6087b61f67cf45a0e | refs/heads/master | 2020-04-13T07:09:16.437325 | 2019-02-26T03:20:13 | 2019-02-26T03:20:13 | 163,042,029 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,965 | java | package com.kaifantech.component.timer.agv.server;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.kaifantech.component.dao.AGVConnectMsgDao;
import com.kaifantech.component.service.agv.simulator.YufengAgvServerWorker;
import com.kaifantech.component.service.comm.YufengAgvManager;
import com.kaifantech.init.sys.SystemClient;
import com.kaifantech.init.sys.params.SystemParameters;
import com.kaifantech.util.seq.ThreadID;
import com.kaifantech.util.thread.ThreadTool;
import com.ytgrading.util.AppTool;
@Component
@Lazy(false)
public class YufengAgvServerTimer {
private static boolean isRunning = false;
private static String timerType = "IOT模拟器";
private final Logger logger = Logger.getLogger(YufengAgvServerTimer.class);
@Autowired
private YufengAgvServerWorker agvServerWorker;
@Autowired
private AGVConnectMsgDao msgDao;
public YufengAgvServerTimer() {
logger.info(timerType + "开始启动!");
}
@Scheduled(cron = "0/1 * * * * ?")
public void resolute() {
if (!SystemClient.CLIENT.equals(SystemClient.Client.YUFENG)) {
return;
}
if (!SystemParameters.isConnectIotServer()) {
return;
}
if (!isRunning) {
Thread.currentThread().setName(timerType + (ThreadID.number++));
isRunning = true;
agvSimulate();
}
isRunning = false;
}
private void agvSimulate() {
ThreadTool.run(() -> {
agvServerWorker.startConnect();
});
}
@Scheduled(initialDelay = 5000, fixedDelay = 1000)
public void getMsgFromAgv() {
if (!SystemClient.CLIENT.equals(SystemClient.Client.YUFENG)) {
return;
}
String msg = agvServerWorker.getMap().get(1).getMsgReceived();
if (AppTool.isNull(msg)) {
return;
}
YufengAgvManager.nextMsg = msg;
msgDao.addAMsg(msg, "getMsgFromAgv", 1);
}
}
| [
"huyulin11@sina.cn"
] | huyulin11@sina.cn |
760d48a5d4378962563f8e0740acb30a7fd1c7b4 | 29d87d3c781b36d5ab5b114ddfe60f23cd81ceb0 | /org/wargamer2010/signshop/operations/takeShopItems.java | fe51c02de9ea6ebeff65ed79b86a129a0bd55dd9 | [] | no_license | MixxCraft/SignShop | 4855b8f7b33154d4ed4a8f4392585f5d91833c97 | 241fe404d8d2d7ec064ee80a9a69039d2b9d542d | refs/heads/master | 2021-01-21T08:44:35.583956 | 2014-03-29T22:33:01 | 2014-03-29T22:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,903 | java | package org.wargamer2010.signshop.operations;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.block.Block;
import org.wargamer2010.signshop.configuration.SignShopConfig;
import org.wargamer2010.signshop.util.itemUtil;
import java.util.List;
import java.util.LinkedList;
public class takeShopItems implements SignShopOperation {
@Override
public Boolean setupOperation(SignShopArguments ssArgs) {
if(ssArgs.getContainables().isEmpty()) {
ssArgs.getPlayer().get().sendMessage(SignShopConfig.getError("chest_missing", ssArgs.getMessageParts()));
return false;
}
ItemStack[] isTotalItems = itemUtil.getAllItemStacksForContainables(ssArgs.getContainables().get());
if(!ssArgs.isOperationParameter("allowemptychest") && isTotalItems.length == 0) {
ssArgs.getPlayer().get().sendMessage(SignShopConfig.getError("chest_empty", ssArgs.getMessageParts()));
return false;
}
ssArgs.getItems().set(isTotalItems);
ssArgs.setMessagePart("!items", itemUtil.itemStackToString(ssArgs.getItems().get()));
return true;
}
@Override
public Boolean checkRequirements(SignShopArguments ssArgs, Boolean activeCheck) {
if(ssArgs.getItems().get() == null) {
ssArgs.getPlayer().get().sendMessage(SignShopConfig.getError("no_items_defined_for_shop", ssArgs.getMessageParts()));
return false;
}
Boolean bStockOK = itemUtil.stockOKForContainables(ssArgs.getContainables().get(), ssArgs.getItems().get(), true);
ssArgs.setMessagePart("!items", itemUtil.itemStackToString(ssArgs.getItems().get()));
if(!bStockOK)
ssArgs.sendFailedRequirementsMessage("out_of_stock");
if(!bStockOK && activeCheck)
itemUtil.updateStockStatus(ssArgs.getSign().get(), ChatColor.DARK_RED);
else if(activeCheck)
itemUtil.updateStockStatus(ssArgs.getSign().get(), ChatColor.DARK_BLUE);
return bStockOK;
}
@Override
public Boolean runOperation(SignShopArguments ssArgs) {
InventoryHolder Holder = itemUtil.getFirstStockOKForContainables(ssArgs.getContainables().get(), ssArgs.getItems().get(), true);
if(Holder == null)
return false;
Holder.getInventory().removeItem(ssArgs.getItems().get());
if(!itemUtil.stockOKForContainables(ssArgs.getContainables().get(), ssArgs.getItems().get(), true))
itemUtil.updateStockStatus(ssArgs.getSign().get(), ChatColor.DARK_RED);
else
itemUtil.updateStockStatus(ssArgs.getSign().get(), ChatColor.DARK_BLUE);
ssArgs.setMessagePart("!items", itemUtil.itemStackToString(ssArgs.getItems().get()));
return true;
}
}
| [
"vincentspaa@hotmail.com"
] | vincentspaa@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.