repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
kenyaehrs/inventory
api/src/main/java/org/openmrs/module/inventory/model/InventoryStoreDrugIndentDetail.java
1662
package org.openmrs.module.inventory.model; import java.io.Serializable; import java.util.Date; import org.openmrs.module.hospitalcore.model.InventoryDrug; import org.openmrs.module.hospitalcore.model.InventoryDrugFormulation; import org.openmrs.module.hospitalcore.model.InventoryStoreDrugIndent; public class InventoryStoreDrugIndentDetail implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private InventoryStoreDrugIndent indent; private InventoryDrug drug; private InventoryDrugFormulation formulation; private Integer quantity; private Integer mainStoreTransfer; private Date createdOn; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public InventoryStoreDrugIndent getIndent() { return indent; } public void setIndent(InventoryStoreDrugIndent indent) { this.indent = indent; } public InventoryDrug getDrug() { return drug; } public void setDrug(InventoryDrug drug) { this.drug = drug; } public InventoryDrugFormulation getFormulation() { return formulation; } public void setFormulation(InventoryDrugFormulation formulation) { this.formulation = formulation; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public Integer getMainStoreTransfer() { return mainStoreTransfer; } public void setMainStoreTransfer(Integer mainStoreTransfer) { this.mainStoreTransfer = mainStoreTransfer; } }
gpl-2.0
AfzalivE/venuevue-android
venuevue/src/main/java/com/afzaln/venuevue/api/LoginRequest.java
1885
package com.afzaln.venuevue.api; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; /** * Created by afzal on 1/16/2014. */ public class LoginRequest extends Request<String> { private static final String TAG = LoginRequest.class.getSimpleName(); private static final String sUrl = VvApi.hostname + "/oauth/access_token"; private final Listener<String> mListener; private Map<String, String> mParams; public LoginRequest(Map<String, String> params, Listener<String> listener, ErrorListener errorListener) { super(Method.POST, sUrl, errorListener); mListener = listener; mParams = params; } @Override public Map<String, String> getParams() { return mParams; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); return headers; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String jsonString = new String(response.data); try { JSONObject resp = new JSONObject(jsonString); resp.put("username", mParams.get("username")); resp.put("password", mParams.get("password")); jsonString = resp.toString(); } catch (JSONException e) { e.printStackTrace(); } return Response.success(jsonString, getCacheEntry()); } @Override protected void deliverResponse(String response) { mListener.onResponse(response); } }
gpl-2.0
CumpsD/calimero
src/tuwien/auto/calimero/process/ProcessCommunicationBase.java
11543
/* Calimero 2 - A library for KNX network access Copyright (c) 2010, 2015 B. Malinowsky This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package tuwien.auto.calimero.process; import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.Priority; import tuwien.auto.calimero.datapoint.Datapoint; import tuwien.auto.calimero.dptxlator.DPTXlator; import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXFormatException; import tuwien.auto.calimero.exception.KNXTimeoutException; import tuwien.auto.calimero.link.KNXLinkClosedException; import tuwien.auto.calimero.link.KNXNetworkLink; /** * Process communication interface for writing to a KNX network. * <p> * * @author B. Malinowsky */ public interface ProcessCommunicationBase { /** * Represents "on" of datapoint type <b>Switch</b> (DPT ID 1.001), value = * {@value #BOOL_ON}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_ON = true; /** * Represents "off" of datapoint type <b>Switch</b> (DPT ID 1.001), value = * {@value #BOOL_OFF}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_OFF = false; /** * Represents "up" of datapoint type <b>Up/Down</b> (DPT ID 1.008), value = * {@value #BOOL_UP}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_UP = false; /** * Represents "down" of datapoint type <b>Up/Down</b> (DPT ID 1.008), value = * {@value #BOOL_DOWN}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_DOWN = true; /** * Represents "start" of datapoint type <b>Start</b> (DPT ID 1.010), value = * {@value #BOOL_START}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_START = true; /** * Represents "stop" of datapoint type <b>Start</b> (DPT ID 1.010), value = * {@value #BOOL_STOP}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_STOP = false; /** * Represents "increase" of datapoint type <b>Step</b> (DPT ID 1.007), value = * {@value #BOOL_INCREASE}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_INCREASE = true; /** * Represents "decrease" of datapoint type <b>Step</b> (DPT ID 1.007), value = * {@value #BOOL_DECREASE}. * <p> * * @see #write(GroupAddress, boolean) * @see #write(GroupAddress, boolean, int) */ boolean BOOL_DECREASE = false; /** * Represents the scaling format of datapoint type <b>Scaling</b> (DPT ID 5.001). * <p> * This format scales the 8 Bit unsigned value range from 0 to 100. * * @see #write(GroupAddress, int, String) */ String SCALING = "5.001"; /** * Represents the unscaled format, no scaling is used (like in datapoint types * <b>Unsigned count</b> (DPT ID 5.010) or <b>Decimal factor</b> (DPT ID 5.005) ). * <p> * * @see #write(GroupAddress, int, String) */ String UNSCALED = "5.010"; /** * Represents the scaling format of datapoint type <b>Angle</b> (DPT ID 5.003). * <p> * This format scales the 8 Bit unsigned value range from 0 to 360. * * @see #write(GroupAddress, int, String) */ String ANGLE = "5.003"; /** * Sets the KNX message priority for KNX messages to send. * <p> * * @param p new priority to use */ void setPriority(Priority p); /** * Returns the currently used KNX message priority for KNX messages. * <p> * * @return message Priority */ Priority getPriority(); /** * Adds the specified event listener <code>l</code> to receive events from this * process communicator. * <p> * If <code>l</code> was already added as listener, no action is performed. * * @param l the listener to add */ void addProcessListener(ProcessListener l); /** * Removes the specified event listener <code>l</code>, so it does no longer * receive events from this process communicator. * <p> * If <code>l</code> was not added in the first place, no action is performed. * * @param l the listener to remove */ void removeProcessListener(ProcessListener l); /** * Writes a boolean datapoint value to a group destination. * <p> * * @param dst group destination to write to * @param value boolean value to write, consider the predefined BOOL_* constants (e.g. * {@link #BOOL_ON}) * @throws KNXTimeoutException on a timeout during send * @throws KNXLinkClosedException if network link to KNX network is closed */ void write(GroupAddress dst, boolean value) throws KNXTimeoutException, KNXLinkClosedException; /** * Writes a 8 bit unsigned datapoint value to a group destination. * <p> * The predefined scaling format constants are equal to DPT identifiers of the 8 Bit * DPT translator, any other suiting IDs of that type might be specified as well. * * @param dst group destination to write to * @param value unsigned scaled value to write, 0 &lt;= value &lt;= scale format * specific upper value * @param scale scaling of the read value before return, one of {@link #SCALING}, * {@link #UNSCALED}, {@link #ANGLE} * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, int value, String scale) throws KNXException; /** * Writes a 3 bit controlled datapoint value to a group destination. * <p> * * @param dst group destination to write to * @param control control information, one of the predefined BOOL_* constants of DPT * <b>Step</b> and DPT <b>Up/Down</b> * @param stepcode stepcode value, 0 &lt;= value &lt;= 7 * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, boolean control, int stepcode) throws KNXException; /** * @deprecated Use {@link #write(GroupAddress, float, boolean)}. * @param dst group destination to write to * @param value float value to write * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, float value) throws KNXException; /** * Writes a float datapoint value to a group destination. * <p> * The supplied float value is written according to the specified float datapoint type. * * @param dst group destination to write to * @param value float value to write * @param use4ByteFloat specifies the float type of the datapoint; either writes a 2-byte KNX * float of DPT main number 9 (<code>false</code>), or a 4-byte float of DPT main number * 14 (<code>true</code>) * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, float value, boolean use4ByteFloat) throws KNXException; /** * Writes a string datapoint value to a group destination. * <p> * The supported character set covers at least ISO-8859-1 (Latin 1), with an allowed * string length of 14 characters. * * @param dst group destination to write to * @param value string value to write * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, String value) throws KNXException; /** * Writes the content of the supplied DPTXlator to a group destination. * * @param dst group destination to write to * @param value DPTXlator which's value to write * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException on other write problems */ void write(GroupAddress dst, DPTXlator value) throws KNXException; /** * Writes a datapoint value to a group destination. * <p> * The used KNX message priority is according the supplied datapoint priority. * * @param dp the datapoint for write * @param value datapoint value in textual representation according the datapoint its * type * @throws KNXTimeoutException on a timeout during send * @throws KNXFormatException on translation problem of the supplied datapoint value * @throws KNXLinkClosedException if network link to KNX network is closed * @throws KNXException if no appropriate DPT translator for the datapoint type is * available */ void write(Datapoint dp, String value) throws KNXException; /** * Detaches the network link from this process communicator. * <p> * If no network link is attached, no action is performed. * <p> * Note that a detach does not trigger a close of the used network link. * * @return the formerly attached KNX network link, or <code>null</code> if already * detached */ KNXNetworkLink detach(); }
gpl-2.0
hhxcode/okhttp
Anony_Okhttp_library/src/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java
96557
package com.fasterxml.jackson.core.json; import java.io.*; import java.util.Arrays; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserBase; import com.fasterxml.jackson.core.io.CharTypes; import com.fasterxml.jackson.core.io.IOContext; import com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; import com.fasterxml.jackson.core.util.*; import static com.fasterxml.jackson.core.JsonTokenId.*; /** * This is a concrete implementation of {@link JsonParser}, which is based on a {@link java.io.InputStream} as the input source. * <p> * Note: non-final since version 2.3. */ public class UTF8StreamJsonParser extends ParserBase { final static byte BYTE_LF = (byte) '\n'; // This is the main input-code lookup table, fetched eagerly private final static int[] _icUTF8 = CharTypes.getInputCodeUtf8(); // Latin1 encoding is not supported, but we do use 8-bit subset for // pre-processing task, to simplify first pass, keep it fast. protected final static int[] _icLatin1 = CharTypes.getInputCodeLatin1(); /* * /********************************************************** /* Configuration * /********************************************************** */ /** * Codec used for data binding when (if) requested; typically full <code>ObjectMapper</code>, but that abstract is not part of core * package. */ protected ObjectCodec _objectCodec; /** * Symbol table that contains field names encountered so far */ final protected ByteQuadsCanonicalizer _symbols; /* * /********************************************************** /* Parsing state * /********************************************************** */ /** * Temporary buffer used for name parsing. */ protected int[] _quadBuffer = new int[16]; /** * Flag that indicates that the current token has not yet been fully processed, and needs to be finished for some access (or skipped to * obtain the next token) */ protected boolean _tokenIncomplete = false; /** * Temporary storage for partially parsed name bytes. */ private int _quad1; /* * /********************************************************** /* Input buffering (from former 'StreamBasedParserBase') * /********************************************************** */ protected InputStream _inputStream; /* * /********************************************************** /* Current input data * /********************************************************** */ /** * Current buffer from which data is read; generally data is read into buffer from input source, but in some cases pre-loaded buffer is * handed to the parser. */ protected byte[] _inputBuffer; /** * Flag that indicates whether the input buffer is recycable (and needs to be returned to recycler once we are done) or not. * <p> * If it is not, it also means that parser can NOT modify underlying buffer. */ protected boolean _bufferRecyclable; /* * /********************************************************** /* Life-cycle /********************************************************** */ public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, ByteQuadsCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, features); _inputStream = in; _objectCodec = codec; _symbols = sym; _inputBuffer = inputBuffer; _inputPtr = start; _inputEnd = end; _currInputRowStart = start; // If we have offset, need to omit that from byte offset, so: _currInputProcessed = -start; _bufferRecyclable = bufferRecyclable; } @Override public ObjectCodec getCodec() { return _objectCodec; } @Override public void setCodec(ObjectCodec c) { _objectCodec = c; } /* * /********************************************************** /* Overrides for life-cycle * /********************************************************** */ @Override public int releaseBuffered(OutputStream out) throws IOException { int count = _inputEnd - _inputPtr; if (count < 1) { return 0; } // let's just advance ptr to end int origPtr = _inputPtr; out.write(_inputBuffer, origPtr, count); return count; } @Override public Object getInputSource() { return _inputStream; } /* * /********************************************************** /* Overrides, low-level reading * /********************************************************** */ @Override protected final boolean loadMore() throws IOException { _currInputProcessed += _inputEnd; _currInputRowStart -= _inputEnd; if (_inputStream != null) { int space = _inputBuffer.length; if (space == 0) { // only occurs when we've been closed return false; } int count = _inputStream.read(_inputBuffer, 0, space); if (count > 0) { _inputPtr = 0; _inputEnd = count; return true; } // End of input _closeInput(); // Should never return 0, so let's fail if (count == 0) { throw new IOException("InputStream.read() returned 0 characters when trying to read " + _inputBuffer.length + " bytes"); } } return false; } /** * Helper method that will try to load at least specified number bytes in input buffer, possible moving existing data around if necessary */ protected final boolean _loadToHaveAtLeast(int minAvailable) throws IOException { // No input stream, no leading (either we are closed, or have non-stream input source) if (_inputStream == null) { return false; } // Need to move remaining data in front? int amount = _inputEnd - _inputPtr; if (amount > 0 && _inputPtr > 0) { _currInputProcessed += _inputPtr; _currInputRowStart -= _inputPtr; System.arraycopy(_inputBuffer, _inputPtr, _inputBuffer, 0, amount); _inputEnd = amount; } else { _inputEnd = 0; } _inputPtr = 0; while (_inputEnd < minAvailable) { int count = _inputStream.read(_inputBuffer, _inputEnd, _inputBuffer.length - _inputEnd); if (count < 1) { // End of input _closeInput(); // Should never return 0, so let's fail if (count == 0) { throw new IOException("InputStream.read() returned 0 characters when trying to read " + amount + " bytes"); } return false; } _inputEnd += count; } return true; } @Override protected void _closeInput() throws IOException { /* * 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close() on the underlying InputStream, unless we "own" it, or * auto-closing feature is enabled. */ if (_inputStream != null) { if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_SOURCE)) { _inputStream.close(); } _inputStream = null; } } /** * Method called to release internal buffers owned by the base reader. This may be called along with {@link #_closeInput} (for example, * when explicitly closing this reader instance), or separately (if need be). */ @Override protected void _releaseBuffers() throws IOException { super._releaseBuffers(); // Merge found symbols, if any: _symbols.release(); if (_bufferRecyclable) { byte[] buf = _inputBuffer; if (buf != null) { /* * 21-Nov-2014, tatu: Let's not set it to null; this way should get slightly more meaningful error messages in case someone * closes parser indirectly, without realizing. */ _inputBuffer = ByteArrayBuilder.NO_BYTES; _ioContext.releaseReadIOBuffer(buf); } } } /* * /********************************************************** /* Public API, data access * /********************************************************** */ @Override public String getText() throws IOException { if (_currToken == JsonToken.VALUE_STRING) { if (_tokenIncomplete) { _tokenIncomplete = false; return _finishAndReturnString(); // only strings can be incomplete } return _textBuffer.contentsAsString(); } return _getText2(_currToken); } // // // Let's override default impls for improved performance // @since 2.1 @Override public String getValueAsString() throws IOException { if (_currToken == JsonToken.VALUE_STRING) { if (_tokenIncomplete) { _tokenIncomplete = false; return _finishAndReturnString(); // only strings can be incomplete } return _textBuffer.contentsAsString(); } if (_currToken == JsonToken.FIELD_NAME) { return getCurrentName(); } return super.getValueAsString(null); } // @since 2.1 @Override public String getValueAsString(String defValue) throws IOException { if (_currToken == JsonToken.VALUE_STRING) { if (_tokenIncomplete) { _tokenIncomplete = false; return _finishAndReturnString(); // only strings can be incomplete } return _textBuffer.contentsAsString(); } if (_currToken == JsonToken.FIELD_NAME) { return getCurrentName(); } return super.getValueAsString(defValue); } // since 2.6 @Override public int getValueAsInt() throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { // inlined 'getIntValue()' if ((_numTypesValid & NR_INT) == 0) { if (_numTypesValid == NR_UNKNOWN) { return _parseIntValue(); } if ((_numTypesValid & NR_INT) == 0) { convertNumberToInt(); } } return _numberInt; } return super.getValueAsInt(0); } // since 2.6 @Override public int getValueAsInt(int defValue) throws IOException { JsonToken t = _currToken; if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { // inlined 'getIntValue()' if ((_numTypesValid & NR_INT) == 0) { if (_numTypesValid == NR_UNKNOWN) { return _parseIntValue(); } if ((_numTypesValid & NR_INT) == 0) { convertNumberToInt(); } } return _numberInt; } return super.getValueAsInt(defValue); } protected final String _getText2(JsonToken t) { if (t == null) { return null; } switch (t.id()) { case ID_FIELD_NAME: return _parsingContext.getCurrentName(); case ID_STRING: // fall through case ID_NUMBER_INT: case ID_NUMBER_FLOAT: return _textBuffer.contentsAsString(); default: return t.asString(); } } @Override public char[] getTextCharacters() throws IOException { if (_currToken != null) { // null only before/after document switch (_currToken.id()) { case ID_FIELD_NAME: if (!_nameCopied) { String name = _parsingContext.getCurrentName(); int nameLen = name.length(); if (_nameCopyBuffer == null) { _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen); } else if (_nameCopyBuffer.length < nameLen) { _nameCopyBuffer = new char[nameLen]; } name.getChars(0, nameLen, _nameCopyBuffer, 0); _nameCopied = true; } return _nameCopyBuffer; case ID_STRING: if (_tokenIncomplete) { _tokenIncomplete = false; _finishString(); // only strings can be incomplete } // fall through case ID_NUMBER_INT: case ID_NUMBER_FLOAT: return _textBuffer.getTextBuffer(); default: return _currToken.asCharArray(); } } return null; } @Override public int getTextLength() throws IOException { if (_currToken != null) { // null only before/after document switch (_currToken.id()) { case ID_FIELD_NAME: return _parsingContext.getCurrentName().length(); case ID_STRING: if (_tokenIncomplete) { _tokenIncomplete = false; _finishString(); // only strings can be incomplete } // fall through case ID_NUMBER_INT: case ID_NUMBER_FLOAT: return _textBuffer.size(); default: return _currToken.asCharArray().length; } } return 0; } @Override public int getTextOffset() throws IOException { // Most have offset of 0, only some may have other values: if (_currToken != null) { switch (_currToken.id()) { case ID_FIELD_NAME: return 0; case ID_STRING: if (_tokenIncomplete) { _tokenIncomplete = false; _finishString(); // only strings can be incomplete } // fall through case ID_NUMBER_INT: case ID_NUMBER_FLOAT: return _textBuffer.getTextOffset(); default: } } return 0; } @Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException { if (_currToken != JsonToken.VALUE_STRING && (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT || _binaryValue == null)) { _reportError("Current token (" + _currToken + ") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary"); } /* * To ensure that we won't see inconsistent data, better clear up state... */ if (_tokenIncomplete) { try { _binaryValue = _decodeBase64(b64variant); } catch (IllegalArgumentException iae) { throw _constructError("Failed to decode VALUE_STRING as base64 (" + b64variant + "): " + iae.getMessage()); } /* * let's clear incomplete only now; allows for accessing other textual content in error cases */ _tokenIncomplete = false; } else { // may actually require conversion... if (_binaryValue == null) { ByteArrayBuilder builder = _getByteArrayBuilder(); _decodeBase64(getText(), builder, b64variant); _binaryValue = builder.toByteArray(); } } return _binaryValue; } @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException { // if we have already read the token, just use whatever we may have if (!_tokenIncomplete || _currToken != JsonToken.VALUE_STRING) { byte[] b = getBinaryValue(b64variant); out.write(b); return b.length; } // otherwise do "real" incremental parsing... byte[] buf = _ioContext.allocBase64Buffer(); try { return _readBinary(b64variant, out, buf); } finally { _ioContext.releaseBase64Buffer(buf); } } protected int _readBinary(Base64Variant b64variant, OutputStream out, byte[] buffer) throws IOException { int outputPtr = 0; final int outputEnd = buffer.length - 3; int outputCount = 0; while (true) { // first, we'll skip preceding white space, if any int ch; do { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = (int) _inputBuffer[_inputPtr++] & 0xFF; } while (ch <= INT_SPACE); int bits = b64variant.decodeBase64Char(ch); if (bits < 0) { // reached the end, fair and square? if (ch == INT_QUOTE) { break; } bits = _decodeBase64Escape(b64variant, ch, 0); if (bits < 0) { // white space to skip continue; } } // enough room? If not, flush if (outputPtr > outputEnd) { outputCount += outputPtr; out.write(buffer, 0, outputPtr); outputPtr = 0; } int decodedData = bits; // then second base64 char; can't get padding yet, nor ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); if (bits < 0) { bits = _decodeBase64Escape(b64variant, ch, 1); } decodedData = (decodedData << 6) | bits; // third base64 char; can be padding, but not ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); // First branch: can get padding (-> 1 byte) if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { // as per [JACKSON-631], could also just be 'missing' padding if (ch == '"' && !b64variant.usesPadding()) { decodedData >>= 4; buffer[outputPtr++] = (byte) decodedData; break; } bits = _decodeBase64Escape(b64variant, ch, 2); } if (bits == Base64Variant.BASE64_VALUE_PADDING) { // Ok, must get padding if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; if (!b64variant.usesPaddingChar(ch)) { throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '" + b64variant.getPaddingChar() + "'"); } // Got 12 bits, only need 8, need to shift decodedData >>= 4; buffer[outputPtr++] = (byte) decodedData; continue; } } // Nope, 2 or 3 bytes decodedData = (decodedData << 6) | bits; // fourth and last base64 char; can be padding, but not ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { // as per [JACKSON-631], could also just be 'missing' padding if (ch == '"' && !b64variant.usesPadding()) { decodedData >>= 2; buffer[outputPtr++] = (byte) (decodedData >> 8); buffer[outputPtr++] = (byte) decodedData; break; } bits = _decodeBase64Escape(b64variant, ch, 3); } if (bits == Base64Variant.BASE64_VALUE_PADDING) { /* * With padding we only get 2 bytes; but we have to shift it a bit so it is identical to triplet case with partial output. * 3 chars gives 3x6 == 18 bits, of which 2 are dummies, need to discard: */ decodedData >>= 2; buffer[outputPtr++] = (byte) (decodedData >> 8); buffer[outputPtr++] = (byte) decodedData; continue; } } // otherwise, our triplet is now complete decodedData = (decodedData << 6) | bits; buffer[outputPtr++] = (byte) (decodedData >> 16); buffer[outputPtr++] = (byte) (decodedData >> 8); buffer[outputPtr++] = (byte) decodedData; } _tokenIncomplete = false; if (outputPtr > 0) { outputCount += outputPtr; out.write(buffer, 0, outputPtr); } return outputCount; } // As per [Issue#108], must ensure we call the right method @Override public JsonLocation getTokenLocation() { return new JsonLocation(_ioContext.getSourceReference(), getTokenCharacterOffset(), -1L, // bytes, chars getTokenLineNr(), getTokenColumnNr()); } // As per [Issue#108], must ensure we call the right method @Override public JsonLocation getCurrentLocation() { int col = _inputPtr - _currInputRowStart + 1; // 1-based return new JsonLocation(_ioContext.getSourceReference(), _currInputProcessed + _inputPtr, -1L, // bytes, chars _currInputRow, col); } /* * /********************************************************** /* Public API, traversal, basic * /********************************************************** */ /** * @return Next token from the stream, if any found, or null to indicate end-of-input */ @Override public JsonToken nextToken() throws IOException { /* * First: field names are special -- we will always tokenize (part of) value along with field name to simplify state handling. If so, * can and need to use secondary token: */ if (_currToken == JsonToken.FIELD_NAME) { return _nextAfterName(); } // But if we didn't already have a name, and (partially?) decode number, // need to ensure no numeric information is leaked _numTypesValid = NR_UNKNOWN; if (_tokenIncomplete) { _skipString(); // only strings can be partial } int i = _skipWSOrEnd(); if (i < 0) { // end-of-input // Close/release things like input source, symbol table and recyclable buffers close(); return (_currToken = null); } // First, need to ensure we know the starting location of token // after skipping leading white space _tokenInputTotal = _currInputProcessed + _inputPtr - 1; _tokenInputRow = _currInputRow; _tokenInputCol = _inputPtr - _currInputRowStart - 1; // finally: clear any data retained so far _binaryValue = null; // Closing scope? if (i == INT_RBRACKET) { if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(i, '}'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_ARRAY); } if (i == INT_RCURLY) { if (!_parsingContext.inObject()) { _reportMismatchedEndMarker(i, ']'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_OBJECT); } // Nope: do we then expect a comma? if (_parsingContext.expectComma()) { if (i != INT_COMMA) { _reportUnexpectedChar(i, "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries"); } i = _skipWS(); } /* * And should we now have a name? Always true for Object contexts, since the intermediate 'expect-value' state is never retained. */ if (!_parsingContext.inObject()) { return _nextTokenNotInObject(i); } // So first parse the field name itself: String n = _parseName(i); _parsingContext.setCurrentName(n); _currToken = JsonToken.FIELD_NAME; i = _skipColon(); // Ok: we must have a value... what is it? Strings are very common, check first: if (i == INT_QUOTE) { _tokenIncomplete = true; _nextToken = JsonToken.VALUE_STRING; return _currToken; } JsonToken t; switch (i) { case '-': t = _parseNegNumber(); break; /* * Should we have separate handling for plus? Although it is not allowed per se, it may be erroneously used, and could be indicate by * a more specific error message. */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': t = _parsePosNumber(i); break; case 'f': _matchToken("false", 1); t = JsonToken.VALUE_FALSE; break; case 'n': _matchToken("null", 1); t = JsonToken.VALUE_NULL; break; case 't': _matchToken("true", 1); t = JsonToken.VALUE_TRUE; break; case '[': t = JsonToken.START_ARRAY; break; case '{': t = JsonToken.START_OBJECT; break; default: t = _handleUnexpectedValue(i); } _nextToken = t; return _currToken; } private final JsonToken _nextTokenNotInObject(int i) throws IOException { if (i == INT_QUOTE) { _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_STRING); } switch (i) { case '[': _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); return (_currToken = JsonToken.START_ARRAY); case '{': _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); return (_currToken = JsonToken.START_OBJECT); case 't': _matchToken("true", 1); return (_currToken = JsonToken.VALUE_TRUE); case 'f': _matchToken("false", 1); return (_currToken = JsonToken.VALUE_FALSE); case 'n': _matchToken("null", 1); return (_currToken = JsonToken.VALUE_NULL); case '-': return (_currToken = _parseNegNumber()); /* * Should we have separate handling for plus? Although it is not allowed per se, it may be erroneously used, and could be * indicated by a more specific error message. */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return (_currToken = _parsePosNumber(i)); } return (_currToken = _handleUnexpectedValue(i)); } private final JsonToken _nextAfterName() { _nameCopied = false; // need to invalidate if it was copied JsonToken t = _nextToken; _nextToken = null; // Also: may need to start new context? if (t == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); } else if (t == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); } return (_currToken = t); } /* * /********************************************************** /* Public API, traversal, nextXxxValue/nextFieldName * /********************************************************** */ @Override public boolean nextFieldName(SerializableString str) throws IOException { // // // Note: most of code below is copied from nextToken() _numTypesValid = NR_UNKNOWN; if (_currToken == JsonToken.FIELD_NAME) { // can't have name right after name _nextAfterName(); return false; } if (_tokenIncomplete) { _skipString(); } int i = _skipWSOrEnd(); if (i < 0) { // end-of-input close(); _currToken = null; return false; } _tokenInputTotal = _currInputProcessed + _inputPtr - 1; _tokenInputRow = _currInputRow; _tokenInputCol = _inputPtr - _currInputRowStart - 1; // finally: clear any data retained so far _binaryValue = null; // Closing scope? if (i == INT_RBRACKET) { if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(i, '}'); } _parsingContext = _parsingContext.getParent(); _currToken = JsonToken.END_ARRAY; return false; } if (i == INT_RCURLY) { if (!_parsingContext.inObject()) { _reportMismatchedEndMarker(i, ']'); } _parsingContext = _parsingContext.getParent(); _currToken = JsonToken.END_OBJECT; return false; } // Nope: do we then expect a comma? if (_parsingContext.expectComma()) { if (i != INT_COMMA) { _reportUnexpectedChar(i, "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries"); } i = _skipWS(); } if (!_parsingContext.inObject()) { _nextTokenNotInObject(i); return false; } // // // This part differs, name parsing if (i == INT_QUOTE) { // when doing literal match, must consider escaping: byte[] nameBytes = str.asQuotedUTF8(); final int len = nameBytes.length; // 22-May-2014, tatu: Actually, let's require 4 more bytes for faster skipping // of colon that follows name if ((_inputPtr + len + 4) < _inputEnd) { // maybe... // first check length match by final int end = _inputPtr + len; if (_inputBuffer[end] == INT_QUOTE) { int offset = 0; int ptr = _inputPtr; while (true) { if (ptr == end) { // yes, match! _parsingContext.setCurrentName(str.getValue()); i = _skipColonFast(ptr + 1); _isNextTokenNameYes(i); return true; } if (nameBytes[offset] != _inputBuffer[ptr]) { break; } ++offset; ++ptr; } } } } return _isNextTokenNameMaybe(i, str); } @Override public String nextFieldName() throws IOException { // // // Note: this is almost a verbatim copy of nextToken() _numTypesValid = NR_UNKNOWN; if (_currToken == JsonToken.FIELD_NAME) { _nextAfterName(); return null; } if (_tokenIncomplete) { _skipString(); } int i = _skipWSOrEnd(); if (i < 0) { close(); _currToken = null; return null; } _tokenInputTotal = _currInputProcessed + _inputPtr - 1; _tokenInputRow = _currInputRow; _tokenInputCol = _inputPtr - _currInputRowStart - 1; _binaryValue = null; if (i == INT_RBRACKET) { if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(i, '}'); } _parsingContext = _parsingContext.getParent(); _currToken = JsonToken.END_ARRAY; return null; } if (i == INT_RCURLY) { if (!_parsingContext.inObject()) { _reportMismatchedEndMarker(i, ']'); } _parsingContext = _parsingContext.getParent(); _currToken = JsonToken.END_OBJECT; return null; } // Nope: do we then expect a comma? if (_parsingContext.expectComma()) { if (i != INT_COMMA) { _reportUnexpectedChar(i, "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries"); } i = _skipWS(); } if (!_parsingContext.inObject()) { _nextTokenNotInObject(i); return null; } final String nameStr = _parseName(i); _parsingContext.setCurrentName(nameStr); _currToken = JsonToken.FIELD_NAME; i = _skipColon(); if (i == INT_QUOTE) { _tokenIncomplete = true; _nextToken = JsonToken.VALUE_STRING; return nameStr; } JsonToken t; switch (i) { case '-': t = _parseNegNumber(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': t = _parsePosNumber(i); break; case 'f': _matchToken("false", 1); t = JsonToken.VALUE_FALSE; break; case 'n': _matchToken("null", 1); t = JsonToken.VALUE_NULL; break; case 't': _matchToken("true", 1); t = JsonToken.VALUE_TRUE; break; case '[': t = JsonToken.START_ARRAY; break; case '{': t = JsonToken.START_OBJECT; break; default: t = _handleUnexpectedValue(i); } _nextToken = t; return nameStr; } // Variant called when we know there's at least 4 more bytes available private final int _skipColonFast(int ptr) throws IOException { int i = _inputBuffer[ptr++]; if (i == INT_COLON) { // common case, no leading space i = _inputBuffer[ptr++]; if (i > INT_SPACE) { // nor trailing if (i != INT_SLASH && i != INT_HASH) { _inputPtr = ptr; return i; } } else if (i == INT_SPACE || i == INT_TAB) { i = (int) _inputBuffer[ptr++]; if (i > INT_SPACE) { if (i != INT_SLASH && i != INT_HASH) { _inputPtr = ptr; return i; } } } _inputPtr = ptr - 1; return _skipColon2(true); // true -> skipped colon } if (i == INT_SPACE || i == INT_TAB) { i = _inputBuffer[ptr++]; } if (i == INT_COLON) { i = _inputBuffer[ptr++]; if (i > INT_SPACE) { if (i != INT_SLASH && i != INT_HASH) { _inputPtr = ptr; return i; } } else if (i == INT_SPACE || i == INT_TAB) { i = (int) _inputBuffer[ptr++]; if (i > INT_SPACE) { if (i != INT_SLASH && i != INT_HASH) { _inputPtr = ptr; return i; } } } _inputPtr = ptr - 1; return _skipColon2(true); } _inputPtr = ptr - 1; return _skipColon2(false); } private final void _isNextTokenNameYes(int i) throws IOException { _currToken = JsonToken.FIELD_NAME; switch (i) { case '"': _tokenIncomplete = true; _nextToken = JsonToken.VALUE_STRING; return; case '[': _nextToken = JsonToken.START_ARRAY; return; case '{': _nextToken = JsonToken.START_OBJECT; return; case 't': _matchToken("true", 1); _nextToken = JsonToken.VALUE_TRUE; return; case 'f': _matchToken("false", 1); _nextToken = JsonToken.VALUE_FALSE; return; case 'n': _matchToken("null", 1); _nextToken = JsonToken.VALUE_NULL; return; case '-': _nextToken = _parseNegNumber(); return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': _nextToken = _parsePosNumber(i); return; } _nextToken = _handleUnexpectedValue(i); } private final boolean _isNextTokenNameMaybe(int i, SerializableString str) throws IOException { // // // and this is back to standard nextToken() String n = _parseName(i); _parsingContext.setCurrentName(n); final boolean match = n.equals(str.getValue()); _currToken = JsonToken.FIELD_NAME; i = _skipColon(); // Ok: we must have a value... what is it? Strings are very common, check first: if (i == INT_QUOTE) { _tokenIncomplete = true; _nextToken = JsonToken.VALUE_STRING; return match; } JsonToken t; switch (i) { case '[': t = JsonToken.START_ARRAY; break; case '{': t = JsonToken.START_OBJECT; break; case 't': _matchToken("true", 1); t = JsonToken.VALUE_TRUE; break; case 'f': _matchToken("false", 1); t = JsonToken.VALUE_FALSE; break; case 'n': _matchToken("null", 1); t = JsonToken.VALUE_NULL; break; case '-': t = _parseNegNumber(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': t = _parsePosNumber(i); break; default: t = _handleUnexpectedValue(i); } _nextToken = t; return match; } @Override public String nextTextValue() throws IOException { // two distinct cases; either got name and we know next type, or 'other' if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' _nameCopied = false; JsonToken t = _nextToken; _nextToken = null; _currToken = t; if (t == JsonToken.VALUE_STRING) { if (_tokenIncomplete) { _tokenIncomplete = false; return _finishAndReturnString(); } return _textBuffer.contentsAsString(); } if (t == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); } else if (t == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); } return null; } // !!! TODO: optimize this case as well return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; } @Override public int nextIntValue(int defaultValue) throws IOException { // two distinct cases; either got name and we know next type, or 'other' if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' _nameCopied = false; JsonToken t = _nextToken; _nextToken = null; _currToken = t; if (t == JsonToken.VALUE_NUMBER_INT) { return getIntValue(); } if (t == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); } else if (t == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); } return defaultValue; } // !!! TODO: optimize this case as well return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue; } @Override public long nextLongValue(long defaultValue) throws IOException { // two distinct cases; either got name and we know next type, or 'other' if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' _nameCopied = false; JsonToken t = _nextToken; _nextToken = null; _currToken = t; if (t == JsonToken.VALUE_NUMBER_INT) { return getLongValue(); } if (t == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); } else if (t == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); } return defaultValue; } // !!! TODO: optimize this case as well return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue; } @Override public Boolean nextBooleanValue() throws IOException { // two distinct cases; either got name and we know next type, or 'other' if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' _nameCopied = false; JsonToken t = _nextToken; _nextToken = null; _currToken = t; if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; } if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; } if (t == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); } else if (t == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); } return null; } JsonToken t = nextToken(); if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; } if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; } return null; } /* * /********************************************************** /* Internal methods, number parsing * /********************************************************** */ /** * Initial parsing method for number values. It needs to be able to parse enough input to be able to determine whether the value is to be * considered a simple integer value, or a more generic decimal value: latter of which needs to be expressed as a floating point number. * The basic rule is that if the number has no fractional or exponential part, it is an integer; otherwise a floating point number. * <p> * Because much of input has to be processed in any case, no partial parsing is done: all input text will be stored for further * processing. However, actual numeric value conversion will be deferred, since it is usually the most complicated and costliest part of * processing. */ protected JsonToken _parsePosNumber(int c) throws IOException { char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); // One special case: if first char is 0, must not be followed by a digit if (c == INT_0) { c = _verifyNoLeadingZeroes(); } // Ok: we can first just add digit we saw first: outBuf[0] = (char) c; int intLen = 1; int outPtr = 1; // And then figure out how far we can read without further checks // for either input or output int end = _inputPtr + outBuf.length - 1; // 1 == outPtr if (end > _inputEnd) { end = _inputEnd; } // With this, we have a nice and tight loop: while (true) { if (_inputPtr >= end) { // split across boundary, offline return _parseNumber2(outBuf, outPtr, false, intLen); } c = (int) _inputBuffer[_inputPtr++] & 0xFF; if (c < INT_0 || c > INT_9) { break; } ++intLen; outBuf[outPtr++] = (char) c; } if (c == '.' || c == 'e' || c == 'E') { return _parseFloat(outBuf, outPtr, c, false, intLen); } --_inputPtr; // to push back trailing char (comma etc) _textBuffer.setCurrentLength(outPtr); // As per #105, need separating space between root values; check here if (_parsingContext.inRoot()) { _verifyRootSpace(c); } // And there we have it! return resetInt(false, intLen); } protected JsonToken _parseNegNumber() throws IOException { char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); int outPtr = 0; // Need to prepend sign? outBuf[outPtr++] = '-'; // Must have something after sign too if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int c = (int) _inputBuffer[_inputPtr++] & 0xFF; // Note: must be followed by a digit if (c < INT_0 || c > INT_9) { return _handleInvalidNumberStart(c, true); } // One special case: if first char is 0, must not be followed by a digit if (c == INT_0) { c = _verifyNoLeadingZeroes(); } // Ok: we can first just add digit we saw first: outBuf[outPtr++] = (char) c; int intLen = 1; // And then figure out how far we can read without further checks // for either input or output int end = _inputPtr + outBuf.length - outPtr; if (end > _inputEnd) { end = _inputEnd; } // With this, we have a nice and tight loop: while (true) { if (_inputPtr >= end) { // Long enough to be split across boundary, so: return _parseNumber2(outBuf, outPtr, true, intLen); } c = (int) _inputBuffer[_inputPtr++] & 0xFF; if (c < INT_0 || c > INT_9) { break; } ++intLen; outBuf[outPtr++] = (char) c; } if (c == '.' || c == 'e' || c == 'E') { return _parseFloat(outBuf, outPtr, c, true, intLen); } --_inputPtr; // to push back trailing char (comma etc) _textBuffer.setCurrentLength(outPtr); // As per #105, need separating space between root values; check here if (_parsingContext.inRoot()) { _verifyRootSpace(c); } // And there we have it! return resetInt(true, intLen); } /** * Method called to handle parsing when input is split across buffer boundary (or output is longer than segment used to store it) */ private final JsonToken _parseNumber2(char[] outBuf, int outPtr, boolean negative, int intPartLength) throws IOException { // Ok, parse the rest while (true) { if (_inputPtr >= _inputEnd && !loadMore()) { _textBuffer.setCurrentLength(outPtr); return resetInt(negative, intPartLength); } int c = (int) _inputBuffer[_inputPtr++] & 0xFF; if (c > INT_9 || c < INT_0) { if (c == INT_PERIOD || c == INT_e || c == INT_E) { return _parseFloat(outBuf, outPtr, c, negative, intPartLength); } break; } if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } outBuf[outPtr++] = (char) c; ++intPartLength; } --_inputPtr; // to push back trailing char (comma etc) _textBuffer.setCurrentLength(outPtr); // As per #105, need separating space between root values; check here if (_parsingContext.inRoot()) { _verifyRootSpace(_inputBuffer[_inputPtr++] & 0xFF); } // And there we have it! return resetInt(negative, intPartLength); } /** * Method called when we have seen one zero, and want to ensure it is not followed by another */ private final int _verifyNoLeadingZeroes() throws IOException { // Ok to have plain "0" if (_inputPtr >= _inputEnd && !loadMore()) { return INT_0; } int ch = _inputBuffer[_inputPtr] & 0xFF; // if not followed by a number (probably '.'); return zero as is, to be included if (ch < INT_0 || ch > INT_9) { return INT_0; } // [JACKSON-358]: we may want to allow them, after all... if (!isEnabled(Feature.ALLOW_NUMERIC_LEADING_ZEROS)) { reportInvalidNumber("Leading zeroes not allowed"); } // if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number) ++_inputPtr; // Leading zero to be skipped if (ch == INT_0) { while (_inputPtr < _inputEnd || loadMore()) { ch = _inputBuffer[_inputPtr] & 0xFF; if (ch < INT_0 || ch > INT_9) { // followed by non-number; retain one zero return INT_0; } ++_inputPtr; // skip previous zeroes if (ch != INT_0) { // followed by other number; return break; } } } return ch; } private final JsonToken _parseFloat(char[] outBuf, int outPtr, int c, boolean negative, int integerPartLength) throws IOException { int fractLen = 0; boolean eof = false; // And then see if we get other parts if (c == INT_PERIOD) { // yes, fraction outBuf[outPtr++] = (char) c; fract_loop: while (true) { if (_inputPtr >= _inputEnd && !loadMore()) { eof = true; break fract_loop; } c = (int) _inputBuffer[_inputPtr++] & 0xFF; if (c < INT_0 || c > INT_9) { break fract_loop; } ++fractLen; if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } outBuf[outPtr++] = (char) c; } // must be followed by sequence of ints, one minimum if (fractLen == 0) { reportUnexpectedNumberChar(c, "Decimal point not followed by a digit"); } } int expLen = 0; if (c == INT_e || c == INT_E) { // exponent? if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } outBuf[outPtr++] = (char) c; // Not optional, can require that we get one more char if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c = (int) _inputBuffer[_inputPtr++] & 0xFF; // Sign indicator? if (c == '-' || c == '+') { if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } outBuf[outPtr++] = (char) c; // Likewise, non optional: if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c = (int) _inputBuffer[_inputPtr++] & 0xFF; } exp_loop: while (c <= INT_9 && c >= INT_0) { ++expLen; if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } outBuf[outPtr++] = (char) c; if (_inputPtr >= _inputEnd && !loadMore()) { eof = true; break exp_loop; } c = (int) _inputBuffer[_inputPtr++] & 0xFF; } // must be followed by sequence of ints, one minimum if (expLen == 0) { reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit"); } } // Ok; unless we hit end-of-input, need to push last char read back if (!eof) { --_inputPtr; // As per #105, need separating space between root values; check here if (_parsingContext.inRoot()) { _verifyRootSpace(c); } } _textBuffer.setCurrentLength(outPtr); // And there we have it! return resetFloat(negative, integerPartLength, fractLen, expLen); } /** * Method called to ensure that a root-value is followed by a space token. * <p> * NOTE: caller MUST ensure there is at least one character available; and that input pointer is AT given char (not past) */ private final void _verifyRootSpace(int ch) throws IOException { // caller had pushed it back, before calling; reset ++_inputPtr; // TODO? Handle UTF-8 char decoding for error reporting switch (ch) { case ' ': case '\t': return; case '\r': _skipCR(); return; case '\n': ++_currInputRow; _currInputRowStart = _inputPtr; return; } _reportMissingRootWS(ch); } /* * /********************************************************** /* Internal methods, secondary parsing * /********************************************************** */ protected final String _parseName(int i) throws IOException { if (i != INT_QUOTE) { return _handleOddName(i); } // First: can we optimize out bounds checks? if ((_inputPtr + 13) > _inputEnd) { // Need up to 12 chars, plus one trailing (quote) return slowParseName(); } // If so, can also unroll loops nicely /* * 25-Nov-2008, tatu: This may seem weird, but here we do NOT want to worry about UTF-8 decoding. Rather, we'll assume that part is ok * (if not it will get caught later on), and just handle quotes and backslashes here. */ final byte[] input = _inputBuffer; final int[] codes = _icLatin1; int q = input[_inputPtr++] & 0xFF; if (codes[q] == 0) { i = input[_inputPtr++] & 0xFF; if (codes[i] == 0) { q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] == 0) { q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] == 0) { q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] == 0) { _quad1 = q; return parseMediumName(i); } if (i == INT_QUOTE) { // 4 byte/char case or broken return findName(q, 4); } return parseName(q, i, 4); } if (i == INT_QUOTE) { // 3 byte/char case or broken return findName(q, 3); } return parseName(q, i, 3); } if (i == INT_QUOTE) { // 2 byte/char case or broken return findName(q, 2); } return parseName(q, i, 2); } if (i == INT_QUOTE) { // one byte/char case or broken return findName(q, 1); } return parseName(q, i, 1); } if (q == INT_QUOTE) { // special case, "" return ""; } return parseName(0, q, 0); // quoting or invalid char } protected final String parseMediumName(int q2) throws IOException { final byte[] input = _inputBuffer; final int[] codes = _icLatin1; // Ok, got 5 name bytes so far int i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 5 bytes return findName(_quad1, q2, 1); } return parseName(_quad1, q2, i, 1); // quoting or invalid char } q2 = (q2 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 6 bytes return findName(_quad1, q2, 2); } return parseName(_quad1, q2, i, 2); } q2 = (q2 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 7 bytes return findName(_quad1, q2, 3); } return parseName(_quad1, q2, i, 3); } q2 = (q2 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 8 bytes return findName(_quad1, q2, 4); } return parseName(_quad1, q2, i, 4); } return parseMediumName2(i, q2); } /** * @since 2.6 */ protected final String parseMediumName2(int q3, final int q2) throws IOException { final byte[] input = _inputBuffer; final int[] codes = _icLatin1; // Got 9 name bytes so far int i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 9 bytes return findName(_quad1, q2, q3, 1); } return parseName(_quad1, q2, q3, i, 1); } q3 = (q3 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 10 bytes return findName(_quad1, q2, q3, 2); } return parseName(_quad1, q2, q3, i, 2); } q3 = (q3 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 11 bytes return findName(_quad1, q2, q3, 3); } return parseName(_quad1, q2, q3, i, 3); } q3 = (q3 << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { // 12 bytes return findName(_quad1, q2, q3, 4); } return parseName(_quad1, q2, q3, i, 4); } return parseLongName(i, q2, q3); } protected final String parseLongName(int q, final int q2, int q3) throws IOException { _quadBuffer[0] = _quad1; _quadBuffer[1] = q2; _quadBuffer[2] = q3; // As explained above, will ignore UTF-8 encoding at this point final byte[] input = _inputBuffer; final int[] codes = _icLatin1; int qlen = 3; while ((_inputPtr + 4) <= _inputEnd) { int i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { return findName(_quadBuffer, qlen, q, 1); } return parseEscapedName(_quadBuffer, qlen, q, i, 1); } q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { return findName(_quadBuffer, qlen, q, 2); } return parseEscapedName(_quadBuffer, qlen, q, i, 2); } q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { return findName(_quadBuffer, qlen, q, 3); } return parseEscapedName(_quadBuffer, qlen, q, i, 3); } q = (q << 8) | i; i = input[_inputPtr++] & 0xFF; if (codes[i] != 0) { if (i == INT_QUOTE) { return findName(_quadBuffer, qlen, q, 4); } return parseEscapedName(_quadBuffer, qlen, q, i, 4); } // Nope, no end in sight. Need to grow quad array etc if (qlen >= _quadBuffer.length) { _quadBuffer = growArrayBy(_quadBuffer, qlen); } _quadBuffer[qlen++] = q; q = i; } /* * Let's offline if we hit buffer boundary (otherwise would need to [try to] align input, which is bit complicated and may not always * be possible) */ return parseEscapedName(_quadBuffer, qlen, 0, q, 0); } /** * Method called when not even first 8 bytes are guaranteed to come consequtively. Happens rarely, so this is offlined; plus we'll also do * full checks for escaping etc. */ protected String slowParseName() throws IOException { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(": was expecting closing '\"' for name"); } } int i = _inputBuffer[_inputPtr++] & 0xFF; if (i == INT_QUOTE) { // special case, "" return ""; } return parseEscapedName(_quadBuffer, 0, 0, i, 0); } private final String parseName(int q1, int ch, int lastQuadBytes) throws IOException { return parseEscapedName(_quadBuffer, 0, q1, ch, lastQuadBytes); } private final String parseName(int q1, int q2, int ch, int lastQuadBytes) throws IOException { _quadBuffer[0] = q1; return parseEscapedName(_quadBuffer, 1, q2, ch, lastQuadBytes); } private final String parseName(int q1, int q2, int q3, int ch, int lastQuadBytes) throws IOException { _quadBuffer[0] = q1; _quadBuffer[1] = q2; return parseEscapedName(_quadBuffer, 2, q3, ch, lastQuadBytes); } /** * Slower parsing method which is generally branched to when an escape sequence is detected (or alternatively for long names, one crossing * input buffer boundary). Needs to be able to handle more exceptional cases, gets slower, and hance is offlined to a separate method. */ protected final String parseEscapedName(int[] quads, int qlen, int currQuad, int ch, int currQuadBytes) throws IOException { /* * 25-Nov-2008, tatu: This may seem weird, but here we do not want to worry about UTF-8 decoding yet. Rather, we'll assume that part * is ok (if not it will get caught later on), and just handle quotes and backslashes here. */ final int[] codes = _icLatin1; while (true) { if (codes[ch] != 0) { if (ch == INT_QUOTE) { // we are done break; } // Unquoted white space? if (ch != INT_BACKSLASH) { // As per [JACKSON-208], call can now return: _throwUnquotedSpace(ch, "name"); } else { // Nope, escape sequence ch = _decodeEscaped(); } /* * Oh crap. May need to UTF-8 (re-)encode it, if it's beyond 7-bit ascii. Gets pretty messy. If this happens often, may want * to use different name canonicalization to avoid these hits. */ if (ch > 127) { // Ok, we'll need room for first byte right away if (currQuadBytes >= 4) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = 0; currQuadBytes = 0; } if (ch < 0x800) { // 2-byte currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); ++currQuadBytes; // Second byte gets output below: } else { // 3 bytes; no need to worry about surrogates here currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); ++currQuadBytes; // need room for middle byte? if (currQuadBytes >= 4) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = 0; currQuadBytes = 0; } currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); ++currQuadBytes; } // And same last byte in both cases, gets output below: ch = 0x80 | (ch & 0x3f); } } // Ok, we have one more byte to add at any rate: if (currQuadBytes < 4) { ++currQuadBytes; currQuad = (currQuad << 8) | ch; } else { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = ch; currQuadBytes = 1; } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(" in field name"); } } ch = _inputBuffer[_inputPtr++] & 0xFF; } if (currQuadBytes > 0) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = pad(currQuad, currQuadBytes); } String name = _symbols.findName(quads, qlen); if (name == null) { name = addName(quads, qlen, currQuadBytes); } return name; } /** * Method called when we see non-white space character other than double quote, when expecting a field name. In standard mode will just * throw an expection; but in non-standard modes may be able to parse name. */ protected String _handleOddName(int ch) throws IOException { // [JACKSON-173]: allow single quotes if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { return _parseAposName(); } // [JACKSON-69]: allow unquoted names if feature enabled: if (!isEnabled(Feature.ALLOW_UNQUOTED_FIELD_NAMES)) { char c = (char) _decodeCharForError(ch); _reportUnexpectedChar(c, "was expecting double-quote to start field name"); } /* * Also: note that although we use a different table here, it does NOT handle UTF-8 decoding. It'll just pass those high-bit codes as * acceptable for later decoding. */ final int[] codes = CharTypes.getInputCodeUtf8JsNames(); // Also: must start with a valid character... if (codes[ch] != 0) { _reportUnexpectedChar(ch, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name"); } /* * Ok, now; instead of ultra-optimizing parsing here (as with regular JSON names), let's just use the generic "slow" variant. Can * measure its impact later on if need be */ int[] quads = _quadBuffer; int qlen = 0; int currQuad = 0; int currQuadBytes = 0; while (true) { // Ok, we have one more byte to add at any rate: if (currQuadBytes < 4) { ++currQuadBytes; currQuad = (currQuad << 8) | ch; } else { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = ch; currQuadBytes = 1; } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(" in field name"); } } ch = _inputBuffer[_inputPtr] & 0xFF; if (codes[ch] != 0) { break; } ++_inputPtr; } if (currQuadBytes > 0) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; } String name = _symbols.findName(quads, qlen); if (name == null) { name = addName(quads, qlen, currQuadBytes); } return name; } /* * Parsing to support [JACKSON-173]. Plenty of duplicated code; main reason being to try to avoid slowing down fast path for valid JSON -- * more alternatives, more code, generally bit slower execution. */ protected String _parseAposName() throws IOException { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(": was expecting closing '\'' for name"); } } int ch = _inputBuffer[_inputPtr++] & 0xFF; if (ch == '\'') { // special case, '' return ""; } int[] quads = _quadBuffer; int qlen = 0; int currQuad = 0; int currQuadBytes = 0; // Copied from parseEscapedFieldName, with minor mods: final int[] codes = _icLatin1; while (true) { if (ch == '\'') { break; } // additional check to skip handling of double-quotes if (ch != '"' && codes[ch] != 0) { if (ch != '\\') { // Unquoted white space? // As per [JACKSON-208], call can now return: _throwUnquotedSpace(ch, "name"); } else { // Nope, escape sequence ch = _decodeEscaped(); } /* * Oh crap. May need to UTF-8 (re-)encode it, if it's beyond 7-bit ascii. Gets pretty messy. If this happens often, may want * to use different name canonicalization to avoid these hits. */ if (ch > 127) { // Ok, we'll need room for first byte right away if (currQuadBytes >= 4) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = 0; currQuadBytes = 0; } if (ch < 0x800) { // 2-byte currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); ++currQuadBytes; // Second byte gets output below: } else { // 3 bytes; no need to worry about surrogates here currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); ++currQuadBytes; // need room for middle byte? if (currQuadBytes >= 4) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = 0; currQuadBytes = 0; } currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); ++currQuadBytes; } // And same last byte in both cases, gets output below: ch = 0x80 | (ch & 0x3f); } } // Ok, we have one more byte to add at any rate: if (currQuadBytes < 4) { ++currQuadBytes; currQuad = (currQuad << 8) | ch; } else { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = currQuad; currQuad = ch; currQuadBytes = 1; } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(" in field name"); } } ch = _inputBuffer[_inputPtr++] & 0xFF; } if (currQuadBytes > 0) { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = pad(currQuad, currQuadBytes); } String name = _symbols.findName(quads, qlen); if (name == null) { name = addName(quads, qlen, currQuadBytes); } return name; } /* * /********************************************************** /* Internal methods, symbol (name) handling * /********************************************************** */ private final String findName(int q1, int lastQuadBytes) throws JsonParseException { q1 = pad(q1, lastQuadBytes); // Usually we'll find it from the canonical symbol table already String name = _symbols.findName(q1); if (name != null) { return name; } // If not, more work. We'll need add stuff to buffer _quadBuffer[0] = q1; return addName(_quadBuffer, 1, lastQuadBytes); } private final String findName(int q1, int q2, int lastQuadBytes) throws JsonParseException { q2 = pad(q2, lastQuadBytes); // Usually we'll find it from the canonical symbol table already String name = _symbols.findName(q1, q2); if (name != null) { return name; } // If not, more work. We'll need add stuff to buffer _quadBuffer[0] = q1; _quadBuffer[1] = q2; return addName(_quadBuffer, 2, lastQuadBytes); } private final String findName(int q1, int q2, int q3, int lastQuadBytes) throws JsonParseException { q3 = pad(q3, lastQuadBytes); String name = _symbols.findName(q1, q2, q3); if (name != null) { return name; } int[] quads = _quadBuffer; quads[0] = q1; quads[1] = q2; quads[2] = pad(q3, lastQuadBytes); return addName(quads, 3, lastQuadBytes); } private final String findName(int[] quads, int qlen, int lastQuad, int lastQuadBytes) throws JsonParseException { if (qlen >= quads.length) { _quadBuffer = quads = growArrayBy(quads, quads.length); } quads[qlen++] = pad(lastQuad, lastQuadBytes); String name = _symbols.findName(quads, qlen); if (name == null) { return addName(quads, qlen, lastQuadBytes); } return name; } /** * This is the main workhorse method used when we take a symbol table miss. It needs to demultiplex individual bytes, decode multi-byte * chars (if any), and then construct Name instance and add it to the symbol table. */ private final String addName(int[] quads, int qlen, int lastQuadBytes) throws JsonParseException { /* * Ok: must decode UTF-8 chars. No other validation is needed, since unescaping has been done earlier as necessary (as well as error * reporting for unescaped control chars) */ // 4 bytes per quad, except last one maybe less int byteLen = (qlen << 2) - 4 + lastQuadBytes; /* * And last one is not correctly aligned (leading zero bytes instead need to shift a bit, instead of trailing). Only need to shift it * for UTF-8 decoding; need revert for storage (since key will not be aligned, to optimize lookup speed) */ int lastQuad; if (lastQuadBytes < 4) { lastQuad = quads[qlen - 1]; // 8/16/24 bit left shift quads[qlen - 1] = (lastQuad << ((4 - lastQuadBytes) << 3)); } else { lastQuad = 0; } // Need some working space, TextBuffer works well: char[] cbuf = _textBuffer.emptyAndGetCurrentSegment(); int cix = 0; for (int ix = 0; ix < byteLen;) { int ch = quads[ix >> 2]; // current quad, need to shift+mask int byteIx = (ix & 3); ch = (ch >> ((3 - byteIx) << 3)) & 0xFF; ++ix; if (ch > 127) { // multi-byte int needed; if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) ch &= 0x1F; needed = 1; } else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) ch &= 0x0F; needed = 2; } else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all... ch &= 0x07; needed = 3; } else { // 5- and 6-byte chars not valid xml chars _reportInvalidInitial(ch); needed = ch = 1; // never really gets this far } if ((ix + needed) > byteLen) { _reportInvalidEOF(" in field name"); } // Ok, always need at least one more: int ch2 = quads[ix >> 2]; // current quad, need to shift+mask byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2); } ch = (ch << 6) | (ch2 & 0x3F); if (needed > 1) { ch2 = quads[ix >> 2]; byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2); } ch = (ch << 6) | (ch2 & 0x3F); if (needed > 2) { // 4 bytes? (need surrogates on output) ch2 = quads[ix >> 2]; byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2 & 0xFF); } ch = (ch << 6) | (ch2 & 0x3F); } } if (needed > 2) { // surrogate pair? once again, let's output one here, one later on ch -= 0x10000; // to normalize it starting with 0x0 if (cix >= cbuf.length) { cbuf = _textBuffer.expandCurrentSegment(); } cbuf[cix++] = (char) (0xD800 + (ch >> 10)); ch = 0xDC00 | (ch & 0x03FF); } } if (cix >= cbuf.length) { cbuf = _textBuffer.expandCurrentSegment(); } cbuf[cix++] = (char) ch; } // Ok. Now we have the character array, and can construct the String String baseName = new String(cbuf, 0, cix); // And finally, un-align if necessary if (lastQuadBytes < 4) { quads[qlen - 1] = lastQuad; } return _symbols.addName(baseName, quads, qlen); } /* * /********************************************************** /* Internal methods, String value parsing * /********************************************************** */ @Override protected void _finishString() throws IOException { // First, single tight loop for ASCII content, not split across input buffer boundary: int ptr = _inputPtr; if (ptr >= _inputEnd) { loadMoreGuaranteed(); ptr = _inputPtr; } int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); final int[] codes = _icUTF8; final int max = Math.min(_inputEnd, (ptr + outBuf.length)); final byte[] inputBuffer = _inputBuffer; while (ptr < max) { int c = (int) inputBuffer[ptr] & 0xFF; if (codes[c] != 0) { if (c == INT_QUOTE) { _inputPtr = ptr + 1; _textBuffer.setCurrentLength(outPtr); return; } break; } ++ptr; outBuf[outPtr++] = (char) c; } _inputPtr = ptr; _finishString2(outBuf, outPtr); } /** * @since 2.6 */ protected String _finishAndReturnString() throws IOException { // First, single tight loop for ASCII content, not split across input buffer boundary: int ptr = _inputPtr; if (ptr >= _inputEnd) { loadMoreGuaranteed(); ptr = _inputPtr; } int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); final int[] codes = _icUTF8; final int max = Math.min(_inputEnd, (ptr + outBuf.length)); final byte[] inputBuffer = _inputBuffer; while (ptr < max) { int c = (int) inputBuffer[ptr] & 0xFF; if (codes[c] != 0) { if (c == INT_QUOTE) { _inputPtr = ptr + 1; return _textBuffer.setCurrentAndReturn(outPtr); } break; } ++ptr; outBuf[outPtr++] = (char) c; } _inputPtr = ptr; _finishString2(outBuf, outPtr); return _textBuffer.contentsAsString(); } private final void _finishString2(char[] outBuf, int outPtr) throws IOException { int c; // Here we do want to do full decoding, hence: final int[] codes = _icUTF8; final byte[] inputBuffer = _inputBuffer; main_loop: while (true) { // Then the tight ASCII non-funny-char loop: ascii_loop: while (true) { int ptr = _inputPtr; if (ptr >= _inputEnd) { loadMoreGuaranteed(); ptr = _inputPtr; } if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } final int max = Math.min(_inputEnd, (ptr + (outBuf.length - outPtr))); while (ptr < max) { c = (int) inputBuffer[ptr++] & 0xFF; if (codes[c] != 0) { _inputPtr = ptr; break ascii_loop; } outBuf[outPtr++] = (char) c; } _inputPtr = ptr; } // Ok: end marker, escape or multi-byte? if (c == INT_QUOTE) { break main_loop; } switch (codes[c]) { case 1: // backslash c = _decodeEscaped(); break; case 2: // 2-byte UTF c = _decodeUtf8_2(c); break; case 3: // 3-byte UTF if ((_inputEnd - _inputPtr) >= 2) { c = _decodeUtf8_3fast(c); } else { c = _decodeUtf8_3(c); } break; case 4: // 4-byte UTF c = _decodeUtf8_4(c); // Let's add first part right away: outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } c = 0xDC00 | (c & 0x3FF); // And let the other char output down below break; default: if (c < INT_SPACE) { // As per [JACKSON-208], call can now return: _throwUnquotedSpace(c, "string value"); } else { // Is this good enough error message? _reportInvalidChar(c); } } // Need more room? if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } // Ok, let's add char to output: outBuf[outPtr++] = (char) c; } _textBuffer.setCurrentLength(outPtr); } /** * Method called to skim through rest of unparsed String value, if it is not needed. This can be done bit faster if contents need not be * stored for future access. */ protected void _skipString() throws IOException { _tokenIncomplete = false; // Need to be fully UTF-8 aware here: final int[] codes = _icUTF8; final byte[] inputBuffer = _inputBuffer; main_loop: while (true) { int c; ascii_loop: while (true) { int ptr = _inputPtr; int max = _inputEnd; if (ptr >= max) { loadMoreGuaranteed(); ptr = _inputPtr; max = _inputEnd; } while (ptr < max) { c = (int) inputBuffer[ptr++] & 0xFF; if (codes[c] != 0) { _inputPtr = ptr; break ascii_loop; } } _inputPtr = ptr; } // Ok: end marker, escape or multi-byte? if (c == INT_QUOTE) { break main_loop; } switch (codes[c]) { case 1: // backslash _decodeEscaped(); break; case 2: // 2-byte UTF _skipUtf8_2(c); break; case 3: // 3-byte UTF _skipUtf8_3(c); break; case 4: // 4-byte UTF _skipUtf8_4(c); break; default: if (c < INT_SPACE) { // As per [JACKSON-208], call can now return: _throwUnquotedSpace(c, "string value"); } else { // Is this good enough error message? _reportInvalidChar(c); } } } } /** * Method for handling cases where first non-space character of an expected value token is not legal for standard JSON content. */ protected JsonToken _handleUnexpectedValue(int c) throws IOException { // Most likely an error, unless we are to allow single-quote-strings switch (c) { case ']': case '}': // Error: neither is valid at this point; valid closers have // been handled earlier _reportUnexpectedChar(c, "expected a value"); case '\'': if (isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { return _handleApos(); } break; case 'N': _matchToken("NaN", 1); if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { return resetAsNaN("NaN", Double.NaN); } _reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); break; case 'I': _matchToken("Infinity", 1); if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { return resetAsNaN("Infinity", Double.POSITIVE_INFINITY); } _reportError("Non-standard token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); break; case '+': // note: '-' is taken as number if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOFInValue(); } } return _handleInvalidNumberStart(_inputBuffer[_inputPtr++] & 0xFF, false); } // [Issue#77] Try to decode most likely token if (Character.isJavaIdentifierStart(c)) { _reportInvalidToken("" + ((char) c), "('true', 'false' or 'null')"); } // but if it doesn't look like a token: _reportUnexpectedChar(c, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')"); return null; } protected JsonToken _handleApos() throws IOException { int c = 0; // Otherwise almost verbatim copy of _finishString() int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); // Here we do want to do full decoding, hence: final int[] codes = _icUTF8; final byte[] inputBuffer = _inputBuffer; main_loop: while (true) { // Then the tight ascii non-funny-char loop: ascii_loop: while (true) { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } int max = _inputEnd; { int max2 = _inputPtr + (outBuf.length - outPtr); if (max2 < max) { max = max2; } } while (_inputPtr < max) { c = (int) inputBuffer[_inputPtr++] & 0xFF; if (c == '\'' || codes[c] != 0) { break ascii_loop; } outBuf[outPtr++] = (char) c; } } // Ok: end marker, escape or multi-byte? if (c == '\'') { break main_loop; } switch (codes[c]) { case 1: // backslash if (c != '\'') { // marked as special, isn't here c = _decodeEscaped(); } break; case 2: // 2-byte UTF c = _decodeUtf8_2(c); break; case 3: // 3-byte UTF if ((_inputEnd - _inputPtr) >= 2) { c = _decodeUtf8_3fast(c); } else { c = _decodeUtf8_3(c); } break; case 4: // 4-byte UTF c = _decodeUtf8_4(c); // Let's add first part right away: outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } c = 0xDC00 | (c & 0x3FF); // And let the other char output down below break; default: if (c < INT_SPACE) { _throwUnquotedSpace(c, "string value"); } // Is this good enough error message? _reportInvalidChar(c); } // Need more room? if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } // Ok, let's add char to output: outBuf[outPtr++] = (char) c; } _textBuffer.setCurrentLength(outPtr); return JsonToken.VALUE_STRING; } /** * Method called if expected numeric value (due to leading sign) does not look like a number */ protected JsonToken _handleInvalidNumberStart(int ch, boolean neg) throws IOException { while (ch == 'I') { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOFInValue(); } } ch = _inputBuffer[_inputPtr++]; String match; if (ch == 'N') { match = neg ? "-INF" : "+INF"; } else if (ch == 'n') { match = neg ? "-Infinity" : "+Infinity"; } else { break; } _matchToken(match, 3); if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { return resetAsNaN(match, neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); } _reportError("Non-standard token '" + match + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); } reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value"); return null; } protected final void _matchToken(String matchStr, int i) throws IOException { final int len = matchStr.length(); if ((_inputPtr + len) >= _inputEnd) { _matchToken2(matchStr, i); return; } do { if (_inputBuffer[_inputPtr] != matchStr.charAt(i)) { _reportInvalidToken(matchStr.substring(0, i)); } ++_inputPtr; } while (++i < len); int ch = _inputBuffer[_inputPtr] & 0xFF; if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars _checkMatchEnd(matchStr, i, ch); } } private final void _matchToken2(String matchStr, int i) throws IOException { final int len = matchStr.length(); do { if (((_inputPtr >= _inputEnd) && !loadMore()) || (_inputBuffer[_inputPtr] != matchStr.charAt(i))) { _reportInvalidToken(matchStr.substring(0, i)); } ++_inputPtr; } while (++i < len); // but let's also ensure we either get EOF, or non-alphanum char... if (_inputPtr >= _inputEnd && !loadMore()) { return; } int ch = _inputBuffer[_inputPtr] & 0xFF; if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars _checkMatchEnd(matchStr, i, ch); } } private final void _checkMatchEnd(String matchStr, int i, int ch) throws IOException { // but actually only alphanums are problematic char c = (char) _decodeCharForError(ch); if (Character.isJavaIdentifierPart(c)) { _reportInvalidToken(matchStr.substring(0, i)); } } /* * /********************************************************** /* Internal methods, ws skipping, escape/unescape * /********************************************************** */ private final int _skipWS() throws IOException { while (_inputPtr < _inputEnd) { int i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { --_inputPtr; return _skipWS2(); } return i; } if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } } return _skipWS2(); } private final int _skipWS2() throws IOException { while (_inputPtr < _inputEnd || loadMore()) { int i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH) { _skipComment(); continue; } if (i == INT_HASH) { if (_skipYAMLComment()) { continue; } } return i; } if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } } throw _constructError("Unexpected end-of-input within/between " + _parsingContext.getTypeDesc() + " entries"); } private final int _skipWSOrEnd() throws IOException { // Let's handle first character separately since it is likely that // it is either non-whitespace; or we have longer run of white space if (_inputPtr >= _inputEnd) { if (!loadMore()) { return _eofAsNextChar(); } } int i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { --_inputPtr; return _skipWSOrEnd2(); } return i; } if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } while (_inputPtr < _inputEnd) { i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { --_inputPtr; return _skipWSOrEnd2(); } return i; } if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } } return _skipWSOrEnd2(); } private final int _skipWSOrEnd2() throws IOException { while ((_inputPtr < _inputEnd) || loadMore()) { int i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH) { _skipComment(); continue; } if (i == INT_HASH) { if (_skipYAMLComment()) { continue; } } return i; } else if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } } // We ran out of input... return _eofAsNextChar(); } private final int _skipColon() throws IOException { if ((_inputPtr + 4) >= _inputEnd) { return _skipColon2(false); } // Fast path: colon with optional single-space/tab before and/or after: int i = _inputBuffer[_inputPtr]; if (i == INT_COLON) { // common case, no leading space i = _inputBuffer[++_inputPtr]; if (i > INT_SPACE) { // nor trailing if (i == INT_SLASH || i == INT_HASH) { return _skipColon2(true); } ++_inputPtr; return i; } if (i == INT_SPACE || i == INT_TAB) { i = (int) _inputBuffer[++_inputPtr]; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { return _skipColon2(true); } ++_inputPtr; return i; } } return _skipColon2(true); // true -> skipped colon } if (i == INT_SPACE || i == INT_TAB) { i = _inputBuffer[++_inputPtr]; } if (i == INT_COLON) { i = _inputBuffer[++_inputPtr]; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { return _skipColon2(true); } ++_inputPtr; return i; } if (i == INT_SPACE || i == INT_TAB) { i = (int) _inputBuffer[++_inputPtr]; if (i > INT_SPACE) { if (i == INT_SLASH || i == INT_HASH) { return _skipColon2(true); } ++_inputPtr; return i; } } return _skipColon2(true); } return _skipColon2(false); } private final int _skipColon2(boolean gotColon) throws IOException { while (_inputPtr < _inputEnd || loadMore()) { int i = _inputBuffer[_inputPtr++] & 0xFF; if (i > INT_SPACE) { if (i == INT_SLASH) { _skipComment(); continue; } if (i == INT_HASH) { if (_skipYAMLComment()) { continue; } } if (gotColon) { return i; } if (i != INT_COLON) { if (i < INT_SPACE) { _throwInvalidSpace(i); } _reportUnexpectedChar(i, "was expecting a colon to separate field name and value"); } gotColon = true; } else if (i != INT_SPACE) { if (i == INT_LF) { ++_currInputRow; _currInputRowStart = _inputPtr; } else if (i == INT_CR) { _skipCR(); } else if (i != INT_TAB) { _throwInvalidSpace(i); } } } throw _constructError("Unexpected end-of-input within/between " + _parsingContext.getTypeDesc() + " entries"); } private final void _skipComment() throws IOException { if (!isEnabled(Feature.ALLOW_COMMENTS)) { _reportUnexpectedChar('/', "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)"); } // First: check which comment (if either) it is: if (_inputPtr >= _inputEnd && !loadMore()) { _reportInvalidEOF(" in a comment"); } int c = _inputBuffer[_inputPtr++] & 0xFF; if (c == '/') { _skipLine(); } else if (c == '*') { _skipCComment(); } else { _reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment"); } } private final void _skipCComment() throws IOException { // Need to be UTF-8 aware here to decode content (for skipping) final int[] codes = CharTypes.getInputCodeComment(); // Ok: need the matching '*/' main_loop: while ((_inputPtr < _inputEnd) || loadMore()) { int i = (int) _inputBuffer[_inputPtr++] & 0xFF; int code = codes[i]; if (code != 0) { switch (code) { case '*': if (_inputPtr >= _inputEnd && !loadMore()) { break main_loop; } if (_inputBuffer[_inputPtr] == INT_SLASH) { ++_inputPtr; return; } break; case INT_LF: ++_currInputRow; _currInputRowStart = _inputPtr; break; case INT_CR: _skipCR(); break; case 2: // 2-byte UTF _skipUtf8_2(i); break; case 3: // 3-byte UTF _skipUtf8_3(i); break; case 4: // 4-byte UTF _skipUtf8_4(i); break; default: // e.g. -1 // Is this good enough error message? _reportInvalidChar(i); } } } _reportInvalidEOF(" in a comment"); } private final boolean _skipYAMLComment() throws IOException { if (!isEnabled(Feature.ALLOW_YAML_COMMENTS)) { return false; } _skipLine(); return true; } /** * Method for skipping contents of an input line; usually for CPP and YAML style comments. */ private final void _skipLine() throws IOException { // Ok: need to find EOF or linefeed final int[] codes = CharTypes.getInputCodeComment(); while ((_inputPtr < _inputEnd) || loadMore()) { int i = (int) _inputBuffer[_inputPtr++] & 0xFF; int code = codes[i]; if (code != 0) { switch (code) { case INT_LF: ++_currInputRow; _currInputRowStart = _inputPtr; return; case INT_CR: _skipCR(); return; case '*': // nop for these comments break; case 2: // 2-byte UTF _skipUtf8_2(i); break; case 3: // 3-byte UTF _skipUtf8_3(i); break; case 4: // 4-byte UTF _skipUtf8_4(i); break; default: // e.g. -1 if (code < 0) { // Is this good enough error message? _reportInvalidChar(i); } } } } } @Override protected char _decodeEscaped() throws IOException { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(" in character escape sequence"); } } int c = (int) _inputBuffer[_inputPtr++]; switch (c) { // First, ones that are mapped case 'b': return '\b'; case 't': return '\t'; case 'n': return '\n'; case 'f': return '\f'; case 'r': return '\r'; // And these are to be returned as they are case '"': case '/': case '\\': return (char) c; case 'u': // and finally hex-escaped break; default: return _handleUnrecognizedCharacterEscape((char) _decodeCharForError(c)); } // Ok, a hex escape. Need 4 characters int value = 0; for (int i = 0; i < 4; ++i) { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOF(" in character escape sequence"); } } int ch = (int) _inputBuffer[_inputPtr++]; int digit = CharTypes.charToHex(ch); if (digit < 0) { _reportUnexpectedChar(ch, "expected a hex-digit for character escape sequence"); } value = (value << 4) | digit; } return (char) value; } protected int _decodeCharForError(int firstByte) throws IOException { int c = firstByte & 0xFF; if (c > 0x7F) { // if >= 0, is ascii and fine as is int needed; // Ok; if we end here, we got multi-byte combination if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) c &= 0x1F; needed = 1; } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) c &= 0x0F; needed = 2; } else if ((c & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all... c &= 0x07; needed = 3; } else { _reportInvalidInitial(c & 0xFF); needed = 1; // never gets here } int d = nextByte(); if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF); } c = (c << 6) | (d & 0x3F); if (needed > 1) { // needed == 1 means 2 bytes total d = nextByte(); // 3rd byte if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF); } c = (c << 6) | (d & 0x3F); if (needed > 2) { // 4 bytes? (need surrogates) d = nextByte(); if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF); } c = (c << 6) | (d & 0x3F); } } } return c; } /* * /********************************************************** /* Internal methods,UTF8 decoding * /********************************************************** */ private final int _decodeUtf8_2(int c) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } return ((c & 0x1F) << 6) | (d & 0x3F); } private final int _decodeUtf8_3(int c1) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c1 &= 0x0F; int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } int c = (c1 << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); return c; } private final int _decodeUtf8_3fast(int c1) throws IOException { c1 &= 0x0F; int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } int c = (c1 << 6) | (d & 0x3F); d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); return c; } /** * @return Character value <b>minus 0x10000</c>; this so that caller can readily expand it to actual surrogates */ private final int _decodeUtf8_4(int c) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = ((c & 0x07) << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } /* * note: won't change it to negative here, since caller already knows it'll need a surrogate */ return ((c << 6) | (d & 0x3F)) - 0x10000; } private final void _skipUtf8_2(int c) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c = (int) _inputBuffer[_inputPtr++]; if ((c & 0xC0) != 0x080) { _reportInvalidOther(c & 0xFF, _inputPtr); } } /* * Alas, can't heavily optimize skipping, since we still have to do validity checks... */ private final void _skipUtf8_3(int c) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } // c &= 0x0F; c = (int) _inputBuffer[_inputPtr++]; if ((c & 0xC0) != 0x080) { _reportInvalidOther(c & 0xFF, _inputPtr); } if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c = (int) _inputBuffer[_inputPtr++]; if ((c & 0xC0) != 0x080) { _reportInvalidOther(c & 0xFF, _inputPtr); } } private final void _skipUtf8_4(int c) throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } } /* * /********************************************************** /* Internal methods, input loading * /********************************************************** */ /** * We actually need to check the character value here (to see if we have \n following \r). */ protected final void _skipCR() throws IOException { if (_inputPtr < _inputEnd || loadMore()) { if (_inputBuffer[_inputPtr] == BYTE_LF) { ++_inputPtr; } } ++_currInputRow; _currInputRowStart = _inputPtr; } private int nextByte() throws IOException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return _inputBuffer[_inputPtr++] & 0xFF; } /* * /********************************************************** /* Internal methods, error reporting * /********************************************************** */ protected void _reportInvalidToken(String matchedPart) throws IOException { _reportInvalidToken(matchedPart, "'null', 'true', 'false' or NaN"); } protected void _reportInvalidToken(String matchedPart, String msg) throws IOException { StringBuilder sb = new StringBuilder(matchedPart); /* * Let's just try to find what appears to be the token, using regular Java identifier character rules. It's just a heuristic, nothing * fancy here (nor fast). */ while (true) { if (_inputPtr >= _inputEnd && !loadMore()) { break; } int i = (int) _inputBuffer[_inputPtr++]; char c = (char) _decodeCharForError(i); if (!Character.isJavaIdentifierPart(c)) { break; } sb.append(c); } _reportError("Unrecognized token '" + sb.toString() + "': was expecting " + msg); } protected void _reportInvalidChar(int c) throws JsonParseException { // Either invalid WS or illegal UTF-8 start char if (c < INT_SPACE) { _throwInvalidSpace(c); } _reportInvalidInitial(c); } protected void _reportInvalidInitial(int mask) throws JsonParseException { _reportError("Invalid UTF-8 start byte 0x" + Integer.toHexString(mask)); } protected void _reportInvalidOther(int mask) throws JsonParseException { _reportError("Invalid UTF-8 middle byte 0x" + Integer.toHexString(mask)); } protected void _reportInvalidOther(int mask, int ptr) throws JsonParseException { _inputPtr = ptr; _reportInvalidOther(mask); } public static int[] growArrayBy(int[] arr, int more) { if (arr == null) { return new int[more]; } return Arrays.copyOf(arr, arr.length + more); } /* * /********************************************************** /* Internal methods, binary access * /********************************************************** */ /** * Efficient handling for incremental parsing of base64-encoded textual content. */ protected final byte[] _decodeBase64(Base64Variant b64variant) throws IOException { ByteArrayBuilder builder = _getByteArrayBuilder(); // main_loop: while (true) { // first, we'll skip preceding white space, if any int ch; do { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = (int) _inputBuffer[_inputPtr++] & 0xFF; } while (ch <= INT_SPACE); int bits = b64variant.decodeBase64Char(ch); if (bits < 0) { // reached the end, fair and square? if (ch == INT_QUOTE) { return builder.toByteArray(); } bits = _decodeBase64Escape(b64variant, ch, 0); if (bits < 0) { // white space to skip continue; } } int decodedData = bits; // then second base64 char; can't get padding yet, nor ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); if (bits < 0) { bits = _decodeBase64Escape(b64variant, ch, 1); } decodedData = (decodedData << 6) | bits; // third base64 char; can be padding, but not ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); // First branch: can get padding (-> 1 byte) if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { // as per [JACKSON-631], could also just be 'missing' padding if (ch == '"' && !b64variant.usesPadding()) { decodedData >>= 4; builder.append(decodedData); return builder.toByteArray(); } bits = _decodeBase64Escape(b64variant, ch, 2); } if (bits == Base64Variant.BASE64_VALUE_PADDING) { // Ok, must get padding if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; if (!b64variant.usesPaddingChar(ch)) { throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '" + b64variant.getPaddingChar() + "'"); } // Got 12 bits, only need 8, need to shift decodedData >>= 4; builder.append(decodedData); continue; } } // Nope, 2 or 3 bytes decodedData = (decodedData << 6) | bits; // fourth and last base64 char; can be padding, but not ws if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } ch = _inputBuffer[_inputPtr++] & 0xFF; bits = b64variant.decodeBase64Char(ch); if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { // as per [JACKSON-631], could also just be 'missing' padding if (ch == '"' && !b64variant.usesPadding()) { decodedData >>= 2; builder.appendTwoBytes(decodedData); return builder.toByteArray(); } bits = _decodeBase64Escape(b64variant, ch, 3); } if (bits == Base64Variant.BASE64_VALUE_PADDING) { /* * With padding we only get 2 bytes; but we have to shift it a bit so it is identical to triplet case with partial output. * 3 chars gives 3x6 == 18 bits, of which 2 are dummies, need to discard: */ decodedData >>= 2; builder.appendTwoBytes(decodedData); continue; } } // otherwise, our triplet is now complete decodedData = (decodedData << 6) | bits; builder.appendThreeBytes(decodedData); } } /* * /********************************************************** /* Internal methods, other * /********************************************************** */ /** * Helper method needed to fix [Issue#148], masking of 0x00 character */ private final static int pad(int q, int bytes) { return (bytes == 4) ? q : (q | (-1 << (bytes << 3))); } }
gpl-2.0
ksmaheshkumar/ache
src/main/java/focusedCrawler/crawler/CrawlerException.java
1566
/* ############################################################################ ## ## Copyright (C) 2006-2009 University of Utah. All rights reserved. ## ## This file is part of DeepPeep. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL included in the packaging of ## this file. Please review the following to ensure GNU General Public ## Licensing requirements will be met: ## http://www.opensource.org/licenses/gpl-license.php ## ## If you are unsure which license is appropriate for your use (for ## instance, you are interested in developing a commercial derivative ## of DeepPeep), please contact us at deeppeep@sci.utah.edu. ## ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ## ############################################################################ */ package focusedCrawler.crawler; /** * <p>Description: Exception thrown by the crawler</p> * * <p>Copyright: Copyright (c) 2004</p> * * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class CrawlerException extends Exception{ public Throwable detail; public CrawlerException() { super(); } public CrawlerException(String message) { super(message); } public CrawlerException(String message,Throwable detail) { super(message); this.detail = detail; } }
gpl-2.0
FerdinandBrunauer/Diplomarbeit
Programmierung/OpenDataUtilities/src/digitalsalzburg/opendata/OpenDataPackage.java
1325
package digitalsalzburg.opendata; import java.util.ArrayList; import java.util.List; public class OpenDataPackage { private String id; private String name; private String notes; private List<OpenDataResource> resources; private List<OpenDataTag> tags; private String title; public OpenDataPackage(String id){ resources = new ArrayList<OpenDataResource>(); tags = new ArrayList<OpenDataTag>(); this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public List<OpenDataResource> getResources() { return resources; } public void setResources(List<OpenDataResource> resources) { this.resources = resources; } public void addResource(OpenDataResource resource){ this.resources.add(resource); } public List<OpenDataTag> getTags() { return tags; } public void setTags(List<OpenDataTag> tags) { this.tags = tags; } public void addTag(OpenDataTag tag){ this.tags.add(tag); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
gpl-2.0
Arquisoft/Trivial5b
game/src/main/java/logica/User.java
1020
package logica; public class User { private String nombre; private String apellidos; private String login; private String password; public User(){} public User(String nombre, String apellidos, String login, String password) { super(); this.nombre = nombre; this.apellidos = apellidos; this.login = login; this.password = password; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [nombre=" + nombre + ", apellidos=" + apellidos + ", login=" + login + ", password=" + password + "]"; } }
gpl-2.0
kompics/kompics-scala
docs/src/main/java/jexamples/simulation/pingpong/ScenarioGen.java
4598
package jexamples.simulation.pingpong; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import se.sics.kompics.Init; import se.sics.kompics.network.Address; import se.sics.kompics.simulator.SimulationScenario; import se.sics.kompics.simulator.adaptor.Operation1; import se.sics.kompics.simulator.adaptor.Operation2; import se.sics.kompics.simulator.adaptor.distributions.extra.BasicIntSequentialDistribution; import se.sics.kompics.simulator.events.system.StartNodeEvent; public class ScenarioGen { public static final int PORT = 12345; public static final String IP_PREFIX = "192.193.0."; static Operation1<StartNodeEvent, Integer> startPongerOp = new Operation1<StartNodeEvent, Integer>() { @Override public StartNodeEvent generate(final Integer self) { return new StartNodeEvent() { TAddress selfAdr; { try { selfAdr = new TAddress(InetAddress.getByName(IP_PREFIX + self), PORT); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } @Override public Map<String, Object> initConfigUpdate() { HashMap<String, Object> config = new HashMap<>(); config.put("pingpong.ponger.addr", selfAdr); return config; } @Override public Address getNodeAddress() { return selfAdr; } @Override public Class<PongerParent> getComponentDefinition() { return PongerParent.class; } @Override public Init getComponentInit() { return Init.NONE; } @Override public String toString() { return "StartPonger<" + selfAdr.toString() + ">"; } }; } }; static Operation2<StartNodeEvent, Integer, Integer> startPingerOp = new Operation2<StartNodeEvent, Integer, Integer>() { @Override public StartNodeEvent generate(final Integer self, final Integer ponger) { return new StartNodeEvent() { TAddress selfAdr; TAddress pongerAdr; { try { selfAdr = new TAddress(InetAddress.getByName(IP_PREFIX + self), PORT); pongerAdr = new TAddress(InetAddress.getByName(IP_PREFIX + ponger), PORT); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } @Override public Map<String, Object> initConfigUpdate() { HashMap<String, Object> config = new HashMap<>(); config.put("pingpong.pinger.addr", selfAdr); config.put("pingpong.pinger.pongeraddr", pongerAdr); return config; } @Override public Address getNodeAddress() { return selfAdr; } @Override public Class<PingerParent> getComponentDefinition() { return PingerParent.class; } @Override public Init getComponentInit() { return Init.NONE; } @Override public String toString() { return "StartPinger<" + selfAdr.toString() + ">"; } }; } }; public static SimulationScenario simplePing() { SimulationScenario scen = new SimulationScenario() { { SimulationScenario.StochasticProcess ponger = new SimulationScenario.StochasticProcess() { { eventInterarrivalTime(constant(1000)); raise(5, startPongerOp, new BasicIntSequentialDistribution(1)); } }; SimulationScenario.StochasticProcess pinger = new SimulationScenario.StochasticProcess() { { eventInterarrivalTime(constant(1000)); raise( 5, startPingerOp, new BasicIntSequentialDistribution(6), new BasicIntSequentialDistribution(1)); } }; ponger.start(); pinger.startAfterTerminationOf(1000, ponger); terminateAfterTerminationOf(10000, pinger); } }; return scen; } }
gpl-2.0
g2x3k/Drftpd2Stable
src/org/drftpd/slave/Connection.java
1479
/* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.slave; import java.io.IOException; import java.io.Serializable; import java.net.Socket; /** * @author mog * @version $Id: Connection.java 1765 2007-08-04 04:14:28Z tdsoul $ */ public abstract class Connection implements Serializable { public static final int TIMEOUT = 10000; public abstract Socket connect(int buffersize) throws IOException; protected void setSockOpts(Socket sock) throws IOException { /* * IPTOS_LOWCOST (0x02) * IPTOS_RELIABILITY (0x04) * IPTOS_THROUGHPUT (0x08) * IPTOS_LOWDELAY (0x10) */ sock.setTrafficClass(0x08); sock.setSoTimeout(TIMEOUT); } public abstract void abort(); }
gpl-2.0
ljx0305/ice
java/src/IceGridGUI/src/main/java/com/zeroc/IceGridGUI/ApplicationObserverI.java
4040
// ********************************************************************** // // Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** package com.zeroc.IceGridGUI; import javax.swing.SwingUtilities; import com.zeroc.IceGrid.*; class ApplicationObserverI implements ApplicationObserver { ApplicationObserverI(String instanceName, Coordinator coordinator) { _instanceName = instanceName; _coordinator = coordinator; _trace = coordinator.traceObservers(); } // // Runs in the UI thread // synchronized void waitForInit() { // // TODO: configurable timeout // long timeout = 10000; if(!_initialized) { try { wait(timeout); } catch(InterruptedException e) { } } if(_initialized) { _coordinator.applicationInit(_instanceName, _serial, _applications); } else { throw new com.zeroc.Ice.TimeoutException(); } } @Override public synchronized void applicationInit(int serial, java.util.List<ApplicationInfo> applications, com.zeroc.Ice.Current current) { if(_trace) { if(applications.size() == 0) { _coordinator.traceObserver("applicationInit (no application);" + "serial is " + serial); } else { String names = ""; for(ApplicationInfo p : applications) { names += " " + p.descriptor.name; } _coordinator.traceObserver("applicationInit for application" + (applications.size() == 1 ? "" : "s") + names + "; serial is " + serial); } } _initialized = true; _serial = serial; _applications = applications; notify(); } @Override public void applicationAdded(final int serial, final ApplicationInfo info, com.zeroc.Ice.Current current) { if(_trace) { _coordinator.traceObserver("applicationAdded for application " + info.descriptor.name + "; serial is " + serial); } SwingUtilities.invokeLater(() -> { _coordinator.applicationAdded(serial, info); }); } @Override public void applicationRemoved(final int serial, final String name, final com.zeroc.Ice.Current current) { if(_trace) { _coordinator.traceObserver("applicationRemoved for application " + name + "; serial is " + serial); } SwingUtilities.invokeLater(() -> { _coordinator.applicationRemoved(serial, name); }); } @Override public void applicationUpdated(final int serial, final ApplicationUpdateInfo info, com.zeroc.Ice.Current current) { if(_trace) { _coordinator.traceObserver("applicationUpdated for application " + info.descriptor.name + "; serial is " + serial); } SwingUtilities.invokeLater(() -> { _coordinator.applicationUpdated(serial, info); }); } private final Coordinator _coordinator; private final boolean _trace; private boolean _initialized = false; // // Values given to init // private final String _instanceName; private int _serial; private java.util.List<ApplicationInfo> _applications; }
gpl-2.0
naomiHauret/OdysseeDesMaths
core/src/com/odysseedesmaths/minigames/arriveeremarquable/entities/Entity.java
788
package com.odysseedesmaths.minigames.arriveeremarquable.entities; import com.odysseedesmaths.minigames.arriveeremarquable.ArriveeRemarquable; import com.odysseedesmaths.minigames.arriveeremarquable.map.Case; public abstract class Entity { private ArriveeRemarquable minigame; private Case maCase; public Entity(ArriveeRemarquable minigame, Case c) { this.minigame = minigame; this.maCase = c; } public Entity(ArriveeRemarquable minigame) { this(minigame, null); } public Case getCase() { return maCase; } public void setCase(Case c) { if (getCase() != null) { getCase().free(); } maCase = c; } public ArriveeRemarquable getMinigame() { return minigame; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest14235.java
2436
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest14235") public class BenchmarkTest14235 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { javax.servlet.http.Cookie[] cookies = request.getCookies(); String param = null; boolean foundit = false; if (cookies != null) { for (javax.servlet.http.Cookie cookie : cookies) { if (cookie.getName().equals("foo")) { param = cookie.getValue(); foundit = true; } } if (!foundit) { // no cookie found in collection param = ""; } } else { // no cookies param = ""; } String bar = doSomething(param); try { java.io.FileInputStream fis = new java.io.FileInputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar); } catch (Exception e) { // OK to swallow any exception // TODO: Fix this. System.out.println("File exception caught and swallowed: " + e.getMessage()); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = param.split(" ")[0]; return bar; } }
gpl-2.0
silen85/shujutongji
app/src/main/java/com/lesso/data/adapter/HorizontalBarAdapter.java
2841
package com.lesso.data.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ProgressBar; import android.widget.TextView; import com.lesso.data.R; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by meisl on 2015/6/25. */ public class HorizontalBarAdapter extends BaseAdapter { private int[] processbar_stys = {R.drawable.processbar_sty1, R.drawable.processbar_sty2, R.drawable.processbar_sty3, R.drawable.processbar_sty4, R.drawable.processbar_sty5, R.drawable.processbar_sty6, R.drawable.processbar_sty7, R.drawable.processbar_sty8}; private Context context; private LayoutInflater layoutInflater; private List<Map<String, String>> list = new ArrayList<Map<String, String>>(); private int layoutlistid; public HorizontalBarAdapter(Context context, List<Map<String, String>> listobject, int listcontextid) { this.context = context; this.layoutInflater = LayoutInflater.from(this.context); this.list = listobject; this.layoutlistid = listcontextid; } @Override public int getCount() { return this.list.size(); } @Override public Object getItem(int i) { return this.list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; if (view == null) { view = layoutInflater.inflate(this.layoutlistid, null); viewHolder = new ViewHolder(); viewHolder.product_name = (TextView) view.findViewById(R.id.product_name); viewHolder.product_num = (TextView) view.findViewById(R.id.product_num); viewHolder.product_percent = (ProgressBar) view.findViewById(R.id.product_percent); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } viewHolder.product_percent.setProgressDrawable (context.getResources().getDrawable(processbar_stys[i % processbar_stys.length])); this.writeData(viewHolder, i); return view; } private void writeData(ViewHolder viewHolder, int position) { Map<String, String> itemData = (Map) getItem(position); viewHolder.product_name.setText(itemData.get("product_name")); viewHolder.product_num.setText(itemData.get("product_num")); viewHolder.product_percent.setProgress(Integer.parseInt(itemData.get("product_percent"))); } class ViewHolder { TextView product_name; TextView product_num; ProgressBar product_percent; } }
gpl-2.0
elitak/peertrust
sandbox/Mailrank/supportfiles/BerkeleyDB/MRAddressKeyCreator.java
1686
import com.sleepycat.je.SecondaryKeyCreator; import com.sleepycat.je.SecondaryDatabase; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.bind.tuple.TupleBinding; import java.io.UnsupportedEncodingException; /** * Created by IntelliJ IDEA. * User: broso * Date: Aug 2, 2004 * Time: 5:11:08 PM * To change this template use File | Settings | File Templates. */ public class MRAddressKeyCreator implements SecondaryKeyCreator{ private TupleBinding binding; public MRAddressKeyCreator(TupleBinding binding) { this.binding = binding; } /** * Creates the Index of Addresses in the secondary Database * @param mySecDB The secondary database * @param myKey The primary key * @param myData The data containing the new key * @param myNewKey The new key created from the data * @return */ public boolean createSecondaryKey(SecondaryDatabase mySecDB, DatabaseEntry myKey, DatabaseEntry myData, DatabaseEntry myNewKey) { if (myData == null) { return false; } else { MRData myMRData = (MRData) binding.entryToObject(myData); String address = myMRData.getAddress(); try { myNewKey.setData(address.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // Will never occur, the primary DB will not run without UTF-8 System.out.println("UTF-8 not supported on this platform"); System.exit(-1); } return true; } } }
gpl-2.0
SrirangaDigital/shankara-android
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/NavActivity.java
2612
package co.ideaportal.srirangadigital.shankaraandroid; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.hb.views.PinnedSectionListView; import androidx.appcompat.widget.Toolbar; import co.ideaportal.srirangadigital.shankaraandroid.books.BookActivity; import co.ideaportal.srirangadigital.shankaraandroid.event.BookLinkClicked; import co.ideaportal.srirangadigital.shankaraandroid.model.Level; import co.ideaportal.srirangadigital.shankaraandroid.model.Link; import static co.ideaportal.srirangadigital.shankaraandroid.Constants.PARENT; import static co.ideaportal.srirangadigital.shankaraandroid.Constants.getFormattedString; public class NavActivity extends BaseActivity { public static final int ROOT_PARENT_ID = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.book_nav); initToolbar(); initPinnedSectionView(); } private void initToolbar() { Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle(Constants.getFormattedString(this, R.string.title)); setSupportActionBar(toolbar); ((Toolbar) findViewById(R.id.toolbar_secondary)).setTitle(getFormattedString(this, R.string.subtitle)); toolbar.setNavigationIcon(R.mipmap.logo); } private void initPinnedSectionView() { PinnedSectionListView booksList = findViewById(R.id.booksList); final RootNavAdapter adapter = new RootNavAdapter(this, dataSource, ROOT_PARENT_ID); booksList.setAdapter(adapter); booksList.setOnItemClickListener((parent, view, position, id) -> { Link link = adapter.getItem(position); if (link.level == Level.BOOK_TYPE) return; Intent intent = new Intent(NavActivity.this, BookActivity.class); intent.putExtra(PARENT, link); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); postEvent(new BookLinkClicked(link)); }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_nav, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (R.id.menu_info == item.getItemId()) { startActivity(new Intent(this, InfoActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); return true; } return super.onOptionsItemSelected(item); } }
gpl-2.0
coder212/audiosynthetizer
AudioSinthetyzer/src/com/contoh/audiosinthetyzer/AudioSinthetyzerActivity.java
2488
package com.contoh.audiosinthetyzer; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AudioSinthetyzerActivity extends Activity implements OnClickListener { Button start,end; AudioSynthetysTask audiosynth; boolean keepOnGoing = false; float synth_frequency = 440; //440 Hz, Middle A @Override protected void onCreate(Bundle savedInstanceState) { // TODOs Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); start = (Button)findViewById(R.id.start); start.setOnClickListener(this); end = (Button)findViewById(R.id.end); end.setOnClickListener(this); end.setEnabled(false); } @Override protected void onPause() { // TODOs Auto-generated method stub super.onPause(); keepOnGoing = false; end.setEnabled(false); start.setEnabled(true); } @Override public void onClick(View v) { // TODOs Auto-generated method stub if(v == start){ keepOnGoing = true; audiosynth = new AudioSynthetysTask(); audiosynth.execute(); end.setEnabled(true); start.setEnabled(false); }else if(v == end){ keepOnGoing = false; end.setEnabled(false); start.setEnabled(true); } } private class AudioSynthetysTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... params) { // TODOs Auto-generated method stub final int SAMPLE_RATE = 11025; @SuppressWarnings("deprecation") int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); @SuppressWarnings("deprecation") AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM); audioTrack.play(); short[] buffer = new short[minSize]; float angular_frequency = (float)(2*Math.PI)* synth_frequency / SAMPLE_RATE; float angle = 0; while(keepOnGoing){ for(int i =0 ;i < buffer.length;i++){ buffer[i] = (short)(Short.MAX_VALUE * ((float)Math.sin(angle))); angle += angular_frequency; } audioTrack.write(buffer, 0, buffer.length); } return null; } } }
gpl-2.0
stenzek/dolphin
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/features/settings/ui/SettingsActivityView.java
3982
package org.dolphinemu.dolphinemu.features.settings.ui; import android.content.IntentFilter; import android.os.Bundle; import org.dolphinemu.dolphinemu.features.settings.model.Settings; import org.dolphinemu.dolphinemu.utils.DirectoryStateReceiver; /** * Abstraction for the Activity that manages SettingsFragments. */ public interface SettingsActivityView { /** * Show a new SettingsFragment. * * @param menuTag Identifier for the settings group that should be displayed. * @param addToStack Whether or not this fragment should replace a previous one. */ void showSettingsFragment(MenuTag menuTag, Bundle extras, boolean addToStack, String gameId); /** * Called by a contained Fragment to get access to the Setting HashMap * loaded from disk, so that each Fragment doesn't need to perform its own * read operation. * * @return A possibly null HashMap of Settings. */ Settings getSettings(); /** * Used to provide the Activity with Settings HashMaps if a Fragment already * has one; for example, if a rotation occurs, the Fragment will not be killed, * but the Activity will, so the Activity needs to have its HashMaps resupplied. * * @param settings The ArrayList of all the Settings HashMaps. */ void setSettings(Settings settings); /** * Called when an asynchronous load operation completes. * * @param settings The (possibly null) result of the ini load operation. */ void onSettingsFileLoaded(Settings settings); /** * Called when an asynchronous load operation fails. */ void onSettingsFileNotFound(); /** * Display a popup text message on screen. * * @param message The contents of the onscreen message. */ void showToastMessage(String message); /** * Show the previous fragment. */ void popBackStack(); /** * End the activity. */ void finish(); /** * Called by a containing Fragment to tell the Activity that a setting was changed; * unless this has been called, the Activity will not save to disk. */ void onSettingChanged(); /** * Called by a containing Fragment to tell the containing Activity that a GCPad's setting * was modified. * * @param menuTag Identifier for the GCPad that was modified. * @param value New setting for the GCPad. */ void onGcPadSettingChanged(MenuTag menuTag, int value); /** * Called by a containing Fragment to tell the containing Activity that a Wiimote's setting * was modified. * * @param menuTag Identifier for Wiimote that was modified. * @param value New setting for the Wiimote. */ void onWiimoteSettingChanged(MenuTag menuTag, int value); /** * Called by a containing Fragment to tell the containing Activity that an extension setting * was modified. * * @param menuTag Identifier for the extension that was modified. * @param value New setting for the extension. */ void onExtensionSettingChanged(MenuTag menuTag, int value); /** * Show loading dialog while loading the settings */ void showLoading(); /** * Hide the loading the dialog */ void hideLoading(); /** * Show a hint to the user that the app needs write to external storage access */ void showPermissionNeededHint(); /** * Show a hint to the user that the app needs the external storage to be mounted */ void showExternalStorageNotMountedHint(); /** * Start the DirectoryInitializationService and listen for the result. * * @param receiver the broadcast receiver for the DirectoryInitializationService * @param filter the Intent broadcasts to be received. */ void startDirectoryInitializationService(DirectoryStateReceiver receiver, IntentFilter filter); /** * Stop listening to the DirectoryInitializationService. * * @param receiver The broadcast receiver to unregister. */ void stopListeningToDirectoryInitializationService(DirectoryStateReceiver receiver); }
gpl-2.0
DrewG/mzmine2
src/main/java/net/sf/mzmine/modules/visualization/kendrickmassplot/chartutils/XYBlockPixelSizePaintScales.java
14427
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU * General private License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 2 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 private License for more details. * * You should have received a copy of the GNU General private License along with MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.modules.visualization.kendrickmassplot.chartutils; import java.awt.Color; import java.awt.Paint; import com.google.common.collect.Range; /** * Paint scales for XYZ datasets These scales can be used with the XYBlockRenderer * * @author Ansgar Korf (ansgar.korf@uni-muenster.de) */ public class XYBlockPixelSizePaintScales { /* * Method to select the right scale for the applied settings in the modules kendrickmassplot and * vankrevelendiagram */ public static Paint[] getPaintColors(String zAxisScaleType, Range<Double> zScaleRange, String paintScaleStyle) { Paint[] scale = null; // lower and upper bound if (zAxisScaleType.contains("percentile") && zScaleRange.lowerEndpoint() != 0 && zScaleRange.upperEndpoint() != 100) { if (paintScaleStyle.contains("Rainbow")) { scale = getFullRainBowScaleLowerUpperBound(); } else if (paintScaleStyle.contains("red")) { scale = getRedScaleLowerUpperBound(); } else if (paintScaleStyle.contains("green")) { scale = getGreenScaleLowerUpperBound(); } else if (paintScaleStyle.contains("yellow")) { scale = getYellowScaleLowerUpperBound(); } else if (paintScaleStyle.contains("cyan")) { scale = getCyanScaleLowerUpperBound(); } } // lower bound else if (zAxisScaleType.contains("percentile") && zScaleRange.lowerEndpoint() != 0 && zScaleRange.upperEndpoint() == 100) { if (paintScaleStyle.contains("Rainbow")) { scale = getFullRainBowScaleLowerBound(); } else if (paintScaleStyle.contains("red")) { scale = getRedScaleLowerBound(); } else if (paintScaleStyle.contains("green")) { scale = getGreenScaleLowerBound(); } else if (paintScaleStyle.contains("yellow")) { scale = getYellowScaleLowerBound(); } else if (paintScaleStyle.contains("cyan")) { scale = getCyanScaleLowerBound(); } } // upper bound else if (zAxisScaleType.contains("percentile") && zScaleRange.lowerEndpoint() == 0 && zScaleRange.upperEndpoint() != 100) { if (paintScaleStyle.contains("Rainbow")) { scale = getFullRainBowScaleUpperBound(); } else if (paintScaleStyle.contains("red")) { scale = getRedScaleUpperBound(); } else if (paintScaleStyle.contains("green")) { scale = getGreenScaleUpperBound(); } else if (paintScaleStyle.contains("yellow")) { scale = getYellowScaleUpperBound(); } else if (paintScaleStyle.contains("cyan")) { scale = getCyanScaleUpperBound(); } } // no bound else { if (paintScaleStyle.contains("Rainbow")) { scale = getFullRainBowScale(); } else if (paintScaleStyle.contains("red")) { scale = getRedScale(); } else if (paintScaleStyle.contains("green")) { scale = getGreenScale(); } else if (paintScaleStyle.contains("yellow")) { scale = getYellowScale(); } else if (paintScaleStyle.contains("cyan")) { scale = getCyanScale(); } } return scale; } /* * returns an array with rainbow colors */ public static Paint[] getFullRainBowScale() { int ncolor = 360; Color[] readRainbow = new Color[ncolor]; Color[] rainbow = new Color[ncolor]; float x = (float) (1. / (ncolor + 160)); for (int i = 0; i < rainbow.length; i++) { readRainbow[i] = new Color(Color.HSBtoRGB((i) * x, 1.0F, 1.0F)); } for (int i = 0; i < rainbow.length; i++) { rainbow[i] = readRainbow[readRainbow.length - i - 1]; } return rainbow; } /* * returns an array with rainbow colors with black as lower bound and magenta as upper bound */ public static Paint[] getFullRainBowScaleLowerUpperBound() { int ncolor = 360; Color[] readRainbow = new Color[ncolor]; Color[] rainbow = new Color[ncolor + 10]; float x = (float) (1. / (ncolor + 160)); for (int i = 0; i < readRainbow.length; i++) { readRainbow[i] = new Color(Color.HSBtoRGB((i) * x, 1.0F, 1.0F)); } for (int i = 0; i < 5; i++) { rainbow[i] = new Color(0, 0, 0); } for (int i = 5; i < readRainbow.length - 5; i++) { rainbow[i] = readRainbow[readRainbow.length - i - 1]; } for (int i = rainbow.length - 5; i < rainbow.length; i++) { rainbow[i] = new Color(244, 66, 223); } return rainbow; } /* * returns an array with rainbow colors with black as lower bound */ public static Paint[] getFullRainBowScaleLowerBound() { int ncolor = 360; Color[] readRainbow = new Color[ncolor]; Color[] rainbow = new Color[ncolor + 5]; float x = (float) (1. / (ncolor + 160)); for (int i = 0; i < readRainbow.length; i++) { readRainbow[i] = new Color(Color.HSBtoRGB((i) * x, 1.0F, 1.0F)); } for (int i = 0; i < 5; i++) { rainbow[i] = new Color(0, 0, 0); } for (int i = 5; i < readRainbow.length; i++) { rainbow[i] = readRainbow[readRainbow.length - i - 1]; } return rainbow; } /* * returns an array with rainbow colors with magenta as upper bound */ public static Paint[] getFullRainBowScaleUpperBound() { int ncolor = 360; Color[] readRainbow = new Color[ncolor]; Color[] rainbow = new Color[ncolor + 5]; float x = (float) (1. / (ncolor + 160)); for (int i = 0; i < readRainbow.length; i++) { readRainbow[i] = new Color(Color.HSBtoRGB((i) * x, 1.0F, 1.0F)); } for (int i = 0; i < readRainbow.length - 5; i++) { rainbow[i] = readRainbow[readRainbow.length - i - 1]; } for (int i = rainbow.length - 5; i < rainbow.length; i++) { rainbow[i] = new Color(244, 66, 223); } return rainbow; } /* * returns an array with red colors */ public static Paint[] getRedScale() { int ncolor = 190; Color[] redScale = new Color[ncolor]; for (int i = 0; i < redScale.length; i++) { redScale[i] = new Color(255, redScale.length - i - 1, redScale.length - i - 1); } return redScale; } /* * returns an array with red colors with black as lower bound and magenta as upper bound */ public static Paint[] getRedScaleLowerUpperBound() { int ncolor = 190; Color[] redScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { redScale[i] = new Color(0, 0, 0); } for (int i = 5; i < redScale.length - 5; i++) { redScale[i] = new Color(255, redScale.length - i - 1, redScale.length - i - 1); } for (int i = redScale.length - 5; i < redScale.length; i++) { redScale[i] = new Color(244, 66, 223); } return redScale; } /* * returns an array with red colors with black as lower bound */ public static Paint[] getRedScaleLowerBound() { int ncolor = 190; Color[] redScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { redScale[i] = new Color(0, 0, 0); } for (int i = 5; i < redScale.length - 5; i++) { redScale[i] = new Color(255, redScale.length - i - 1, redScale.length - i - 1); } return redScale; } /* * returns an array with red colors magenta as upper bound */ public static Paint[] getRedScaleUpperBound() { int ncolor = 190; Color[] redScale = new Color[ncolor]; for (int i = 0; i < redScale.length - 5; i++) { redScale[i] = new Color(255, redScale.length - i - 1, redScale.length - i - 1); } for (int i = redScale.length - 5; i < redScale.length; i++) { redScale[i] = new Color(244, 66, 223); } return redScale; } /* * returns an array with green colors */ public static Paint[] getGreenScale() { int ncolor = 190; Color[] greenScale = new Color[ncolor]; for (int i = 0; i < greenScale.length; i++) { greenScale[i] = new Color(greenScale.length - i - 1, 255, greenScale.length - i - 1); } return greenScale; } /* * returns an array with green colors with black as lower bound and magenta as upper bound */ public static Paint[] getGreenScaleLowerUpperBound() { int ncolor = 190; Color[] greenScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { greenScale[i] = new Color(0, 0, 0); } for (int i = 5; i < greenScale.length - 5; i++) { greenScale[i] = new Color(greenScale.length - i - 1, 255, greenScale.length - i - 1); } for (int i = greenScale.length - 5; i < greenScale.length; i++) { greenScale[i] = new Color(244, 66, 223); } return greenScale; } /* * returns an array with red colors with black as lower bound */ public static Paint[] getGreenScaleLowerBound() { int ncolor = 190; Color[] greenScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { greenScale[i] = new Color(0, 0, 0); } for (int i = 5; i < greenScale.length - 5; i++) { greenScale[i] = new Color(greenScale.length - i - 1, 255, greenScale.length - i - 1); } return greenScale; } /* * returns an array with red colors magenta as upper bound */ public static Paint[] getGreenScaleUpperBound() { int ncolor = 190; Color[] greenScale = new Color[ncolor]; for (int i = 0; i < greenScale.length - 5; i++) { greenScale[i] = new Color(greenScale.length - i - 1, 255, greenScale.length - i - 1); } for (int i = greenScale.length - 5; i < greenScale.length; i++) { greenScale[i] = new Color(244, 66, 223); } return greenScale; } /* * returns an array with yellow colors */ public static Paint[] getYellowScale() { int ncolor = 190; Color[] yellowScale = new Color[ncolor]; for (int i = 0; i < yellowScale.length; i++) { yellowScale[i] = new Color(255, 255, yellowScale.length - i - 1); } return yellowScale; } /* * returns an array with yellow colors with black as lower bound and magenta as upper bound */ public static Paint[] getYellowScaleLowerUpperBound() { int ncolor = 190; Color[] yellowScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { yellowScale[i] = new Color(0, 0, 0); } for (int i = 5; i < yellowScale.length - 5; i++) { yellowScale[i] = new Color(255, 255, yellowScale.length - i - 1); } for (int i = yellowScale.length - 5; i < yellowScale.length; i++) { yellowScale[i] = new Color(244, 66, 223); } return yellowScale; } /* * returns an array with yellow colors with black as lower bound */ public static Paint[] getYellowScaleLowerBound() { int ncolor = 190; Color[] yellowScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { yellowScale[i] = new Color(0, 0, 0); } for (int i = 5; i < yellowScale.length - 5; i++) { yellowScale[i] = new Color(255, 255, yellowScale.length - i - 1); } return yellowScale; } /* * returns an array with yellow colors with magenta as upper bound */ public static Paint[] getYellowScaleUpperBound() { int ncolor = 190; Color[] yellowScale = new Color[ncolor]; for (int i = 0; i < yellowScale.length - 5; i++) { yellowScale[i] = new Color(yellowScale.length - i - 1, yellowScale.length - i - 1, 255); } for (int i = yellowScale.length - 5; i < yellowScale.length; i++) { yellowScale[i] = new Color(244, 66, 223); } return yellowScale; } /* * returns an array with cyan colors */ public static Paint[] getCyanScale() { int ncolor = 190; Color[] cyanScale = new Color[ncolor]; for (int i = 0; i < cyanScale.length; i++) { cyanScale[i] = new Color(cyanScale.length - i - 1, 255, 255); } return cyanScale; } /* * returns an array with cyan colors with black as lower bound and magenta as upper bound */ public static Paint[] getCyanScaleLowerUpperBound() { int ncolor = 190; Color[] cyanScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { cyanScale[i] = new Color(0, 0, 0); } for (int i = 5; i < cyanScale.length - 5; i++) { cyanScale[i] = new Color(cyanScale.length - i - 1, 255, 255); } for (int i = cyanScale.length - 5; i < cyanScale.length; i++) { cyanScale[i] = new Color(244, 66, 223); } return cyanScale; } /* * returns an array with yellow colors with black as lower bound */ public static Paint[] getCyanScaleLowerBound() { int ncolor = 190; Color[] cyanScale = new Color[ncolor]; for (int i = 0; i < 5; i++) { cyanScale[i] = new Color(0, 0, 0); } for (int i = 5; i < cyanScale.length - 5; i++) { cyanScale[i] = new Color(cyanScale.length - i - 1, 255, 255); } return cyanScale; } /* * returns an array with yellow colors with magenta as upper bound */ public static Paint[] getCyanScaleUpperBound() { int ncolor = 190; Color[] cyanScale = new Color[ncolor]; for (int i = 0; i < cyanScale.length - 5; i++) { cyanScale[i] = new Color(cyanScale.length - i - 1, 255, 255); } for (int i = cyanScale.length - 5; i < cyanScale.length; i++) { cyanScale[i] = new Color(244, 66, 223); } return cyanScale; } }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-arq/src/main/java/com/hp/hpl/jena/sparql/sse/ItemTransformer.java
2677
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.hpl.jena.sparql.sse; import java.util.ArrayDeque ; import java.util.Deque ; import com.hp.hpl.jena.graph.Node ; public class ItemTransformer { public static Item transform(ItemTransform transform, Item item) { TransformerApply v = new TransformerApply(transform) ; item.visit(v) ; return v.result() ; } // Is it worth being an ItemVisitor? // Why not directly dispatch - and make the "visit" operation return a result static class TransformerApply implements ItemVisitor { Deque<Item> stack = new ArrayDeque<Item>() ; private void push(Item item) { stack.push(item) ; } private Item pop() { return stack.pop() ; } private ItemTransform transform ; public TransformerApply(ItemTransform transform) { this.transform = transform ; } public Item result() { return stack.peek() ; } @Override public void visit(Item item, ItemList list) { ItemList newList = new ItemList(item.getLine(), item.getColumn()) ; for ( Item subItem : list ) { subItem.visit(this) ; Item newItem = pop(); newList.add(newItem) ; } Item newItemList = Item.createList(newList, item.getLine(), item.getColumn()) ; push(newItemList) ; } @Override public void visit(Item item, Node node) { Item newItem = transform.transform(item, node) ; push(newItem) ; } @Override public void visit(Item item, String symbol) { Item newItem = transform.transform(item, symbol) ; push(newItem) ; } @Override public void visitNil() { push(Item.nil) ; } } }
gpl-2.0
deathspeeder/class-guard
spring-framework-3.2.x/spring-core/src/main/java/org/springframework/core/io/support/EncodedResource.java
4627
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.io.support; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Holder that combines a {@link org.springframework.core.io.Resource} * with a specific encoding to be used for reading from the resource. * * <p>Used as argument for operations that support to read content with * a specific encoding (usually through a {@code java.io.Reader}. * * @author Juergen Hoeller * @since 1.2.6 * @see java.io.Reader */ public class EncodedResource { private final Resource resource; private String encoding; private Charset charset; /** * Create a new EncodedResource for the given Resource, * not specifying a specific encoding. * @param resource the Resource to hold */ public EncodedResource(Resource resource) { Assert.notNull(resource, "Resource must not be null"); this.resource = resource; } /** * Create a new EncodedResource for the given Resource, * using the specified encoding. * @param resource the Resource to hold * @param encoding the encoding to use for reading from the resource */ public EncodedResource(Resource resource, String encoding) { Assert.notNull(resource, "Resource must not be null"); this.resource = resource; this.encoding = encoding; } /** * Create a new EncodedResource for the given Resource, * using the specified encoding. * @param resource the Resource to hold * @param charset the charset to use for reading from the resource */ public EncodedResource(Resource resource, Charset charset) { Assert.notNull(resource, "Resource must not be null"); this.resource = resource; this.charset = charset; } /** * Return the Resource held. */ public final Resource getResource() { return this.resource; } /** * Return the encoding to use for reading from the resource, * or {@code null} if none specified. */ public final String getEncoding() { return this.encoding; } /** * Return the charset to use for reading from the resource, * or {@code null} if none specified. */ public final Charset getCharset() { return this.charset; } /** * Determine whether a {@link Reader} is required as opposed to an {@link InputStream}, * i.e. whether an encoding or a charset has been specified. * @see #getReader() * @see #getInputStream() */ public boolean requiresReader() { return (this.encoding != null || this.charset != null); } /** * Open a {@code java.io.Reader} for the specified resource, * using the specified encoding (if any). * @throws IOException if opening the Reader failed * @see #requiresReader() */ public Reader getReader() throws IOException { if (this.charset != null) { return new InputStreamReader(this.resource.getInputStream(), this.charset); } else if (this.encoding != null) { return new InputStreamReader(this.resource.getInputStream(), this.encoding); } else { return new InputStreamReader(this.resource.getInputStream()); } } /** * Open an {@code java.io.InputStream} for the specified resource, * typically assuming that there is no specific encoding to use. * @throws IOException if opening the InputStream failed * @see #requiresReader() */ public InputStream getInputStream() throws IOException { return this.resource.getInputStream(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof EncodedResource) { EncodedResource otherRes = (EncodedResource) obj; return (this.resource.equals(otherRes.resource) && ObjectUtils.nullSafeEquals(this.encoding, otherRes.encoding)); } return false; } @Override public int hashCode() { return this.resource.hashCode(); } @Override public String toString() { return this.resource.toString(); } }
gpl-2.0
JogleLew/Checklist
src/com/Joglestudio/Checklist/AddItemActivity.java
15512
package com.Joglestudio.Checklist; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.*; import org.apache.http.util.EncodingUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * Created by jogle on 14/10/7. */ public class AddItemActivity extends Activity { private DataModel data = new DataModel(); public static final String theme[] = {"深色主题","浅色主题"}; private int pos; private int themeNum; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.additemmain); changeTheme(); Intent toEditIntent = getIntent(); int i = toEditIntent.getIntExtra("position", -1); pos = i; String s; if (!isFileExists("editing" + i + ".dat")) writeFileData("editing" + i + ".dat", "\n0 0 0 0 0\n1\nfalse"); s = readFileData("editing" + i + ".dat"); data = DataModel.getUnpackedData(s); final TextView editText = (TextView) findViewById(R.id.edittext1); editText.setText(data.getItemName()); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { data.setItemName(editText.getText().toString()); String s = DataModel.getPackedString(data); writeFileData("editing" + pos + ".dat", s); } }); TextView editTime = (TextView) findViewById(R.id.edittime1); if (data.getYear() != 0 && data.getMinute() >= 10) editTime.setText(data.getYear() + "年" + data.getMonth() + "月" + data.getDay() + "日\n" + data.getHour() + "点" + data.getMinute() + "分"); if (data.getYear() != 0 && data.getMinute() < 10) editTime.setText(data.getYear() + "年" + data.getMonth() + "月" + data.getDay() + "日\n" + data.getHour() + "点0" + data.getMinute() + "分"); themeNum = Integer.parseInt(readFileData("theme.dat")); ImageView image = (ImageView) findViewById(R.id.imagedisplay); if (themeNum == 0) { switch (data.getImagePicked()) { case 1: image.setImageResource(R.drawable.w1); break; case 2: image.setImageResource(R.drawable.w2); break; case 3: image.setImageResource(R.drawable.w3); break; case 4: image.setImageResource(R.drawable.w4); break; case 5: image.setImageResource(R.drawable.w5); break; case 6: image.setImageResource(R.drawable.w6); break; case 7: image.setImageResource(R.drawable.w7); break; case 8: image.setImageResource(R.drawable.w8); break; case 9: image.setImageResource(R.drawable.w9); break; case 10: image.setImageResource(R.drawable.w10); break; default: image.setImageResource(R.drawable.w1); break; } } else if (themeNum == 1){ switch (data.getImagePicked()) { case 1: image.setImageResource(R.drawable.w1); break; case 2: image.setImageResource(R.drawable.b2); break; case 3: image.setImageResource(R.drawable.b3); break; case 4: image.setImageResource(R.drawable.b4); break; case 5: image.setImageResource(R.drawable.b5); break; case 6: image.setImageResource(R.drawable.b6); break; case 7: image.setImageResource(R.drawable.b7); break; case 8: image.setImageResource(R.drawable.b8); break; case 9: image.setImageResource(R.drawable.b9); break; case 10: image.setImageResource(R.drawable.b10); break; default: image.setImageResource(R.drawable.w1); break; } } Button backButton = (Button) findViewById(R.id.backtomain); backButton.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ Intent backToMainIntent = new Intent(); backToMainIntent.setClass(AddItemActivity.this, ItemListActivity.class); deleteTheFile("editing" + pos + ".dat"); startActivity(backToMainIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); } }); Button sureButton = (Button) findViewById(R.id.sureaddgroup); sureButton.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ if (data.getYear() == 0){ new AlertDialog.Builder(AddItemActivity.this) .setTitle("备忘录") .setMessage("请设置时间。") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } else { Intent sureIntent = new Intent(); sureIntent.setClass(AddItemActivity.this, ItemListActivity.class); TextView itemName = (TextView) findViewById(R.id.edittext1); data.setItemName(itemName.getText().toString()); String s = DataModel.getPackedString(data); writeFileData("editing" + pos + ".dat", s); deleteFile(pos + ".dat"); renameFile("editing" + pos + ".dat", pos + ".dat"); writeFileData("count.dat", (pos + 1) + ""); startActivity(sureIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); } } }); Button chooseTimeButton = (Button) findViewById(R.id.choosetime); chooseTimeButton.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ Intent chooseTimeIntent = new Intent(); chooseTimeIntent.setClass(AddItemActivity.this, TimePickForAddActivity.class); TextView itemName = (TextView) findViewById(R.id.edittext1); data.setItemName(itemName.getText().toString()); String s = DataModel.getPackedString(data); writeFileData("editing" + pos + ".dat", s); chooseTimeIntent.putExtra("position", pos); startActivity(chooseTimeIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); } }); Button chooseImageButton = (Button) findViewById(R.id.chooseimage); chooseImageButton.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ Intent chooseImageIntent = new Intent(); chooseImageIntent.setClass(AddItemActivity.this, ImagePickForAddActivity.class); TextView itemName = (TextView) findViewById(R.id.edittext1); data.setItemName(itemName.getText().toString()); String s = DataModel.getPackedString(data); writeFileData("editing" + pos + ".dat", s); chooseImageIntent.putExtra("position", pos); startActivity(chooseImageIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); } }); } private void writeFileData(String fileName,String message){ try{ FileOutputStream fout = openFileOutput(fileName, Context.MODE_PRIVATE); byte [] bytes = message.getBytes(); fout.write(bytes); fout.close(); } catch(Exception e){ e.printStackTrace(); } } private String readFileData(String fileName){ String res=""; try{ FileInputStream fin = openFileInput(fileName); int length = fin.available(); byte [] buffer = new byte[length]; fin.read(buffer); res = EncodingUtils.getString(buffer, "UTF-8"); fin.close(); } catch (IOException e) { e.printStackTrace(); } return res; } private boolean isFileExists(String fileName){ String s = this.getFilesDir().getPath()+"/"+fileName; File file = new File(s); return file.exists(); } private void deleteTheFile(String fileName){ String s = this.getFilesDir().getPath()+"/"+fileName; File file = new File(s); file.delete(); } private void renameFile(String fileName, String newName){ String s = this.getFilesDir().getPath()+"/"+fileName; String news = this.getFilesDir().getPath()+"/"+newName; File file = new File(s); File newfile = new File(news); file.renameTo(newfile); } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Intent backToMainIntent = new Intent(); backToMainIntent.setClass(AddItemActivity.this, ItemListActivity.class); deleteTheFile("editing" + pos + ".dat"); startActivity(backToMainIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); break; case KeyEvent.KEYCODE_MENU: showMenu(); break; } return super.onKeyDown(keyCode, event); } private void showMenu(){ new AlertDialog.Builder(AddItemActivity.this) .setTitle("设定") .setItems(ItemListActivity.menu, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { if (i == 0){ showThemePicker(); } else if (i == 1) showInfo(); } }) .show(); } private void showThemePicker(){ new AlertDialog.Builder(this) .setTitle("选择主题") .setItems(theme, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { writeFileData("theme.dat", i + ""); Intent themeIntent = new Intent(); themeIntent.setClass(AddItemActivity.this, AddItemActivity.class); themeIntent.putExtra("position", pos); startActivity(themeIntent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); AddItemActivity.this.finish(); } }) .show(); } public void showInfo(){ new AlertDialog.Builder(this) .setTitle("备忘录") .setMessage("作者:吕佳高\n\n" + "简介:一款实用的备忘录软件,方便记录自己需要做的事情和勾选已经完成的事件。\n\n" + "使用说明:短按以勾选或取消勾选,长按以编辑和删除项目\n\n" + "版本:1.0") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } private void changeTheme(){ themeNum = Integer.parseInt(readFileData("theme.dat")); if (themeNum == 1) { RelativeLayout titleBar1 = (RelativeLayout) findViewById(R.id.titlebar2); titleBar1.setBackgroundColor(0xFFFFFFFF); Button addButton = (Button) findViewById(R.id.sureaddgroup); addButton.setTextColor(0xFF27C7FF); Button backButton = (Button) findViewById(R.id.backtomain); backButton.setTextColor(0xFF27C7FF); TextView title = (TextView) findViewById(R.id.title2); title.setTextColor(0xFF000000); TextView subtitle = (TextView) findViewById(R.id.subtitle2); subtitle.setTextColor(0xFF000000); LinearLayout addItemLayout = (LinearLayout) findViewById(R.id.additemlayout); addItemLayout.setBackgroundColor(0xFFFFFFFF); TextView textName1 = (TextView) findViewById(R.id.textname1); textName1.setTextColor(0xFF000000); EditText editText = (EditText) findViewById(R.id.edittext1); editText.setTextColor(0xFF000000); TextView textName2 = (TextView) findViewById(R.id.textname2); textName2.setTextColor(0xFF000000); TextView editTime1 = (TextView) findViewById(R.id.edittime1); editTime1.setTextColor(0xFF000000); Button chooseTime = (Button) findViewById(R.id.choosetime); chooseTime.setTextColor(0xFF27C7FF); chooseTime.setBackgroundColor(0x00FFFFFF); TextView textView2 = (TextView) findViewById(R.id.textView2); textView2.setTextColor(0xFF000000); Button chooseImage = (Button) findViewById(R.id.chooseimage); chooseImage.setTextColor(0xFF27C7FF); chooseImage.setBackgroundColor(0x00FFFFFF); } } }
gpl-2.0
TLmaK0/avl-crrcsim-editor
src/main/java/com/abajar/crrcsimeditor/crrcsim/MassInertia.java
3064
/* * Copyright (C) 2015 Hugo Freire Gil * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * */ package com.abajar.crrcsimeditor.crrcsim; import com.abajar.crrcsimeditor.view.annotations.CRRCSimEditorField; import java.io.Serializable; import javax.xml.bind.annotation.XmlAttribute; /** * * @author Hugo */ public class MassInertia implements Serializable { private String version = "1"; private String units = "1"; @Override public String toString() { return "mass"; } @CRRCSimEditorField(text="mass", help="total aireplane mass" ) private float Mass; @CRRCSimEditorField(text="I_xx", help="Moment of Inertia xx" ) private float I_xx; @CRRCSimEditorField(text="I_yy", help="Moment of Inertia yy" ) private float I_yy; @CRRCSimEditorField(text="I_zz", help="Moment of Inertia zz" ) private float I_zz; @CRRCSimEditorField(text="I_xz", help="Product of Inertia xz" ) private float I_xz; public MassInertia() { } /** * @return the version */ @XmlAttribute(name="version") public String getVersion() { return version; } /** * @param version the version to set */ public void setVersion(String version) { this.version = version; } /** * @return the units */ @XmlAttribute(name="units") public String getUnits() { return units; } /** * @param units the units to set */ public void setUnits(String units) { this.units = units; } /** * @return the Mass */ @XmlAttribute(name="Mass") public float getMass() { return Mass; } /** * @param Mass the Mass to set */ public void setMass(float Mass) { this.Mass = Mass; } /** * @return the I_xx */ @XmlAttribute(name="I_xx") public float getI_xx() { return I_xx; } /** * @param I_xx the I_xx to set */ public void setI_xx(float I_xx) { this.I_xx = I_xx; } /** * @return the I_yy */ @XmlAttribute(name="I_yy") public float getI_yy() { return I_yy; } /** * @param I_yy the I_yy to set */ public void setI_yy(float I_yy) { this.I_yy = I_yy; } /** * @return the I_zz */ @XmlAttribute(name="I_zz") public float getI_zz() { return I_zz; } /** * @param I_zz the I_zz to set */ public void setI_zz(float I_zz) { this.I_zz = I_zz; } /** * @return the I_xz */ @XmlAttribute(name="I_xz") public float getI_xz() { return I_xz; } /** * @param I_xz the I_xz to set */ public void setI_xz(float I_xz) { this.I_xz = I_xz; } }
gpl-2.0
jorgegalvez/funeralesmodernos
FunerariaEAR/FunerariaWAR/src/java/sv/com/fm/web/ui/catalogos/GestorMejorasCtrl.java
12059
/* * ESTE COMPONENTE FUE REALIZADO BAJO LA METODOLOGÍA DE DESARROLLO * DE FUNERALES MODERNOS Y SE ENCUENTRA PROTEGIDO * POR LAS LEYES DE DERECHOS DE AUTOR. * @author Jorge Galvez * Funerales Modernos 2015 */ package sv.com.fm.web.ui.catalogos; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zul.Button; import org.zkoss.zul.FieldComparator; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listheader; import org.zkoss.zul.Listitem; import org.zkoss.zul.Messagebox; import org.zkoss.zul.Window; import sv.com.fm.business.dto.GenericResponse; import sv.com.fm.business.ejb.GestorCatalogosBeanLocal; import sv.com.fm.business.entity.Mejoras; import sv.com.fm.business.exception.FmBusinessException; import sv.com.fm.business.exception.FmBusinessRolledbackException; import sv.com.fm.business.exception.FmWebException; import sv.com.fm.business.exception.ServiceLocatorException; import sv.com.fm.business.util.Constants; import sv.com.fm.business.util.ServiceLocator; import sv.com.fm.web.ui.catalogos.rendered.MejorasItemRendered; import sv.com.fm.web.ui.util.BaseController; import sv.com.fm.web.ui.util.MensajeMultilinea; /** * * @author Jorge Galvez */ public class GestorMejorasCtrl extends BaseController{ //Componentes de Negocio private static final long serialVersionUID = -6102616129515843465L; private static final transient Logger logger = Logger.getLogger(GestorMejorasCtrl.class.getCanonicalName()); private ServiceLocator serviceLocator; private GestorCatalogosBeanLocal catalogosBean; private List<Mejoras> listaMejoras; private Mejoras mejorasSelected; private GenericResponse respuesta; //Componentes ZUL protected Window listaMejorasWindow; protected Button btnAgregarMejoras; protected Button btnRefrescarMejoras; protected Button btnBuscarMejoras; protected Listbox lstBoxMejoras; protected Listheader lhCodigoMejoras; protected Listheader lhDescripcionMejoras; protected Listheader lhFechaActualizacionMejoras; protected Listheader lhAcciones; /** * Metodo Constructor de la clase */ public GestorMejorasCtrl() { logger.log(Level.INFO, "[GestorMejorasCtrl]INIT"); try { serviceLocator = ServiceLocator.getInstance(); catalogosBean = serviceLocator.getService(Constants.JNDI_CATALOGOS_BEAN); } catch (ServiceLocatorException ex) { logger.log(Level.SEVERE, ex.getLocalizedMessage()); ex.printStackTrace(); } } /** * Metodo que ejecuta la ejecución de la ventana * * @param event * @throws Exception */ public void onCreate$listaMejorasWindow(Event event) throws Exception { logger.log(Level.INFO, "[GestorMejorasCtrl][onCreate$listaMejorasWindow]"); try { doOnCreateCommon(this.listaMejorasWindow, event); MensajeMultilinea.doSetTemplate(); loadDatos(Constants.CARGA_BASE_NOMBRE); setOrderByListHeader(); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage()); e.printStackTrace(); } } /** * Método que permite la carga de los datos registrado en el catalogo */ public void loadDatos(Integer tipoCarga) { logger.log(Level.INFO, "[GestorMejorasCtrl][loadDatos]"); try { listaMejoras = catalogosBean.cargarMejoras(tipoCarga); if (listaMejoras == null) { listaMejoras = new ArrayList<Mejoras>(); } lstBoxMejoras.setModel(new ListModelList(listaMejoras)); lstBoxMejoras.setItemRenderer(new MejorasItemRendered()); } catch (FmBusinessException rbe) { logger.log(Level.SEVERE, rbe.getLocalizedMessage()); rbe.printStackTrace(); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage()); e.printStackTrace(); } } /** * Método que permite refrescar la lista a demanda normalmente es utilizado * despues de una busqueda y se requiera volver la lista a su estado inicial * * @param event */ public void onClick$btnRefrescarMejoras(Event event) { logger.info("[GestorMejorasCtrl][onClick$btnRefrescarMejoras]"); try { loadDatos(Constants.CARGA_BASE_NOMBRE); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage()); e.printStackTrace(); } } /** * Método del botón que permite mostrar el formulario para agregar un nuevo * registro al catalogo * * @param event */ public void onClick$btnAgregarMejoras(Event event) { logger.log(Level.INFO, "[GestorMejorasCtrl][onClick$btnAgregarMejoras]"); try { HashMap map = new HashMap(); map.put("gestorMejorasCtrl", this); map.put("accion", Constants.ACCION_MANTTO_NEW); Executions.createComponents("/WEB-INF/xhtml/mantenimientos/mejorasCRUD/mejorasMtto.zul", null, map); } catch (Exception e) { e.printStackTrace(); MensajeMultilinea.show("Se mostró una excepción al crear componente!!", Constants.MENSAJE_TIPO_ALERTA); } } /** * Método del botón que permite mostrar el formulario para realizar una * búsqueda en el cátalogo * * @param event */ public void onClick$btnBuscarMejoras(Event event) { logger.log(Level.INFO, "[GestorMejorasCtrl][onClick$btnBuscarMejoras]"); try { HashMap map = new HashMap(); map.put("gestorMejorasCtrl", this); Executions.createComponents("/WEB-INF/xhtml/mantenimientos/mejorasCRUD/mejorasBusqueda.zul", null, map); } catch (Exception e) { e.printStackTrace(); MensajeMultilinea.show("Se mostró una excepción al crear componente!!", Constants.MENSAJE_TIPO_ALERTA); } } /** * Método del botón que permite eliminar un registro * * @param event */ public void onEliminarMejorasClicked(Event event) { logger.log(Level.INFO, "[GestorMejorasCtrl][onEliminarMejorasClicked]"); try { if (event instanceof org.zkoss.zk.ui.event.ForwardEvent) { ForwardEvent ev = (ForwardEvent) event; Button btn = (Button) ev.getOrigin().getTarget(); Listitem item = (Listitem) btn.getAttribute("data"); if (item != null) { mejorasSelected = (Mejoras) item.getAttribute("data"); if (mejorasSelected != null) { MensajeMultilinea.show("¿Está seguro que desea eliminar esta Mejora?", Constants.MENSAJE_TIPO_INTERRROGACION, new EventListener() { public void onEvent(Event evt) throws FmWebException { Integer selected = (((Integer) evt.getData()).intValue()); if (selected == Messagebox.OK) { try { respuesta = catalogosBean.eliminarRegistro(mejorasSelected); if (respuesta.getCodigoRespuesta() == Constants.CODE_OPERATION_OK) { MensajeMultilinea.show(respuesta.getMensajeRespuesta(), Constants.MENSAJE_TIPO_INFO); loadDatos(Constants.CARGA_BASE_NOMBRE); } else { MensajeMultilinea.show(respuesta.getMensajeRespuesta(), Constants.MENSAJE_TIPO_ERROR); } } catch (Exception ex) { logger.log(Level.SEVERE, ex.getLocalizedMessage()); ex.printStackTrace(); } } else if (selected == Messagebox.CANCEL) { //cancelar la eliminacion logger.log(Level.INFO, "[GestorMejorasCtrl][onEliminarMejorasClicked] cancelo la acción"); } } }); } } else { logger.log(Level.SEVERE, "[onEliminarMejorasClicked]No se ha seleccionado un registro"); } } } catch (FmBusinessRolledbackException rbe) { logger.log(Level.SEVERE, rbe.getLocalizedMessage()); rbe.printStackTrace(); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage()); e.printStackTrace(); } } /** * Método para ordenar registros por columna seleccionada */ private void setOrderByListHeader() { try { lhCodigoMejoras.setSortAscending(new FieldComparator("codigoMejoras", true)); lhCodigoMejoras.setSortDescending(new FieldComparator("codigoMejoras", false)); lhDescripcionMejoras.setSortAscending(new FieldComparator("descripcionMejoras", true)); lhDescripcionMejoras.setSortDescending(new FieldComparator("descripcionMejoras", false)); lhFechaActualizacionMejoras.setSortAscending(new FieldComparator("fechaEvento", true)); lhFechaActualizacionMejoras.setSortDescending(new FieldComparator("fechaEvento", false)); } catch (Exception e) { e.printStackTrace(); } } /** * Método del botón que permite editar un registro * * @param event */ public void onEditarMejorasClicked(ForwardEvent event) { logger.log(Level.INFO, "[GestorMejorasCtrl][onEditarMejorasClicked]"); try { if (event instanceof ForwardEvent) { ForwardEvent ev = (ForwardEvent) event; Button btn = (Button) ev.getOrigin().getTarget(); Listitem item = (Listitem) btn.getAttribute("data"); if (item != null) { mejorasSelected = (Mejoras) item.getAttribute("data"); if (mejorasSelected != null) { HashMap map = new HashMap(); map.put("gestorMejorasCtrl", this); map.put("mejorasSelected", mejorasSelected); map.put("accion", Constants.ACCION_MANTTO_MODIFY); Executions.createComponents("/WEB-INF/xhtml/mantenimientos/mejorasCRUD/mejorasMtto.zul", null, map); } else { MensajeMultilinea.show("Seleccione un registro!!", Constants.MENSAJE_TIPO_ALERTA); } } } } catch (Exception e) { MensajeMultilinea.show("Ocurrió una excepción al crear componente!!", Constants.MENSAJE_TIPO_ERROR); e.printStackTrace(); } } public void mostrarDatosListbox() { logger.log(Level.INFO, "[GestorMejorasCtrl][mostrarDatosListbox]"); try { if (listaMejoras == null) { listaMejoras = new ArrayList<Mejoras>(); } lstBoxMejoras.setModel(new ListModelList(listaMejoras)); lstBoxMejoras.setItemRenderer(new MejorasItemRendered()); } catch (Exception e) { e.printStackTrace(); } } public List<Mejoras> getListaMejoras() { return listaMejoras; } public void setListaMejoras(List<Mejoras> listaMejoras) { this.listaMejoras = listaMejoras; } }
gpl-2.0
Norkart/NK-VirtualGlobe
Xj3D/src/java/org/web3d/vrml/renderer/j3d/nodes/enveffects/J3DBackground.java
26821
/***************************************************************************** * Web3d.org Copyright (c) 2001 * Java Source * * This source is licensed under the GNU LGPL v2.1 * Please read http://www.gnu.org/copyleft/lgpl.html for more information * * This software comes with the standard NO WARRANTY disclaimer for any * purpose. Use it at your own risk. If there's a problem you get to fix it. * ****************************************************************************/ package org.web3d.vrml.renderer.j3d.nodes.enveffects; // Standard imports import java.awt.image.*; import javax.media.j3d.*; import java.awt.Toolkit; import java.awt.Graphics; import java.awt.Color; import java.awt.Image; import java.awt.geom.AffineTransform; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import org.j3d.renderer.java3d.texture.J3DTextureCache; import org.j3d.renderer.java3d.texture.J3DTextureCacheFactory; import org.j3d.texture.TextureCacheFactory; import org.j3d.util.ImageUtils; // Application specific imports import org.web3d.vrml.lang.*; import org.web3d.util.ObjectArray; import org.web3d.vrml.nodes.VRMLNodeType; import org.web3d.vrml.nodes.VRMLUrlListener; import org.web3d.vrml.renderer.common.nodes.enveffects.BaseBackground; import org.web3d.vrml.renderer.j3d.nodes.J3DBackgroundNodeType; import org.web3d.vrml.renderer.j3d.nodes.J3DPathAwareNodeType; import org.web3d.vrml.renderer.j3d.nodes.J3DParentPathRequestHandler; /** * A node that can represents a VRML Background node. * <p> * * @author Justin Couch * @version $Revision: 1.11 $ */ public class J3DBackground extends BaseBackground implements J3DBackgroundNodeType, J3DPathAwareNodeType { /** Property describing the minification filter to use */ private static final String MINFILTER_PROP = "org.web3d.vrml.nodes.loader.minfilter"; /** Property describing the maxification filter to use */ private static final String MAGFILTER_PROP = "org.web3d.vrml.nodes.loader.maxfilter"; /** Property describing the rescalling method to use */ private static final String RESCALE_PROP = "org.web3d.vrml.nodes.loader.rescale"; /** The default filter to use for magnification. */ private static final int DEFAULT_MAGFILTER = Texture.NICEST; //private static final int DEFAULT_MAGFILTER = Texture.BASE_LEVEL_LINEAR; /** The value read from the system property for MAXFILTER */ /** The default filter to use for minification. */ private static final int DEFAULT_MINFILTER = Texture.NICEST; //private static final int DEFAULT_MINFILTER = Texture.BASE_LEVEL_LINEAR; /** The default rescale method */ private static final int DEFAULT_RESCALE = AffineTransformOp.TYPE_BILINEAR; /** The value read from the system property for MAXFILTER */ private static final int magfilter; /** The value read from the system property for MINFILTER */ private static final int minfilter; /** The value read from the system property for RESCALE */ private static final int rescale; /** J3D Implementation that we put the background geometry in */ private Group backgroundImpl; /** Textures for each side */ private Texture2D[] textureList; /** List of items that have changed since last frame */ private boolean[] textureChangeFlags; /** The Texture cache in use */ private J3DTextureCache cache; /** This is the current parent path pointer used to construct the path */ private J3DParentPathRequestHandler parentPathHandler; /** A listing of all path handlers registered */ private ObjectArray allParentPaths; // Temp arrays for copying stuff for the scene graph path private Object[] tmpPathArray; private Node[] tmpNodeArray; /** * Static initializer for setting up the system properties */ static { final HashMap minmagMap = new HashMap(8); minmagMap.put("NICEST", new Integer(Texture.NICEST)); minmagMap.put("FASTEST", new Integer(Texture.FASTEST)); minmagMap.put("BASE_LEVEL_POINT", new Integer(Texture.BASE_LEVEL_POINT)); minmagMap.put("BASE_LEVEL_LINEAR", new Integer(Texture.BASE_LEVEL_LINEAR)); minmagMap.put("LINEAR_SHARPEN", new Integer(Texture.LINEAR_SHARPEN)); minmagMap.put("LINEAR_SHARPEN_RGB", new Integer(Texture.LINEAR_SHARPEN_RGB)); minmagMap.put("LINEAR_SHARPEN_ALPHA", new Integer(Texture.LINEAR_SHARPEN_ALPHA)); minmagMap.put("FILTER4", new Integer(Texture.FILTER4)); final HashMap rescaleMap = new HashMap(2); rescaleMap.put("BILINEAR", new Integer(AffineTransformOp.TYPE_BILINEAR)); rescaleMap.put("NEAREST_NEIGHBOR", new Integer(AffineTransformOp.TYPE_NEAREST_NEIGHBOR)); int[] vars = (int[])AccessController.doPrivileged( new PrivilegedAction() { public Object run() { int[] ret_val = new int[3]; Integer i; String prop = System.getProperty(MINFILTER_PROP); if(prop != null) { i = (Integer)minmagMap.get(prop); ret_val[0] = (i != null) ? i.intValue() : DEFAULT_MINFILTER; } else ret_val[0] = DEFAULT_MINFILTER; prop = System.getProperty(MAGFILTER_PROP); if(prop != null) { i = (Integer)minmagMap.get(prop); ret_val[1] = (i != null) ? i.intValue() : DEFAULT_MAGFILTER; } else ret_val[1] = DEFAULT_MAGFILTER; prop = System.getProperty(RESCALE_PROP); if(prop != null) { i = (Integer)rescaleMap.get(prop); ret_val[2] = (i != null) ? i.intValue() : DEFAULT_RESCALE; } else ret_val[2] = DEFAULT_RESCALE; return ret_val; } } ); minfilter = vars[0]; magfilter = vars[1]; rescale = vars[2]; } /** * Create a new, default instance of this class. */ public J3DBackground() { super(); init(); } /** * Construct a new instance of this node based on the details from the * given node. * <P> * * @param node The node to copy * @throws IllegalArgumentException The node is not the right type. */ public J3DBackground(VRMLNodeType node) { super(node); init(); } //---------------------------------------------------------- // Methods required by the J3DBackgroundNodeType interface. //---------------------------------------------------------- /** * A check to see if the parent scene graph path has changed from last * time we checked for this node. Assumes that the call is being made on * a node that we checked on last frame. If this has been just changed with * a new binding call then the caller should just immediately request the * current path anyway. * * @return true if the parent path has changed since last frame */ public boolean hasScenePathChanged() { if(parentPathHandler == null) return true; else return parentPathHandler.hasParentPathChanged(); } /** * Fetch the scene graph path from the root of the scene to this node. * Typically used for the getLocalToVWorld transformation handling. If * the node returns null then there is no path to the root of the scene * ie this node is somehow orphaned during the last frame. * * @return The fully qualified path from the root to here or null */ public SceneGraphPath getSceneGraphPath() { if(parentPathHandler == null) { if(allParentPaths.size() == 0) return null; else parentPathHandler = (J3DParentPathRequestHandler)allParentPaths.get(0); } ObjectArray path_array = parentPathHandler.getParentPath(this); if(path_array == null) return null; int path_size = path_array.size(); if((tmpPathArray == null) || tmpPathArray.length < path_size) { tmpPathArray = new Object[path_size]; tmpNodeArray = new Node[path_size - 1]; } path_array.toArray(tmpPathArray); Locale locale = (Locale)tmpPathArray[0]; for(int i = 1; i < path_size; i++) tmpNodeArray[i - 1] = (Node)tmpPathArray[i]; return new SceneGraphPath(locale, tmpNodeArray, backgroundImpl); } /** * Get the list of textures defined for this background that have changed * since the last frame. The array contains the textures in the order * back, front, left, right, top, bottom. If the texture hasn't changed is no texture defined, then that array element is null. * * @param changes An array to copy in the flags of the individual textures * that have changed * @param textures The list of textures that have changed for this background. * @return true if anything changed since the last time */ public boolean getChangedTextures(Texture2D[] textures, boolean[] changes) { boolean ret_val = false; for(int i = 0; i < 6; i++) { changes[i] = textureChangeFlags[i]; if(textureChangeFlags[i]) { textures[i] = textureList[i]; ret_val = true; textureChangeFlags[i] = false; } } return ret_val; } /** * Get the list of textures defined for this background. The array contains * the textures in the order front, back, left, right, top, bottom. If * there is no texture defined, then that array element is null. * * @return The list of textures for this background. */ public Texture2D[] getBackgroundTextures() { return textureList; } //---------------------------------------------------------- // Methods from the J3DPathAwareNodeType interface. //---------------------------------------------------------- /** * Add a handler for the parent path requesting. If the request is made * more than once, extra copies should be added (for example a DEF and USE * of the same node in the same children field of a Group). * * @param h The new handler to add */ public void addParentPathListener(J3DParentPathRequestHandler h) { allParentPaths.add(h); } /** * Remove a handler for the parent path requesting. If there are multiple * copies of this handler registered, then the first one should be removed. * * @param h The new handler to add */ public void removeParentPathListener(J3DParentPathRequestHandler h) { allParentPaths.remove(h); if(parentPathHandler == h) parentPathHandler = null; } //---------------------------------------------------------- // Methods required by the VRMLMultiExternalNodeType interface. //---------------------------------------------------------- /** * Set the content of this node to the given object. The object is then * cast by the internal representation to the form it needs. This should * be one of the forms that the prefered class type call generates. * * @param mimetype The mime type of this object if known * @param content The content of the object * @throws IllegalArguementException The content object is not supported */ public void setContent(int index, String mimetype, Object content) throws IllegalArgumentException { if(content == null) return; // All of these are screwed currently because we don't know which URL was // the final one that got loaded. So we punt and use the first one. switch(index) { case FIELD_BACK_URL: if(!checkForCached(vfBackUrl, BACK)) { buildTexture(content, mimetype, BACK); cache.registerTexture(textureList[BACK], loadedUri[FIELD_BACK_URL]); } textureChangeFlags[BACK] = true; break; case FIELD_FRONT_URL: if(!checkForCached(vfFrontUrl, FRONT)) { buildTexture(content, mimetype, FRONT); cache.registerTexture(textureList[FRONT], loadedUri[FIELD_FRONT_URL]); } textureChangeFlags[FRONT] = true; break; case FIELD_LEFT_URL: if(!checkForCached(vfLeftUrl, LEFT)) { buildTexture(content, mimetype, LEFT); cache.registerTexture(textureList[LEFT], loadedUri[FIELD_LEFT_URL]); } textureChangeFlags[LEFT] = true; break; case FIELD_RIGHT_URL: if(!checkForCached(vfRightUrl, RIGHT)) { buildTexture(content, mimetype, RIGHT); cache.registerTexture(textureList[RIGHT], loadedUri[FIELD_RIGHT_URL]); } textureChangeFlags[RIGHT] = true; break; case FIELD_TOP_URL: if(!checkForCached(vfTopUrl, TOP)) { buildTexture(content, mimetype, TOP); cache.registerTexture(textureList[TOP], loadedUri[FIELD_TOP_URL]); } textureChangeFlags[TOP] = true; break; case FIELD_BOTTOM_URL: if(!checkForCached(vfBottomUrl, BOTTOM)) { buildTexture(content, mimetype, BOTTOM); cache.registerTexture(textureList[BOTTOM], loadedUri[FIELD_BOTTOM_URL]); } textureChangeFlags[BOTTOM] = true; break; } } //---------------------------------------------------------- // Methods required by the J3DVRMLNode interface. //---------------------------------------------------------- /** * Provide the set of mappings that override anything that the loader * might set. Default implementation does nothing. * <p> * * If the key is set, but the value is null or zero length, then all * capabilities on that node will be disabled. If the key is set the * values override all settings that the loader may wish to normally * make. This can be very dangerous if the loader is used for a file * format that includes its own internal animation engine, so be very * careful with this request. * * @param capBits The capability bits to be set * @param freqBits The frequency bits to be set */ public void setCapabilityOverrideMap(Map capBits, Map freqBits) { } /** * Set the mapping of capability bits that the user would like to * make sure is set. The end output is that the capabilities are the union * of what the loader wants and what the user wants. Default implementation * does nothing. * <p> * If the map contains a key, but the value is null or zero length, the * request is ignored. * * @param capBits The capability bits to be set * @param freqBits The frequency bits to be set */ public void setCapabilityRequiredMap(Map capBits, Map freqBits) { } /** * Get the Java3D scene graph object representation of this node. This will * need to be cast to the appropriate parent type when being used. * * @return The J3D representation. */ public SceneGraphObject getSceneGraphObject() { return backgroundImpl; } //---------------------------------------------------------- // Methods required by the VRMLNodeType interface. //---------------------------------------------------------- /** * Set the version of VRML that this node should represent. Different * versions have different capabilities, even within the same node. * * @param major The major version number of this scene * @param minor The minor version number of this scene * @param isStatic true if this node is under a static group and won't * change after the setup is finished */ public void setVersion(int major, int minor, boolean isStatic) { super.setVersion(major, minor, isStatic); if(isStatic) return; backgroundImpl.setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ); backgroundImpl.setCapability(BranchGroup.ALLOW_DETACH); } /** * Notification that the construction phase of this node has finished. * If the node would like to do any internal processing, such as setting * up geometry, then go for it now. */ public void setupFinished() { if(!inSetup) return; super.setupFinished(); checkForCached(vfBackUrl, BACK); checkForCached(vfFrontUrl, FRONT); checkForCached(vfLeftUrl, LEFT); checkForCached(vfRightUrl, RIGHT); checkForCached(vfTopUrl, TOP); checkForCached(vfBottomUrl, BOTTOM); } //---------------------------------------------------------- // Internal convenience methods //---------------------------------------------------------- /** * Internal initialization method used to construct the Java3D geometry. */ private void init() { allParentPaths = new ObjectArray(); backgroundImpl = new BranchGroup(); textureList = new Texture2D[6]; textureChangeFlags = new boolean[6]; cache = J3DTextureCacheFactory.getCache(TextureCacheFactory.WEAKREF_CACHE); } /** * Internal convenience method to check for a cached texture * * @param urls The list of URLs to check * @param int The index in the texture list to look at * @return true if a cached version was found */ private boolean checkForCached(String[] urls, int index) { boolean ret_val = false; if((urls != null) && (urls.length > 0)) { for(int i = 0; (i < urls.length) && !ret_val; i++) { if(cache.checkTexture(urls[i]) == true) { try { textureList[index] = (Texture2D)cache.fetchTexture(urls[i]); loadState[index] = LOAD_COMPLETE; ret_val = true; } catch(IOException io) { // ignore and reload } } } } return ret_val; } /** * Convenience method to take a pre-built Image object and turn it into a * texture. Also register it in the cache. * * @param content The content object to process * @param mime The mime type accompanying the object * @param index The texture index for the textureList */ private void buildTexture(Object content, String mime, int index) { BufferedImage img = null; boolean alpha = false; boolean premultAlpha = false; if(content instanceof BufferedImage) { img = (BufferedImage)content; // Hack for handling ImageLoader problems if(mime.equals("image/jpeg")) alpha = false; else if(mime.equals("image/png")) alpha = true; else if(mime.equals("image/gif")) alpha = false; else { System.out.println("Unknown type for BufferedImage, " + "assume alpa=false type:" + mime); alpha = false; } } else if(content instanceof ImageProducer) { img = ImageUtils.createBufferedImage((ImageProducer)content); // Determine Alpha ColorModel cm = img.getColorModel(); alpha = cm.hasAlpha(); premultAlpha = cm.isAlphaPremultiplied(); } else { System.out.println("Unknown content type: " + content + " for field " + getFieldDeclaration(index)); return; } if(premultAlpha) { System.out.println("J3DBackground: Unhandled case where " + "isAlphaPremultiplied = true"); } int texType; int format = ImageComponent2D.FORMAT_RGBA; switch(img.getType()) { case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_BYTE_BINARY: case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_RGB: format = ImageComponent2D.FORMAT_RGB; break; case BufferedImage.TYPE_CUSTOM: // no idea what this should be, so default to RGBA case BufferedImage.TYPE_INT_ARGB: case BufferedImage.TYPE_INT_ARGB_PRE: case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: format = ImageComponent2D.FORMAT_RGBA; break; case BufferedImage.TYPE_BYTE_GRAY: case BufferedImage.TYPE_USHORT_GRAY: format = ImageComponent2D.FORMAT_CHANNEL8; break; case BufferedImage.TYPE_BYTE_INDEXED: if(alpha) format = ImageComponent2D.FORMAT_RGBA; else format = ImageComponent2D.FORMAT_RGB; break; case BufferedImage.TYPE_USHORT_555_RGB: format = ImageComponent2D.FORMAT_RGB5; break; case BufferedImage.TYPE_USHORT_565_RGB: format = ImageComponent2D.FORMAT_RGB5; break; default: System.out.println("Unknown FORMAT for image: " + img); } int newWidth = nearestPowerTwo(img.getWidth()); int newHeight = nearestPowerTwo(img.getHeight()); img = scaleTexture(img, newWidth, newHeight); ImageComponent2D img_comp = null; try { img_comp = new ImageComponent2D(format, img, false, false); // These are needed for cacheing img_comp.setCapability(ImageComponent.ALLOW_FORMAT_READ); img_comp.setCapability(ImageComponent.ALLOW_SIZE_READ); } catch (Exception e) { System.out.println("Error creating background image: "); e.printStackTrace(); return; } textureList[index] = createTexture(img_comp, alpha); } /** * Given an image component setup the texture for this node. * @param */ private Texture2D createTexture(ImageComponent image, boolean alpha) { int tex_type = getTextureFormat(image); int width = image.getWidth(); int height = image.getHeight(); Texture2D texture = new Texture2D(Texture2D.BASE_LEVEL, tex_type, width, height); texture.setMinFilter(minfilter); texture.setMagFilter(magfilter); texture.setBoundaryModeS(Texture.CLAMP_TO_EDGE); texture.setBoundaryModeT(Texture.CLAMP_TO_EDGE); texture.setImage(0,image); texture.setCapability(Texture.ALLOW_IMAGE_READ); texture.setCapability(Texture.ALLOW_SIZE_READ); texture.setCapability(Texture.ALLOW_FORMAT_READ); return texture; } /** * Scale a texture. Generally used to scale a texture to a power of 2. * * @param bi The texture to scale * @param newWidth The new width * @param newHeight The new height */ private BufferedImage scaleTexture(BufferedImage bi, int newWidth, int newHeight) { int width = bi.getWidth(); int height = bi.getHeight(); if (width == newWidth && height == newHeight) return bi; System.out.println("Rescaling background to: " + newWidth + " x " + newHeight); double xScale = (float)newWidth / (float)width; double yScale = (float)newHeight / (float)height; AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale); AffineTransformOp atop = new AffineTransformOp(at,rescale); return atop.filter(bi, null); } /** * From the image component format, generate the appropriate texture * format. * * @param comp The image component to get the value from * @return The appropriate corresponding texture format value */ private int getTextureFormat(ImageComponent comp) { int ret_val = Texture.RGB; switch(comp.getFormat()) { case ImageComponent.FORMAT_CHANNEL8: // could also be alpha, but we'll punt for now. We really need // the user to pass in this information. Need to think of a // good way of doing this. ret_val = Texture.LUMINANCE; break; case ImageComponent.FORMAT_LUM4_ALPHA4: case ImageComponent.FORMAT_LUM8_ALPHA8: ret_val = Texture.LUMINANCE_ALPHA; break; case ImageComponent.FORMAT_R3_G3_B2: case ImageComponent.FORMAT_RGB: case ImageComponent.FORMAT_RGB4: case ImageComponent.FORMAT_RGB5: ret_val = Texture.RGB; break; case ImageComponent.FORMAT_RGB5_A1: // case ImageComponent.FORMAT_RGB8: case ImageComponent.FORMAT_RGBA: case ImageComponent.FORMAT_RGBA4: // case ImageComponent.FORMAT_RGBA8: ret_val = Texture.RGBA; break; } return ret_val; } /** * Determine the nearest power of two value for a given argument. * This function uses the formal ln(x) / ln(2) = log2(x) * * @return The power-of-two-ized value */ private int nearestPowerTwo(int val) { int log = (int) Math.ceil(Math.log(val) / Math.log(2)); return (int) Math.pow(2,log); } }
gpl-2.0
active-learning/active-learning-scala
src/main/java/clus/algo/rules/ClusRuleHeuristicSSD.java
4179
/************************************************************************* * Clus - Software for Predictive Clustering * * Copyright (C) 2007 * * Katholieke Universiteit Leuven, Leuven, Belgium * * Jozef Stefan Institute, Ljubljana, Slovenia * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. * *************************************************************************/ package clus.algo.rules; import clus.main.*; import clus.statistic.*; import clus.data.rows.*; import clus.data.type.ClusAttrType; import clus.heuristic.*; import clus.data.attweights.*; public class ClusRuleHeuristicSSD extends ClusHeuristic { protected RowData m_Data; protected String m_BasicDist; protected ClusStatistic m_NegStat; protected ClusAttributeWeights m_TargetWeights; protected ClusStatManager m_StatManager; // Copied from SSDHeuristic.java public ClusRuleHeuristicSSD(ClusStatManager statManager, String basicdist, ClusStatistic negstat, ClusAttributeWeights targetweights) { m_StatManager = statManager; m_BasicDist = basicdist; m_NegStat = negstat; m_TargetWeights = targetweights; } // Copied from SSDHeuristic.java public void setData(RowData data) { m_Data = data; } // Larger values are better! // Only the second parameter make sense for rules, i.e., statistic for covered examples public double calcHeuristic(ClusStatistic tstat, ClusStatistic pstat, ClusStatistic missing) { double n_pos = pstat.m_SumWeight; // Acceptable? if (n_pos < Settings.MINIMAL_WEIGHT) { return Double.NEGATIVE_INFINITY; } // Calculate value double offset = m_StatManager.getSettings().getHeurDispOffset(); double def_value = getTrainDataHeurValue(); //System.out.print("Inside calcHeuristic()"); //System.out.println(" - default SS: "+def_value); double value = pstat.getSVarS(m_TargetWeights, m_Data); //System.out.print("raw SS: "+value); // Normalization with the purpose of getting most of the single variances within the // [0,1] interval. This weight is in stdev units, // default value = 4 = (-2sigma,2sigma) should cover 95% of examples // This will only be important when combining different types of atts double norm = m_StatManager.getSettings().getVarBasedDispNormWeight(); value = 1 / (norm*norm) * (1 - value / def_value) + offset; // Normalized version of 'value = def_value -value + offset' //System.out.println(", combined disp. value: "+value); // Coverage part double train_sum_w = m_StatManager.getTrainSetStat(ClusAttrType.ATTR_USE_CLUSTERING).getTotalWeight(); double cov_par = m_StatManager.getSettings().getHeurCoveragePar(); value *= Math.pow(n_pos/train_sum_w, cov_par); //System.out.println(" cov: "+n_pos+"/"+train_sum_w+", final value: "+value); //+" -> -"+value); if (value < 1e-6) return Double.NEGATIVE_INFINITY; return value; } public String getName() { return "SS Reduction for Rules ("+m_BasicDist+", "+m_TargetWeights.getName()+")"; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest09613.java
2133
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark 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 * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest09613") public class BenchmarkTest09613 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headers = request.getHeaders("foo"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } String bar = new Test().doSomething(param); // javax.servlet.http.HttpSession.setAttribute(java.lang.String,java.lang.Object^) request.getSession().setAttribute( "foo", bar); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = param; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
lanceewing/jagi
src/com/sierra/agi/logic/interpret/instruction/InstructionAddV.java
3729
/* * InstructionAdd.java */ package com.sierra.agi.logic.interpret.instruction; import com.sierra.agi.*; import com.sierra.agi.logic.*; import com.sierra.agi.logic.interpret.*; import com.sierra.agi.logic.interpret.jit.*; import com.sierra.jit.code.*; import java.io.*; /** * Add Instruction. * * <P><CODE><B>add.n</B> Instruction 0x05</CODE><BR> * The value of variable <CODE>v[p1]</CODE> is incremented by <CODE>p2</CODE>, * i.e. <CODE>v[p1] += p2</CODE>. * </P> * * <P><CODE><B>add.v</B> Instruction 0x06</CODE><BR> * The value of variable <CODE>v[p1]</CODE> is incremented by <CODE>v[p2]</CODE>, * i.e. <CODE>v[p1] += v[p2]</CODE>. * </P> * * If the value is greater than <CODE>255</CODE> the result wraps over * <CODE>0</CODE> (so <CODE>250 + 10 == 4</CODE>). * * @author Dr. Z * @version 0.00.00.01 */ public class InstructionAddV extends InstructionBi implements Compilable { /** * Creates new Add Instruction (V). * * @param context Game context where this instance of the instruction will be used. (ignored) * @param stream Logic Stream. Instruction must be written in uninterpreted format. * @param reader LogicReader used in the reading of this instruction. (ignored) * @param bytecode Bytecode of the current instruction. * @throws IOException I/O Exception are throw when <CODE>stream.read()</CODE> fails. */ public InstructionAddV(InputStream stream, LogicReader reader, short bytecode, short engineEmulation) throws IOException { super(stream, bytecode); } /** * Execute the Instruction. * * @param logic Logic used to execute the instruction. * @param logicContext Logic Context used to execute the instruction. * @return Returns the number of byte of the uninterpreted instruction. */ public int execute(Logic logic, LogicContext logicContext) { short v = logicContext.getVar(p2); if (v > 0) { v += logicContext.getVar(p1); v &= 0xff; logicContext.setVar(p1, v); } return 3; } /** * Compile the Instruction into Java Bytecode. * * @param compileContext Logic Compile Context. */ public void compile(LogicCompileContext compileContext) { Scope scope = compileContext.scope; scope.addLoadVariable("logicContext"); scope.addPushConstant(p1); scope.addDuplicateLong(); scope.addInvokeSpecial("com.sierra.agi.logic.LogicContext", "getVar", "(S)S"); compileContext.compileGetVariableValue(p2); scope.addIntegerAdd(); scope.addPushConstant(0xff); scope.addIntegerAnd(); scope.addInvokeSpecial("com.sierra.agi.logic.LogicContext", "setVar", "(SS)V"); } //#ifdef DEBUG /** * Retreive the AGI Instruction name and parameters. * <B>For debugging purpose only. Will be removed in final releases.</B> * * @return Returns the textual names of the instruction. */ public String[] getNames() { String[] names = new String[3]; names[0] = "add"; names[1] = "v" + p1; names[2] = "v" + p2; return names; } /** * Returns a String representation of the expression. * <B>For debugging purpose only. Will be removed in final releases.</B> * * @return Returns a String representation. */ public String toString() { StringBuffer buffer = new StringBuffer("v"); buffer.append(p1); buffer.append(" += v"); buffer.append(p2); return buffer.toString(); } //#endif DEBUG }
gpl-2.0
nologic/nabs
client/trunk/shared/libraries/je-3.2.44/src/com/sleepycat/je/EnvironmentMutableConfig.java
10525
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2007 Oracle. All rights reserved. * * $Id: EnvironmentMutableConfig.java,v 1.29.2.1 2007/02/01 14:49:41 cwl Exp $ */ package com.sleepycat.je; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import com.sleepycat.je.config.ConfigParam; import com.sleepycat.je.config.EnvironmentParams; import com.sleepycat.je.dbi.DbConfigManager; import com.sleepycat.je.dbi.EnvironmentImpl; /** * Javadoc for this public class is generated * via the doc templates in the doc_src directory. */ public class EnvironmentMutableConfig implements Cloneable { /* * Change copyHandlePropsTo and Environment.copyToHandleConfig * when adding fields here. */ private boolean txnNoSync = false; private boolean txnWriteNoSync = false; /* * Cache size is a category of property that is calculated within the * environment. It is only supplied when returning the cache size to the * application and never used internally; internal code directly checks * with the MemoryBudget class; */ protected long cacheSize; /** * Note that in the implementation we choose not to extend Properties * in order to keep the configuration type safe. */ protected Properties props; /** * For unit testing, to prevent loading of je.properties. */ private boolean loadPropertyFile = true; /** * Internal boolean that says whether or not to validate params. Setting * it to false means that parameter value validatation won't be performed * during setVal() calls. Only should be set to false by unit tests using * DbInternal. */ boolean validateParams = true; /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public EnvironmentMutableConfig() { props = new Properties(); } /** * Used by EnvironmentConfig to construct from properties. */ EnvironmentMutableConfig(Properties properties) throws IllegalArgumentException { DbConfigManager.validateProperties(properties, false, // forReplication this.getClass().getName()); /* For safety, copy the passed in properties. */ props = new Properties(); props.putAll(properties); } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public void setTxnNoSync(boolean noSync) { txnNoSync = noSync; } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public boolean getTxnNoSync() { return txnNoSync; } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public void setTxnWriteNoSync(boolean writeNoSync) { txnWriteNoSync = writeNoSync; } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public boolean getTxnWriteNoSync() { return txnWriteNoSync; } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public void setCacheSize(long totalBytes) throws IllegalArgumentException { DbConfigManager.setVal(props, EnvironmentParams.MAX_MEMORY, Long.toString(totalBytes), validateParams); } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public long getCacheSize() { /* * CacheSize is filled in from the EnvironmentImpl by way of * copyHandleProps. */ return cacheSize; } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public void setCachePercent(int percent) throws IllegalArgumentException { DbConfigManager.setVal(props, EnvironmentParams.MAX_MEMORY_PERCENT, Integer.toString(percent), validateParams); } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public int getCachePercent() { String val = DbConfigManager.getVal(props, EnvironmentParams.MAX_MEMORY_PERCENT); try { return Integer.parseInt(val); } catch (NumberFormatException e) { throw new IllegalArgumentException ("Cache percent is not a valid integer: " + e.getMessage()); } } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public void setConfigParam(String paramName, String value) throws IllegalArgumentException { DbConfigManager.setConfigParam(props, paramName, value, true, /* require mutability. */ validateParams, false /* forReplication */); } /** * Javadoc for this public method is generated via * the doc templates in the doc_src directory. */ public String getConfigParam(String paramName) throws IllegalArgumentException { return DbConfigManager.getConfigParam(props, paramName); } /* * Helpers */ void setValidateParams(boolean validateParams) { this.validateParams = validateParams; } /** * Check that the immutable values in the environment config used to open * an environment match those in the config object saved by the underlying * shared EnvironmentImpl. */ void checkImmutablePropsForEquality(EnvironmentMutableConfig passedConfig) throws IllegalArgumentException { Properties passedProps = passedConfig.props; Iterator iter = EnvironmentParams.SUPPORTED_PARAMS.keySet().iterator(); while (iter.hasNext()) { String paramName = (String) iter.next(); ConfigParam param = (ConfigParam) EnvironmentParams.SUPPORTED_PARAMS.get(paramName); assert param != null; if (!param.isMutable()) { String paramVal = props.getProperty(paramName); String useParamVal = passedProps.getProperty(paramName); if ((paramVal != null) ? (!paramVal.equals(useParamVal)) : (useParamVal != null)) { throw new IllegalArgumentException (paramName + " is set to " + useParamVal + " in the config parameter" + " which is incompatible" + " with the value of " + paramVal + " in the" + " underlying environment"); } } } } /** * Overrides Object.clone() to clone all properties, used by this class and * EnvironmentConfig. */ protected Object clone() throws CloneNotSupportedException { EnvironmentMutableConfig copy = (EnvironmentMutableConfig) super.clone(); copy.props = (Properties) props.clone(); return copy; } /** * Used by Environment to create a copy of the application * supplied configuration. Done this way to provide non-public cloning. */ EnvironmentMutableConfig cloneMutableConfig() { try { EnvironmentMutableConfig copy = (EnvironmentMutableConfig) clone(); /* Remove all immutable properties. */ copy.clearImmutableProps(); return copy; } catch (CloneNotSupportedException willNeverOccur) { return null; } } /** * Copies the per-handle properties of this object to the given config * object. */ void copyHandlePropsTo(EnvironmentMutableConfig other) { other.txnNoSync = txnNoSync; other.txnWriteNoSync = txnWriteNoSync; } /** * Copies all mutable props to the given config object. */ void copyMutablePropsTo(EnvironmentMutableConfig toConfig) { Properties toProps = toConfig.props; Enumeration propNames = props.propertyNames(); while (propNames.hasMoreElements()) { String paramName = (String) propNames.nextElement(); ConfigParam param = (ConfigParam) EnvironmentParams.SUPPORTED_PARAMS.get(paramName); assert param != null; if (param.isMutable()) { String newVal = props.getProperty(paramName); toProps.setProperty(paramName, newVal); } } } /** * Fill in the properties calculated by the environment to the given * config object. */ void fillInEnvironmentGeneratedProps(EnvironmentImpl envImpl) { cacheSize = envImpl.getMemoryBudget().getMaxMemory(); } /** * Removes all immutable props. */ private void clearImmutableProps() { Enumeration propNames = props.propertyNames(); while (propNames.hasMoreElements()) { String paramName = (String) propNames.nextElement(); ConfigParam param = (ConfigParam) EnvironmentParams.SUPPORTED_PARAMS.get(paramName); assert param != null; if (!param.isMutable()) { props.remove(paramName); } } } Properties getProps() { return props; } /** * For unit testing, to prevent loading of je.properties. */ void setLoadPropertyFile(boolean loadPropertyFile) { this.loadPropertyFile = loadPropertyFile; } /** * For unit testing, to prevent loading of je.properties. */ boolean getLoadPropertyFile() { return loadPropertyFile; } /** * Testing support */ int getNumExplicitlySetParams() { return props.size(); } public String toString() { return props.toString(); } }
gpl-2.0
Ignishky/lotr_tcg
src/test/java/fr/ducloyer/lotr/presentation/PHandTest.java
2417
package fr.ducloyer.lotr.presentation; import fr.ducloyer.lotr.AbstractTest; import org.junit.Before; import org.junit.Test; import java.awt.*; import static org.assertj.core.api.Assertions.*; public class PHandTest extends AbstractTest { private PHand hand; private PCard pCard, pCard2, pCard3; @Override @Before public void setUp() { super.setUp(); pCard = new PCard(testImage, false, null); pCard2 = new PCard(testImage, false, null); pCard3 = new PCard(testImage, false, null); hand = new PHand(); } @Test public void card_should_have_face_visible() { hand.add(pCard); assertThat(pCard.isFaceVisible()).isTrue(); assertThat(hand.getComponentCount()).isEqualTo(1); } @Test public void should_have_correct_after_each_add() { hand.add(pCard); assertThat(pCard.getLocation()).isEqualTo(new Point(0, 0)); assertThat(hand.getSize()).isEqualTo(new Dimension(PCard.WIDTH, PCard.HEIGHT)); hand.add(pCard2); assertThat(pCard.getLocation()).isEqualTo(new Point(0, 0)); assertThat(pCard2.getLocation()).isEqualTo(new Point(PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS, 0)); assertThat(hand.getSize()).isEqualTo(new Dimension(PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS + PCard.WIDTH, PCard.HEIGHT)); hand.add(pCard3); assertThat(pCard.getLocation()).isEqualTo(new Point(0, 0)); assertThat(pCard2.getLocation()).isEqualTo(new Point(PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS, 0)); assertThat(pCard3.getLocation()).isEqualTo(new Point(2 * (PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS), 0)); assertThat(hand.getSize()).isEqualTo(new Dimension(2 * (PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS) + PCard.WIDTH, PCard.HEIGHT)); } @Test public void should_have_no_hole_after_playing_card() { hand.add(pCard); hand.add(pCard2); hand.add(pCard3); assertThat(hand.getComponentCount()).isEqualTo(3); hand.remove(pCard2); assertThat(hand.getComponentCount()).isEqualTo(2); assertThat(hand.getComponent(0)).isEqualTo(pCard); assertThat(pCard.getLocation()).isEqualTo(new Point(0, 0)); assertThat(hand.getComponent(1)).isEqualTo(pCard3); assertThat(pCard3.getLocation()).isEqualTo(new Point(PCard.WIDTH + PHand.SPACE_BETWEEN_CARDS, 0)); } }
gpl-2.0
mobile-event-processing/Asper
source/test/com/espertech/esper/event/property/TestPropertyParser.java
3062
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.event.property; import com.espertech.esper.event.EventAdapterService; import com.espertech.esper.support.event.SupportEventAdapterService; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.List; public class TestPropertyParser extends TestCase { private EventAdapterService eventAdapterService; public void setUp() { eventAdapterService = SupportEventAdapterService.getService(); } public void testParse() throws Exception { Property property = PropertyParser.parse("a", false); assertEquals("a", ((SimpleProperty)property).getPropertyNameAtomic()); property = PropertyParser.parse("i[1]", false); assertEquals("i", ((IndexedProperty)property).getPropertyNameAtomic()); assertEquals(1, ((IndexedProperty)property).getIndex()); property = PropertyParser.parse("m('key')", false); assertEquals("m", ((MappedProperty)property).getPropertyNameAtomic()); assertEquals("key", ((MappedProperty)property).getKey()); property = PropertyParser.parse("a.b[2].c('m')", false); List<Property> nested = ((NestedProperty)property).getProperties(); assertEquals(3, nested.size()); assertEquals("a", ((SimpleProperty)nested.get(0)).getPropertyNameAtomic()); assertEquals("b", ((IndexedProperty)nested.get(1)).getPropertyNameAtomic()); assertEquals(2, ((IndexedProperty)nested.get(1)).getIndex()); assertEquals("c", ((MappedProperty)nested.get(2)).getPropertyNameAtomic()); assertEquals("m", ((MappedProperty)nested.get(2)).getKey()); property = PropertyParser.parse("a", true); assertEquals("a", ((DynamicSimpleProperty)property).getPropertyNameAtomic()); } public void testParseMapKey() throws Exception { assertEquals("a", tryKey("a")); } private String tryKey(String key) throws Exception { String propertyName = "m(\"" + key + "\")"; log.debug(".tryKey propertyName=" + propertyName + " key=" + key); Property property = PropertyParser.parse(propertyName, false); return ((MappedProperty)property).getKey(); } private static Log log = LogFactory.getLog(TestPropertyParser.class); }
gpl-2.0
nmalacarne/project_sanity
src/project_sanity/skill/shield/Intercept.java
318
/* * 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 project_sanity.skill.shield; /** * * @author nicholas */ public class Intercept extends AShield { }
gpl-2.0
mateusz-matela/djvu-html5
djvu-html5/src/com/lizardtech/djvu/Pixmap.java
518
package com.lizardtech.djvu; /** * Common interface for IWPixmap and GPixmap */ public interface Pixmap extends Codec { int getMemoryUsage(); int getWidth(); int getHeight(); /** * Create a pixmap with the specified subsample rate and bounds. * * @param subsample rate at which to subsample * @param rect Bounding box of the desired pixmap. * @param retval An old pixmap to try updating, or null. * * @return DOCUMENT ME! */ GPixmap getPixmap(int subsample, GRect rect, GPixmap retval); }
gpl-2.0
zhangtianye/kdeconnect-android
src/org/kde/kdeconnect/UserInterface/List/TextItem.java
1586
/* * Copyright 2014 Albert Vaca Cintora <albertvaka@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kde.kdeconnect.UserInterface.List; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class TextItem implements ListAdapter.Item { private final String title; public TextItem(String title) { this.title = title; } @Override public View inflateView(LayoutInflater layoutInflater) { TextView v = new TextView(layoutInflater.getContext()); v.setText(title); v.setTextAppearance(layoutInflater.getContext(), android.support.v7.appcompat.R.style.TextAppearance_AppCompat_Medium /*android.R.style.TextAppearance_DeviceDefault_Medium*/); return v; } }
gpl-2.0
tastybento/multiworldmoney
src/main/java/com/wasteofplastic/multiworldmoney/WorldChangeListener.java
3597
package com.wasteofplastic.multiworldmoney; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import net.milkbowl.vault.economy.EconomyResponse; class WorldChangeListener implements Listener { private final MultiWorldMoney plugin; /** * @param plugin plugin */ public WorldChangeListener(MultiWorldMoney plugin) { this.plugin = plugin; } @EventHandler(ignoreCancelled = true) public void onWorldLoad(PlayerChangedWorldEvent event) { Player player = event.getPlayer(); World from = event.getFrom(); if (from != null) { // Deduce what the new balance needs to be // All worlds in the same group use the same balance List<World> groupWorlds = plugin.getGroupWorlds(from); if (groupWorlds.contains(player.getWorld())) { plugin.getPlayers().setBalance(player, from, 0D); // The world they are moving to is in the same group, so keep the balance, but remove it from the // last world otherwise there will be a dupe } else { // The player has moved to a new group // Save their balance in the old world that they just left double oldBalance = plugin.roundDown(plugin.getVh().getEcon().getBalance(player),2); plugin.getPlayers().setBalance(player, from, oldBalance); // Now work out what their new balance needs to be double newBalance = 0D; // Rationalize all the money in the group worlds and put it into the player's world for (World world : plugin.getGroupWorlds(player.getWorld())) { newBalance += plugin.getPlayers().getBalance(player, world); // Set the balance to zero in these other worlds if (!world.equals(player.getWorld())) { plugin.getPlayers().setBalance(player, world, 0D); } } plugin.getPlayers().setBalance(player, player.getWorld(), newBalance); // Now make the player's economy balance this value if (oldBalance > newBalance) { // Withdraw some money to make the oldBalance = newBalance EconomyResponse response = plugin.getVh().getEcon().withdrawPlayer(player, (oldBalance-newBalance)); if (!response.transactionSuccess()) { if (response.errorMessage != null && response.errorMessage.equalsIgnoreCase("Loan was not permitted")) { plugin.getLogger().warning("Negative balances not permitted by economy. Setting balance to zero."); plugin.getVh().getEcon().withdrawPlayer(player, oldBalance); } } } else if (oldBalance < newBalance) { plugin.getVh().getEcon().depositPlayer(player, (newBalance-oldBalance)); } } // Done - show the balance if requested if (plugin.getSettings().isShowBalance()) { player.sendMessage(ChatColor.GOLD + plugin.getSettings().getNewWorldMessage().replace("[balance]" , plugin.getVh().getEcon().format(plugin.getVh().getEcon().getBalance(player)))); } } } }
gpl-2.0
jsrck/android
src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java
38311
/* * ownCloud Android client application * * @author Mario Danic * Copyright (C) 2017 Mario Danic * Copyright (C) 2012 Bartek Przybylski * Copyright (C) 2012-2016 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.fragment; import android.animation.LayoutTransition; import android.app.Activity; import android.content.res.Configuration; import android.graphics.PorterDuff; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.getbase.floatingactionbutton.AddFloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.db.PreferenceManager; import com.owncloud.android.lib.common.utils.Log_OC; import com.owncloud.android.lib.resources.files.SearchOperation; import com.owncloud.android.ui.ExtendedListView; import com.owncloud.android.ui.activity.FileDisplayActivity; import com.owncloud.android.ui.activity.FolderPickerActivity; import com.owncloud.android.ui.activity.OnEnforceableRefreshListener; import com.owncloud.android.ui.activity.UploadFilesActivity; import com.owncloud.android.ui.adapter.FileListListAdapter; import com.owncloud.android.ui.adapter.LocalFileListAdapter; import com.owncloud.android.ui.events.SearchEvent; import com.owncloud.android.utils.ThemeUtils; import org.greenrobot.eventbus.EventBus; import org.parceler.Parcel; import java.util.ArrayList; import third_parties.in.srain.cube.GridViewWithHeaderAndFooter; public class ExtendedListFragment extends Fragment implements OnItemClickListener, OnEnforceableRefreshListener, SearchView.OnQueryTextListener { protected static final String TAG = ExtendedListFragment.class.getSimpleName(); protected static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION"; private static final String KEY_INDEXES = "INDEXES"; private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS"; private static final String KEY_TOPS = "TOPS"; private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL"; private static final String KEY_EMPTY_LIST_MESSAGE = "EMPTY_LIST_MESSAGE"; private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE"; public static final float minColumnSize = 2.0f; private int maxColumnSize = 5; private int maxColumnSizePortrait = 5; private int maxColumnSizeLandscape = 10; private ScaleGestureDetector mScaleGestureDetector = null; protected SwipeRefreshLayout mRefreshListLayout; protected SwipeRefreshLayout mRefreshGridLayout; protected SwipeRefreshLayout mRefreshEmptyLayout; protected LinearLayout mEmptyListContainer; protected TextView mEmptyListMessage; protected TextView mEmptyListHeadline; protected ImageView mEmptyListIcon; protected ProgressBar mEmptyListProgress; private FloatingActionsMenu mFabMain; private FloatingActionButton mFabUpload; private FloatingActionButton mFabMkdir; private FloatingActionButton mFabUploadFromApp; // Save the state of the scroll in browsing private ArrayList<Integer> mIndexes; private ArrayList<Integer> mFirstPositions; private ArrayList<Integer> mTops; private int mHeightCell = 0; private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null; protected AbsListView mCurrentListView; private ExtendedListView mListView; private View mListFooterView; private GridViewWithHeaderAndFooter mGridView; private View mGridFooterView; private BaseAdapter mAdapter; protected SearchView searchView; private Handler handler = new Handler(); private float mScale = -1f; @Parcel public enum SearchType { NO_SEARCH, REGULAR_FILTER, FILE_SEARCH, FAVORITE_SEARCH, FAVORITE_SEARCH_FILTER, VIDEO_SEARCH, VIDEO_SEARCH_FILTER, PHOTO_SEARCH, PHOTOS_SEARCH_FILTER, RECENTLY_MODIFIED_SEARCH, RECENTLY_MODIFIED_SEARCH_FILTER, RECENTLY_ADDED_SEARCH, RECENTLY_ADDED_SEARCH_FILTER, // not a real filter, but nevertheless SHARED_FILTER } protected void setListAdapter(BaseAdapter listAdapter) { mAdapter = listAdapter; mCurrentListView.setAdapter(listAdapter); mCurrentListView.invalidateViews(); } protected AbsListView getListView() { return mCurrentListView; } public FloatingActionButton getFabUpload() { return mFabUpload; } public FloatingActionButton getFabUploadFromApp() { return mFabUploadFromApp; } public FloatingActionButton getFabMkdir() { return mFabMkdir; } public FloatingActionsMenu getFabMain() { return mFabMain; } public void switchToGridView() { if (!isGridEnabled()) { mListView.setAdapter(null); mRefreshListLayout.setVisibility(View.GONE); mRefreshGridLayout.setVisibility(View.VISIBLE); mCurrentListView = mGridView; setListAdapter(mAdapter); } } public void switchToListView() { if (isGridEnabled()) { mGridView.setAdapter(null); mRefreshGridLayout.setVisibility(View.GONE); mRefreshListLayout.setVisibility(View.VISIBLE); mCurrentListView = mListView; setListAdapter(mAdapter); } } public boolean isGridEnabled() { return (mCurrentListView != null && mCurrentListView.equals(mGridView)); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { final MenuItem item = menu.findItem(R.id.action_search); searchView = (SearchView) MenuItemCompat.getActionView(item); searchView.setOnQueryTextListener(this); final Handler handler = new Handler(); DisplayMetrics displaymetrics = new DisplayMetrics(); Activity activity; if ((activity = getActivity()) != null) { activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = displaymetrics.widthPixels; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { searchView.setMaxWidth((int) (width * 0.4)); } else { if (activity instanceof FolderPickerActivity) { searchView.setMaxWidth((int) (width * 0.8)); } else { searchView.setMaxWidth((int) (width * 0.7)); } } } searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, final boolean hasFocus) { if (hasFocus) { mFabMain.collapse(); } handler.postDelayed(new Runnable() { @Override public void run() { if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) { setFabEnabled(!hasFocus); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { BottomNavigationView bottomNavigationView = (BottomNavigationView) getActivity(). findViewById(R.id.bottom_navigation_view); if (hasFocus) { bottomNavigationView.setVisibility(View.GONE); } else { bottomNavigationView.setVisibility(View.VISIBLE); } } } } }, 100); } }); final View mSearchEditFrame = searchView .findViewById(android.support.v7.appcompat.R.id.search_edit_frame); ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { int oldVisibility = -1; @Override public void onGlobalLayout() { int currentVisibility = mSearchEditFrame.getVisibility(); if (currentVisibility != oldVisibility) { if (currentVisibility == View.VISIBLE) { setEmptyListMessage(SearchType.REGULAR_FILTER); } else { setEmptyListMessage(SearchType.NO_SEARCH); } oldVisibility = currentVisibility; } } }); int fontColor = ThemeUtils.fontColor(); LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar); TextView searchBadge = (TextView) searchView.findViewById(R.id.search_badge); searchBadge.setTextColor(fontColor); searchBadge.setHintTextColor(fontColor); ImageView searchButton = (ImageView) searchView.findViewById(R.id.search_button); searchButton.setImageDrawable(ThemeUtils.tintDrawable(R.drawable.ic_search, fontColor)); searchBar.setLayoutTransition(new LayoutTransition()); } public boolean onQueryTextChange(final String query) { if (getFragmentManager() != null && getFragmentManager(). findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT) instanceof ExtendedListFragment) { performSearch(query, false); return true; } else { return false; } } @Override public boolean onQueryTextSubmit(String query) { performSearch(query, true); return true; } private void performSearch(final String query, boolean isSubmit) { handler.removeCallbacksAndMessages(null); if (!TextUtils.isEmpty(query)) { int delay = 500; if (isSubmit) { delay = 0; } if (mAdapter != null && mAdapter instanceof FileListListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { if (AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext()))) { EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH, SearchEvent.UnsetType.NO_UNSET)); } else { FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter; fileListListAdapter.getFilter().filter(query); } } }, delay); } else if (mAdapter != null && mAdapter instanceof LocalFileListAdapter) { handler.postDelayed(new Runnable() { @Override public void run() { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } }, delay); } if (searchView != null && delay == 0) { searchView.clearFocus(); } } else { Activity activity; if ((activity = getActivity()) != null) { if (activity instanceof FileDisplayActivity) { FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity; fileDisplayActivity.resetSearchView(); fileDisplayActivity.refreshListOfFilesFragment(true); } else if (activity instanceof UploadFilesActivity) { LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter; localFileListAdapter.filter(query); } else if (activity instanceof FolderPickerActivity) { ((FolderPickerActivity) activity).refreshListOfFilesFragment(true); } } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log_OC.d(TAG, "onCreateView"); View v = inflater.inflate(R.layout.list_fragment, null); setupEmptyList(v); mListView = (ExtendedListView) (v.findViewById(R.id.list_root)); mListView.setOnItemClickListener(this); mListFooterView = inflater.inflate(R.layout.list_footer, null, false); mGridView = (GridViewWithHeaderAndFooter) (v.findViewById(R.id.grid_root)); mScale = PreferenceManager.getGridColumns(getContext()); setGridViewColumns(1f); mGridView.setOnItemClickListener(this); mGridFooterView = inflater.inflate(R.layout.list_footer, null, false); mScaleGestureDetector = new ScaleGestureDetector(MainApp.getAppContext(),new ScaleListener()); mGridView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mScaleGestureDetector.onTouchEvent(motionEvent); if (motionEvent.getAction() == MotionEvent.ACTION_UP) { view.performClick(); } return false; } }); if (savedInstanceState != null) { int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION); if (mCurrentListView!= null && mCurrentListView.equals(mListView)) { Log_OC.v(TAG, "Setting and centering around list position " + referencePosition); mListView.setAndCenterSelection(referencePosition); } else { Log_OC.v(TAG, "Setting grid position " + referencePosition); mGridView.setSelection(referencePosition); } } // Pull-down to refresh layout mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_list); mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_grid); mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_empty); onCreateSwipeToRefresh(mRefreshListLayout); onCreateSwipeToRefresh(mRefreshGridLayout); onCreateSwipeToRefresh(mRefreshEmptyLayout); mListView.setEmptyView(mRefreshEmptyLayout); mGridView.setEmptyView(mRefreshEmptyLayout); int primaryColor = ThemeUtils.primaryColor(); int primaryColorDark = ThemeUtils.primaryDarkColor(); int fontColor = ThemeUtils.fontColor(); mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main); AddFloatingActionButton addButton = mFabMain.getAddButton(); addButton.setColorNormal(primaryColor); addButton.setColorPressed(primaryColorDark); addButton.setPlusColor(fontColor); mFabUpload = (FloatingActionButton) v.findViewById(R.id.fab_upload); mFabUpload.setColorNormal(primaryColor); mFabUpload.setColorPressed(primaryColorDark); mFabUpload.setIconDrawable(ThemeUtils.tintDrawable(R.drawable.ic_action_upload, fontColor)); mFabMkdir = (FloatingActionButton) v.findViewById(R.id.fab_mkdir); mFabMkdir.setColorNormal(primaryColor); mFabMkdir.setColorPressed(primaryColorDark); mFabMkdir.setIconDrawable(ThemeUtils.tintDrawable(R.drawable.ic_action_create_dir, fontColor)); mFabUploadFromApp = (FloatingActionButton) v.findViewById(R.id.fab_upload_from_app); mFabUploadFromApp.setColorNormal(primaryColor); mFabUploadFromApp.setColorPressed(primaryColorDark); mFabUploadFromApp.setIconDrawable(ThemeUtils.tintDrawable(R.drawable.ic_import, fontColor)); boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils. getCurrentOwnCloudAccount(MainApp.getAppContext())); if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams(); final float scale = v.getResources().getDisplayMetrics().density; BottomNavigationView bottomNavigationView = (BottomNavigationView) v.findViewById(R.id.bottom_navigation_view); // convert the DP into pixel int pixel = (int) (32 * scale + 0.5f); layoutParams.setMargins(0, 0, pixel / 2, bottomNavigationView.getMeasuredHeight() + pixel * 2); } mCurrentListView = mListView; // list by default if (savedInstanceState != null) { if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) { switchToGridView(); } int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION); if (isGridEnabled()) { Log_OC.v(TAG, "Setting grid position " + referencePosition); mGridView.setSelection(referencePosition); } else { Log_OC.v(TAG, "Setting and centering around list position " + referencePosition); mListView.setAndCenterSelection(referencePosition); } } return v; } public void setEmptyListVisible() { mEmptyListContainer.setVisibility(View.VISIBLE); } private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { setGridViewColumns(detector.getScaleFactor()); PreferenceManager.setGridColumns(getContext(), mScale); mAdapter.notifyDataSetChanged(); return true; } } private void setGridViewColumns(float scaleFactor) { if (mScale == -1f) { mGridView.setNumColumns(GridView.AUTO_FIT); mScale = mGridView.getNumColumns(); } mScale *= 1.f - (scaleFactor - 1.f); mScale = Math.max(minColumnSize, Math.min(mScale, maxColumnSize)); Integer scaleInt = Math.round(mScale); mGridView.setNumColumns(scaleInt); mGridView.invalidateViews(); } protected void setupEmptyList(View view) { mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view); mEmptyListMessage = (TextView) view.findViewById(R.id.empty_list_view_text); mEmptyListHeadline = (TextView) view.findViewById(R.id.empty_list_view_headline); mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon); mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress); mEmptyListProgress.getIndeterminateDrawable().setColorFilter(ThemeUtils.primaryColor(), PorterDuff.Mode.SRC_IN); } /** * {@inheritDoc} */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES); mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS); mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS); mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL); setMessageForEmptyList(savedInstanceState.getString(KEY_EMPTY_LIST_MESSAGE)); } else { mIndexes = new ArrayList<>(); mFirstPositions = new ArrayList<>(); mTops = new ArrayList<>(); mHeightCell = 0; } mScale = PreferenceManager.getGridColumns(getContext()); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log_OC.d(TAG, "onSaveInstanceState()"); savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled()); savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition()); savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes); savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions); savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops); savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell); savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText()); PreferenceManager.setGridColumns(getContext(), mScale); } /** * Calculates the position of the item that will be used as a reference to * reposition the visible items in the list when the device is turned to * other position. * <p> * The current policy is take as a reference the visible item in the center * of the screen. * * @return The position in the list of the visible item in the center of the * screen. */ protected int getReferencePosition() { if (mCurrentListView != null) { return (mCurrentListView.getFirstVisiblePosition() + mCurrentListView.getLastVisiblePosition()) / 2; } else { return 0; } } public int getColumnSize() { return Math.round(mScale); } /* * Restore index and position */ protected void restoreIndexAndTopPosition() { if (mIndexes.size() > 0) { // needs to be checked; not every browse-up had a browse-down before int index = mIndexes.remove(mIndexes.size() - 1); final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1); int top = mTops.remove(mTops.size() - 1); Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: " + top + "; index: " + index); if (mCurrentListView != null && mCurrentListView.equals(mListView)) { if (mHeightCell * index <= mListView.getHeight()) { mListView.setSelectionFromTop(firstPosition, top); } else { mListView.setSelectionFromTop(index, 0); } } else { if (mHeightCell * index <= mGridView.getHeight()) { mGridView.setSelection(firstPosition); //mGridView.smoothScrollToPosition(firstPosition); } else { mGridView.setSelection(index); //mGridView.smoothScrollToPosition(index); } } } } /* * Save index and top position */ protected void saveIndexAndTopPosition(int index) { mIndexes.add(index); int firstPosition = mCurrentListView.getFirstVisiblePosition(); mFirstPositions.add(firstPosition); View view = mCurrentListView.getChildAt(0); int top = (view == null) ? 0 : view.getTop(); mTops.add(top); // Save the height of a cell mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // to be @overridden } @Override public void onRefresh() { if (searchView != null) { searchView.onActionViewCollapsed(); Activity activity; if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) { FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity; fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isDrawerIndicatorAvailable()); } } mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } public void setOnRefreshListener(OnEnforceableRefreshListener listener) { mOnRefreshListener = listener; } /** * Disables swipe gesture. * <p> * Sets the 'enabled' state of the refresh layouts contained in the fragment. * <p> * When 'false' is set, prevents user gestures but keeps the option to refresh programatically, * * @param enabled Desired state for capturing swipe gesture. */ public void setSwipeEnabled(boolean enabled) { mRefreshListLayout.setEnabled(enabled); mRefreshGridLayout.setEnabled(enabled); mRefreshEmptyLayout.setEnabled(enabled); } /** * Sets the 'visibility' state of the FAB contained in the fragment. * <p> * When 'false' is set, FAB visibility is set to View.GONE programmatically, * * @param enabled Desired visibility for the FAB. */ public void setFabEnabled(final boolean enabled) { if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (enabled) { mFabMain.setVisibility(View.VISIBLE); } else { mFabMain.setVisibility(View.GONE); } } }); } } /** * Set message for empty list view. */ public void setMessageForEmptyList(String message) { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListMessage.setText(message); } } /** * displays an empty list information with a headline, a message and a not to be tinted icon. * * @param headline the headline * @param message the message * @param icon the icon to be shown */ public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) { setMessageForEmptyList(headline, message, icon, false); } /** * displays an empty list information with a headline, a message and an icon. * * @param headline the headline * @param message the message * @param icon the icon to be shown * @param tintIcon flag if the given icon should be tinted with primary color */ public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon, final boolean tintIcon) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(headline); mEmptyListMessage.setText(message); if (tintIcon) { mEmptyListIcon.setImageDrawable(ThemeUtils.tintDrawable(icon, ThemeUtils.primaryColor())); } else { mEmptyListIcon.setImageResource(icon); } mEmptyListIcon.setVisibility(View.VISIBLE); mEmptyListProgress.setVisibility(View.GONE); mEmptyListMessage.setVisibility(View.VISIBLE); } } }); } public void setEmptyListMessage(final SearchType searchType) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (searchType == SearchType.NO_SEARCH) { setMessageForEmptyList( R.string.file_list_empty_headline, R.string.file_list_empty, R.drawable.ic_list_empty_folder, true ); } else if (searchType == SearchType.FILE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_favorite_headline, R.string.file_list_empty_favorites_filter_list, R.drawable.ic_star_light_yellow); } else if (searchType == SearchType.VIDEO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTO_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.REGULAR_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_search, R.string.file_list_empty_search, R.drawable.ic_search_light_grey); } else if (searchType == SearchType.FAVORITE_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_favorites_filter, R.drawable.ic_star_light_yellow); } else if (searchType == SearchType.VIDEO_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos, R.string.file_list_empty_text_videos_filter, R.drawable.ic_list_empty_video); } else if (searchType == SearchType.PHOTOS_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos, R.string.file_list_empty_text_photos_filter, R.drawable.ic_list_empty_image); } else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_modified_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.RECENTLY_ADDED_SEARCH_FILTER) { setMessageForEmptyList(R.string.file_list_empty_headline_server_search, R.string.file_list_empty_recently_added_filter, R.drawable.ic_list_empty_recent); } else if (searchType == SearchType.SHARED_FILTER) { setMessageForEmptyList(R.string.file_list_empty_shared_headline, R.string.file_list_empty_shared, R.drawable.ic_list_empty_shared); } } }); } /** * Set message for empty list view. */ public void setEmptyListLoadingMessage() { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (mEmptyListContainer != null && mEmptyListMessage != null) { mEmptyListHeadline.setText(R.string.file_list_loading); mEmptyListMessage.setText(""); mEmptyListIcon.setVisibility(View.GONE); mEmptyListProgress.setVisibility(View.VISIBLE); } } }); } /** * Get the text of EmptyListMessage TextView. * * @return String empty text view text-value */ public String getEmptyViewText() { return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : ""; } protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) { int primaryColor = ThemeUtils.primaryColor(); int darkColor = ThemeUtils.primaryDarkColor(); int accentColor = ThemeUtils.primaryAccentColor(); // Colors in animations // TODO change this to use darker and lighter color, again. refreshLayout.setColorSchemeColors(accentColor, primaryColor, darkColor); refreshLayout.setOnRefreshListener(this); } @Override public void onRefresh(boolean ignoreETag) { mRefreshListLayout.setRefreshing(false); mRefreshGridLayout.setRefreshing(false); mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } protected void setChoiceMode(int choiceMode) { mListView.setChoiceMode(choiceMode); mGridView.setChoiceMode(choiceMode); } protected void setMultiChoiceModeListener(AbsListView.MultiChoiceModeListener listener) { mListView.setMultiChoiceModeListener(listener); mGridView.setMultiChoiceModeListener(listener); } /** * TODO doc * To be called before setAdapter, or GridViewWithHeaderAndFooter will throw an exception * * @param enabled flag if footer should be shown/calculated */ protected void setFooterEnabled(boolean enabled) { if (enabled) { if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) { if (mGridFooterView.getParent() != null) { ((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView); } mGridView.addFooterView(mGridFooterView, null, false); } mGridFooterView.invalidate(); if (mListView.getFooterViewsCount() == 0) { if (mListFooterView.getParent() != null) { ((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView); } mListView.addFooterView(mListFooterView, null, false); } mListFooterView.invalidate(); } else { mGridView.removeFooterView(mGridFooterView); mListView.removeFooterView(mListFooterView); } } /** * set the list/grid footer text. * * @param text the footer text */ protected void setFooterText(String text) { if (text != null && text.length() > 0) { ((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text); ((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text); setFooterEnabled(true); } else { setFooterEnabled(false); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { maxColumnSize = maxColumnSizeLandscape; } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { maxColumnSize = maxColumnSizePortrait; } else { maxColumnSize = maxColumnSizePortrait; } if (mGridView != null && mGridView.getNumColumns() > maxColumnSize) { mGridView.setNumColumns(maxColumnSize); mGridView.invalidateViews(); } } }
gpl-2.0
FITeagle/fiteagle-adapter-container
src/main/java/org/fiteagle/adapters/containers/docker/internal/ContainerInspection.java
1022
package org.fiteagle.adapters.containers.docker.internal; import com.google.gson.JsonElement; import com.google.gson.JsonObject; // TODO: Extend information captured by ContainerInspection public class ContainerInspection { /** * Container configuration */ public final ContainerConfiguration config; private ContainerInspection(ContainerConfiguration cconfig) { config = cconfig; } /** * Parse inspection information from a JSON object. */ public static ContainerInspection fromJSON(JsonElement element) throws DockerException { if (element == null || !element.isJsonObject()) throw new DockerException("Container inspection info must be an object"); JsonObject object = element.getAsJsonObject(); // Configuration if (!object.has("Config")) throw new DockerException("Container inspection info does not match expected schema"); ContainerConfiguration config = ContainerConfiguration.fromJSON(object.get("Config")); // Assemble return new ContainerInspection(config); } }
gpl-2.0
lixiaofei123/myblog
src/main/java/cn/com/lixiaofei/blog/validation/JScript.java
694
package cn.com.lixiaofei.blog.validation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Constraint(validatedBy = JScriptValidator.class) // 具体的实现 @Target({ java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.FIELD }) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Documented public @interface JScript { String message() default "{Cannot.contain.Spaces}"; // 提示信息,可以写死,可以填写国际化的key Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
gpl-2.0
digantDj/Gifff-Talk
TMessagesProj/src/main/java/org/giffftalk/messenger/support/widget/AdapterHelper.java
28333
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giffftalk.messenger.support.widget; import android.support.v4.util.Pools; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.giffftalk.messenger.support.widget.RecyclerView.*; /** * Helper class that can enqueue and process adapter update operations. * <p> * To support animations, RecyclerView presents an older version the Adapter to best represent * previous state of the layout. Sometimes, this is not trivial when items are removed that were * not laid out, in which case, RecyclerView has no way of providing that item's view for * animations. * <p> * AdapterHelper creates an UpdateOp for each adapter data change then pre-processes them. During * pre processing, AdapterHelper finds out which UpdateOps can be deferred to second layout pass * and which cannot. For the UpdateOps that cannot be deferred, AdapterHelper will change them * according to previously deferred operation and dispatch them before the first layout pass. It * also takes care of updating deferred UpdateOps since order of operations is changed by this * process. * <p> * Although operations may be forwarded to LayoutManager in different orders, resulting data set * is guaranteed to be the consistent. */ class AdapterHelper implements OpReorderer.Callback { final static int POSITION_TYPE_INVISIBLE = 0; final static int POSITION_TYPE_NEW_OR_LAID_OUT = 1; private static final boolean DEBUG = false; private static final String TAG = "AHT"; private Pools.Pool<UpdateOp> mUpdateOpPool = new Pools.SimplePool<UpdateOp>(UpdateOp.POOL_SIZE); final ArrayList<UpdateOp> mPendingUpdates = new ArrayList<UpdateOp>(); final ArrayList<UpdateOp> mPostponedList = new ArrayList<UpdateOp>(); final Callback mCallback; Runnable mOnItemProcessedCallback; final boolean mDisableRecycler; final OpReorderer mOpReorderer; private int mExistingUpdateTypes = 0; AdapterHelper(Callback callback) { this(callback, false); } AdapterHelper(Callback callback, boolean disableRecycler) { mCallback = callback; mDisableRecycler = disableRecycler; mOpReorderer = new OpReorderer(this); } AdapterHelper addUpdateOp(UpdateOp... ops) { Collections.addAll(mPendingUpdates, ops); return this; } void reset() { recycleUpdateOpsAndClearList(mPendingUpdates); recycleUpdateOpsAndClearList(mPostponedList); mExistingUpdateTypes = 0; } void preProcess() { mOpReorderer.reorderOps(mPendingUpdates); final int count = mPendingUpdates.size(); for (int i = 0; i < count; i++) { UpdateOp op = mPendingUpdates.get(i); switch (op.cmd) { case UpdateOp.ADD: applyAdd(op); break; case UpdateOp.REMOVE: applyRemove(op); break; case UpdateOp.UPDATE: applyUpdate(op); break; case UpdateOp.MOVE: applyMove(op); break; } if (mOnItemProcessedCallback != null) { mOnItemProcessedCallback.run(); } } mPendingUpdates.clear(); } void consumePostponedUpdates() { final int count = mPostponedList.size(); for (int i = 0; i < count; i++) { mCallback.onDispatchSecondPass(mPostponedList.get(i)); } recycleUpdateOpsAndClearList(mPostponedList); mExistingUpdateTypes = 0; } private void applyMove(UpdateOp op) { // MOVE ops are pre-processed so at this point, we know that item is still in the adapter. // otherwise, it would be converted into a REMOVE operation postponeAndUpdateViewHolders(op); } private void applyRemove(UpdateOp op) { int tmpStart = op.positionStart; int tmpCount = 0; int tmpEnd = op.positionStart + op.itemCount; int type = -1; for (int position = op.positionStart; position < tmpEnd; position++) { boolean typeChanged = false; ViewHolder vh = mCallback.findViewHolder(position); if (vh != null || canFindInPreLayout(position)) { // If a ViewHolder exists or this is a newly added item, we can defer this update // to post layout stage. // * For existing ViewHolders, we'll fake its existence in the pre-layout phase. // * For items that are added and removed in the same process cycle, they won't // have any effect in pre-layout since their add ops are already deferred to // post-layout pass. if (type == POSITION_TYPE_INVISIBLE) { // Looks like we have other updates that we cannot merge with this one. // Create an UpdateOp and dispatch it to LayoutManager. UpdateOp newOp = obtainUpdateOp(UpdateOp.REMOVE, tmpStart, tmpCount, null); dispatchAndUpdateViewHolders(newOp); typeChanged = true; } type = POSITION_TYPE_NEW_OR_LAID_OUT; } else { // This update cannot be recovered because we don't have a ViewHolder representing // this position. Instead, post it to LayoutManager immediately if (type == POSITION_TYPE_NEW_OR_LAID_OUT) { // Looks like we have other updates that we cannot merge with this one. // Create UpdateOp op and dispatch it to LayoutManager. UpdateOp newOp = obtainUpdateOp(UpdateOp.REMOVE, tmpStart, tmpCount, null); postponeAndUpdateViewHolders(newOp); typeChanged = true; } type = POSITION_TYPE_INVISIBLE; } if (typeChanged) { position -= tmpCount; // also equal to tmpStart tmpEnd -= tmpCount; tmpCount = 1; } else { tmpCount++; } } if (tmpCount != op.itemCount) { // all 1 effect recycleUpdateOp(op); op = obtainUpdateOp(UpdateOp.REMOVE, tmpStart, tmpCount, null); } if (type == POSITION_TYPE_INVISIBLE) { dispatchAndUpdateViewHolders(op); } else { postponeAndUpdateViewHolders(op); } } private void applyUpdate(UpdateOp op) { int tmpStart = op.positionStart; int tmpCount = 0; int tmpEnd = op.positionStart + op.itemCount; int type = -1; for (int position = op.positionStart; position < tmpEnd; position++) { ViewHolder vh = mCallback.findViewHolder(position); if (vh != null || canFindInPreLayout(position)) { // deferred if (type == POSITION_TYPE_INVISIBLE) { UpdateOp newOp = obtainUpdateOp(UpdateOp.UPDATE, tmpStart, tmpCount, op.payload); dispatchAndUpdateViewHolders(newOp); tmpCount = 0; tmpStart = position; } type = POSITION_TYPE_NEW_OR_LAID_OUT; } else { // applied if (type == POSITION_TYPE_NEW_OR_LAID_OUT) { UpdateOp newOp = obtainUpdateOp(UpdateOp.UPDATE, tmpStart, tmpCount, op.payload); postponeAndUpdateViewHolders(newOp); tmpCount = 0; tmpStart = position; } type = POSITION_TYPE_INVISIBLE; } tmpCount++; } if (tmpCount != op.itemCount) { // all 1 effect Object payload = op.payload; recycleUpdateOp(op); op = obtainUpdateOp(UpdateOp.UPDATE, tmpStart, tmpCount, payload); } if (type == POSITION_TYPE_INVISIBLE) { dispatchAndUpdateViewHolders(op); } else { postponeAndUpdateViewHolders(op); } } private void dispatchAndUpdateViewHolders(UpdateOp op) { // tricky part. // traverse all postpones and revert their changes on this op if necessary, apply updated // dispatch to them since now they are after this op. if (op.cmd == UpdateOp.ADD || op.cmd == UpdateOp.MOVE) { throw new IllegalArgumentException("should not dispatch add or move for pre layout"); } if (DEBUG) { Log.d(TAG, "dispatch (pre)" + op); Log.d(TAG, "postponed state before:"); for (UpdateOp updateOp : mPostponedList) { Log.d(TAG, updateOp.toString()); } Log.d(TAG, "----"); } // handle each pos 1 by 1 to ensure continuity. If it breaks, dispatch partial // TODO Since move ops are pushed to end, we should not need this anymore int tmpStart = updatePositionWithPostponed(op.positionStart, op.cmd); if (DEBUG) { Log.d(TAG, "pos:" + op.positionStart + ",updatedPos:" + tmpStart); } int tmpCnt = 1; int offsetPositionForPartial = op.positionStart; final int positionMultiplier; switch (op.cmd) { case UpdateOp.UPDATE: positionMultiplier = 1; break; case UpdateOp.REMOVE: positionMultiplier = 0; break; default: throw new IllegalArgumentException("op should be remove or update." + op); } for (int p = 1; p < op.itemCount; p++) { final int pos = op.positionStart + (positionMultiplier * p); int updatedPos = updatePositionWithPostponed(pos, op.cmd); if (DEBUG) { Log.d(TAG, "pos:" + pos + ",updatedPos:" + updatedPos); } boolean continuous = false; switch (op.cmd) { case UpdateOp.UPDATE: continuous = updatedPos == tmpStart + 1; break; case UpdateOp.REMOVE: continuous = updatedPos == tmpStart; break; } if (continuous) { tmpCnt++; } else { // need to dispatch this separately UpdateOp tmp = obtainUpdateOp(op.cmd, tmpStart, tmpCnt, op.payload); if (DEBUG) { Log.d(TAG, "need to dispatch separately " + tmp); } dispatchFirstPassAndUpdateViewHolders(tmp, offsetPositionForPartial); recycleUpdateOp(tmp); if (op.cmd == UpdateOp.UPDATE) { offsetPositionForPartial += tmpCnt; } tmpStart = updatedPos;// need to remove previously dispatched tmpCnt = 1; } } Object payload = op.payload; recycleUpdateOp(op); if (tmpCnt > 0) { UpdateOp tmp = obtainUpdateOp(op.cmd, tmpStart, tmpCnt, payload); if (DEBUG) { Log.d(TAG, "dispatching:" + tmp); } dispatchFirstPassAndUpdateViewHolders(tmp, offsetPositionForPartial); recycleUpdateOp(tmp); } if (DEBUG) { Log.d(TAG, "post dispatch"); Log.d(TAG, "postponed state after:"); for (UpdateOp updateOp : mPostponedList) { Log.d(TAG, updateOp.toString()); } Log.d(TAG, "----"); } } void dispatchFirstPassAndUpdateViewHolders(UpdateOp op, int offsetStart) { mCallback.onDispatchFirstPass(op); switch (op.cmd) { case UpdateOp.REMOVE: mCallback.offsetPositionsForRemovingInvisible(offsetStart, op.itemCount); break; case UpdateOp.UPDATE: mCallback.markViewHoldersUpdated(offsetStart, op.itemCount, op.payload); break; default: throw new IllegalArgumentException("only remove and update ops can be dispatched" + " in first pass"); } } private int updatePositionWithPostponed(int pos, int cmd) { final int count = mPostponedList.size(); for (int i = count - 1; i >= 0; i--) { UpdateOp postponed = mPostponedList.get(i); if (postponed.cmd == UpdateOp.MOVE) { int start, end; if (postponed.positionStart < postponed.itemCount) { start = postponed.positionStart; end = postponed.itemCount; } else { start = postponed.itemCount; end = postponed.positionStart; } if (pos >= start && pos <= end) { //i'm affected if (start == postponed.positionStart) { if (cmd == UpdateOp.ADD) { postponed.itemCount++; } else if (cmd == UpdateOp.REMOVE) { postponed.itemCount--; } // op moved to left, move it right to revert pos++; } else { if (cmd == UpdateOp.ADD) { postponed.positionStart++; } else if (cmd == UpdateOp.REMOVE) { postponed.positionStart--; } // op was moved right, move left to revert pos--; } } else if (pos < postponed.positionStart) { // postponed MV is outside the dispatched OP. if it is before, offset if (cmd == UpdateOp.ADD) { postponed.positionStart++; postponed.itemCount++; } else if (cmd == UpdateOp.REMOVE) { postponed.positionStart--; postponed.itemCount--; } } } else { if (postponed.positionStart <= pos) { if (postponed.cmd == UpdateOp.ADD) { pos -= postponed.itemCount; } else if (postponed.cmd == UpdateOp.REMOVE) { pos += postponed.itemCount; } } else { if (cmd == UpdateOp.ADD) { postponed.positionStart++; } else if (cmd == UpdateOp.REMOVE) { postponed.positionStart--; } } } if (DEBUG) { Log.d(TAG, "dispath (step" + i + ")"); Log.d(TAG, "postponed state:" + i + ", pos:" + pos); for (UpdateOp updateOp : mPostponedList) { Log.d(TAG, updateOp.toString()); } Log.d(TAG, "----"); } } for (int i = mPostponedList.size() - 1; i >= 0; i--) { UpdateOp op = mPostponedList.get(i); if (op.cmd == UpdateOp.MOVE) { if (op.itemCount == op.positionStart || op.itemCount < 0) { mPostponedList.remove(i); recycleUpdateOp(op); } } else if (op.itemCount <= 0) { mPostponedList.remove(i); recycleUpdateOp(op); } } return pos; } private boolean canFindInPreLayout(int position) { final int count = mPostponedList.size(); for (int i = 0; i < count; i++) { UpdateOp op = mPostponedList.get(i); if (op.cmd == UpdateOp.MOVE) { if (findPositionOffset(op.itemCount, i + 1) == position) { return true; } } else if (op.cmd == UpdateOp.ADD) { // TODO optimize. final int end = op.positionStart + op.itemCount; for (int pos = op.positionStart; pos < end; pos++) { if (findPositionOffset(pos, i + 1) == position) { return true; } } } } return false; } private void applyAdd(UpdateOp op) { postponeAndUpdateViewHolders(op); } private void postponeAndUpdateViewHolders(UpdateOp op) { if (DEBUG) { Log.d(TAG, "postponing " + op); } mPostponedList.add(op); switch (op.cmd) { case UpdateOp.ADD: mCallback.offsetPositionsForAdd(op.positionStart, op.itemCount); break; case UpdateOp.MOVE: mCallback.offsetPositionsForMove(op.positionStart, op.itemCount); break; case UpdateOp.REMOVE: mCallback.offsetPositionsForRemovingLaidOutOrNewView(op.positionStart, op.itemCount); break; case UpdateOp.UPDATE: mCallback.markViewHoldersUpdated(op.positionStart, op.itemCount, op.payload); break; default: throw new IllegalArgumentException("Unknown update op type for " + op); } } boolean hasPendingUpdates() { return mPendingUpdates.size() > 0; } boolean hasAnyUpdateTypes(int updateTypes) { return (mExistingUpdateTypes & updateTypes) != 0; } int findPositionOffset(int position) { return findPositionOffset(position, 0); } int findPositionOffset(int position, int firstPostponedItem) { int count = mPostponedList.size(); for (int i = firstPostponedItem; i < count; ++i) { UpdateOp op = mPostponedList.get(i); if (op.cmd == UpdateOp.MOVE) { if (op.positionStart == position) { position = op.itemCount; } else { if (op.positionStart < position) { position--; // like a remove } if (op.itemCount <= position) { position++; // like an add } } } else if (op.positionStart <= position) { if (op.cmd == UpdateOp.REMOVE) { if (position < op.positionStart + op.itemCount) { return -1; } position -= op.itemCount; } else if (op.cmd == UpdateOp.ADD) { position += op.itemCount; } } } return position; } /** * @return True if updates should be processed. */ boolean onItemRangeChanged(int positionStart, int itemCount, Object payload) { mPendingUpdates.add(obtainUpdateOp(UpdateOp.UPDATE, positionStart, itemCount, payload)); mExistingUpdateTypes |= UpdateOp.UPDATE; return mPendingUpdates.size() == 1; } /** * @return True if updates should be processed. */ boolean onItemRangeInserted(int positionStart, int itemCount) { mPendingUpdates.add(obtainUpdateOp(UpdateOp.ADD, positionStart, itemCount, null)); mExistingUpdateTypes |= UpdateOp.ADD; return mPendingUpdates.size() == 1; } /** * @return True if updates should be processed. */ boolean onItemRangeRemoved(int positionStart, int itemCount) { mPendingUpdates.add(obtainUpdateOp(UpdateOp.REMOVE, positionStart, itemCount, null)); mExistingUpdateTypes |= UpdateOp.REMOVE; return mPendingUpdates.size() == 1; } /** * @return True if updates should be processed. */ boolean onItemRangeMoved(int from, int to, int itemCount) { if (from == to) { return false; // no-op } if (itemCount != 1) { throw new IllegalArgumentException("Moving more than 1 item is not supported yet"); } mPendingUpdates.add(obtainUpdateOp(UpdateOp.MOVE, from, to, null)); mExistingUpdateTypes |= UpdateOp.MOVE; return mPendingUpdates.size() == 1; } /** * Skips pre-processing and applies all updates in one pass. */ void consumeUpdatesInOnePass() { // we still consume postponed updates (if there is) in case there was a pre-process call // w/o a matching consumePostponedUpdates. consumePostponedUpdates(); final int count = mPendingUpdates.size(); for (int i = 0; i < count; i++) { UpdateOp op = mPendingUpdates.get(i); switch (op.cmd) { case UpdateOp.ADD: mCallback.onDispatchSecondPass(op); mCallback.offsetPositionsForAdd(op.positionStart, op.itemCount); break; case UpdateOp.REMOVE: mCallback.onDispatchSecondPass(op); mCallback.offsetPositionsForRemovingInvisible(op.positionStart, op.itemCount); break; case UpdateOp.UPDATE: mCallback.onDispatchSecondPass(op); mCallback.markViewHoldersUpdated(op.positionStart, op.itemCount, op.payload); break; case UpdateOp.MOVE: mCallback.onDispatchSecondPass(op); mCallback.offsetPositionsForMove(op.positionStart, op.itemCount); break; } if (mOnItemProcessedCallback != null) { mOnItemProcessedCallback.run(); } } recycleUpdateOpsAndClearList(mPendingUpdates); mExistingUpdateTypes = 0; } public int applyPendingUpdatesToPosition(int position) { final int size = mPendingUpdates.size(); for (int i = 0; i < size; i ++) { UpdateOp op = mPendingUpdates.get(i); switch (op.cmd) { case UpdateOp.ADD: if (op.positionStart <= position) { position += op.itemCount; } break; case UpdateOp.REMOVE: if (op.positionStart <= position) { final int end = op.positionStart + op.itemCount; if (end > position) { return RecyclerView.NO_POSITION; } position -= op.itemCount; } break; case UpdateOp.MOVE: if (op.positionStart == position) { position = op.itemCount;//position end } else { if (op.positionStart < position) { position -= 1; } if (op.itemCount <= position) { position += 1; } } break; } } return position; } boolean hasUpdates() { return !mPostponedList.isEmpty() && !mPendingUpdates.isEmpty(); } /** * Queued operation to happen when child views are updated. */ static class UpdateOp { static final int ADD = 1; static final int REMOVE = 1 << 1; static final int UPDATE = 1 << 2; static final int MOVE = 1 << 3; static final int POOL_SIZE = 30; int cmd; int positionStart; Object payload; // holds the target position if this is a MOVE int itemCount; UpdateOp(int cmd, int positionStart, int itemCount, Object payload) { this.cmd = cmd; this.positionStart = positionStart; this.itemCount = itemCount; this.payload = payload; } String cmdToString() { switch (cmd) { case ADD: return "add"; case REMOVE: return "rm"; case UPDATE: return "up"; case MOVE: return "mv"; } return "??"; } @Override public String toString() { return Integer.toHexString(System.identityHashCode(this)) + "[" + cmdToString() + ",s:" + positionStart + "c:" + itemCount +",p:"+payload + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateOp op = (UpdateOp) o; if (cmd != op.cmd) { return false; } if (cmd == MOVE && Math.abs(itemCount - positionStart) == 1) { // reverse of this is also true if (itemCount == op.positionStart && positionStart == op.itemCount) { return true; } } if (itemCount != op.itemCount) { return false; } if (positionStart != op.positionStart) { return false; } if (payload != null) { if (!payload.equals(op.payload)) { return false; } } else if (op.payload != null) { return false; } return true; } @Override public int hashCode() { int result = cmd; result = 31 * result + positionStart; result = 31 * result + itemCount; return result; } } @Override public UpdateOp obtainUpdateOp(int cmd, int positionStart, int itemCount, Object payload) { UpdateOp op = mUpdateOpPool.acquire(); if (op == null) { op = new UpdateOp(cmd, positionStart, itemCount, payload); } else { op.cmd = cmd; op.positionStart = positionStart; op.itemCount = itemCount; op.payload = payload; } return op; } @Override public void recycleUpdateOp(UpdateOp op) { if (!mDisableRecycler) { op.payload = null; mUpdateOpPool.release(op); } } void recycleUpdateOpsAndClearList(List<UpdateOp> ops) { final int count = ops.size(); for (int i = 0; i < count; i++) { recycleUpdateOp(ops.get(i)); } ops.clear(); } /** * Contract between AdapterHelper and RecyclerView. */ static interface Callback { ViewHolder findViewHolder(int position); void offsetPositionsForRemovingInvisible(int positionStart, int itemCount); void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount); void markViewHoldersUpdated(int positionStart, int itemCount, Object payloads); void onDispatchFirstPass(UpdateOp updateOp); void onDispatchSecondPass(UpdateOp updateOp); void offsetPositionsForAdd(int positionStart, int itemCount); void offsetPositionsForMove(int from, int to); } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/eggs/PSystemLost.java
3090
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 4041 $ * */ package net.sourceforge.plantuml.eggs; import java.awt.Font; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import net.sourceforge.plantuml.AbstractPSystem; import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.DiagramDescriptionImpl; import net.sourceforge.plantuml.core.ImageData; import net.sourceforge.plantuml.graphic.GraphicStrings; import net.sourceforge.plantuml.graphic.HtmlColorUtils; import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.ImageBuilder; import net.sourceforge.plantuml.ugraphic.UAntiAliasing; import net.sourceforge.plantuml.ugraphic.UFont; public class PSystemLost extends AbstractPSystem { private final List<String> strings = new ArrayList<String>(); public PSystemLost() { strings.add("Thank you for choosing Oceanic Airlines."); } public ImageData exportDiagram(OutputStream os, int num, FileFormatOption fileFormat) throws IOException { final GraphicStrings result = getGraphicStrings(); final ImageBuilder imageBuilder = new ImageBuilder(new ColorMapperIdentity(), 1.0, result.getBackcolor(), getMetadata(), null, 0, 0, null, false); imageBuilder.addUDrawable(result); return imageBuilder.writeImageTOBEMOVED(fileFormat, os); } private GraphicStrings getGraphicStrings() throws IOException { final UFont font = new UFont("SansSerif", Font.PLAIN, 12); return new GraphicStrings(strings, font, HtmlColorUtils.BLACK, HtmlColorUtils.WHITE, UAntiAliasing.ANTI_ALIASING_ON, null, null); } public DiagramDescription getDescription() { return new DiagramDescriptionImpl("(Lost)", getClass()); } }
gpl-2.0
jurkov/j-algo-mod
src/org/jalgo/module/dijkstra/gui/components/ResultTableModel.java
2981
package org.jalgo.module.dijkstra.gui.components; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Observable; import java.util.Observer; import javax.swing.table.AbstractTableModel; import org.jalgo.main.util.Messages; import org.jalgo.module.dijkstra.gui.Controller; import org.jalgo.module.dijkstra.model.Node; import org.jalgo.module.dijkstra.model.State; /** * This class defines the <code>TableModel</code> for the result table in * algorithm mode. * * @author Alexander Claus */ public class ResultTableModel extends AbstractTableModel implements Observer { private List<String> targetNodes; private List<String> shortestPaths; private List<String> pathLengths; private List<List<String>> tableContent; private static final String[] columnNames = new String[] { Messages.getString("dijkstra", //$NON-NLS-1$ "AlgorithmResultTableComposite.Target_node"),//$NON-NLS-1$ Messages.getString("dijkstra", //$NON-NLS-1$ "AlgorithmResultTableComposite.Shortest_path"), //$NON-NLS-1$; Messages.getString("dijkstra", //$NON-NLS-1$ "AlgorithmResultTableComposite.Path_length")}; //$NON-NLS-1$; public ResultTableModel(Controller controller) { targetNodes = new LinkedList<String>(); shortestPaths = new LinkedList<String>(); pathLengths = new LinkedList<String>(); tableContent = new ArrayList<List<String>>(); tableContent.add(targetNodes); tableContent.add(shortestPaths); tableContent.add(pathLengths); controller.addObserver(this); } public int getRowCount() { return targetNodes.size(); } public int getColumnCount() { return 3; } @Override public String getColumnName(int column) { return columnNames[column]; } public Object getValueAt(int rowIndex, int columnIndex) { return tableContent.get(columnIndex).get(rowIndex); } /** * Updates the table content. */ public void update(Observable o, Object arg) { Controller controller = (Controller)o; // only react, when in algorithm mode if (controller.getEditingMode() != Controller.MODE_ALGORITHM) return; State dj = controller.getState(controller.getCurrentStep()); if (dj != null) { if (dj.getBorderStates() == null) return; targetNodes.clear(); shortestPaths.clear(); pathLengths.clear(); Iterator iter = dj.getGraph().getNodeList().iterator(); dj.getBorderStates().iterator(); while (iter.hasNext()) { Node node = (Node)iter.next(); if (node != dj.getGraph().getStartNode()) { targetNodes.add(node.getLabel()); String strPath = node.getShortestPath(); if (strPath.length() > 0) shortestPaths.add( "(" + node.getShortestPath() + "," + //$NON-NLS-1$ //$NON-NLS-2$ node.getIndex() + ")"); //$NON-NLS-1$ else shortestPaths.add(""); if (node.getDistance() > 0) pathLengths.add( "" + node.getDistance()); //$NON-NLS-1$ else pathLengths.add(""); } } fireTableDataChanged(); } } }
gpl-2.0
LMendesM/MALI
src/view/server/MainWindow.java
33208
package view.server; import controller.StationJpaController; import java.io.File; import javax.persistence.EntityManagerFactory; import javax.swing.JDialog; import javax.swing.JOptionPane; import static javax.swing.JOptionPane.INFORMATION_MESSAGE; import javax.swing.table.DefaultTableModel; import model.Station; import persistence.PersistenceSingleton; import util.ProcessesUpdater; import util.StationsUpdater; public class MainWindow extends javax.swing.JFrame { private void configureJDialog(JDialog jDialog, String title) { jDialog.setModal(true); jDialog.setSize(800, 600); jDialog.setResizable(false); jDialog.setLocationRelativeTo(null); jDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE); jDialog.setTitle(title); } private void listStationProcesses() { EntityManagerFactory emf = PersistenceSingleton.getInstance().getEntityManagerFactory(); StationJpaController stationJpaController = new StationJpaController(emf); DefaultTableModel dtm = (DefaultTableModel) jTableStations.getModel(); long selectedStation = (long) dtm.getValueAt(jTableStations.getSelectedRow(), 0); Station station = stationJpaController.findStation(selectedStation); jDialogStationData.setVisible(true); jDialogStationData.setTitle(station.getName()); ProcessesUpdater processesUpdater = new ProcessesUpdater(); processesUpdater.setjTable(jTableProcesses); processesUpdater.setStation(station); Thread thread = new Thread(processesUpdater); thread.start(); } public MainWindow() { initComponents(); setLocationRelativeTo(null); setExtendedState(MAXIMIZED_BOTH); configureJDialog(jDialogSettings, "Configurações"); configureJDialog(jDialogFileChooser, "Selecione um arquivo para envio"); configureJDialog(jDialogStationData, null); StationsUpdater stationsUpdater = new StationsUpdater(); stationsUpdater.setjTable(jTableStations); Thread thread = new Thread(stationsUpdater); thread.start(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDialogSettings = new javax.swing.JDialog(); jDesktopPaneSettingsBody = new javax.swing.JDesktopPane(); jLabelStationsUpdateFrequency = new javax.swing.JLabel(); jSpinnerStationsUpdateFrequency = new javax.swing.JSpinner(); jLabelSeconds1 = new javax.swing.JLabel(); jLabelUpdateProcessEach = new javax.swing.JLabel(); jLabelProcessUpdateFrequency = new javax.swing.JSpinner(); jLabelSeconds2 = new javax.swing.JLabel(); jButtonCancel = new javax.swing.JButton(); jButtonSave = new javax.swing.JButton(); jDialogFileChooser = new javax.swing.JDialog(); jFileChooser = new javax.swing.JFileChooser(); jDialogStationData = new javax.swing.JDialog(); jDesktopPaneOuterBackground = new javax.swing.JDesktopPane(); jTabbedPane1 = new javax.swing.JTabbedPane(); jDesktopPaneInnerBackground1 = new javax.swing.JDesktopPane(); jLabelName = new javax.swing.JLabel(); jTextFieldName = new javax.swing.JTextField(); jLabelMAC = new javax.swing.JLabel(); jTextFieldMAC = new javax.swing.JTextField(); jLabelIPv4 = new javax.swing.JLabel(); jTextFieldIPv4 = new javax.swing.JTextField(); jLabelIPv6 = new javax.swing.JLabel(); jTextFieldIPv6 = new javax.swing.JTextField(); jLabelCPUCores = new javax.swing.JLabel(); jTextFieldCPUCores = new javax.swing.JTextField(); jLabelTotalRAM = new javax.swing.JLabel(); jTextFieldTotalRAM = new javax.swing.JTextField(); jLabelFreeRAM = new javax.swing.JLabel(); jTextFieldFreeRAM = new javax.swing.JTextField(); jLabelOperationalSystem = new javax.swing.JLabel(); jTextFieldOperationalSystem = new javax.swing.JTextField(); jLabelLastLogin = new javax.swing.JLabel(); jTextFieldLastLogin = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); jTableProcesses = new javax.swing.JTable(); jDesktopPane1 = new javax.swing.JDesktopPane(); jScrollPane1 = new javax.swing.JScrollPane(); jTableStations = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jMenuBar = new javax.swing.JMenuBar(); jMenuEdit = new javax.swing.JMenu(); jMenuItemSettings = new javax.swing.JMenuItem(); jMenuHelp = new javax.swing.JMenu(); jMenuItemAbout = new javax.swing.JMenuItem(); jLabelStationsUpdateFrequency.setForeground(new java.awt.Color(255, 255, 255)); jLabelStationsUpdateFrequency.setText("Atualizar estações a cada"); jLabelSeconds1.setForeground(new java.awt.Color(255, 255, 255)); jLabelSeconds1.setText("seg"); jLabelUpdateProcessEach.setForeground(new java.awt.Color(255, 255, 255)); jLabelUpdateProcessEach.setText("Atualizar processos a cada"); jLabelSeconds2.setForeground(java.awt.Color.white); jLabelSeconds2.setText("seg"); jButtonCancel.setText("Cancelar"); jButtonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelActionPerformed(evt); } }); jButtonSave.setText("Salvar"); javax.swing.GroupLayout jDesktopPaneSettingsBodyLayout = new javax.swing.GroupLayout(jDesktopPaneSettingsBody); jDesktopPaneSettingsBody.setLayout(jDesktopPaneSettingsBodyLayout); jDesktopPaneSettingsBodyLayout.setHorizontalGroup( jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPaneSettingsBodyLayout.createSequentialGroup() .addContainerGap() .addGroup(jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPaneSettingsBodyLayout.createSequentialGroup() .addComponent(jLabelStationsUpdateFrequency) .addGap(18, 18, 18) .addComponent(jSpinnerStationsUpdateFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSeconds1)) .addGroup(jDesktopPaneSettingsBodyLayout.createSequentialGroup() .addComponent(jLabelUpdateProcessEach) .addGap(18, 18, 18) .addComponent(jLabelProcessUpdateFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSeconds2))) .addContainerGap(551, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPaneSettingsBodyLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonCancel) .addGap(18, 18, 18) .addComponent(jButtonSave) .addContainerGap()) ); jDesktopPaneSettingsBodyLayout.setVerticalGroup( jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPaneSettingsBodyLayout.createSequentialGroup() .addContainerGap() .addGroup(jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelStationsUpdateFrequency) .addComponent(jSpinnerStationsUpdateFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelSeconds1)) .addGap(18, 18, 18) .addGroup(jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelUpdateProcessEach) .addComponent(jLabelProcessUpdateFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelSeconds2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 486, Short.MAX_VALUE) .addGroup(jDesktopPaneSettingsBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonSave) .addComponent(jButtonCancel)) .addContainerGap()) ); jDesktopPaneSettingsBody.setLayer(jLabelStationsUpdateFrequency, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jSpinnerStationsUpdateFrequency, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jLabelSeconds1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jLabelUpdateProcessEach, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jLabelProcessUpdateFrequency, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jLabelSeconds2, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jButtonCancel, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneSettingsBody.setLayer(jButtonSave, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout jDialogSettingsLayout = new javax.swing.GroupLayout(jDialogSettings.getContentPane()); jDialogSettings.getContentPane().setLayout(jDialogSettingsLayout); jDialogSettingsLayout.setHorizontalGroup( jDialogSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPaneSettingsBody) ); jDialogSettingsLayout.setVerticalGroup( jDialogSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPaneSettingsBody) ); jFileChooser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jFileChooserActionPerformed(evt); } }); javax.swing.GroupLayout jDialogFileChooserLayout = new javax.swing.GroupLayout(jDialogFileChooser.getContentPane()); jDialogFileChooser.getContentPane().setLayout(jDialogFileChooserLayout); jDialogFileChooserLayout.setHorizontalGroup( jDialogFileChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jFileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE) ); jDialogFileChooserLayout.setVerticalGroup( jDialogFileChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jFileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE) ); jLabelName.setForeground(new java.awt.Color(255, 255, 255)); jLabelName.setText("Nome"); jTextFieldName.setEditable(false); jLabelMAC.setForeground(new java.awt.Color(255, 255, 255)); jLabelMAC.setText("MAC"); jTextFieldMAC.setEditable(false); jLabelIPv4.setForeground(new java.awt.Color(255, 255, 255)); jLabelIPv4.setText("IPv4"); jTextFieldIPv4.setEditable(false); jLabelIPv6.setForeground(new java.awt.Color(255, 255, 255)); jLabelIPv6.setText("IPv6"); jTextFieldIPv6.setEditable(false); jLabelCPUCores.setForeground(new java.awt.Color(255, 255, 255)); jLabelCPUCores.setText("Núcleos da CPU"); jTextFieldCPUCores.setEditable(false); jLabelTotalRAM.setForeground(new java.awt.Color(255, 255, 255)); jLabelTotalRAM.setText("RAM total"); jTextFieldTotalRAM.setEditable(false); jLabelFreeRAM.setForeground(new java.awt.Color(255, 255, 255)); jLabelFreeRAM.setText("RAM livre"); jTextFieldFreeRAM.setEditable(false); jLabelOperationalSystem.setForeground(new java.awt.Color(255, 255, 255)); jLabelOperationalSystem.setText("Sistema Operacional"); jTextFieldOperationalSystem.setEditable(false); jLabelLastLogin.setForeground(new java.awt.Color(255, 255, 255)); jLabelLastLogin.setText("Último login"); jTextFieldLastLogin.setEditable(false); javax.swing.GroupLayout jDesktopPaneInnerBackground1Layout = new javax.swing.GroupLayout(jDesktopPaneInnerBackground1); jDesktopPaneInnerBackground1.setLayout(jDesktopPaneInnerBackground1Layout); jDesktopPaneInnerBackground1Layout.setHorizontalGroup( jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPaneInnerBackground1Layout.createSequentialGroup() .addContainerGap() .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelOperationalSystem) .addComponent(jLabelLastLogin, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelFreeRAM, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelTotalRAM, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelCPUCores, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelIPv6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelIPv4, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelMAC, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelName, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldLastLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE) .addComponent(jTextFieldName) .addComponent(jTextFieldMAC) .addComponent(jTextFieldIPv4) .addComponent(jTextFieldIPv6) .addComponent(jTextFieldCPUCores) .addComponent(jTextFieldTotalRAM) .addComponent(jTextFieldFreeRAM) .addComponent(jTextFieldOperationalSystem)) .addContainerGap()) ); jDesktopPaneInnerBackground1Layout.setVerticalGroup( jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPaneInnerBackground1Layout.createSequentialGroup() .addContainerGap() .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelName) .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelMAC) .addComponent(jTextFieldMAC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelIPv4) .addComponent(jTextFieldIPv4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelIPv6) .addComponent(jTextFieldIPv6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelCPUCores) .addComponent(jTextFieldCPUCores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelTotalRAM) .addComponent(jTextFieldTotalRAM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelFreeRAM) .addComponent(jTextFieldFreeRAM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelOperationalSystem) .addComponent(jTextFieldOperationalSystem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jDesktopPaneInnerBackground1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelLastLogin) .addComponent(jTextFieldLastLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jDesktopPaneInnerBackground1.setLayer(jLabelName, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldName, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelMAC, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldMAC, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelIPv4, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldIPv4, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelIPv6, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldIPv6, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelCPUCores, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldCPUCores, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelTotalRAM, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldTotalRAM, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelFreeRAM, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldFreeRAM, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelOperationalSystem, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldOperationalSystem, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jLabelLastLogin, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPaneInnerBackground1.setLayer(jTextFieldLastLogin, javax.swing.JLayeredPane.DEFAULT_LAYER); jTabbedPane1.addTab("Informações", jDesktopPaneInnerBackground1); jTableProcesses.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "", "PID", "CMD" } ) { Class[] types = new Class [] { java.lang.Long.class, java.lang.Boolean.class, java.lang.Integer.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, true, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(jTableProcesses); jTabbedPane1.addTab("Processos", jScrollPane2); javax.swing.GroupLayout jDesktopPaneOuterBackgroundLayout = new javax.swing.GroupLayout(jDesktopPaneOuterBackground); jDesktopPaneOuterBackground.setLayout(jDesktopPaneOuterBackgroundLayout); jDesktopPaneOuterBackgroundLayout.setHorizontalGroup( jDesktopPaneOuterBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); jDesktopPaneOuterBackgroundLayout.setVerticalGroup( jDesktopPaneOuterBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) ); jDesktopPaneOuterBackground.setLayer(jTabbedPane1, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout jDialogStationDataLayout = new javax.swing.GroupLayout(jDialogStationData.getContentPane()); jDialogStationData.getContentPane().setLayout(jDialogStationDataLayout); jDialogStationDataLayout.setHorizontalGroup( jDialogStationDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPaneOuterBackground) ); jDialogStationDataLayout.setVerticalGroup( jDialogStationDataLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPaneOuterBackground) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("MALI - Monitor Acadêmico para Laboratórios de Informática"); jTableStations.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "", "Nome", "MAC", "IPv4", "IPv6", "Núcleos da CPU", "RAM Total", "RAM Livre", "Último Login", "S.O." } ) { Class[] types = new Class [] { java.lang.Long.class, java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Long.class, java.lang.Long.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, true, false, false, false, false, false, false, false, true, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTableStations.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableStationsMouseClicked(evt); } }); jScrollPane1.setViewportView(jTableStations); jButton1.setText("Enviar arquivo"); javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1); jDesktopPane1.setLayout(jDesktopPane1Layout); jDesktopPane1Layout.setHorizontalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1146, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap()) ); jDesktopPane1Layout.setVerticalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addContainerGap() .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addComponent(jButton1) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 693, Short.MAX_VALUE)) .addContainerGap()) ); jDesktopPane1.setLayer(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER); jMenuEdit.setText("Editar"); jMenuItemSettings.setText("Configurações"); jMenuItemSettings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSettingsActionPerformed(evt); } }); jMenuEdit.add(jMenuItemSettings); jMenuBar.add(jMenuEdit); jMenuHelp.setText("Ajuda"); jMenuItemAbout.setText("Sobre"); jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemAboutActionPerformed(evt); } }); jMenuHelp.add(jMenuItemAbout); jMenuBar.add(jMenuHelp); setJMenuBar(jMenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPane1) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAboutActionPerformed String message = "MALI - Monitor Acadêmico para Laboratórios de Informática\n" + "\n" + "Esse aplicativo é um projeto do PIBIC-Jr. - Programa Institucional de Bolsas de Iniciação Científica Júnior\n" + "Desenvolvimento de aplicativo multiplataforma para controle de laboratórios de informática\n" + "\n" + "Financiamento:\n" + "CEFET-MG - Centro Federal de Educação Tecnológica de Minas Gerais\n" + "FAPEMIG - Fundação de Amparo à Pesquisa de Minas Gerais\n" + "\n" + "Autor: Lucas Mendes Martins\n" + "Orientador: Weider Pereira Rodrigues\n" + "Co-orientador: Daniel Guimarães do Lago"; JOptionPane.showMessageDialog(this, message, "Sobre", INFORMATION_MESSAGE); }//GEN-LAST:event_jMenuItemAboutActionPerformed private void jMenuItemSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSettingsActionPerformed jDialogSettings.setVisible(true); }//GEN-LAST:event_jMenuItemSettingsActionPerformed private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed jDialogSettings.dispose(); }//GEN-LAST:event_jButtonCancelActionPerformed private void jFileChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooserActionPerformed jDialogFileChooser.dispose(); File file = jFileChooser.getSelectedFile(); if (file != null) { System.out.println(file); //Aqui será chamada uma janela para selecionar quais estações receberão o arquivo } jFileChooser.setSelectedFile(null); }//GEN-LAST:event_jFileChooserActionPerformed private void jTableStationsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableStationsMouseClicked if (evt.getClickCount() >= 2) { listStationProcesses(); } }//GEN-LAST:event_jTableStationsMouseClicked public static void main(String args[]) { 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(() -> { new MainWindow().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButtonCancel; private javax.swing.JButton jButtonSave; private javax.swing.JDesktopPane jDesktopPane1; private javax.swing.JDesktopPane jDesktopPaneInnerBackground1; private javax.swing.JDesktopPane jDesktopPaneOuterBackground; private javax.swing.JDesktopPane jDesktopPaneSettingsBody; private javax.swing.JDialog jDialogFileChooser; private javax.swing.JDialog jDialogSettings; private javax.swing.JDialog jDialogStationData; private javax.swing.JFileChooser jFileChooser; private javax.swing.JLabel jLabelCPUCores; private javax.swing.JLabel jLabelFreeRAM; private javax.swing.JLabel jLabelIPv4; private javax.swing.JLabel jLabelIPv6; private javax.swing.JLabel jLabelLastLogin; private javax.swing.JLabel jLabelMAC; private javax.swing.JLabel jLabelName; private javax.swing.JLabel jLabelOperationalSystem; private javax.swing.JSpinner jLabelProcessUpdateFrequency; private javax.swing.JLabel jLabelSeconds1; private javax.swing.JLabel jLabelSeconds2; private javax.swing.JLabel jLabelStationsUpdateFrequency; private javax.swing.JLabel jLabelTotalRAM; private javax.swing.JLabel jLabelUpdateProcessEach; private javax.swing.JMenuBar jMenuBar; private javax.swing.JMenu jMenuEdit; private javax.swing.JMenu jMenuHelp; private javax.swing.JMenuItem jMenuItemAbout; private javax.swing.JMenuItem jMenuItemSettings; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSpinner jSpinnerStationsUpdateFrequency; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTableProcesses; private javax.swing.JTable jTableStations; private javax.swing.JTextField jTextFieldCPUCores; private javax.swing.JTextField jTextFieldFreeRAM; private javax.swing.JTextField jTextFieldIPv4; private javax.swing.JTextField jTextFieldIPv6; private javax.swing.JTextField jTextFieldLastLogin; private javax.swing.JTextField jTextFieldMAC; private javax.swing.JTextField jTextFieldName; private javax.swing.JTextField jTextFieldOperationalSystem; private javax.swing.JTextField jTextFieldTotalRAM; // End of variables declaration//GEN-END:variables }
gpl-2.0
SergeiKutanov/VladAmbulance
src/ru/vladambulance/swing/patient/ObjectiveData/AmbulanceCallOutResults/AmbulanceCallOutResult.java
1377
package ru.vladambulance.swing.patient.ObjectiveData.AmbulanceCallOutResults; import ru.vladambulance.sql.Dictionary; import ru.vladambulance.sql.DictionaryBean; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: sergei * Date: 4/6/13 * Time: 10:01 AM * To change this template use File | Settings | File Templates. */ public class AmbulanceCallOutResult extends Dictionary implements DictionaryBean{ public static final String TABLE = "ambulance_call_out_result_types"; public AmbulanceCallOutResult(Integer id){ super.setTableName(AmbulanceCallOutResult.TABLE); super.queryInit(); if(id != null){ this.setId(id); this.retrieve(); } } public static ArrayList<AmbulanceCallOutResult> getItems(){ ArrayList<Dictionary> dictionaries = Dictionary.getItems( AmbulanceCallOutResult.TABLE ); ArrayList<AmbulanceCallOutResult> ambulanceCallOutResults = new ArrayList<AmbulanceCallOutResult>(); for(Dictionary dictionary : dictionaries){ AmbulanceCallOutResult AmbulanceCallOutResult = new AmbulanceCallOutResult(dictionary.getId()); ambulanceCallOutResults.add(AmbulanceCallOutResult); } return ambulanceCallOutResults; } public AmbulanceCallOutResult(){ this(null); } }
gpl-2.0
karianna/jdk8_tl
jdk/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java
15532
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.*; /** * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList} * for all of its operations. Thus, it shares the same basic properties: * <ul> * <li>It is best suited for applications in which set sizes generally * stay small, read-only operations * vastly outnumber mutative operations, and you need * to prevent interference among threads during traversal. * <li>It is thread-safe. * <li>Mutative operations (<tt>add</tt>, <tt>set</tt>, <tt>remove</tt>, etc.) * are expensive since they usually entail copying the entire underlying * array. * <li>Iterators do not support the mutative <tt>remove</tt> operation. * <li>Traversal via iterators is fast and cannot encounter * interference from other threads. Iterators rely on * unchanging snapshots of the array at the time the iterators were * constructed. * </ul> * * <p> <b>Sample Usage.</b> The following code sketch uses a * copy-on-write set to maintain a set of Handler objects that * perform some action upon state updates. * * <pre> {@code * class Handler { void handle(); ... } * * class X { * private final CopyOnWriteArraySet<Handler> handlers * = new CopyOnWriteArraySet<Handler>(); * public void addHandler(Handler h) { handlers.add(h); } * * private long internalState; * private synchronized void changeState() { internalState = ...; } * * public void update() { * changeState(); * for (Handler handler : handlers) * handler.handle(); * } * }}</pre> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @see CopyOnWriteArrayList * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements java.io.Serializable { private static final long serialVersionUID = 5457747651344034263L; private final CopyOnWriteArrayList<E> al; /** * Creates an empty set. */ public CopyOnWriteArraySet() { al = new CopyOnWriteArrayList<E>(); } /** * Creates a set containing all of the elements of the specified * collection. * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection is null */ public CopyOnWriteArraySet(Collection<? extends E> c) { al = new CopyOnWriteArrayList<E>(); al.addAllAbsent(c); } /** * Returns the number of elements in this set. * * @return the number of elements in this set */ public int size() { return al.size(); } /** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return al.isEmpty(); } /** * Returns <tt>true</tt> if this set contains the specified element. * More formally, returns <tt>true</tt> if and only if this set * contains an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ public boolean contains(Object o) { return al.contains(o); } /** * Returns an array containing all of the elements in this set. * If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * * <p>The returned array will be "safe" in that no references to it * are maintained by this set. (In other words, this method must * allocate a new array even if this set is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all the elements in this set */ public Object[] toArray() { return al.toArray(); } /** * Returns an array containing all of the elements in this set; the * runtime type of the returned array is that of the specified array. * If the set fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this set. * * <p>If this set fits in the specified array with room to spare * (i.e., the array has more elements than this set), the element in * the array immediately following the end of the set is set to * <tt>null</tt>. (This is useful in determining the length of this * set <i>only</i> if the caller knows that this set does not contain * any null elements.) * * <p>If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements * in the same order. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a set known to contain only strings. * The following code can be used to dump the set into a newly allocated * array of <tt>String</tt>: * * <pre> {@code String[] y = x.toArray(new String[0]);}</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of this set are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing all the elements in this set * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in this * set * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { return al.toArray(a); } /** * Removes all of the elements from this set. * The set will be empty after this call returns. */ public void clear() { al.clear(); } /** * Removes the specified element from this set if it is present. * More formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, * if this set contains such an element. Returns <tt>true</tt> if * this set contained the element (or equivalently, if this set * changed as a result of the call). (This set will not contain the * element once the call returns.) * * @param o object to be removed from this set, if present * @return <tt>true</tt> if this set contained the specified element */ public boolean remove(Object o) { return al.remove(o); } /** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * the set contains no element <tt>e2</tt> such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return al.addIfAbsent(e); } /** * Returns <tt>true</tt> if this set contains all of the elements of the * specified collection. If the specified collection is also a set, this * method returns <tt>true</tt> if it is a <i>subset</i> of this set. * * @param c collection to be checked for containment in this set * @return <tt>true</tt> if this set contains all of the elements of the * specified collection * @throws NullPointerException if the specified collection is null * @see #contains(Object) */ public boolean containsAll(Collection<?> c) { return al.containsAll(c); } /** * Adds all of the elements in the specified collection to this set if * they're not already present. If the specified collection is also a * set, the <tt>addAll</tt> operation effectively modifies this set so * that its value is the <i>union</i> of the two sets. The behavior of * this operation is undefined if the specified collection is modified * while the operation is in progress. * * @param c collection containing elements to be added to this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { return al.addAllAbsent(c) > 0; } /** * Removes from this set all of its elements that are contained in the * specified collection. If the specified collection is also a set, * this operation effectively modifies this set so that its value is the * <i>asymmetric set difference</i> of the two sets. * * @param c collection containing elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean removeAll(Collection<?> c) { return al.removeAll(c); } /** * Retains only the elements in this set that are contained in the * specified collection. In other words, removes from this set all of * its elements that are not contained in the specified collection. If * the specified collection is also a set, this operation effectively * modifies this set so that its value is the <i>intersection</i> of the * two sets. * * @param c collection containing elements to be retained in this set * @return <tt>true</tt> if this set changed as a result of the call * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean retainAll(Collection<?> c) { return al.retainAll(c); } /** * Returns an iterator over the elements contained in this set * in the order in which these elements were added. * * <p>The returned iterator provides a snapshot of the state of the set * when the iterator was constructed. No synchronization is needed while * traversing the iterator. The iterator does <em>NOT</em> support the * <tt>remove</tt> method. * * @return an iterator over the elements in this set */ public Iterator<E> iterator() { return al.iterator(); } /** * Compares the specified object with this set for equality. * Returns {@code true} if the specified object is the same object * as this object, or if it is also a {@link Set} and the elements * returned by an {@linkplain List#iterator() iterator} over the * specified set are the same as the elements returned by an * iterator over this set. More formally, the two iterators are * considered to return the same elements if they return the same * number of elements and for every element {@code e1} returned by * the iterator over the specified set, there is an element * {@code e2} returned by the iterator over this set such that * {@code (e1==null ? e2==null : e1.equals(e2))}. * * @param o object to be compared for equality with this set * @return {@code true} if the specified object is equal to this set */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> set = (Set<?>)(o); Iterator<?> it = set.iterator(); // Uses O(n^2) algorithm that is only appropriate // for small sets, which CopyOnWriteArraySets should be. // Use a single snapshot of underlying array Object[] elements = al.getArray(); int len = elements.length; // Mark matched elements to avoid re-checking boolean[] matched = new boolean[len]; int k = 0; outer: while (it.hasNext()) { if (++k > len) return false; Object x = it.next(); for (int i = 0; i < len; ++i) { if (!matched[i] && eq(x, elements[i])) { matched[i] = true; continue outer; } } return false; } return k == len; } /** * Tests for equality, coping with nulls. */ private static boolean eq(Object o1, Object o2) { return (o1 == null) ? o2 == null : o1.equals(o2); } }
gpl-2.0
Isangeles/Senlin
src/main/java/pl/isangeles/senlin/gui/tools/InfoFrame.java
2385
/* * InfoFrame.java * * Copyright 2017 Dariusz Sikora <dev@isangeles.pl> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ package pl.isangeles.senlin.gui.tools; import java.awt.FontFormatException; import java.io.IOException; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import pl.isangeles.senlin.gui.InfoField; import pl.isangeles.senlin.util.Coords; /** * Class for UI information frame * * @author Isangeles */ class InfoFrame extends InfoField implements UiElement { private boolean openReq; /** * Loading info frame constructor * * @param gc Slick game container * @throws SlickException * @throws IOException * @throws FontFormatException */ public InfoFrame(GameContainer gc) throws SlickException, IOException, FontFormatException { super(Coords.getSize(200f), Coords.getSize(70f), gc); } @Override public void draw(float x, float y) { super.draw(x, y, false); } /** Opens information frame */ public void open(String information) { setText(information); openReq = true; } /* (non-Javadoc) * @see pl.isangeles.senlin.gui.tools.UiElement#close() */ @Override public void close() { openReq = false; reset(); } /* (non-Javadoc) * @see pl.isangeles.senlin.gui.tools.UiElement#update() */ @Override public void update() {} /* (non-Javadoc) * @see pl.isangeles.senlin.gui.tools.UiElement#reset() */ @Override public void reset() { moveMOA(Coords.getX("BR", 0), Coords.getY("BR", 0)); } /* (non-Javadoc) * @see pl.isangeles.senlin.gui.tools.UiElement#isOpenReq() */ @Override public boolean isOpenReq() { return openReq; } }
gpl-2.0
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02758.java
2807
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark 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. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest02758") public class BenchmarkTest02758 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("vector"); String bar = doSomething(param); byte[] input = new byte[1000]; String str = "?"; Object inputParam = param; if (inputParam instanceof String) str = ((String) inputParam); if (inputParam instanceof java.io.InputStream) { int i = ((java.io.InputStream) inputParam).read(input); if (i == -1) { response.getWriter().println("This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } str = new String(input, 0, i); } javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie", str); cookie.setSecure(false); response.addCookie(cookie); response.getWriter().println("Created cookie: 'SomeCookie': with value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(str) + "' and secure flag set to: false"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { StringBuilder sbxyz17742 = new StringBuilder(param); String bar = sbxyz17742.append("_SafeStuff").toString(); return bar; } }
gpl-2.0
pburlov/ultracipher
core/src/main/java/de/burlov/ultracipher/core/CSVSettings.java
2302
/* Copyright (C) 2009 Paul Burlov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.burlov.ultracipher.core; import au.com.bytecode.opencsv.CSVWriter; public class CSVSettings { private int nameColumn = 0; private int tagsColumn = 1; private int dataColumn = 2; private char separator = CSVWriter.DEFAULT_SEPARATOR; private char quoteChar = CSVWriter.DEFAULT_QUOTE_CHARACTER; private char escapeChar = CSVWriter.DEFAULT_ESCAPE_CHARACTER; private String lineEnd = CSVWriter.DEFAULT_LINE_END; public CSVSettings() { super(); } public int getNameColumn() { return nameColumn; } public void setNameColumn(int nameColumn) { this.nameColumn = nameColumn; } public int getTagsColumn() { return tagsColumn; } public void setTagsColumn(int tagsColumn) { this.tagsColumn = tagsColumn; } public int getDataColumn() { return dataColumn; } public void setDataColumn(int dataColumn) { this.dataColumn = dataColumn; } public char getSeparator() { return separator; } public void setSeparator(char separator) { this.separator = separator; } public char getQuoteChar() { return quoteChar; } public void setQuoteChar(char quoteChar) { this.quoteChar = quoteChar; } public char getEscapeChar() { return escapeChar; } public void setEscapeChar(char escapeChar) { this.escapeChar = escapeChar; } public String getLineEnd() { return lineEnd; } public void setLineEnd(String lineEnd) { this.lineEnd = lineEnd; } }
gpl-2.0
baeda/ash
src/main/java/org/ashlang/ash/type/OperatorMap.java
2238
/* * The Ash Project * Copyright (C) 2017 Peter Skrypalle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ashlang.ash.type; import org.apache.commons.lang3.tuple.Triple; import java.util.HashMap; import java.util.Map; import static org.ashlang.ash.type.Operator.*; import static org.ashlang.ash.type.Types.BOOL; import static org.ashlang.ash.type.Types.INVALID; public class OperatorMap { private final Map<Triple<Type, Operator, Type>, Type> opMap; public OperatorMap() { opMap = new HashMap<>(); Types.allExactTypes(IntType.class) .forEach(type -> { entry(type, ADD, type, type); entry(type, SUB, type, type); entry(type, MUL, type, type); entry(type, DIV, type, type); entry(type, MOD, type, type); }); Types.allTypes().stream() .filter(Types::allValid) .forEach(type -> { entry(type, EQUALS, type, BOOL); entry(type, NOT_EQUALS, type, BOOL); entry(type, LT, type, BOOL); entry(type, GT, type, BOOL); entry(type, LT_EQ, type, BOOL); entry(type, GT_EQ, type, BOOL); }); } private void entry(Type left, Operator op, Type right, Type result) { opMap.put(Triple.of(left, op, right), result); } public Type getResultOf(Type left, Operator op, Type right) { Triple<Type, Operator, Type> key = Triple.of(left, op, right); return opMap.getOrDefault(key, INVALID); } }
gpl-2.0
Gronkdalonka/Rezeptinator
Rezeptinator/src/sync/DatabaseInteractions.java
2091
package sync; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import android.util.Log; import HelpClasses.Recipe; import database.Database_Functions; public class DatabaseInteractions { private String tag = "REZEPTINATORDEBUG"; private Database_Functions dbInstance = database.Database_Functions.getInstance(); private HashMap<Recipe[], HashMap> dumpDatabase() { //get all recipes Recipe[] allRecipes = dbInstance.GetReceipts(null, null); // get all ingredient groups String[] allIngredientGroups = dbInstance.GetAllGroups(false); //get all ingredients HashMap<String, String[]> ingredientsAndGroups = new HashMap(); for (String ingredGroup : allIngredientGroups) { String[] ingredients = dbInstance.GetIngredientsByGroup(ingredGroup); ingredientsAndGroups.put(ingredGroup, ingredients); } //create complete package HashMap<Recipe[], HashMap> collection = new HashMap(); collection.put(allRecipes, ingredientsAndGroups); return collection; } public void dumpToLogcat() { //debug function HashMap<Recipe[], HashMap> dump = dumpDatabase(); Log.d(tag, dump.toString()); //convert to human readable form Recipe[] allRecipes = null; HashMap<String, String[]> ingredientsAndGroups = new HashMap(); for(Map.Entry<Recipe[], HashMap> entry : dump.entrySet()) { allRecipes = entry.getKey(); ingredientsAndGroups = entry.getValue(); } for (Recipe recipe : allRecipes) { Log.d(tag, "Name: "+recipe.get_name() + " mealtime: "+ recipe.get_meal() + " ingredients: " + Arrays.toString(recipe.get_ingredients()) + " preparation: " + recipe.get_preparation() ); } for (Map.Entry<String, String[]>ingredientGroup : ingredientsAndGroups.entrySet()){ Log.d(tag, "Group: "+ingredientGroup.getKey()+" Ingredients: " + Arrays.toString(ingredientGroup.getValue())); } } private void createTmpDatabase() { //create a new temporary Database for export and import } private void exportDatabase() { //export a Database (to SDCard, Dropbox, etc) } }
gpl-2.0
digantDj/Gifff-Talk
TMessagesProj/src/main/java/org/giffftalk/messenger/exoplayer/upstream/Allocation.java
1727
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giffftalk.messenger.exoplayer.upstream; /** * An allocation within a byte array. * <p> * The allocation's length is obtained by calling {@link Allocator#getIndividualAllocationLength()} * on the {@link Allocator} from which it was obtained. */ public final class Allocation { /** * The array containing the allocated space. The allocated space may not be at the start of the * array, and so {@link #translateOffset(int)} method must be used when indexing into it. */ public final byte[] data; private final int offset; /** * @param data The array containing the allocated space. * @param offset The offset of the allocated space within the array. */ public Allocation(byte[] data, int offset) { this.data = data; this.offset = offset; } /** * Translates a zero-based offset into the allocation to the corresponding {@link #data} offset. * * @param offset The zero-based offset to translate. * @return The corresponding offset in {@link #data}. */ public int translateOffset(int offset) { return this.offset + offset; } }
gpl-2.0
steplerbush/GPUOracul
src/main/java/org/oracul/service/filter/SimpleCORSFilter.java
876
package org.oracul.service.filter; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class SimpleCORSFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, resp); } @Override public void destroy() { } }
gpl-2.0
Disguiser-w/SE2
ELS_CLIENT/src/test/java/businessbl/DriverManagerTest.java
1166
package businessbl; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import businesslogic.businessbl.controller.DriverManagerController; import vo.DriverVO; public class DriverManagerTest { private DriverManagerController controller; // @Before // public void setUp() throws Exception { // controller = new DriverManagerController(); // } // // @Test // public void testGetDriverInfo() { // ArrayList<DriverVO> vos = controller.getDriverInfo(); // String ID = vos.get(0).ID; // assertEquals("025-000-111", ID); // } // // @Test // public void testAddDriver() { //// DriverVO vo = new DriverVO(null, null, null, null, null, null, null, null); //// assertEquals(true, controller.addDriver(vo)); // } // // @Test // public void testDeleteDriver() { //// DriverVO vo = new DriverVO(null, null, null, null, null, null, null, null); //// assertEquals(true, controller.deleteDriver(vo)); // } // // @Test // public void testModifyDriver() { //// DriverVO vo = new DriverVO(null, null, null, null, null, null, null, null); //// assertEquals(true, controller.modifyDriver(vo)); // } }
gpl-2.0
specify/specify6
src/edu/ku/brc/helpers/Encryption.java
15115
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.ku.brc.helpers; import java.io.ByteArrayOutputStream; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * This will encrypt and decrypt strings. I added a couple of helper methods for getting to and from an array of bytes to a string. * THis is mostly needed so passwords are not stored in clear text.<br><br> * This was taken from a news group on www.codecomments.com I changed it a little for our needs. * @code_status Complete ** * @author chris (some guy on the web) * @author rods * */ public class Encryption { private static final Logger log = Logger.getLogger(Encryption.class); private static String encryptDecryptPassword = "KU BRC Specify"; //$NON-NLS-1$ /* * The "iteration count" for the key generation algorithm. Basically, this means that the * processing that is done to generate the key happens 1000 times. You won't even notice the * difference while encrypting or decrypting text, but an attacker will notice a *big* * difference when brute forcing keys! */ static final int ITERATION_COUNT = 1000; /* Length of the salt (see below for details on what the salt is) */ static final int SALT_LENGTH = 8; /* Which encryption algorithm we're using. */ static final String ALGORITHM = "PBEWithMD5AndDES"; //$NON-NLS-1$ /* * The name of a provider class to add to the system before running, if using a provider that's * not permanently installed. */ static final String EXTRA_PROVIDER = null; /** * @return the encryptDecryptPassword */ public static String getEncryptDecryptPassword() { return encryptDecryptPassword; } /** * @param encryptDecryptPassword the encryptDecryptPassword to set */ public static void setEncryptDecryptPassword(String encryptDecryptPassword) { Encryption.encryptDecryptPassword = encryptDecryptPassword; } /** * Encrypts the string from its array of bytes * @param input the actual string (in bytes) that is to be encrypted * @param password a password, which is really any string, but must be the same string that was used to decrypt it. * @return a byte array of the encrypted chars * @throws Exception in case something goes wrong */ public static byte[] encrypt(byte[] input, char[] password) throws Exception { /* * Get ourselves a random number generator, needed in a number of places for encrypting. */ SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$ /* * A "salt" is considered an essential part of password-based encryption. The salt is * selected at random for each encryption. It is not considered "sensitive", so it is tacked * onto the generated ciphertext without any special processing. It doesn't matter if an * attacker actually gets the salt. The salt is used as part of the key, with the very * useful result that if you Encryption the same plaintext with the same password twice, you * get *different* ciphertexts. There are lots of pages on the 'net with information about * salts and password-based encryption, so read them if you want more details. Suffice to * say salt=good, no salt=bad. */ byte[] salt = new byte[SALT_LENGTH]; sr.nextBytes(salt); /* * We've now got enough information to build the actual key. We do this by encapsulating the * variables in a PBEKeySpec and using a SecretKeyFactory to transform the spec into a key. */ PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT); SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM); SecretKey key = skf.generateSecret(keyspec); /* * We'll use a ByteArrayOutputStream to conveniently gather up data as it's encrypted. */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); /* * We've to a key, but to actually Encryption something, we need a "cipher". The cipher is * created, then initialized with the key, salt, and iteration count. We use a * PBEParameterSpec to hold the salt and iteration count needed by the Cipher object. */ PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key, paramspec, sr); /* * First, in our output, we need to save the salt in plain unencrypted form. */ baos.write(salt); /* * Next, Encryption our plaintext using the Cipher object, and write it into our output buffer. */ baos.write(cipher.doFinal(input)); /* * We're done. For security reasons, we probably want the PBEKeySpec object to clear its * internal copy of the password, so it can't be stolen later. */ keyspec.clearPassword(); return baos.toByteArray(); } /** * Decrypt the string from its array of bytes * @param input the actual string (in bytes) that is to be decrypted * @param password a password, which is really any string, but must be the same string that was used to encrypt it. * @return a byte array of the decrypted chars * @throws Exception in case something goes wrong */ public static byte[] decrypt(final byte[] input, final char[] password) throws Exception { /* * The first SALT_LENGTH bytes of the input ciphertext are actually the salt, not the * ciphertext. */ byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(input, 0, salt, 0, SALT_LENGTH); /* * We can now create a key from our salt (extracted just above), password, and iteration * count. Same procedure to create the key as in Encryption(). */ PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT); SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM); SecretKey key = skf.generateSecret(keyspec); /* * Once again, create a PBEParameterSpec object and a Cipher object. */ PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, paramspec); /* * Decrypt the data. The parameters we pass into doFinal() instruct it to skip the first * SALT_LENGTH bytes of input (which are actually the salt), and then to Encryption the next * (length - SALT_LENGTH) bytes, which are the real ciphertext. */ byte[] output = cipher.doFinal(input, SALT_LENGTH, input.length - SALT_LENGTH); /* Clear the password and return the generated plaintext. */ keyspec.clearPassword(); return output; } /** * Makes a string representing the byte array, each byte is two characters * @param bytes the byte array to be converted * @return the HEX string */ public static String makeHEXStr(final byte[] bytes) { StringBuffer strBuf = new StringBuffer(bytes.length+50); for (int i = 0; i < bytes.length; i++) { String s = Integer.toHexString(bytes[i] & 0xFF); if (s.length() == 1) s = "0" + s; //$NON-NLS-1$ strBuf.append(s.toUpperCase()); } return strBuf.toString(); } /** * Take a string where each two characters represents a HEX byte and convert it back to a byte array * @param str the string to be converted * @return the byte array */ public static byte[] reverseHEXStr(final String str) { int len = str.length() / 2; byte[] bytes = new byte[len]; int inx = 0; for (int i=0;i<len;i++) { int iVal = Integer.parseInt(str.substring(inx, inx+2), 16); bytes[i] = (byte)(iVal > 127 ? iVal-256 : iVal); inx += 2; } return bytes; } /** * Helper to decrypt a string * @param str the string to be decrypted * @return the decrypted string */ public static String decrypt(final String str) { return decrypt(str, encryptDecryptPassword); } /** * Helper to decrypt a string * @param str the string to be decrypted * @return the decrypted string */ public static String decrypt(final String str, final String key) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(key)) { return ""; //$NON-NLS-1$ } // decrypt the password try { return new String(Encryption.decrypt(Encryption.reverseHEXStr(str), key.toCharArray())); } catch (javax.crypto.BadPaddingException bpex) { log.debug("Error decrypting password."); // XXX FIXME Probably want to display a dialog here //$NON-NLS-1$ return null; } catch (Exception ex) { log.error("Error decrypting password."); // XXX FIXME Probably want to display a dialog here //$NON-NLS-1$ return str; } } /** * Encrypts a string and converts it to a string of Hex characaters where each character is two chars * @param str the string to be encrypted * @return the encrypted string which is now a string of Hex chars */ public static String encrypt(final String str) { return encrypt(str, encryptDecryptPassword); } /** * @param str * @param key * @return */ public static String encrypt(final String str, final String key) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(key)) { return ""; //$NON-NLS-1$ } // Encrypt the password before setting it into the pref try { return Encryption.makeHEXStr(Encryption.encrypt(str.getBytes(), key.toCharArray())); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Encryption.class, ex); log.error("Error endcrypting password."); // XXX FIXME Probably want to display a dialog here //$NON-NLS-1$ return str; } } /** I am leaving this here for documentation purposes * @param args input from the command line * @throws Exception some error */ public static void main(final String[] args) throws Exception { /* * If we're configured to use a third-party cryptography provider, where that provider is * not permanently installed, then we need to install it first. */ if (EXTRA_PROVIDER != null) { Provider prov = (Provider) Class.forName(EXTRA_PROVIDER).newInstance(); Security.addProvider(prov); } /* * The Encryption() function above uses a byte[] as input, so it's more general (it can Encryption * anything, not just a String), as well as using a char[] for the password, because it can * be overwritten once it's finished. Strings are immutable, so to purge them from RAM you * have to hope they get garbage collected and then the RAM gets reused. For char[]s you can * simply fill up the array with junk to erase the password from RAM. Anyway, use char[] if * you're concerned about security, but for a test case, a String works fine. */ /* Our input text and password. */ String input = "Hello World!"; //$NON-NLS-1$ String password = "abcd"; //$NON-NLS-1$ byte[] inputBytes = input.getBytes(); char[] passwordChars = password.toCharArray(); /* Encrypt the data. */ byte[] ciphertext = encrypt(inputBytes, passwordChars); System.out.println("Ciphertext:"); //$NON-NLS-1$ /* * This is just a little loop I made up which displays the encrypted data in hexadecimal, 30 * bytes to a line. Obviously, the ciphertext won't necessarily be a recognizable String, * and it'll probably have control characters and such in it. We don't even want to convert * it to a String, let alone display it onscreen. If you need text, investigate some kind of * encoding at this point on top of the encryption, like Base64. It's not that hard to * implement and it'll give you text to carry from place to place. Just remember to *de*code * the text before calling decrypt(). */ int i; for (i = 0; i < ciphertext.length; i++) { String s = Integer.toHexString(ciphertext[i] & 0xFF); if (s.length() == 1) s = "0" + s; //$NON-NLS-1$ System.out.print(s); if (i % 30 == 29) System.out.println(); } if ((ciphertext.length - 1) % 30 != 29) System.out.println(); String hexText = makeHEXStr(ciphertext); System.out.println("To: ["+hexText+"]"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.println("From: ["+reverseHEXStr(hexText)+"]****"); //$NON-NLS-1$ //$NON-NLS-2$ /* * Now, decrypt the data. Note that all we need is the password and the ciphertext. */ byte[] output = decrypt(ciphertext, passwordChars); /* Transform the output into a string. */ String sOutput = new String(output); /* Display it. */ System.out.println("Plaintext:\n" + sOutput); //$NON-NLS-1$ } }
gpl-2.0
bdaum/zoraPD
com.bdaum.zoom.gps.gmap3/src/com/bdaum/zoom/gps/naming/google/internal/GooglePlaceParser.java
6328
/* * This file is part of the ZoRa project: http://www.photozora.org. * * ZoRa 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. * * ZoRa 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 ZoRa; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * (c) 2009 Berthold Daum */ package com.bdaum.zoom.gps.naming.google.internal; import java.io.InputStream; import java.text.ParseException; import java.util.HashSet; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.osgi.util.NLS; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.bdaum.zoom.batch.internal.DoneParsingException; import com.bdaum.zoom.common.GeoMessages; import com.bdaum.zoom.core.Core; import com.bdaum.zoom.core.internal.LocationConstants; import com.bdaum.zoom.gps.geonames.AbstractParser; import com.bdaum.zoom.gps.geonames.WebServiceException; @SuppressWarnings("restriction") public class GooglePlaceParser extends AbstractParser { private static final String RESULT = "result"; //$NON-NLS-1$ private static final String LNG = "lng"; //$NON-NLS-1$ private static final String LAT = "lat"; //$NON-NLS-1$ private static final String LOCATION = "location"; //$NON-NLS-1$ private static final String GEOMETRY = "geometry"; //$NON-NLS-1$ private static final String TYPE = "type"; //$NON-NLS-1$ private static final String SHORT_NAME = "short_name"; //$NON-NLS-1$ private static final String LONG_NAME = "long_name"; //$NON-NLS-1$ private static final String ADDRESS_COMPONENT = "address_component"; //$NON-NLS-1$ private static final String GEOCODE_RESPONSE = "GeocodeResponse"; //$NON-NLS-1$ private static final String STATUS = "status";//$NON-NLS-1$ private static final String STATUS_OK = "OK"; //$NON-NLS-1$ private static final String STATUS_QUERYLIMIT = "OVER_QUERY_LIMIT"; //$NON-NLS-1$ public GooglePlaceParser(InputStream in) throws ParserConfigurationException, SAXException { super(in); nf.setMaximumFractionDigits(7); } @Override protected DefaultHandler getHandler() { DefaultHandler handler = new DefaultHandler() { private boolean geo = false; private boolean acomp; private String longName; private Set<String> types = new HashSet<String>(); private String shortName; private boolean geometry; private boolean location; private double lat = Double.NaN; private double lng = Double.NaN; @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (GEOCODE_RESPONSE.equals(qName)) geo = true; else if (geo) { if (ADDRESS_COMPONENT.equals(qName)) { acomp = true; types.clear(); longName = null; shortName = null; } else if (GEOMETRY.equals(qName)) geometry = true; else if (geometry && LOCATION.equals(qName)) location = true; } text.setLength(0); } @Override public void characters(char[] ch, int start, int length) { text.append(ch, start, length); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (geo) { String s = text.toString(); if (STATUS.equals(qName) && !STATUS_OK.equals(s)) { if (STATUS_QUERYLIMIT.equals(s)) throw new WebServiceException( NLS.bind( Messages.GooglePlaceParser_google_web_service_exception, s), new WebServiceException("18")); //$NON-NLS-1$ throw new WebServiceException( NLS.bind( Messages.GooglePlaceParser_google_web_service_exception, s)); } else if (ADDRESS_COMPONENT.equals(qName)) { if (types.contains("country")) { //$NON-NLS-1$ place.setCountryName(longName); place.setCountryCode(shortName); String continentCode = LocationConstants.countryToContinent .get(shortName); if (continentCode != null) place.setContinent(GeoMessages .getString(GeoMessages.PREFIX + continentCode)); } else if (types.contains("postal_code")) //$NON-NLS-1$ place.setPostalcode(longName); else if (types.contains("locality")) //$NON-NLS-1$ place.setName(longName); else if (types.contains("route")) //$NON-NLS-1$ place.setStreet(longName); else if (types.contains("street_number")) //$NON-NLS-1$ place.setStreetnumber(longName); else if (types.contains("administrative_area_level_1")) //$NON-NLS-1$ place.setState(longName); acomp = false; } if (acomp) { if (LONG_NAME.equals(qName)) longName = s; else if (SHORT_NAME.equals(qName)) shortName = s; else if (TYPE.equals(qName)) types.add(s); } else if (geometry && GEOMETRY.equals(qName)) geometry = false; else if (location) { if (LOCATION.equals(qName)) { location = false; } else if (LAT.equals(qName)) { try { lat = getDouble(text.toString()); } catch (ParseException e) { throw new SAXException(e); } } else if (LNG.equals(qName)) { try { lng = getDouble(text.toString()); } catch (ParseException e) { throw new SAXException(e); } } } if (RESULT.equals(qName)) { if (!Double.isNaN(lat) && !Double.isNaN(lng)) place.setDistance(Core.distance(place.getLat(), place.getLon(), lat, lng, 'k')); place.setLat(lat); place.setLon(lng); throw new DoneParsingException(); } } } }; return handler; } }
gpl-2.0
tonysparks/seventh
src/seventh/server/ServerContext.java
6684
/* * see license.txt */ package seventh.server; import java.util.List; import java.util.Random; import java.util.Vector; import java.util.concurrent.atomic.AtomicReference; import harenet.NetConfig; import harenet.api.Server; import harenet.api.impl.HareNetServer; import leola.vm.Leola; import seventh.shared.Console; import seventh.shared.Debugable.DebugableListener; import seventh.shared.MapList.MapEntry; import seventh.shared.RconHash; import seventh.shared.Scripting; import seventh.shared.State; import seventh.shared.StateMachine; /** * Context information for a {@link GameServer} * * @author Tony * */ public class ServerContext { /** * Invalid rcon token */ public static final long INVALID_RCON_TOKEN = -1; private Server server; private GameServer gameServer; private RemoteClients clients; private ServerNetworkProtocol protocol; private Leola runtime; private Console console; private String rconPassword; private MapCycle mapCycle; private ServerSeventhConfig config; private Random random; private StateMachine<State> stateMachine; private AtomicReference<GameSession> gameSession; private List<GameSessionListener> gameSessionListeners; private GameSessionListener sessionListener = new GameSessionListener() { @Override public void onGameSessionDestroyed(GameSession session) { gameSession.set(null); for(GameSessionListener l : gameSessionListeners) { l.onGameSessionDestroyed(session); } } @Override public void onGameSessionCreated(GameSession session) { gameSession.set(session); for(GameSessionListener l : gameSessionListeners) { l.onGameSessionCreated(session); } } }; /** * @param gameServer * @param config * @param runtime */ public ServerContext(GameServer gameServer, ServerSeventhConfig config, Leola runtime, Console console) { this.gameServer = gameServer; this.config = config; this.runtime = runtime; this.console = console; this.rconPassword = config.getRconPassword(); this.random = new Random(); this.clients = new RemoteClients(config.getMaxPlayers()); this.stateMachine = new StateMachine<State>(); NetConfig netConfig = config.getNetConfig(); netConfig.setMaxConnections(config.getMaxPlayers()); this.server = new HareNetServer(netConfig); this.protocol = new ServerNetworkProtocol(this); this.server.addConnectionListener(this.protocol); this.gameSessionListeners = new Vector<>(); addGameSessionListener(this.protocol); this.gameSession = new AtomicReference<>(); this.mapCycle = new MapCycle(config.getMapListings()); } /** * @return true if there is a debug listener */ public boolean hasDebugListener() { return this.gameServer.getDebugListener() != null; } /** * @return the {@link DebugableListener} */ public DebugableListener getDebugableListener() { return this.gameServer.getDebugListener(); } /** * Spawns a new GameSession * * @param map - the map to load */ public void spawnGameSession(MapEntry map) { this.mapCycle.setCurrentMap(map); this.stateMachine.changeState(new LoadingState(this, this.sessionListener, map)); } /** * Spawns a new Game Session */ public void spawnGameSession() { spawnGameSession(mapCycle.getNextMap()); } /** * @return true if there is a {@link GameSession} loaded */ public boolean hasGameSession() { return gameSession.get() != null; } /** * @return the gameSession */ public GameSession getGameSession() { return gameSession.get(); } /** * Adds a {@link GameSessionListener} * * @param l */ public void addGameSessionListener(GameSessionListener l) { this.gameSessionListeners.add(l); } /** * Removes a {@link GameSessionListener} * * @param l */ public void removeGameSessionListener(GameSessionListener l) { this.gameSessionListeners.remove(l); } /** * Creates a security token for RCON sessions * * @return a security token */ public long createToken() { long token = INVALID_RCON_TOKEN; while(token == INVALID_RCON_TOKEN) { token = this.random.nextLong(); } return token; } /** * @return the port in which this server is listening on */ public int getPort() { return this.gameServer.getPort(); } /** * @param token * @return the hashed rcon password */ public String getRconPassword(long token) { RconHash hash = new RconHash(token); return hash.hash(this.rconPassword); } /** * @return the mapCycle */ public MapCycle getMapCycle() { return mapCycle; } /** * @return the random */ public Random getRandom() { return random; } /** * @return the server */ public Server getServer() { return server; } /** * @return the serverProtocolListener */ public ServerNetworkProtocol getServerProtocol() { return protocol; } /** * @return the stateMachine */ public StateMachine<State> getStateMachine() { return stateMachine; } /** * @return the gameServer */ public GameServer getGameServer() { return gameServer; } /** * @return the console */ public Console getConsole() { return console; } /** * @return the clients */ public RemoteClients getClients() { return clients; } /** * @return the runtime */ public Leola getRuntime() { return runtime; } /** * @return a new instance of the {@link Leola} runtime */ public Leola newRuntime() { Leola runtime = Scripting.newRuntime(); return runtime; } /** * @return the config */ public ServerSeventhConfig getConfig() { return config; } }
gpl-2.0
mevqz/aoc-parser
src/com/gammery/aocparser/EventService.java
5669
/* * AoC-Parser, Copyright (C) 2012 Matías E. Vazquez (matiasevqz@gmail.com) * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.gammery.aocparser; import com.gammery.aocparser.entity.*; import java.util.*; import nu.xom.*; import java.io.*; //FIXME DUDAS /* Deberia usar RuntimeException, IllegalException o usar una propia como ElementNotFoundException?? Si no tiene utilidad crear una creo q es mejor usar RuntimeExp.. ARREGLAR: getEvent y getEventDescrp deben tirar la misma Exception cuando no se encuentre el evento */ //FIXME Esta clase puede ser perfectamente no instanciable. Solo se usa en MapEvent asi q la puedo hacer un attrb static de esa clase y acceder con metodos statics public class EventService { private static Map<Integer,Event> events = new HashMap<Integer,Event>(); private final static String XMLFile = "events.xml"; static { loadXML(XMLFile); }; private static void loadXML(String file) { try { Builder builder = new Builder(); // anteriormente lo usaba directamente, pero ahora los resources estan en el jar... //Document doc = builder.build(new BufferedInputStream(new FileInputStream(file))); //InputStream in = EventService.class.getClassLoader().getResourceAsStream(file); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); //InputStream in = classLoader.getResourceAsStream(file); InputStream in = EventService.class.getClassLoader().getResourceAsStream(file); // InputStream in = EventService.class.getResourceAsStream(file); // con / Document doc = builder.build(new BufferedInputStream(in)); Element root = doc.getRootElement(); Elements eEvents = root.getChildElements("event"); for (int i = 0; i < eEvents.size(); i++) { Event event = new Event(); Element eEvent = eEvents.get(i); event.setID(Integer.parseInt(eEvent.getAttributeValue("id"))); Element eName = eEvent.getFirstChildElement("name"); event.setName(eName.getValue()); Elements langs = eEvent.getChildElements("message"); if (langs != null) { for (int j = 0; j < langs.size(); j++) { Element eMessage = langs.get(j); event.addFormatDescription(eMessage.getAttributeValue("lang"), eMessage.getValue()); } } Element eScore = eEvent.getFirstChildElement("score"); if (eScore != null) event.setScore(Integer.parseInt(eScore.getValue())); Element ePenalty = eEvent.getFirstChildElement("penalty"); if (ePenalty != null) event.setPenalty(Integer.parseInt(ePenalty.getValue())); events.put(event.getID(), event); } } catch (Exception e) { System.err.println("Oops, Exception!!"); e.printStackTrace(); } } //TODO Mejorar las strings de los erroes y agregar el id y el lang a ellas public static Event getEvent(int id) throws IllegalArgumentException { Event event = events.get(id); if (event == null) // throw new IllegalArgumentException("Invalid Event ID"); return new Event(); return event; } // FIXME saque el illegalargumentexc public static String getEventDescription(int id) //throws ElementNotFoundException, LanguageNotFoundException //DUDA si especifico ua super clase tamb tengo q escp las subclases??? // throws RuntimeException, LanguageNotFoundException { String lang = java.util.Locale.getDefault().getLanguage(); return getEventDescription(id, lang); } //TODO Mejorar las strings de los erroes y agregar el id y el lang a ellas public static String getEventDescription(int id, String lang) // throws RuntimeException, LanguageNotFoundException //throws ElementNotFoundException, LanguageNotFoundException { String description = null; try { Event event = getEvent(id); description = event.getFormatDescription(lang); if (description == null) { String def = event.getFormatDescription(); throw new LanguageNotFoundException("Event description language: " + lang + " not found", def); } } catch (IllegalArgumentException e) { throw new RuntimeException("Event description ID: " + id + " not found"); } return description; } // Testing method public static void main(String args[]) { new EventService().display(); } public void display() { for (Event e : events.values()) { System.out.println("Event ID: " + e.getID()); System.out.println("Name: " + e.getName()); for (String lang : e.getDescriptions().keySet()) { String format = String.format(e.getDescriptions().get(lang), "????", "????", 0000); System.out.println(lang + ": " + format); } System.out.println("Score: " + e.getScore()); System.out.println("-----------"); } System.out.println(); } } class LanguageNotFoundException extends RuntimeException { private String format; public LanguageNotFoundException(String error, String s) { super(error); format = s; } // Get the FIRST format description public String getFormatDescription() { return format; } }
gpl-2.0
kainagel/teach-oop
src/main/java/mm_graphics/dd_Capabilities/CapabilitiesTest.java
9574
package mm_graphics.dd_Capabilities; /** * This test shows the different buffer capabilities for each * GraphicsConfiguration on each GraphicsDevice. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * This class wraps a graphics configuration so that it can be * displayed nicely in components. */ class GCWrapper { private GraphicsConfiguration gc; private int index; public GCWrapper(GraphicsConfiguration gc, int index) { this.gc = gc; this.index = index; } public GraphicsConfiguration getGC() { return gc; } public String toString() { return gc.toString(); } } /** * Main frame class. */ public class CapabilitiesTest extends JFrame implements ItemListener { private JComboBox gcSelection = new JComboBox(); private JCheckBox imageAccelerated = new JCheckBox("Accelerated", false); private JCheckBox imageTrueVolatile = new JCheckBox("Volatile", false); private JCheckBox flipping = new JCheckBox("Flipping", false); private JLabel flippingMethod = new JLabel(""); private JCheckBox fullScreen = new JCheckBox("Full Screen Only", false); private JCheckBox multiBuffer = new JCheckBox("Multi-Buffering", false); private JCheckBox fbAccelerated = new JCheckBox("Accelerated", false); private JCheckBox fbTrueVolatile = new JCheckBox("Volatile", false); private JCheckBox bbAccelerated = new JCheckBox("Accelerated", false); private JCheckBox bbTrueVolatile = new JCheckBox("Volatile", false); public CapabilitiesTest(GraphicsDevice dev) { super(dev.getDefaultConfiguration()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { System.exit(0); } }); initComponents(getContentPane()); GraphicsConfiguration[] gcs = dev.getConfigurations(); for (int i = 0; i < gcs.length; i++) { gcSelection.addItem(new GCWrapper(gcs[i], i)); } gcSelection.addItemListener(this); gcChanged(); } /** * Creates and lays out components in the container. * See the comments below for an organizational overview by panel. */ private void initComponents(Container c) { // +=c=====================================================+ // ++=gcPanel==============================================+ // ++ [gcSelection] + // ++=capsPanel============================================+ // +++=imageCapsPanel======================================+ // +++ [imageAccelerated] + // +++ [imageTrueVolatile] + // +++=bufferCapsPanel=====================================+ // ++++=bufferAccessCapsPanel==============================+ // +++++=flippingPanel=====================================+ // +++++ [flipping] + // +++++=fsPanel===========================================+ // +++++ [indentPanel][fullScreen] + // +++++=mbPanel===========================================+ // +++++ [indentPanel][multiBuffer] + // ++++=buffersPanel=======================================+ // +++++=fbPanel===============+=bbPanel===================+ // +++++ + + // +++++ [fbAccelerated] + [bbAccelerated] + // +++++ + + // +++++ [fbTrueVolatile] + [bbTrueVolatile] + // +++++ + + // +=======================================================+ c.setLayout(new BorderLayout()); // Graphics Config JPanel gcPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); c.add(gcPanel, BorderLayout.NORTH); gcSelection.setPreferredSize(new Dimension(400, 30)); gcPanel.add(gcSelection); // Capabilities JPanel capsPanel = new JPanel(new BorderLayout()); c.add(capsPanel, BorderLayout.CENTER); // Image Capabilities JPanel imageCapsPanel = new JPanel(new GridLayout(2, 1)); capsPanel.add(imageCapsPanel, BorderLayout.NORTH); imageCapsPanel.setBorder(BorderFactory.createTitledBorder( "Image Capabilities")); imageAccelerated.setEnabled(false); imageCapsPanel.add(imageAccelerated); imageTrueVolatile.setEnabled(false); imageCapsPanel.add(imageTrueVolatile); // Buffer Capabilities JPanel bufferCapsPanel = new JPanel(new BorderLayout()); capsPanel.add(bufferCapsPanel, BorderLayout.CENTER); bufferCapsPanel.setBorder(BorderFactory.createTitledBorder( "Buffer Capabilities")); // Buffer Access JPanel bufferAccessCapsPanel = new JPanel(new GridLayout(3, 1)); bufferAccessCapsPanel.setPreferredSize(new Dimension(300, 88)); bufferCapsPanel.add(bufferAccessCapsPanel, BorderLayout.NORTH); // Flipping JPanel flippingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); bufferAccessCapsPanel.add(flippingPanel); flippingPanel.add(flipping); flipping.setEnabled(false); flippingPanel.add(flippingMethod); // Full-screen JPanel fsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); bufferAccessCapsPanel.add(fsPanel); JPanel indentPanel = new JPanel(); indentPanel.setPreferredSize(new Dimension(30, 30)); fsPanel.add(indentPanel); fsPanel.add(fullScreen); fullScreen.setEnabled(false); // Multi-buffering JPanel mbPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); bufferAccessCapsPanel.add(mbPanel); indentPanel = new JPanel(); indentPanel.setPreferredSize(new Dimension(30, 30)); mbPanel.add(indentPanel); mbPanel.add(multiBuffer); multiBuffer.setEnabled(false); // Front and Back Buffer Capabilities JPanel buffersPanel = new JPanel(new GridLayout(1, 2)); bufferCapsPanel.add(buffersPanel, BorderLayout.CENTER); // Front Buffer JPanel fbPanel = new JPanel(new GridLayout(2, 1)); fbPanel.setBorder(BorderFactory.createTitledBorder( "Front Buffer")); buffersPanel.add(fbPanel); fbPanel.add(fbAccelerated); fbAccelerated.setEnabled(false); fbPanel.add(fbTrueVolatile); fbTrueVolatile.setEnabled(false); // Back Buffer JPanel bbPanel = new JPanel(new GridLayout(2, 1)); bbPanel.setPreferredSize(new Dimension(250, 80)); bbPanel.setBorder(BorderFactory.createTitledBorder( "Back and Intermediate Buffers")); buffersPanel.add(bbPanel); bbPanel.add(bbAccelerated); bbAccelerated.setEnabled(false); bbPanel.add(bbTrueVolatile); bbTrueVolatile.setEnabled(false); } public void itemStateChanged(ItemEvent ev) { gcChanged(); } private void gcChanged() { GCWrapper wrap = (GCWrapper)gcSelection.getSelectedItem(); //assert wrap != null; GraphicsConfiguration gc = wrap.getGC(); //assert gc != null; //Image Caps ImageCapabilities imageCaps = gc.getImageCapabilities(); imageAccelerated.setSelected(imageCaps.isAccelerated()); imageTrueVolatile.setSelected(imageCaps.isTrueVolatile()); // Buffer Caps BufferCapabilities bufferCaps = gc.getBufferCapabilities(); flipping.setSelected(bufferCaps.isPageFlipping()); flippingMethod.setText(getFlipText(bufferCaps.getFlipContents())); fullScreen.setSelected(bufferCaps.isFullScreenRequired()); multiBuffer.setSelected(bufferCaps.isMultiBufferAvailable()); // Front buffer caps imageCaps = bufferCaps.getFrontBufferCapabilities(); fbAccelerated.setSelected(imageCaps.isAccelerated()); fbTrueVolatile.setSelected(imageCaps.isTrueVolatile()); imageCaps = bufferCaps.getFrontBufferCapabilities(); // Back buffer caps imageCaps = bufferCaps.getBackBufferCapabilities(); bbAccelerated.setSelected(imageCaps.isAccelerated()); bbTrueVolatile.setSelected(imageCaps.isTrueVolatile()); } private static String getFlipText(BufferCapabilities.FlipContents flip) { if (flip == null) { return ""; } else if (flip == BufferCapabilities.FlipContents.UNDEFINED) { return "Method Unspecified"; } else if (flip == BufferCapabilities.FlipContents.BACKGROUND) { return "Cleared to Background"; } else if (flip == BufferCapabilities.FlipContents.PRIOR) { return "Previous Front Buffer"; } else { // if (flip == BufferCapabilities.FlipContents.COPIED) return "Copied"; } } public static void main(String[] args) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = ge.getScreenDevices(); for (int i = 0; i < devices.length; i++) { CapabilitiesTest tst = new CapabilitiesTest(devices[i]); tst.pack(); tst.setVisible(true); } } }
gpl-2.0
sebastian24/PersonalHelper-Android-Application
app/src/main/java/com/onetouchstudio/personalhelper/fragments/converter/LengthConverterFragment.java
9441
package com.onetouchstudio.personalhelper.fragments.converter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import com.iangclifton.android.floatlabel.FloatLabel; import com.onetouchstudio.personalhelper.R; public class LengthConverterFragment extends Fragment { Spinner lengthSpinner; FloatLabel valueLabel; TextView mmValue; TextView cmValue; TextView dmValue; TextView mValue; TextView kmValue; TextView inchValue; TextView ftValue; TextView ydValue; TextView mileValue; double value; double mmCalcValue; double cmCalcValue; double dmCalcValue; double mCalcValue; double kmCalcValue; double inchCalcValue; double ftCalcValue; double ydCalcValue; double mileCalcValue; String[] lengthValueList; public static LengthConverterFragment newInstance() { return new LengthConverterFragment(); } public LengthConverterFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_lenght_converter, container, false); lengthValueList = getResources().getStringArray(R.array.length_value_list); lengthSpinner = (Spinner) view.findViewById(R.id.lengthSpinner); ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), R.layout.custom_spinner_length, lengthValueList); spinnerAdapter.setDropDownViewResource(R.layout.custom_spinner_length); lengthSpinner.setAdapter(spinnerAdapter); valueLabel = (FloatLabel) view.findViewById(R.id.length_amount); mmValue = (TextView) view.findViewById(R.id.mmValue); cmValue = (TextView) view.findViewById(R.id.cmValue); dmValue = (TextView) view.findViewById(R.id.dmValue); mValue = (TextView) view.findViewById(R.id.mValue); kmValue = (TextView) view.findViewById(R.id.kmValue); inchValue = (TextView) view.findViewById(R.id.inchValue); ftValue = (TextView) view.findViewById(R.id.feetValue); ydValue = (TextView) view.findViewById(R.id.yardValue); mileValue = (TextView) view.findViewById(R.id.mileValue); lengthSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { calculateLength(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); valueLabel.getEditText().addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { calculateLength(); } @Override public void afterTextChanged(Editable s) { calculateLength(); } }); return view; } public static String getTitle() { return "Length"; } public void calculateLength(){ String getSelectedType = lengthSpinner.getSelectedItem().toString(); if(valueLabel.getEditText().getText().toString().equals("") || valueLabel.getEditText().getText().toString() == null){ value = 0; } else{ value = Float.parseFloat(valueLabel.getEditText().getText().toString()); } switch (getSelectedType){ case "mm": mmCalcValue = value; cmCalcValue = value * 0.1; dmCalcValue = value * 0.01; mCalcValue = value * 0.001; kmCalcValue = value * 0.000001; inchCalcValue = value * 0.03937; ftCalcValue = value * 0.00328; ydCalcValue = value * 0.001093; mileCalcValue = value * 0.0000006214; break; case "cm": mmCalcValue = value * 10; cmCalcValue = value; dmCalcValue = value * 0.1; mCalcValue = value * 0.01; kmCalcValue = value * 0.00001; inchCalcValue = value * 0.3937; ftCalcValue = value * 0.0328; ydCalcValue = value * 0.01093; mileCalcValue = value * 0.000006214; break; case "dm": mmCalcValue = value * 100; cmCalcValue = value * 10; dmCalcValue = value; mCalcValue = value * 0.1; kmCalcValue = value * 0.0001; inchCalcValue = value * 3.937; ftCalcValue = value * 0.328; ydCalcValue = value * 0.1093; mileCalcValue = value * 0.00006214; break; case "m": mmCalcValue = value * 1000; cmCalcValue = value * 100; dmCalcValue = value * 10; mCalcValue = value; kmCalcValue = value * 0.001; inchCalcValue = value * 39.37; ftCalcValue = value * 3.28; ydCalcValue = value * 1.093; mileCalcValue = value * 0.0006214; break; case "km": mmCalcValue = value * 1000000; cmCalcValue = value * 100000; dmCalcValue = value * 10000; mCalcValue = value * 1000; kmCalcValue = value; inchCalcValue = value * 39370.07; ftCalcValue = value * 3280.83; ydCalcValue = value * 1093.61; mileCalcValue = value * 0.6214; break; case "inch": mmCalcValue = value * 25.4; cmCalcValue = value * 2.54; dmCalcValue = value * 0.254; mCalcValue = value * 0.0254; kmCalcValue = value * 0.0000254; inchCalcValue = value; ftCalcValue = value / 12; ydCalcValue = value / 36; mileCalcValue = value / 63360; break; case "ft": mmCalcValue = value * 304.8; cmCalcValue = value * 30.48; dmCalcValue = value * 3.048; mCalcValue = value * 0.3048; kmCalcValue = value * 0.0003048; inchCalcValue = value * 12; ftCalcValue = value; ydCalcValue = value / 3; mileCalcValue = value / 5280; break; case "yd": mmCalcValue = value * 914.4; cmCalcValue = value * 91.44; dmCalcValue = value * 9.144; mCalcValue = value * 0.9144; kmCalcValue = value * 0.0009144; inchCalcValue = value * 36; ftCalcValue = value * 3; ydCalcValue = value; mileCalcValue = value * 0.00056818; break; case "mile": mmCalcValue = value * 1609344; cmCalcValue = value * 160934.4; dmCalcValue = value * 16093.44; mCalcValue = value * 1609.344; kmCalcValue = value * 1.609344; inchCalcValue = value * 63360; ftCalcValue = value * 5280; ydCalcValue = value * 1760; mileCalcValue = value; break; } mmCalcValue = (double)Math.round(mmCalcValue * 100000) / 100000; cmCalcValue = (double)Math.round(cmCalcValue * 100000) / 100000; dmCalcValue = (double)Math.round(dmCalcValue * 100000) / 100000; mCalcValue = (double)Math.round(mCalcValue * 100000) / 100000; kmCalcValue = (double)Math.round(kmCalcValue * 100000) / 100000; inchCalcValue = (double)Math.round(inchCalcValue * 100000) / 100000; ftCalcValue = (double)Math.round(ftCalcValue * 100000) / 100000; ydCalcValue = (double)Math.round(ydCalcValue * 100000) / 100000; mileCalcValue = (double)Math.round(mileCalcValue * 100000) / 100000; setViews(); } public void setViews(){ mmValue.setText(String.valueOf(mmCalcValue)); cmValue.setText(String.valueOf(cmCalcValue)); dmValue.setText(String.valueOf(dmCalcValue)); mValue.setText(String.valueOf(mCalcValue)); kmValue.setText(String.valueOf(kmCalcValue)); inchValue.setText(String.valueOf(inchCalcValue)); ftValue.setText(String.valueOf(ftCalcValue)); ydValue.setText(String.valueOf(ydCalcValue)); mileValue.setText(String.valueOf(mileCalcValue)); } }
gpl-2.0
SampleSizeShop/GlimmpseWeb
src/edu/ucdenver/bios/glimmpseweb/client/shared/ExplanationButton.java
2169
/* * User Interface for the GLIMMPSE Software System. Processes * incoming HTTP requests for power, sample size, and detectable * difference * * Copyright (C) 2011 Regents of the University of Colorado. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.ucdenver.bios.glimmpseweb.client.shared; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import edu.ucdenver.bios.glimmpseweb.client.GlimmpseWeb; /** * Button which opens and explanation dialog box * * @author Vijay Akula * @author Sarah Kreidler * */ public class ExplanationButton extends Button { private static final String STYLE = "explanationButton"; protected ExplanationDialogBox dialogBox; /** * Constructor * @param buttonText * @param alertTextHeader * @param alertText */ public ExplanationButton(String headerText, String explanationText) { // set up the button itself super(GlimmpseWeb.constants.buttonExplain()); this.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { showDialog(); } }); // set style this.setStyleName(STYLE); dialogBox = new ExplanationDialogBox(headerText, explanationText); } private void showDialog() { dialogBox.center(); } }
gpl-2.0
AlexandruGhergut/IPTAT
src/iptat/gui/Toolbar.java
7549
package iptat.gui; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JToolBar; import iptat.util.CommandGenerator; @SuppressWarnings("serial") public class Toolbar extends JToolBar { private final int IMAGE_SIZE = 16; private CommandGenerator commandGenerator; public Toolbar() { commandGenerator=CommandGenerator.getInstance(); super.setFloatable(false); addFileButtons(); super.addSeparator(); addEditButtons(); super.addSeparator(); addTriangulationButton(); super.addSeparator(); addAffineTransformButtons(); super.add(Box.createHorizontalGlue()); addHelpButton(); } private void addFileButtons() { ImageIcon load = new ImageIcon(getClass().getResource("/res/img/open.png")); load.setImage(getResizedImage(load.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton loadPolygon = new JButton(load); super.add(loadPolygon); loadPolygon.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerLoadPolygon(); } }); loadPolygon.setToolTipText("Load Polygon (Ctrl+O)"); ImageIcon save = new ImageIcon(getClass().getResource("/res/img/save.png")); save.setImage(getResizedImage(save.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton savePolygon = new JButton(save); super.add(savePolygon); savePolygon.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerSavePolygon(); } }); savePolygon.setToolTipText("Save Polygon (Ctrl+S)"); } private void addEditButtons(){ ImageIcon add = new ImageIcon(getClass().getResource("/res/img/add.png")); add.setImage(getResizedImage(add.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton addPoints = new JButton(add); super.add(addPoints); addPoints.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerAddPoints(); } }); addPoints.setToolTipText("Add Points (Ctrl+A)"); ImageIcon delete = new ImageIcon(getClass().getResource("/res/img/clear.png")); delete.setImage(getResizedImage(delete.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton deletePoints = new JButton(delete); super.add(deletePoints); deletePoints.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerClear(); } }); deletePoints.setToolTipText("Reset (R)"); ImageIcon undo = new ImageIcon(getClass().getResource("/res/img/undo.png")); undo.setImage(getResizedImage(undo.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton undoButton = new JButton(undo); super.add(undoButton); undoButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerUndo(); } }); undoButton.setToolTipText("Undo (Ctrl+Z)"); ImageIcon redo = new ImageIcon(getClass().getResource("/res/img/redo.png")); redo.setImage(getResizedImage(redo.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton redoButton = new JButton(redo); super.add(redoButton); redoButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerRedo(); } }); redoButton.setToolTipText("Redo (Ctrl+X)"); } private void addHelpButton(){ ImageIcon help = new ImageIcon(getClass().getResource("/res/img/help.png")); help.setImage(getResizedImage(help.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton helpButton = new JButton(help); super.add(helpButton); helpButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "The purpose of this application is to show " + "the invariance of polygon triangulations under affine transformations.\n"+ "There are three ways you can use to provide a polygon:\n"+ "1. You can click on the drawing board for each vertex you want to add to your polygon;\n"+ "2. You can load a file containing the coordinates of a polygon vertex on each line;\n"+ "3. You can use the \"Add Points (Ctrl+A)\" button;\n"+ "Note: if the polygon vertices are not provided in a counterclockwise order, "+ "the algorithm will reverse their order!\n"+ "There are two available affine transformations:\n" + "1. Zoom (by scrolling the mouse wheel);\n" + "2. Translation (by dragging your mouse while pressing its left button);"); } }); helpButton.setToolTipText("Help"); } private void addTriangulationButton(){ ImageIcon triangulation = new ImageIcon(getClass().getResource("/res/img/triangle.png")); triangulation.setImage(getResizedImage(triangulation.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton triangulationButton = new JButton(triangulation); super.add(triangulationButton); triangulationButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerTriangulate(); } }); triangulationButton.setToolTipText("Triangulate (T)"); } private void addAffineTransformButtons() { ImageIcon zoomIn = new ImageIcon(getClass().getResource("/res/img/zoomIn.png")); zoomIn.setImage(getResizedImage(zoomIn.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton zoomInButton = new JButton(zoomIn); super.add(zoomInButton); zoomInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerZoomIn(); } }); zoomInButton.setToolTipText("Zoom In"); ImageIcon zoomOut = new ImageIcon(getClass().getResource("/res/img/zoomOut.png")); zoomOut.setImage(getResizedImage(zoomOut.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton zoomOutButton = new JButton(zoomOut); super.add(zoomOutButton); zoomOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerZoomOut(); } }); zoomOutButton.setToolTipText("Zoom Out"); ImageIcon zoom = new ImageIcon(getClass().getResource("/res/img/zoom.png")); zoom.setImage(getResizedImage(zoom.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton zoomButton = new JButton(zoom); super.add(zoomButton); zoomButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerZoom(); } }); zoomButton.setToolTipText("Zoom"); ImageIcon translate = new ImageIcon(getClass().getResource("/res/img/translate.png")); translate.setImage(getResizedImage(translate.getImage(), IMAGE_SIZE, IMAGE_SIZE)); JButton translateButton = new JButton(translate); super.add(translateButton); translateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { commandGenerator.triggerTranslate(); } }); translateButton.setToolTipText("Translate"); } private Image getResizedImage(Image src, int width, int height) { BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImage.createGraphics(); g2.drawImage(src, 0, 0, width, height, null); g2.dispose(); return resizedImage; } }
gpl-2.0
ReagentX/heidnerComputerScienceProjects
Temp Sardegna Stuff/Lesson_14_Arrays/ArrayLoopTwo_SOL.java
391
//© A+ Computer Science // www.apluscompsci.com //array loop access example import static java.lang.System.*; public class ArrayLoopTwo_SOL { public static void main(String args[]) { int[] nums = new int[6]; for(int spot=0; spot<nums.length; spot++) { nums[spot] = spot*4; } for( int item : nums ) { System.out.print( item + " " ); } } }
gpl-2.0
anugotta/RadioRake
src/com/asp/radiorake/RecordioBaseActivity.java
5010
package com.asp.radiorake; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.asp.radiorake.recording.RecorderService; import com.aspillai.R; public class RecordioBaseActivity extends SherlockActivity { private static final int ADD_FAVOURITE = 1; private static final int EXIT = 2; private static final int SCHEDULED_RECORDINGS = 3; private static final int RECORDINGS = 4; private static final String TAG = "com.asp.radiorake.RecordioBaseActivity"; @Override public void onResume() { super.onResume(); } @Override public void finish() { super.finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, ADD_FAVOURITE, Menu.NONE, "Add Favourite"); menu.add(Menu.NONE, EXIT, Menu.NONE, "Exit RadioRake!"); menu.add(Menu.NONE, SCHEDULED_RECORDINGS, Menu.NONE, "Scheduled Recordings"); menu.add(Menu.NONE, RECORDINGS, Menu.NONE, "Recordings"); return (super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { RadioApplication radioApplication = (RadioApplication) getApplication(); switch (item.getItemId()) { case ADD_FAVOURITE: RadioDetails radioDetails = new RadioDetails(); if (alreadyPlaying()) { radioDetails = radioApplication.getPlayingStation(); } Intent confirmDetailsIntent = new Intent(RecordioBaseActivity.this, ConfirmDetailsActivity.class); confirmDetailsIntent.putExtra(getString(R.string.radio_details_key), radioDetails); startActivity(confirmDetailsIntent); finish(); return true; case SCHEDULED_RECORDINGS: Intent scheduledRecordingsIntent = new Intent(RecordioBaseActivity.this, ListScheduledRecordingsActivity.class); startActivity(scheduledRecordingsIntent); finish(); return true; case RECORDINGS: Intent recordingsIntent = new Intent(RecordioBaseActivity.this, RecordingsActivity.class); startActivity(recordingsIntent); finish(); return true; case EXIT: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Exit RadioRake?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { checkIfExitingFromRadioActivity(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { } }); builder.create().show(); return true; default: return super.onOptionsItemSelected(item); } } private void checkIfExitingFromRadioActivity() { // if (getClass().getSimpleName().equals("RadioActivity")) { MediaPlayer mediaPlayer = ((RadioApplication) getApplication()).getMediaPlayer(); if (mediaPlayer != null && mediaPlayer.isPlaying()) { PlayerService.sendWakefulWork(getApplicationContext(), createPlayingIntent(null, RadioApplication.StopPlaying)); } if (RecorderService.alreadyRecording()) { RecorderService.cancelRecording(); } // } else { // ((RadioApplication) getApplication()). // (true); // } finish(); } public boolean alreadyPlaying() { RadioApplication radioApplication = (RadioApplication) getApplication(); MediaPlayer mediaPlayer = radioApplication.getMediaPlayer(); return mediaPlayer != null && mediaPlayer.isPlaying(); } protected Intent createRecordingIntent(RadioDetails radioDetails) { Intent intent = new Intent("com.asp.radiorake.recording.RecorderService"); if (radioDetails != null) { intent.putExtra(getString(R.string.radio_details_key), radioDetails); } return intent; } protected Intent createPlayingIntent(RadioDetails radioDetails, int operation) { Intent intent = new Intent("com.asp.radiorake.PlayerService"); if (radioDetails != null) { intent.putExtra(getString(R.string.radio_details_key), radioDetails); } intent.putExtra(getString(R.string.player_service_operation_key), operation); return intent; } }
gpl-2.0
flaviociaware/cwEnsaiosWeb
cwCADSUS/src/main/java/org/hl7/v3/PRPAIN201301UV02MFMIMT700701UV01ControlActProcess.java
17777
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PRPA_IN201301UV02.MFMI_MT700701UV01.ControlActProcess complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PRPA_IN201301UV02.MFMI_MT700701UV01.ControlActProcess"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="id" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="code" type="{urn:hl7-org:v3}CD" minOccurs="0"/> * &lt;element name="text" type="{urn:hl7-org:v3}ED" minOccurs="0"/> * &lt;element name="effectiveTime" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="priorityCode" type="{urn:hl7-org:v3}CE" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="reasonCode" type="{urn:hl7-org:v3}CE" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="languageCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="overseer" type="{urn:hl7-org:v3}MFMI_MT700701UV01.Overseer" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="authorOrPerformer" type="{urn:hl7-org:v3}MFMI_MT700701UV01.AuthorOrPerformer" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="dataEnterer" type="{urn:hl7-org:v3}MFMI_MT700701UV01.DataEnterer" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="informationRecipient" type="{urn:hl7-org:v3}MFMI_MT700701UV01.InformationRecipient" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="subject" type="{urn:hl7-org:v3}PRPA_IN201301UV02.MFMI_MT700701UV01.Subject1" maxOccurs="unbounded"/> * &lt;element name="reasonOf" type="{urn:hl7-org:v3}MFMI_MT700701UV01.Reason" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="classCode" use="required" type="{urn:hl7-org:v3}ActClassControlAct" /> * &lt;attribute name="moodCode" use="required" type="{urn:hl7-org:v3}x_ActMoodIntentEvent" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PRPA_IN201301UV02.MFMI_MT700701UV01.ControlActProcess", propOrder = { "realmCode", "typeId", "templateId", "id", "code", "text", "effectiveTime", "priorityCode", "reasonCode", "languageCode", "overseer", "authorOrPerformer", "dataEnterer", "informationRecipient", "subject", "reasonOf" }) public class PRPAIN201301UV02MFMIMT700701UV01ControlActProcess { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; protected List<II> id; protected CD code; protected ED text; protected IVLTS effectiveTime; protected List<CE> priorityCode; protected List<CE> reasonCode; protected CE languageCode; @XmlElement(nillable = true) protected List<MFMIMT700701UV01Overseer> overseer; @XmlElement(nillable = true) protected List<MFMIMT700701UV01AuthorOrPerformer> authorOrPerformer; @XmlElement(nillable = true) protected List<MFMIMT700701UV01DataEnterer> dataEnterer; @XmlElement(nillable = true) protected List<MFMIMT700701UV01InformationRecipient> informationRecipient; @XmlElement(required = true, nillable = true) protected List<PRPAIN201301UV02MFMIMT700701UV01Subject1> subject; @XmlElement(nillable = true) protected List<MFMIMT700701UV01Reason> reasonOf; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "classCode", required = true) protected ActClassControlAct classCode; @XmlAttribute(name = "moodCode", required = true) protected XActMoodIntentEvent moodCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the id property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the id property. * * <p> * For example, to add a new item, do as follows: * <pre> * getId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getId() { if (id == null) { id = new ArrayList<II>(); } return this.id; } /** * Gets the value of the code property. * * @return * possible object is * {@link CD } * */ public CD getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link CD } * */ public void setCode(CD value) { this.code = value; } /** * Gets the value of the text property. * * @return * possible object is * {@link ED } * */ public ED getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link ED } * */ public void setText(ED value) { this.text = value; } /** * Gets the value of the effectiveTime property. * * @return * possible object is * {@link IVLTS } * */ public IVLTS getEffectiveTime() { return effectiveTime; } /** * Sets the value of the effectiveTime property. * * @param value * allowed object is * {@link IVLTS } * */ public void setEffectiveTime(IVLTS value) { this.effectiveTime = value; } /** * Gets the value of the priorityCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the priorityCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPriorityCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CE } * * */ public List<CE> getPriorityCode() { if (priorityCode == null) { priorityCode = new ArrayList<CE>(); } return this.priorityCode; } /** * Gets the value of the reasonCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the reasonCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReasonCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CE } * * */ public List<CE> getReasonCode() { if (reasonCode == null) { reasonCode = new ArrayList<CE>(); } return this.reasonCode; } /** * Gets the value of the languageCode property. * * @return * possible object is * {@link CE } * */ public CE getLanguageCode() { return languageCode; } /** * Sets the value of the languageCode property. * * @param value * allowed object is * {@link CE } * */ public void setLanguageCode(CE value) { this.languageCode = value; } /** * Gets the value of the overseer property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the overseer property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOverseer().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MFMIMT700701UV01Overseer } * * */ public List<MFMIMT700701UV01Overseer> getOverseer() { if (overseer == null) { overseer = new ArrayList<MFMIMT700701UV01Overseer>(); } return this.overseer; } /** * Gets the value of the authorOrPerformer property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the authorOrPerformer property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuthorOrPerformer().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MFMIMT700701UV01AuthorOrPerformer } * * */ public List<MFMIMT700701UV01AuthorOrPerformer> getAuthorOrPerformer() { if (authorOrPerformer == null) { authorOrPerformer = new ArrayList<MFMIMT700701UV01AuthorOrPerformer>(); } return this.authorOrPerformer; } /** * Gets the value of the dataEnterer property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dataEnterer property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDataEnterer().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MFMIMT700701UV01DataEnterer } * * */ public List<MFMIMT700701UV01DataEnterer> getDataEnterer() { if (dataEnterer == null) { dataEnterer = new ArrayList<MFMIMT700701UV01DataEnterer>(); } return this.dataEnterer; } /** * Gets the value of the informationRecipient property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the informationRecipient property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInformationRecipient().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MFMIMT700701UV01InformationRecipient } * * */ public List<MFMIMT700701UV01InformationRecipient> getInformationRecipient() { if (informationRecipient == null) { informationRecipient = new ArrayList<MFMIMT700701UV01InformationRecipient>(); } return this.informationRecipient; } /** * Gets the value of the subject property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the subject property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSubject().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRPAIN201301UV02MFMIMT700701UV01Subject1 } * * */ public List<PRPAIN201301UV02MFMIMT700701UV01Subject1> getSubject() { if (subject == null) { subject = new ArrayList<PRPAIN201301UV02MFMIMT700701UV01Subject1>(); } return this.subject; } /** * Gets the value of the reasonOf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the reasonOf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReasonOf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MFMIMT700701UV01Reason } * * */ public List<MFMIMT700701UV01Reason> getReasonOf() { if (reasonOf == null) { reasonOf = new ArrayList<MFMIMT700701UV01Reason>(); } return this.reasonOf; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the classCode property. * * @return * possible object is * {@link ActClassControlAct } * */ public ActClassControlAct getClassCode() { return classCode; } /** * Sets the value of the classCode property. * * @param value * allowed object is * {@link ActClassControlAct } * */ public void setClassCode(ActClassControlAct value) { this.classCode = value; } /** * Gets the value of the moodCode property. * * @return * possible object is * {@link XActMoodIntentEvent } * */ public XActMoodIntentEvent getMoodCode() { return moodCode; } /** * Sets the value of the moodCode property. * * @param value * allowed object is * {@link XActMoodIntentEvent } * */ public void setMoodCode(XActMoodIntentEvent value) { this.moodCode = value; } }
gpl-2.0
mfrisbey/WebServer
WebServerLib/src/test/java/com/frisbey/webserver/test/utility/StringUtilsTest.java
2649
/* * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.frisbey.webserver.test.utility; import com.frisbey.webserver.utility.StringUtils; import org.junit.Test; import static junit.framework.TestCase.*; /** * Exercises the StringUtils class. * * @author Mark Frisbey */ public class StringUtilsTest { /** * Validates the isNullOrEmpty method. */ @Test public void isNullOrEmptyTest() { assertTrue("Unexpected result from null string test", StringUtils.isNullOrEmpty(null)); assertTrue("Unexpected result from empty string test", StringUtils.isNullOrEmpty("")); assertFalse("Unexpected result from non-empty string test", StringUtils.isNullOrEmpty("hello")); assertFalse("Unexpected result from whitespace string test", StringUtils.isNullOrEmpty(" ")); } /** * Validates the createPath method. */ @Test public void createPathTest() { assertEquals("Unexpected result from string with backslashes", "/dir1", StringUtils.buildPath("\\dir1")); assertEquals("Unexpected result from string ending with slash", "dir1/", StringUtils.buildPath("dir1/")); assertEquals("Unexpected result from subsequent value not beginning with slash", "/dir1/dir2", StringUtils.buildPath("/dir1", "dir2")); assertEquals("Unexpected result from initial value ending with slash", "/dir1/dir2", StringUtils.buildPath("/dir1\\", "dir2")); assertEquals("Unexpected result from initial value ending with slash AND subsequent value beginning with slash", "/dir1/dir2/", StringUtils.buildPath("/dir1/", "/dir2\\")); } @Test public void trimQueryStringTest() { assertEquals("Unexpected result from string with query string", "/file1.html", StringUtils.trimQueryString("/file1.html?id=10")); assertEquals("Unexpected result from string without query string", "/file1.html", StringUtils.trimQueryString("/file1.html")); } }
gpl-2.0
klst-com/metasfresh
de.metas.swat/de.metas.swat.base/src/main/java/de/metas/adempiere/service/impl/OrderLineBL.java
27382
package de.metas.adempiere.service.impl; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.Timestamp; import java.util.HashSet; import java.util.Properties; import java.util.Set; import org.adempiere.ad.trx.api.ITrx; import org.adempiere.bpartner.service.IBPartnerDAO; import org.adempiere.exceptions.AdempiereException; import org.adempiere.model.GridTabWrapper; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.pricing.api.IEditablePricingContext; import org.adempiere.pricing.api.IPriceListDAO; import org.adempiere.pricing.api.IPricingBL; import org.adempiere.pricing.api.IPricingContext; import org.adempiere.pricing.api.IPricingResult; import org.adempiere.pricing.exceptions.ProductNotOnPriceListException; import org.adempiere.uom.api.IUOMConversionBL; import org.adempiere.util.Check; import org.adempiere.util.LegacyAdapters; import org.adempiere.util.Services; import org.adempiere.util.api.IMsgBL; import org.compiere.model.I_AD_Org; import org.compiere.model.I_C_BPartner_Location; import org.compiere.model.I_C_Order; import org.compiere.model.I_C_Tax; import org.compiere.model.I_C_UOM; import org.compiere.model.I_M_PriceList_Version; import org.compiere.model.I_M_Shipper; import org.compiere.model.MOrder; import org.compiere.model.MOrderLine; import org.compiere.model.MPriceList; import org.compiere.model.MTax; import org.compiere.process.DocAction; import org.compiere.util.Env; import org.slf4j.Logger; import de.metas.adempiere.model.I_M_Product; import de.metas.adempiere.service.IOrderBL; import de.metas.adempiere.service.IOrderLineBL; import de.metas.document.IDocTypeBL; import de.metas.document.engine.IDocActionBL; import de.metas.interfaces.I_C_OrderLine; import de.metas.logging.LogManager; import de.metas.product.IProductDAO; import de.metas.tax.api.ITaxBL; public class OrderLineBL implements IOrderLineBL { private static final Logger logger = LogManager.getLogger(OrderLineBL.class); public static final String SYSCONFIG_CountryAttribute = "de.metas.swat.CountryAttribute"; private final Set<Integer> ignoredOlIds = new HashSet<Integer>(); public static final String CTX_EnforcePriceLimit = "EnforcePriceLimit"; public static final String CTX_DiscountSchema = "DiscountSchema"; private static final String MSG_COUNTER_DOC_MISSING_MAPPED_PRODUCT = "de.metas.order.CounterDocMissingMappedProduct"; @Override public void setPricesIfNotIgnored(final Properties ctx, final I_C_OrderLine orderLine, final int priceListId, final BigDecimal qtyEntered, final BigDecimal factor, boolean usePriceUOM, final String trxName_NOTUSED) { // FIXME refactor and/or keep in sync with #updatePrices if (ignoredOlIds.contains(orderLine.getC_OrderLine_ID())) { return; } final int productId = orderLine.getM_Product_ID(); final int bPartnerId = orderLine.getC_BPartner_ID(); if (productId <= 0 || bPartnerId <= 0) { return; } final IPricingBL pricingBL = Services.get(IPricingBL.class); // // Calculate Pricing Result final BigDecimal priceQty = convertToPriceUOM(qtyEntered, orderLine); final IEditablePricingContext pricingCtx = createPricingContext(orderLine, priceListId, priceQty); pricingCtx.setConvertPriceToContextUOM(!usePriceUOM); final IPricingResult pricingResult = pricingBL.calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { throw new ProductNotOnPriceListException(pricingCtx, orderLine.getLine()); } // // PriceList final BigDecimal priceListStdOld = orderLine.getPriceList_Std(); final BigDecimal priceList = pricingResult.getPriceList(); orderLine.setPriceList_Std(priceList); if (priceListStdOld.compareTo(priceList) != 0) { orderLine.setPriceList(priceList); } // // PriceLimit, PriceStd, Price_UOM_ID orderLine.setPriceLimit(pricingResult.getPriceLimit()); orderLine.setPriceStd(pricingResult.getPriceStd()); orderLine.setPrice_UOM_ID(pricingResult.getPrice_UOM_ID()); // 07090: when setting a priceActual, we also need to specify a PriceUOM // // Set PriceEntered if (orderLine.getPriceEntered().signum() == 0 && !orderLine.isManualPrice()) // task 06727 { // priceEntered is not set, so set it from the PL orderLine.setPriceEntered(pricingResult.getPriceStd()); } // // Discount if (orderLine.getDiscount().signum() == 0 && !orderLine.isManualDiscount()) // task 06727 { // pp.getDiscount is the discount between priceList and priceStd // -> useless for us // metas: Achtung, Rabatt wird aus PriceList und PriceStd ermittelt, nicht aus Discount Schema orderLine.setDiscount(pricingResult.getDiscount()); } // // Calculate PriceActual from PriceEntered and Discount if (orderLine.getPriceActual().signum() == 0) { calculatePriceActual(orderLine, pricingResult.getPrecision()); } // // C_Currency_ID, Price_UOM_ID(again?), M_PriceList_Version_ID orderLine.setC_Currency_ID(pricingResult.getC_Currency_ID()); orderLine.setPrice_UOM_ID(pricingResult.getPrice_UOM_ID()); // task 06942 orderLine.setM_PriceList_Version_ID(pricingResult.getM_PriceList_Version_ID()); updateLineNetAmt(orderLine, qtyEntered, factor); } @Override public void setTaxAmtInfoIfNotIgnored(final Properties ctx, final I_C_OrderLine ol, final String trxName) { if (ignoredOlIds.contains(ol.getC_OrderLine_ID())) { return; } final int taxId = ol.getC_Tax_ID(); if (taxId <= 0) { ol.setTaxAmtInfo(BigDecimal.ZERO); return; } final boolean taxIncluded = isTaxIncluded(ol); final BigDecimal lineAmout = ol.getLineNetAmt(); final int taxPrecision = getPrecision(ol); final I_C_Tax tax = MTax.get(ctx, taxId); final ITaxBL taxBL = Services.get(ITaxBL.class); final BigDecimal taxAmtInfo = taxBL.calculateTax(tax, lineAmout, taxIncluded, taxPrecision); ol.setTaxAmtInfo(taxAmtInfo); } @Override public void setPrices(final I_C_OrderLine ol) { final Properties ctx = InterfaceWrapperHelper.getCtx(ol); final String trxName = InterfaceWrapperHelper.getTrxName(ol); final boolean usePriceUOM = false; setPricesIfNotIgnored(ctx, ol, usePriceUOM, trxName); } @Override public void setPricesIfNotIgnored( final Properties ctx, final I_C_OrderLine ol, final boolean usePriceUOM, final String trxName) { if (ignoredOlIds.contains(ol.getC_OrderLine_ID())) { return; } final org.compiere.model.I_C_Order order = ol.getC_Order(); final int productId = ol.getM_Product_ID(); final int priceListId = order.getM_PriceList_ID(); if (priceListId <= 0 || productId <= 0) { return; } // 06278 : If we have a UOM in product price, we use that one. setPricesIfNotIgnored(ctx, ol, priceListId, ol.getQtyEntered(), BigDecimal.ONE, usePriceUOM, trxName); } @Override public void setShipperIfNotIgnored(final Properties ctx, final I_C_OrderLine ol, final boolean force, final String trxName) { if (ignoredOlIds.contains(ol.getC_OrderLine_ID())) { return; } final org.compiere.model.I_C_Order order = ol.getC_Order(); if (!force && ol.getM_Shipper_ID() > 0) { logger.debug("Nothing to do: force=false and M_Shipper_ID=" + ol.getM_Shipper_ID()); return; } final int orderShipperId = order.getM_Shipper_ID(); if (orderShipperId > 0) { logger.info("Setting M_Shipper_ID=" + orderShipperId + " from " + order); ol.setM_Shipper_ID(orderShipperId); } else { logger.debug("Looking for M_Shipper_ID via ship-to-bpartner of " + order); final int bPartnerID = order.getC_BPartner_ID(); if (bPartnerID <= 0) { logger.warn(order + " has no ship-to-bpartner"); return; } final I_M_Shipper shipper = Services.get(IBPartnerDAO.class).retrieveShipper(bPartnerID, null); if (shipper == null) { // task 07034: nothing to do return; } final int bPartnerShipperId = shipper.getM_Shipper_ID(); logger.info("Setting M_Shipper_ID=" + bPartnerShipperId + " from ship-to-bpartner"); ol.setM_Shipper_ID(bPartnerShipperId); } } @Override public void calculatePriceActualIfNotIgnored(final I_C_OrderLine ol, final int precision) { if (ignoredOlIds.contains(ol.getC_OrderLine_ID())) { return; } calculatePriceActual(ol, precision); } @Override public BigDecimal subtractDiscount(final BigDecimal baseAmount, final BigDecimal discount, final int precision) { BigDecimal multiplier = Env.ONEHUNDRED.subtract(discount); multiplier = multiplier.divide(Env.ONEHUNDRED, precision * 3, RoundingMode.HALF_UP); final BigDecimal result = baseAmount.multiply(multiplier).setScale(precision, RoundingMode.HALF_UP); return result; } @Override public void ignore(final int orderLineId) { ignoredOlIds.add(orderLineId); } @Override public void unignore(final int orderLineId) { ignoredOlIds.remove(orderLineId); } @Override public int getC_TaxCategory_ID(final org.compiere.model.I_C_OrderLine orderLine) { // In case we have a charge, use the tax category from charge if (orderLine.getC_Charge_ID() > 0) { return orderLine.getC_Charge().getC_TaxCategory_ID(); } final IPricingContext pricingCtx = createPricingContext(orderLine); final IPricingResult pricingResult = Services.get(IPricingBL.class).calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { return -1; } return pricingResult.getC_TaxCategory_ID(); } /** * Creates a pricing context with the given orderLine's <code>Price_UOM</code> and with the given order's <code>QtyEntered</code> already being converted to that priceUOM. * <p> * Also assumes that the given line's order has a {@code M_PriceList_ID} */ private IEditablePricingContext createPricingContext(org.compiere.model.I_C_OrderLine orderLine) { final I_C_Order order = orderLine.getC_Order(); final int priceListId; if (order.getM_PriceList_ID() > 0) { priceListId = order.getM_PriceList_ID(); } else { // gh #936: if order.getM_PriceList_ID is 0, then attempt to get the priceListId from the BL. final IOrderBL orderBL = Services.get(IOrderBL.class); priceListId = orderBL.retrievePriceListId(order); } final BigDecimal priceQty = convertQtyEnteredToPriceUOM(orderLine); return createPricingContext(orderLine, priceListId, priceQty); } /** * Creates a pricing context with the given <code>orderLine</code>'s bPartner, date, product, IsSOTrx and <code>Price_UOM</code> * * @param orderLine * @param priceListId * @param qty the for the price. <b>WARNING:</b> this qty might be in any UOM! * @return */ private IEditablePricingContext createPricingContext( final org.compiere.model.I_C_OrderLine orderLine, final int priceListId, final BigDecimal qty) { final IPricingBL pricingBL = Services.get(IPricingBL.class); final org.compiere.model.I_C_Order order = orderLine.getC_Order(); final boolean isSOTrx = order.isSOTrx(); final int productId = orderLine.getM_Product_ID(); int bPartnerId = orderLine.getC_BPartner_ID(); if (bPartnerId <= 0) { bPartnerId = order.getC_BPartner_ID(); } final Timestamp date = getPriceDate(orderLine, order); final I_C_OrderLine ol = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class); final IEditablePricingContext pricingCtx = pricingBL.createInitialContext( productId, bPartnerId, ol.getPrice_UOM_ID(), // task 06942 qty, isSOTrx); pricingCtx.setPriceDate(date); // 03152: setting the 'ol' to allow the subscription system to compute the right price pricingCtx.setReferencedObject(orderLine); pricingCtx.setM_PriceList_ID(priceListId); // PLV is only accurate if PL selected in header // metas: rely on M_PriceList_ID only, don't use M_PriceList_Version_ID // pricingCtx.setM_PriceList_Version_ID(orderLine.getM_PriceList_Version_ID()); return pricingCtx; } /** * task 07080 * * @param orderLine * @param order * @return */ private Timestamp getPriceDate(final org.compiere.model.I_C_OrderLine orderLine, final org.compiere.model.I_C_Order order) { Timestamp date = orderLine.getDatePromised(); // if null, then get date promised from order if (date == null) { date = order.getDatePromised(); } // still null, then get date ordered from order line if (date == null) { date = orderLine.getDateOrdered(); } // still null, then get date ordered from order if (date == null) { date = order.getDateOrdered(); } return date; } @Override public I_C_OrderLine createOrderLine(final org.compiere.model.I_C_Order order) { final MOrderLine olPO = new MOrderLine((MOrder)LegacyAdapters.convertToPO(order)); final I_C_OrderLine ol = InterfaceWrapperHelper.create(olPO, I_C_OrderLine.class); if (order.isSOTrx() && order.isDropShip()) { int C_BPartner_ID = order.getDropShip_BPartner_ID() > 0 ? order.getDropShip_BPartner_ID() : order.getC_BPartner_ID(); ol.setC_BPartner_ID(C_BPartner_ID); final I_C_BPartner_Location deliveryLocation = Services.get(IOrderBL.class).getShipToLocation(order); int C_BPartner_Location_ID = deliveryLocation != null ? deliveryLocation.getC_BPartner_Location_ID() : -1; ol.setC_BPartner_Location_ID(C_BPartner_Location_ID); int AD_User_ID = order.getDropShip_User_ID() > 0 ? order.getDropShip_User_ID() : order.getAD_User_ID(); ol.setAD_User_ID(AD_User_ID); } return ol; } @Override public <T extends I_C_OrderLine> T createOrderLine(org.compiere.model.I_C_Order order, Class<T> orderLineClass) { final I_C_OrderLine orderLine = createOrderLine(order); return InterfaceWrapperHelper.create(orderLine, orderLineClass); } @Override public void updateLineNetAmt( final I_C_OrderLine ol, final BigDecimal qtyEntered, final BigDecimal factor) { Check.assumeNotNull(qtyEntered, "Param qtyEntered not null. Param ol={}", ol); final Properties ctx = InterfaceWrapperHelper.getCtx(ol); final I_C_Order order = ol.getC_Order(); final int priceListId = order.getM_PriceList_ID(); // // We need to get the quantity in the pricing's UOM (if different) final BigDecimal convertedQty = convertToPriceUOM(qtyEntered, ol); // this code has been borrowed from // org.compiere.model.CalloutOrder.amt final int stdPrecision = MPriceList.getStandardPrecision(ctx, priceListId); BigDecimal lineNetAmt = convertedQty.multiply(factor.multiply(ol.getPriceActual())); if (lineNetAmt.scale() > stdPrecision) { lineNetAmt = lineNetAmt.setScale(stdPrecision, BigDecimal.ROUND_HALF_UP); } logger.debug("Setting LineNetAmt={} to {}", lineNetAmt, ol); ol.setLineNetAmt(lineNetAmt); } @Override public void updatePrices(final I_C_OrderLine orderLine) { // FIXME refactor and/or keep in sync with #setPricesIfNotIgnored // Product was not set yet. There is no point to calculate the prices if (orderLine.getM_Product_ID() <= 0) { return; } final IPricingBL pricingBL = Services.get(IPricingBL.class); // // Calculate Pricing Result final IEditablePricingContext pricingCtx = createPricingContext(orderLine); final boolean userPriceUOM = InterfaceWrapperHelper.isNew(orderLine); pricingCtx.setConvertPriceToContextUOM(!userPriceUOM); final IPricingResult pricingResult = pricingBL.calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { throw new ProductNotOnPriceListException(pricingCtx, orderLine.getLine()); } // // PriceList final BigDecimal priceListStdOld = orderLine.getPriceList_Std(); final BigDecimal priceList = pricingResult.getPriceList(); orderLine.setPriceList_Std(priceList); if (priceListStdOld.compareTo(priceList) != 0) { orderLine.setPriceList(priceList); } // // PriceLimit, PriceStd, Price_UOM_ID orderLine.setPriceLimit(pricingResult.getPriceLimit()); orderLine.setPriceStd(pricingResult.getPriceStd()); orderLine.setPrice_UOM_ID(pricingResult.getPrice_UOM_ID()); // 07090: when setting a priceActual, we also need to specify a PriceUOM // // Set PriceEntered and PriceActual only if IsManualPrice=N if (!orderLine.isManualPrice()) { orderLine.setPriceEntered(pricingResult.getPriceStd()); orderLine.setPriceActual(pricingResult.getPriceStd()); } // // Discount // NOTE: Subscription prices do not work with Purchase Orders. if (pricingCtx.isSOTrx()) { if (!orderLine.isManualDiscount()) { // Override discount only if is not manual // Note: only the sales order widnow has the field 'isManualDiscount' orderLine.setDiscount(pricingResult.getDiscount()); } } else { orderLine.setDiscount(pricingResult.getDiscount()); } // // Calculate PriceActual from PriceEntered and Discount calculatePriceActual(orderLine, pricingResult.getPrecision()); // // C_Currency_ID, Price_UOM_ID(again?), M_PriceList_Version_ID orderLine.setC_Currency_ID(pricingResult.getC_Currency_ID()); orderLine.setPrice_UOM_ID(pricingResult.getPrice_UOM_ID()); // task 06942 orderLine.setM_PriceList_Version_ID(pricingResult.getM_PriceList_Version_ID()); // // UI final Properties ctx = InterfaceWrapperHelper.getCtx(orderLine); final int WindowNo = GridTabWrapper.getWindowNo(orderLine); Env.setContext(ctx, WindowNo, CTX_EnforcePriceLimit, pricingResult.isEnforcePriceLimit()); Env.setContext(ctx, WindowNo, CTX_DiscountSchema, pricingResult.isUsesDiscountSchema()); } @Override public void updateQtyReserved(final I_C_OrderLine orderLine) { if (orderLine == null) { logger.debug("Given orderLine is NULL; returning"); return; // not our business } // make two simple checks that work without loading additional stuff if (orderLine.getM_Product_ID() <= 0) { logger.debug("Given orderLine {} has M_Product_ID<=0; setting QtyReserved=0.", orderLine); orderLine.setQtyReserved(BigDecimal.ZERO); return; } if (orderLine.getQtyOrdered().signum() <= 0) { logger.debug("Given orderLine {} has QtyOrdered<=0; setting QtyReserved=0.", orderLine); orderLine.setQtyReserved(BigDecimal.ZERO); return; } final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); final IDocActionBL docActionBL = Services.get(IDocActionBL.class); final I_C_Order order = orderLine.getC_Order(); if (!docActionBL.isDocumentStatusOneOf(order, DocAction.STATUS_InProgress, DocAction.STATUS_Completed, DocAction.STATUS_Closed)) { logger.debug("C_Order {} of given orderLine {} has DocStatus {}; setting QtyReserved=0.", new Object[] { order, orderLine, order.getDocStatus() }); orderLine.setQtyReserved(BigDecimal.ZERO); return; } if (order.getC_DocType_ID() > 0 && docTypeBL.isProposal(order.getC_DocType())) { logger.debug("C_Order {} of given orderLine {} has C_DocType {} which is a proposal; setting QtyReserved=0.", new Object[] { order, orderLine, order.getC_DocType() }); orderLine.setQtyReserved(BigDecimal.ZERO); return; } if (!orderLine.getM_Product().isStocked()) { logger.debug("Given orderLine {} has M_Product {} which is not stocked; setting QtyReserved=0.", new Object[] { orderLine, orderLine.getM_Product() }); orderLine.setQtyReserved(BigDecimal.ZERO); return; } final BigDecimal qtyReservedRaw = orderLine.getQtyOrdered().subtract(orderLine.getQtyDelivered()); final BigDecimal qtyReserved = BigDecimal.ZERO.max(qtyReservedRaw); // not less than zero logger.debug("Given orderLine {} has QtyOrdered={} and QtyDelivered={}; setting QtyReserved={}.", new Object[] { orderLine, orderLine.getQtyOrdered(), orderLine.getQtyDelivered(), qtyReserved }); orderLine.setQtyReserved(qtyReserved); } @Override public void calculatePriceActual(final I_C_OrderLine orderLine, final int precision) { final BigDecimal discount = orderLine.getDiscount(); final BigDecimal priceEntered = orderLine.getPriceEntered(); BigDecimal priceActual; if (priceEntered.signum() == 0) { priceActual = priceEntered; } else { final int precisionToUse; if (precision >= 0) { precisionToUse = precision; } else { // checks to avoid unexplained NPEs Check.errorIf(orderLine.getC_Order_ID() <= 0, "Optional 'precision' param was not set but param 'orderLine' {} has no order", orderLine); final I_C_Order order = orderLine.getC_Order(); Check.errorIf(order.getM_PriceList_ID() <= 0, "Optional 'precision' param was not set but the order of param 'orderLine' {} has no price list", orderLine); precisionToUse = order.getM_PriceList().getPricePrecision(); } priceActual = subtractDiscount(priceEntered, discount, precisionToUse); } orderLine.setPriceActual(priceActual); } @Override public void setM_Product_ID(final I_C_OrderLine orderLine, int M_Product_ID, boolean setUOM) { if (setUOM) { final Properties ctx = InterfaceWrapperHelper.getCtx(orderLine); final I_M_Product product = InterfaceWrapperHelper.create(ctx, M_Product_ID, I_M_Product.class, ITrx.TRXNAME_None); orderLine.setM_Product(product); orderLine.setC_UOM_ID(product.getC_UOM_ID()); } else { orderLine.setM_Product_ID(M_Product_ID); } orderLine.setM_AttributeSetInstance_ID(0); } // setM_Product_ID @Override public I_M_PriceList_Version getPriceListVersion(I_C_OrderLine orderLine) { final Properties ctx = InterfaceWrapperHelper.getCtx(orderLine); final String trxName = InterfaceWrapperHelper.getTrxName(orderLine); if (orderLine.getM_PriceList_Version_ID() > 0) { return InterfaceWrapperHelper.create(ctx, orderLine.getM_PriceList_Version_ID(), I_M_PriceList_Version.class, trxName); } else { // If the line doesn't have a pricelist version, take the one from order. final I_C_Order order = orderLine.getC_Order(); final Boolean processedPLVFiltering = null; // task 09533: the user doesn't know about PLV's processed flag, so we can't filter by it return Services.get(IPriceListDAO.class).retrievePriceListVersionOrNull( order.getM_PriceList(), getPriceDate(orderLine, order), processedPLVFiltering); } } @Override public BigDecimal convertQtyEnteredToPriceUOM(final org.compiere.model.I_C_OrderLine orderLine) { Check.assumeNotNull(orderLine, "orderLine not null"); final BigDecimal qtyEntered = orderLine.getQtyEntered(); final I_C_OrderLine orderLineToUse = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class); final BigDecimal qtyInPriceUOM = convertToPriceUOM(qtyEntered, orderLineToUse); return qtyInPriceUOM; } @Override public BigDecimal convertQtyEnteredToInternalUOM(final org.compiere.model.I_C_OrderLine orderLine) { Check.assumeNotNull(orderLine, "orderLine not null"); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final Properties ctx = InterfaceWrapperHelper.getCtx(orderLine); final BigDecimal qtyEntered = orderLine.getQtyEntered(); if (orderLine.getM_Product_ID() <= 0 || orderLine.getC_UOM_ID() <= 0) { return qtyEntered; } final BigDecimal qtyOrdered = uomConversionBL.convertToProductUOM(ctx, orderLine.getM_Product(), orderLine.getC_UOM(), qtyEntered); return qtyOrdered; } /** * Converts the given <code>qtyEntered</code> from the given <code>orderLine</code>'s <code>C_UOM</code> to the order line's <code>Price_UOM</code>. * If the given <code>orderLine</code> doesn't have both UOMs set, the method just returns the given <code>qtyEntered</code>. * * @param qtyEntered * @param orderLine * @return */ private BigDecimal convertToPriceUOM(final BigDecimal qtyEntered, final I_C_OrderLine orderLine) { Check.assumeNotNull(qtyEntered, "qtyEntered not null"); final I_C_UOM qtyUOM = orderLine.getC_UOM(); if (qtyUOM == null || qtyUOM.getC_UOM_ID() <= 0) { return qtyEntered; } final I_C_UOM priceUOM = orderLine.getPrice_UOM(); if (priceUOM == null || priceUOM.getC_UOM_ID() <= 0) { return qtyEntered; } if (qtyUOM.getC_UOM_ID() == priceUOM.getC_UOM_ID()) { return qtyEntered; } final org.compiere.model.I_M_Product product = orderLine.getM_Product(); final BigDecimal qtyInPriceUOM = Services.get(IUOMConversionBL.class).convertQty(product, qtyEntered, qtyUOM, priceUOM); return qtyInPriceUOM; } @Override public boolean isTaxIncluded(final org.compiere.model.I_C_OrderLine orderLine) { Check.assumeNotNull(orderLine, "orderLine not null"); final I_C_Tax tax = orderLine.getC_Tax(); final org.compiere.model.I_C_Order order = orderLine.getC_Order(); return Services.get(IOrderBL.class).isTaxIncluded(order, tax); } @Override public int getPrecision(final org.compiere.model.I_C_OrderLine orderLine) { final org.compiere.model.I_C_Order order = orderLine.getC_Order(); return Services.get(IOrderBL.class).getPrecision(order); } @Override public boolean isAllowedCounterLineCopy(final org.compiere.model.I_C_OrderLine fromLine) { final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(fromLine, de.metas.interfaces.I_C_OrderLine.class); if (ol.isPackagingMaterial()) { // DO not copy the line if it's packing material. The packaging lines will be created later return false; } return true; } @Override public void copyOrderLineCounter(final org.compiere.model.I_C_OrderLine line, final org.compiere.model.I_C_OrderLine fromLine) { final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(fromLine, de.metas.interfaces.I_C_OrderLine.class); if (ol.isPackagingMaterial()) { // do nothing! the packaging lines will be created later return; } // link the line with the one from the counter document line.setRef_OrderLine_ID(fromLine.getC_OrderLine_ID()); if (line.getM_Product_ID() > 0) // task 09700 { final IProductDAO productDAO = Services.get(IProductDAO.class); final IMsgBL msgBL = Services.get(IMsgBL.class); final I_AD_Org org = line.getAD_Org(); final org.compiere.model.I_M_Product lineProduct = line.getM_Product(); if (lineProduct.getAD_Org_ID() != 0) { // task 09700 the product from the original order is org specific, so we need to substitute it with the product from the counter-org. final org.compiere.model.I_M_Product counterProduct = productDAO.retrieveMappedProductOrNull(lineProduct, org); if (counterProduct == null) { final String msg = msgBL.getMsg(InterfaceWrapperHelper.getCtx(line), MSG_COUNTER_DOC_MISSING_MAPPED_PRODUCT, new Object[] { lineProduct.getValue(), lineProduct.getAD_Org().getName(), org.getName() }); throw new AdempiereException(msg); } line.setM_Product(counterProduct); } } } }
gpl-2.0
Jakenizer/jjrecipes_springmvc
src/main/java/se/jjrecipes/validation/TagValidationDoer.java
411
package se.jjrecipes.validation; import org.apache.commons.lang3.math.NumberUtils; public class TagValidationDoer extends AbstractValidationDoer { @Override boolean validate(Object input) { if (!(input instanceof String[])) return false; String [] in = (String[]) input; for (String row : in) { if(!NumberUtils.isNumber(row) || (Long.valueOf(row) < 1)) return false; } return true; } }
gpl-2.0
cpwc/Nibblegram
TMessagesProj/src/main/java/me/cpwc/nibblegram/ui/Animation/AnimatorListenerAdapter10.java
1263
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.cpwc.nibblegram.ui.Animation; public abstract class AnimatorListenerAdapter10 implements Animator10.AnimatorListener, Animator10.AnimatorPauseListener { @Override public void onAnimationCancel(Animator10 animation) { } @Override public void onAnimationEnd(Animator10 animation) { } @Override public void onAnimationRepeat(Animator10 animation) { } @Override public void onAnimationStart(Animator10 animation) { } @Override public void onAnimationPause(Animator10 animation) { } @Override public void onAnimationResume(Animator10 animation) { } }
gpl-2.0
xstory61/server
src/net/server/handlers/login/ViewCharHandler.java
3398
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.server.handlers.login; import client.MapleCharacter; import client.MapleClient; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.AbstractMaplePacketHandler; import tools.DatabaseConnection; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; public final class ViewCharHandler extends AbstractMaplePacketHandler { @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { try { short charsNum; List<Integer> worlds; List<MapleCharacter> chars; try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT world, id FROM characters WHERE accountid = ?")) { ps.setInt(1, c.getAccID()); charsNum = 0; worlds = new ArrayList<>(); chars = new ArrayList<>(); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int cworld = rs.getByte("world"); boolean inside = false; for (int w : worlds) { if (w == cworld) { inside = true; } } if (!inside) { worlds.add(cworld); } MapleCharacter chr = MapleCharacter.loadCharFromDB(rs.getInt("id"), c, false); chars.add(chr); charsNum++; } } } int unk = charsNum + 3 - charsNum % 3; c.announce(MaplePacketCreator.showAllCharacter(charsNum, unk)); for (Iterator<Integer> it = worlds.iterator(); it.hasNext();) { int w = it.next(); List<MapleCharacter> chrsinworld = new ArrayList<>(); for (MapleCharacter chr : chars) { if (chr.getWorld() == w) { chrsinworld.add(chr); } } c.announce(MaplePacketCreator.showAllCharacterInfo(w, chrsinworld)); } } catch (Exception e) { e.printStackTrace(); } } }
gpl-2.0
javapathshala/JP.Cody
Cody/jp-web-parent/jp-spring-api/src/main/java/com/jp/spring/api/aop/logging/ExampleBean.java
2307
/* * File: ExampleBean.java * Date: 17-Jul-2013 * * This source code is part of Java Pathshala-Wisdom Being Shared. * This program is protected by copyright law but you are authorise to learn * & gain ideas from it. Its unauthorised use is explicitly prohibited & any * addition & removal of material. If want to suggest any changes, * you are welcome to provide your comments on GitHub Social Code Area. * Its unauthorised use gives Java Pathshala the right to obtain retention orders * and to prosecute the authors of any infraction. * * Visit us at www.javapathshala.com */ package com.jp.spring.api.aop.logging; /** * @author dimit.chadha */ public class ExampleBean { /** * The name of the example. */ private String exampleName; /** * The version of the example. */ private String exampleVersion; /** * No-arguments constructor. */ public ExampleBean() { } /** * Constructor accepting arguments to set my state. * * @param newExampleName * Name of this example. * @param newExampleVersion * Version of this example. */ public ExampleBean(final String newExampleName, final String newExampleVersion) { this.exampleName = newExampleName; this.exampleVersion = newExampleVersion; } /** * Provide my example name. * * @return My example name. */ public String getExampleName() { return exampleName; } /** * Set/change my example name. * * @param exampleName * New name for this example. */ public void setExampleName(String exampleName) { this.exampleName = exampleName; } /** * Provide my example version. * * @return My example version. */ public String getExampleVersion() { return exampleVersion; } /** * Set/change the example's version. * * @param exampleVersion * New value for my version. */ public void setExampleVersion(String exampleVersion) { this.exampleVersion = exampleVersion; } /** * Provide my example name with version in parentheses. * * @return My name and version if format "Name (Version)." */ public String provideNameAndVersion() { return this.exampleName + " (" + this.exampleVersion + ")"; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/javax/swing/JEditorPane.java
93012
/* * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package javax.swing; import sun.swing.SwingUtilities2; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.io.*; import java.util.*; import javax.swing.plaf.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.text.html.*; import javax.accessibility.*; /** * A text component to edit various kinds of content. * You can find how-to information and examples of using editor panes in * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/text.html">Using Text Components</a>, * a section in <em>The Java Tutorial.</em> * * <p> * This component uses implementations of the * <code>EditorKit</code> to accomplish its behavior. It effectively * morphs into the proper kind of text editor for the kind * of content it is given. The content type that editor is bound * to at any given time is determined by the <code>EditorKit</code> currently * installed. If the content is set to a new URL, its type is used * to determine the <code>EditorKit</code> that should be used to * load the content. * <p> * By default, the following types of content are known: * <dl> * <dt><b>text/plain</b> * <dd>Plain text, which is the default the type given isn't * recognized. The kit used in this case is an extension of * <code>DefaultEditorKit</code> that produces a wrapped plain text view. * <dt><b>text/html</b> * <dd>HTML text. The kit used in this case is the class * <code>javax.swing.text.html.HTMLEditorKit</code> * which provides HTML 3.2 support. * <dt><b>text/rtf</b> * <dd>RTF text. The kit used in this case is the class * <code>javax.swing.text.rtf.RTFEditorKit</code> * which provides a limited support of the Rich Text Format. * </dl> * <p> * There are several ways to load content into this component. * <ol> * <li> * The {@link #setText setText} method can be used to initialize * the component from a string. In this case the current * <code>EditorKit</code> will be used, and the content type will be * expected to be of this type. * <li> * The {@link #read read} method can be used to initialize the * component from a <code>Reader</code>. Note that if the content type is HTML, * relative references (e.g. for things like images) can't be resolved * unless the &lt;base&gt; tag is used or the <em>Base</em> property * on <code>HTMLDocument</code> is set. * In this case the current <code>EditorKit</code> will be used, * and the content type will be expected to be of this type. * <li> * The {@link #setPage setPage} method can be used to initialize * the component from a URL. In this case, the content type will be * determined from the URL, and the registered <code>EditorKit</code> * for that content type will be set. * </ol> * <p> * Some kinds of content may provide hyperlink support by generating * hyperlink events. The HTML <code>EditorKit</code> will generate * hyperlink events if the <code>JEditorPane</code> is <em>not editable</em> * (<code>JEditorPane.setEditable(false);</code> has been called). * If HTML frames are embedded in the document, the typical response would be * to change a portion of the current document. The following code * fragment is a possible hyperlink listener implementation, that treats * HTML frame events specially, and simply displays any other activated * hyperlinks. * <code><pre> &nbsp; class Hyperactive implements HyperlinkListener { &nbsp; &nbsp; public void hyperlinkUpdate(HyperlinkEvent e) { &nbsp; if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { &nbsp; JEditorPane pane = (JEditorPane) e.getSource(); &nbsp; if (e instanceof HTMLFrameHyperlinkEvent) { &nbsp; HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; &nbsp; HTMLDocument doc = (HTMLDocument)pane.getDocument(); &nbsp; doc.processHTMLFrameHyperlinkEvent(evt); &nbsp; } else { &nbsp; try { &nbsp; pane.setPage(e.getURL()); &nbsp; } catch (Throwable t) { &nbsp; t.printStackTrace(); &nbsp; } &nbsp; } &nbsp; } &nbsp; } &nbsp; } * </pre></code> * <p> * For information on customizing how <b>text/html</b> is rendered please see * {@link #W3C_LENGTH_UNITS} and {@link #HONOR_DISPLAY_PROPERTIES} * <p> * Culturally dependent information in some documents is handled through * a mechanism called character encoding. Character encoding is an * unambiguous mapping of the members of a character set (letters, ideographs, * digits, symbols, or control functions) to specific numeric code values. It * represents the way the file is stored. Example character encodings are * ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is * passed to an user agent (<code>JEditorPane</code>) it is converted to * the document character set (ISO-10646 aka Unicode). * <p> * There are multiple ways to get a character set mapping to happen * with <code>JEditorPane</code>. * <ol> * <li> * One way is to specify the character set as a parameter of the MIME * type. This will be established by a call to the * <a href="#setContentType">setContentType</a> method. If the content * is loaded by the <a href="#setPage">setPage</a> method the content * type will have been set according to the specification of the URL. * It the file is loaded directly, the content type would be expected to * have been set prior to loading. * <li> * Another way the character set can be specified is in the document itself. * This requires reading the document prior to determining the character set * that is desired. To handle this, it is expected that the * <code>EditorKit</code>.read operation throw a * <code>ChangedCharSetException</code> which will * be caught. The read is then restarted with a new Reader that uses * the character set specified in the <code>ChangedCharSetException</code> * (which is an <code>IOException</code>). * </ol> * <p> * <dl> * <dt><b><font size=+1>Newlines</font></b> * <dd> * For a discussion on how newlines are handled, see * <a href="text/DefaultEditorKit.html">DefaultEditorKit</a>. * </dl> * * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @beaninfo * attribute: isContainer false * description: A text component to edit various types of content. * * @author Timothy Prinzing */ public class JEditorPane extends JTextComponent { /** * Creates a new <code>JEditorPane</code>. * The document model is set to <code>null</code>. */ public JEditorPane() { super(); setFocusCycleRoot(true); setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() { public Component getComponentAfter(Container focusCycleRoot, Component aComponent) { if (focusCycleRoot != JEditorPane.this || (!isEditable() && getComponentCount() > 0)) { return super.getComponentAfter(focusCycleRoot, aComponent); } else { Container rootAncestor = getFocusCycleRootAncestor(); return (rootAncestor != null) ? rootAncestor.getFocusTraversalPolicy(). getComponentAfter(rootAncestor, JEditorPane.this) : null; } } public Component getComponentBefore(Container focusCycleRoot, Component aComponent) { if (focusCycleRoot != JEditorPane.this || (!isEditable() && getComponentCount() > 0)) { return super.getComponentBefore(focusCycleRoot, aComponent); } else { Container rootAncestor = getFocusCycleRootAncestor(); return (rootAncestor != null) ? rootAncestor.getFocusTraversalPolicy(). getComponentBefore(rootAncestor, JEditorPane.this) : null; } } public Component getDefaultComponent(Container focusCycleRoot) { return (focusCycleRoot != JEditorPane.this || (!isEditable() && getComponentCount() > 0)) ? super.getDefaultComponent(focusCycleRoot) : null; } protected boolean accept(Component aComponent) { return (aComponent != JEditorPane.this) ? super.accept(aComponent) : false; } }); LookAndFeel.installProperty(this, "focusTraversalKeysForward", JComponent. getManagingFocusForwardTraversalKeys()); LookAndFeel.installProperty(this, "focusTraversalKeysBackward", JComponent. getManagingFocusBackwardTraversalKeys()); } /** * Creates a <code>JEditorPane</code> based on a specified URL for input. * * @param initialPage the URL * @exception IOException if the URL is <code>null</code> * or cannot be accessed */ public JEditorPane(URL initialPage) throws IOException { this(); setPage(initialPage); } /** * Creates a <code>JEditorPane</code> based on a string containing * a URL specification. * * @param url the URL * @exception IOException if the URL is <code>null</code> or * cannot be accessed */ public JEditorPane(String url) throws IOException { this(); setPage(url); } /** * Creates a <code>JEditorPane</code> that has been initialized * to the given text. This is a convenience constructor that calls the * <code>setContentType</code> and <code>setText</code> methods. * * @param type mime type of the given text * @param text the text to initialize with; may be <code>null</code> * @exception NullPointerException if the <code>type</code> parameter * is <code>null</code> */ public JEditorPane(String type, String text) { this(); setContentType(type); setText(text); } /** * Adds a hyperlink listener for notification of any changes, for example * when a link is selected and entered. * * @param listener the listener */ public synchronized void addHyperlinkListener(HyperlinkListener listener) { listenerList.add(HyperlinkListener.class, listener); } /** * Removes a hyperlink listener. * * @param listener the listener */ public synchronized void removeHyperlinkListener(HyperlinkListener listener) { listenerList.remove(HyperlinkListener.class, listener); } /** * Returns an array of all the <code>HyperLinkListener</code>s added * to this JEditorPane with addHyperlinkListener(). * * @return all of the <code>HyperLinkListener</code>s added or an empty * array if no listeners have been added * @since 1.4 */ public synchronized HyperlinkListener[] getHyperlinkListeners() { return listenerList.getListeners(javax.swing.event.HyperlinkListener.class); } /** * Notifies all listeners that have registered interest for * notification on this event type. This is normally called * by the currently installed <code>EditorKit</code> if a content type * that supports hyperlinks is currently active and there * was activity with a link. The listener list is processed * last to first. * * @param e the event * @see EventListenerList */ public void fireHyperlinkUpdate(HyperlinkEvent e) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==HyperlinkListener.class) { ((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e); } } } /** * Sets the current URL being displayed. The content type of the * pane is set, and if the editor kit for the pane is * non-<code>null</code>, then * a new default document is created and the URL is read into it. * If the URL contains and reference location, the location will * be scrolled to by calling the <code>scrollToReference</code> * method. If the desired URL is the one currently being displayed, * the document will not be reloaded. To force a document * reload it is necessary to clear the stream description property * of the document. The following code shows how this can be done: * * <pre> * Document doc = jEditorPane.getDocument(); * doc.putProperty(Document.StreamDescriptionProperty, null); * </pre> * * If the desired URL is not the one currently being * displayed, the <code>getStream</code> method is called to * give subclasses control over the stream provided. * <p> * This may load either synchronously or asynchronously * depending upon the document returned by the <code>EditorKit</code>. * If the <code>Document</code> is of type * <code>AbstractDocument</code> and has a value returned by * <code>AbstractDocument.getAsynchronousLoadPriority</code> * that is greater than or equal to zero, the page will be * loaded on a separate thread using that priority. * <p> * If the document is loaded synchronously, it will be * filled in with the stream prior to being installed into * the editor with a call to <code>setDocument</code>, which * is bound and will fire a property change event. If an * <code>IOException</code> is thrown the partially loaded * document will * be discarded and neither the document or page property * change events will be fired. If the document is * successfully loaded and installed, a view will be * built for it by the UI which will then be scrolled if * necessary, and then the page property change event * will be fired. * <p> * If the document is loaded asynchronously, the document * will be installed into the editor immediately using a * call to <code>setDocument</code> which will fire a * document property change event, then a thread will be * created which will begin doing the actual loading. * In this case, the page property change event will not be * fired by the call to this method directly, but rather will be * fired when the thread doing the loading has finished. * It will also be fired on the event-dispatch thread. * Since the calling thread can not throw an <code>IOException</code> * in the event of failure on the other thread, the page * property change event will be fired when the other * thread is done whether the load was successful or not. * * @param page the URL of the page * @exception IOException for a <code>null</code> or invalid * page specification, or exception from the stream being read * @see #getPage * @beaninfo * description: the URL used to set content * bound: true * expert: true */ public void setPage(URL page) throws IOException { if (page == null) { throw new IOException("invalid url"); } URL loaded = getPage(); // reset scrollbar if (!page.equals(loaded) && page.getRef() == null) { scrollRectToVisible(new Rectangle(0,0,1,1)); } boolean reloaded = false; Object postData = getPostData(); if ((loaded == null) || !loaded.sameFile(page) || (postData != null)) { // different url or POST method, load the new content int p = getAsynchronousLoadPriority(getDocument()); if (p < 0) { // open stream synchronously InputStream in = getStream(page); if (kit != null) { Document doc = initializeModel(kit, page); // At this point, one could either load up the model with no // view notifications slowing it down (i.e. best synchronous // behavior) or set the model and start to feed it on a separate // thread (best asynchronous behavior). p = getAsynchronousLoadPriority(doc); if (p >= 0) { // load asynchronously setDocument(doc); synchronized(this) { pageLoader = new PageLoader(doc, in, loaded, page); pageLoader.execute(); } return; } read(in, doc); setDocument(doc); reloaded = true; } } else { // we may need to cancel background loading if (pageLoader != null) { pageLoader.cancel(true); } // Do everything in a background thread. // Model initialization is deferred to that thread, too. pageLoader = new PageLoader(null, null, loaded, page); pageLoader.execute(); return; } } final String reference = page.getRef(); if (reference != null) { if (!reloaded) { scrollToReference(reference); } else { // Have to scroll after painted. SwingUtilities.invokeLater(new Runnable() { public void run() { scrollToReference(reference); } }); } getDocument().putProperty(Document.StreamDescriptionProperty, page); } firePropertyChange("page", loaded, page); } /** * Create model and initialize document properties from page properties. */ private Document initializeModel(EditorKit kit, URL page) { Document doc = kit.createDefaultDocument(); if (pageProperties != null) { // transfer properties discovered in stream to the // document property collection. for (Enumeration<String> e = pageProperties.keys(); e.hasMoreElements() ;) { String key = e.nextElement(); doc.putProperty(key, pageProperties.get(key)); } pageProperties.clear(); } if (doc.getProperty(Document.StreamDescriptionProperty) == null) { doc.putProperty(Document.StreamDescriptionProperty, page); } return doc; } /** * Return load priority for the document or -1 if priority not supported. */ private int getAsynchronousLoadPriority(Document doc) { return (doc instanceof AbstractDocument ? ((AbstractDocument) doc).getAsynchronousLoadPriority() : -1); } /** * This method initializes from a stream. If the kit is * set to be of type <code>HTMLEditorKit</code>, and the * <code>desc</code> parameter is an <code>HTMLDocument</code>, * then it invokes the <code>HTMLEditorKit</code> to initiate * the read. Otherwise it calls the superclass * method which loads the model as plain text. * * @param in the stream from which to read * @param desc an object describing the stream * @exception IOException as thrown by the stream being * used to initialize * @see JTextComponent#read * @see #setDocument */ public void read(InputStream in, Object desc) throws IOException { if (desc instanceof HTMLDocument && kit instanceof HTMLEditorKit) { HTMLDocument hdoc = (HTMLDocument) desc; setDocument(hdoc); read(in, hdoc); } else { String charset = (String) getClientProperty("charset"); Reader r = (charset != null) ? new InputStreamReader(in, charset) : new InputStreamReader(in); super.read(r, desc); } } /** * This method invokes the <code>EditorKit</code> to initiate a * read. In the case where a <code>ChangedCharSetException</code> * is thrown this exception will contain the new CharSet. * Therefore the <code>read</code> operation * is then restarted after building a new Reader with the new charset. * * @param in the inputstream to use * @param doc the document to load * */ void read(InputStream in, Document doc) throws IOException { if (! Boolean.TRUE.equals(doc.getProperty("IgnoreCharsetDirective"))) { final int READ_LIMIT = 1024 * 10; in = new BufferedInputStream(in, READ_LIMIT); in.mark(READ_LIMIT); } try { String charset = (String) getClientProperty("charset"); Reader r = (charset != null) ? new InputStreamReader(in, charset) : new InputStreamReader(in); kit.read(r, doc, 0); } catch (BadLocationException e) { throw new IOException(e.getMessage()); } catch (ChangedCharSetException changedCharSetException) { String charSetSpec = changedCharSetException.getCharSetSpec(); if (changedCharSetException.keyEqualsCharSet()) { putClientProperty("charset", charSetSpec); } else { setCharsetFromContentTypeParameters(charSetSpec); } try { in.reset(); } catch (IOException exception) { //mark was invalidated in.close(); URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty); if (url != null) { URLConnection conn = url.openConnection(); in = conn.getInputStream(); } else { //there is nothing we can do to recover stream throw changedCharSetException; } } try { doc.remove(0, doc.getLength()); } catch (BadLocationException e) {} doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true)); read(in, doc); } } /** * Loads a stream into the text document model. */ class PageLoader extends SwingWorker<URL, Object> { /** * Construct an asynchronous page loader. */ PageLoader(Document doc, InputStream in, URL old, URL page) { this.in = in; this.old = old; this.page = page; this.doc = doc; } /** * Try to load the document, then scroll the view * to the reference (if specified). When done, fire * a page property change event. */ protected URL doInBackground() { boolean pageLoaded = false; try { if (in == null) { in = getStream(page); if (kit == null) { // We received document of unknown content type. UIManager.getLookAndFeel(). provideErrorFeedback(JEditorPane.this); return old; } } if (doc == null) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { doc = initializeModel(kit, page); setDocument(doc); } }); } catch (InvocationTargetException ex) { UIManager.getLookAndFeel().provideErrorFeedback( JEditorPane.this); return old; } catch (InterruptedException ex) { UIManager.getLookAndFeel().provideErrorFeedback( JEditorPane.this); return old; } } read(in, doc); URL page = (URL) doc.getProperty(Document.StreamDescriptionProperty); String reference = page.getRef(); if (reference != null) { // scroll the page if necessary, but do it on the // event thread... that is the only guarantee that // modelToView can be safely called. Runnable callScrollToReference = new Runnable() { public void run() { URL u = (URL) getDocument().getProperty (Document.StreamDescriptionProperty); String ref = u.getRef(); scrollToReference(ref); } }; SwingUtilities.invokeLater(callScrollToReference); } pageLoaded = true; } catch (IOException ioe) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } finally { if (pageLoaded) { SwingUtilities.invokeLater(new Runnable() { public void run() { JEditorPane.this.firePropertyChange("page", old, page); } }); } return (pageLoaded ? page : old); } } /** * The stream to load the document with */ InputStream in; /** * URL of the old page that was replaced (for the property change event) */ URL old; /** * URL of the page being loaded (for the property change event) */ URL page; /** * The Document instance to load into. This is cached in case a * new Document is created between the time the thread this is created * and run. */ Document doc; } /** * Fetches a stream for the given URL, which is about to * be loaded by the <code>setPage</code> method. By * default, this simply opens the URL and returns the * stream. This can be reimplemented to do useful things * like fetch the stream from a cache, monitor the progress * of the stream, etc. * <p> * This method is expected to have the the side effect of * establishing the content type, and therefore setting the * appropriate <code>EditorKit</code> to use for loading the stream. * <p> * If this the stream was an http connection, redirects * will be followed and the resulting URL will be set as * the <code>Document.StreamDescriptionProperty</code> so that relative * URL's can be properly resolved. * * @param page the URL of the page */ protected InputStream getStream(URL page) throws IOException { final URLConnection conn = page.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection) conn; hconn.setInstanceFollowRedirects(false); Object postData = getPostData(); if (postData != null) { handlePostData(hconn, postData); } int response = hconn.getResponseCode(); boolean redirect = (response >= 300 && response <= 399); /* * In the case of a redirect, we want to actually change the URL * that was input to the new, redirected URL */ if (redirect) { String loc = conn.getHeaderField("Location"); if (loc.startsWith("http", 0)) { page = new URL(loc); } else { page = new URL(page, loc); } return getStream(page); } } // Connection properties handler should be forced to run on EDT, // as it instantiates the EditorKit. if (SwingUtilities.isEventDispatchThread()) { handleConnectionProperties(conn); } else { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { handleConnectionProperties(conn); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } return conn.getInputStream(); } /** * Handle URL connection properties (most notably, content type). */ private void handleConnectionProperties(URLConnection conn) { if (pageProperties == null) { pageProperties = new Hashtable<String, Object>(); } String type = conn.getContentType(); if (type != null) { setContentType(type); pageProperties.put("content-type", type); } pageProperties.put(Document.StreamDescriptionProperty, conn.getURL()); String enc = conn.getContentEncoding(); if (enc != null) { pageProperties.put("content-encoding", enc); } } private Object getPostData() { return getDocument().getProperty(PostDataProperty); } private void handlePostData(HttpURLConnection conn, Object postData) throws IOException { conn.setDoOutput(true); DataOutputStream os = null; try { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); os = new DataOutputStream(conn.getOutputStream()); os.writeBytes((String) postData); } finally { if (os != null) { os.close(); } } } /** * Scrolls the view to the given reference location * (that is, the value returned by the <code>UL.getRef</code> * method for the URL being displayed). By default, this * method only knows how to locate a reference in an * HTMLDocument. The implementation calls the * <code>scrollRectToVisible</code> method to * accomplish the actual scrolling. If scrolling to a * reference location is needed for document types other * than HTML, this method should be reimplemented. * This method will have no effect if the component * is not visible. * * @param reference the named location to scroll to */ public void scrollToReference(String reference) { Document d = getDocument(); if (d instanceof HTMLDocument) { HTMLDocument doc = (HTMLDocument) d; HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A); for (; iter.isValid(); iter.next()) { AttributeSet a = iter.getAttributes(); String nm = (String) a.getAttribute(HTML.Attribute.NAME); if ((nm != null) && nm.equals(reference)) { // found a matching reference in the document. try { int pos = iter.getStartOffset(); Rectangle r = modelToView(pos); if (r != null) { // the view is visible, scroll it to the // center of the current visible area. Rectangle vis = getVisibleRect(); //r.y -= (vis.height / 2); r.height = vis.height; scrollRectToVisible(r); setCaretPosition(pos); } } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } } } } } /** * Gets the current URL being displayed. If a URL was * not specified in the creation of the document, this * will return <code>null</code>, and relative URL's will not be * resolved. * * @return the URL, or <code>null</code> if none */ public URL getPage() { return (URL) getDocument().getProperty(Document.StreamDescriptionProperty); } /** * Sets the current URL being displayed. * * @param url the URL for display * @exception IOException for a <code>null</code> or invalid URL * specification */ public void setPage(String url) throws IOException { if (url == null) { throw new IOException("invalid url"); } URL page = new URL(url); setPage(page); } /** * Gets the class ID for the UI. * * @return the string "EditorPaneUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Creates the default editor kit (<code>PlainEditorKit</code>) for when * the component is first created. * * @return the editor kit */ protected EditorKit createDefaultEditorKit() { return new PlainEditorKit(); } /** * Fetches the currently installed kit for handling content. * <code>createDefaultEditorKit</code> is called to set up a default * if necessary. * * @return the editor kit */ public EditorKit getEditorKit() { if (kit == null) { kit = createDefaultEditorKit(); isUserSetEditorKit = false; } return kit; } /** * Gets the type of content that this editor * is currently set to deal with. This is * defined to be the type associated with the * currently installed <code>EditorKit</code>. * * @return the content type, <code>null</code> if no editor kit set */ public final String getContentType() { return (kit != null) ? kit.getContentType() : null; } /** * Sets the type of content that this editor * handles. This calls <code>getEditorKitForContentType</code>, * and then <code>setEditorKit</code> if an editor kit can * be successfully located. This is mostly convenience method * that can be used as an alternative to calling * <code>setEditorKit</code> directly. * <p> * If there is a charset definition specified as a parameter * of the content type specification, it will be used when * loading input streams using the associated <code>EditorKit</code>. * For example if the type is specified as * <code>text/html; charset=EUC-JP</code> the content * will be loaded using the <code>EditorKit</code> registered for * <code>text/html</code> and the Reader provided to * the <code>EditorKit</code> to load unicode into the document will * use the <code>EUC-JP</code> charset for translating * to unicode. If the type is not recognized, the content * will be loaded using the <code>EditorKit</code> registered * for plain text, <code>text/plain</code>. * * @param type the non-<code>null</code> mime type for the content editing * support * @see #getContentType * @beaninfo * description: the type of content * @throws NullPointerException if the <code>type</code> parameter * is <code>null</code> */ public final void setContentType(String type) { // The type could have optional info is part of it, // for example some charset info. We need to strip that // of and save it. int parm = type.indexOf(";"); if (parm > -1) { // Save the paramList. String paramList = type.substring(parm); // update the content type string. type = type.substring(0, parm).trim(); if (type.toLowerCase().startsWith("text/")) { setCharsetFromContentTypeParameters(paramList); } } if ((kit == null) || (! type.equals(kit.getContentType())) || !isUserSetEditorKit) { EditorKit k = getEditorKitForContentType(type); if (k != null && k != kit) { setEditorKit(k); isUserSetEditorKit = false; } } } /** * This method gets the charset information specified as part * of the content type in the http header information. */ private void setCharsetFromContentTypeParameters(String paramlist) { String charset; try { // paramlist is handed to us with a leading ';', strip it. int semi = paramlist.indexOf(';'); if (semi > -1 && semi < paramlist.length()-1) { paramlist = paramlist.substring(semi + 1); } if (paramlist.length() > 0) { // parse the paramlist into attr-value pairs & get the // charset pair's value HeaderParser hdrParser = new HeaderParser(paramlist); charset = hdrParser.findValue("charset"); if (charset != null) { putClientProperty("charset", charset); } } } catch (IndexOutOfBoundsException e) { // malformed parameter list, use charset we have } catch (NullPointerException e) { // malformed parameter list, use charset we have } catch (Exception e) { // malformed parameter list, use charset we have; but complain System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist); e.printStackTrace(); } } /** * Sets the currently installed kit for handling * content. This is the bound property that * establishes the content type of the editor. * Any old kit is first deinstalled, then if kit is * non-<code>null</code>, * the new kit is installed, and a default document created for it. * A <code>PropertyChange</code> event ("editorKit") is always fired when * <code>setEditorKit</code> is called. * <p> * <em>NOTE: This has the side effect of changing the model, * because the <code>EditorKit</code> is the source of how a * particular type * of content is modeled. This method will cause <code>setDocument</code> * to be called on behalf of the caller to ensure integrity * of the internal state.</em> * * @param kit the desired editor behavior * @see #getEditorKit * @beaninfo * description: the currently installed kit for handling content * bound: true * expert: true */ public void setEditorKit(EditorKit kit) { EditorKit old = this.kit; isUserSetEditorKit = true; if (old != null) { old.deinstall(this); } this.kit = kit; if (this.kit != null) { this.kit.install(this); setDocument(this.kit.createDefaultDocument()); } firePropertyChange("editorKit", old, kit); } /** * Fetches the editor kit to use for the given type * of content. This is called when a type is requested * that doesn't match the currently installed type. * If the component doesn't have an <code>EditorKit</code> registered * for the given type, it will try to create an * <code>EditorKit</code> from the default <code>EditorKit</code> registry. * If that fails, a <code>PlainEditorKit</code> is used on the * assumption that all text documents can be represented * as plain text. * <p> * This method can be reimplemented to use some * other kind of type registry. This can * be reimplemented to use the Java Activation * Framework, for example. * * @param type the non-<code>null</code> content type * @return the editor kit */ public EditorKit getEditorKitForContentType(String type) { if (typeHandlers == null) { typeHandlers = new Hashtable<String, EditorKit>(3); } EditorKit k = typeHandlers.get(type); if (k == null) { k = createEditorKitForContentType(type); if (k != null) { setEditorKitForContentType(type, k); } } if (k == null) { k = createDefaultEditorKit(); } return k; } /** * Directly sets the editor kit to use for the given type. A * look-and-feel implementation might use this in conjunction * with <code>createEditorKitForContentType</code> to install handlers for * content types with a look-and-feel bias. * * @param type the non-<code>null</code> content type * @param k the editor kit to be set */ public void setEditorKitForContentType(String type, EditorKit k) { if (typeHandlers == null) { typeHandlers = new Hashtable<String, EditorKit>(3); } typeHandlers.put(type, k); } /** * Replaces the currently selected content with new content * represented by the given string. If there is no selection * this amounts to an insert of the given text. If there * is no replacement text (i.e. the content string is empty * or <code>null</code>) this amounts to a removal of the * current selection. The replacement text will have the * attributes currently defined for input. If the component is not * editable, beep and return. * * @param content the content to replace the selection with. This * value can be <code>null</code> */ @Override public void replaceSelection(String content) { if (! isEditable()) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); return; } EditorKit kit = getEditorKit(); if(kit instanceof StyledEditorKit) { try { Document doc = getDocument(); Caret caret = getCaret(); boolean composedTextSaved = saveComposedText(caret.getDot()); int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).replace(p0, p1 - p0, content, ((StyledEditorKit)kit).getInputAttributes()); } else { if (p0 != p1) { doc.remove(p0, p1 - p0); } if (content != null && content.length() > 0) { doc.insertString(p0, content, ((StyledEditorKit)kit). getInputAttributes()); } } if (composedTextSaved) { restoreComposedText(); } } catch (BadLocationException e) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } } else { super.replaceSelection(content); } } /** * Creates a handler for the given type from the default registry * of editor kits. The registry is created if necessary. If the * registered class has not yet been loaded, an attempt * is made to dynamically load the prototype of the kit for the * given type. If the type was registered with a <code>ClassLoader</code>, * that <code>ClassLoader</code> will be used to load the prototype. * If there was no registered <code>ClassLoader</code>, * <code>Class.forName</code> will be used to load the prototype. * <p> * Once a prototype <code>EditorKit</code> instance is successfully * located, it is cloned and the clone is returned. * * @param type the content type * @return the editor kit, or <code>null</code> if there is nothing * registered for the given type */ public static EditorKit createEditorKitForContentType(String type) { Hashtable<String, EditorKit> kitRegistry = getKitRegisty(); EditorKit k = kitRegistry.get(type); if (k == null) { // try to dynamically load the support String classname = getKitTypeRegistry().get(type); ClassLoader loader = getKitLoaderRegistry().get(type); try { Class c; if (loader != null) { c = loader.loadClass(classname); } else { // Will only happen if developer has invoked // registerEditorKitForContentType(type, class, null). c = Class.forName(classname, true, Thread.currentThread(). getContextClassLoader()); } k = (EditorKit) c.newInstance(); kitRegistry.put(type, k); } catch (Throwable e) { k = null; } } // create a copy of the prototype or null if there // is no prototype. if (k != null) { return (EditorKit) k.clone(); } return null; } /** * Establishes the default bindings of <code>type</code> to * <code>classname</code>. * The class will be dynamically loaded later when actually * needed, and can be safely changed before attempted uses * to avoid loading unwanted classes. The prototype * <code>EditorKit</code> will be loaded with <code>Class.forName</code> * when registered with this method. * * @param type the non-<code>null</code> content type * @param classname the class to load later */ public static void registerEditorKitForContentType(String type, String classname) { registerEditorKitForContentType(type, classname,Thread.currentThread(). getContextClassLoader()); } /** * Establishes the default bindings of <code>type</code> to * <code>classname</code>. * The class will be dynamically loaded later when actually * needed using the given <code>ClassLoader</code>, * and can be safely changed * before attempted uses to avoid loading unwanted classes. * * @param type the non-<code>null</code> content type * @param classname the class to load later * @param loader the <code>ClassLoader</code> to use to load the name */ public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) { getKitTypeRegistry().put(type, classname); getKitLoaderRegistry().put(type, loader); getKitRegisty().remove(type); } /** * Returns the currently registered <code>EditorKit</code> * class name for the type <code>type</code>. * * @param type the non-<code>null</code> content type * * @since 1.3 */ public static String getEditorKitClassNameForContentType(String type) { return getKitTypeRegistry().get(type); } private static Hashtable<String, String> getKitTypeRegistry() { loadDefaultKitsIfNecessary(); return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey); } private static Hashtable<String, ClassLoader> getKitLoaderRegistry() { loadDefaultKitsIfNecessary(); return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey); } private static Hashtable<String, EditorKit> getKitRegisty() { Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey); if (ht == null) { ht = new Hashtable(3); SwingUtilities.appContextPut(kitRegistryKey, ht); } return ht; } /** * This is invoked every time the registries are accessed. Loading * is done this way instead of via a static as the static is only * called once when running in plugin resulting in the entries only * appearing in the first applet. */ private static void loadDefaultKitsIfNecessary() { if (SwingUtilities.appContextGet(kitTypeRegistryKey) == null) { synchronized(defaultEditorKitMap) { if (defaultEditorKitMap.size() == 0) { defaultEditorKitMap.put("text/plain", "javax.swing.JEditorPane$PlainEditorKit"); defaultEditorKitMap.put("text/html", "javax.swing.text.html.HTMLEditorKit"); defaultEditorKitMap.put("text/rtf", "javax.swing.text.rtf.RTFEditorKit"); defaultEditorKitMap.put("application/rtf", "javax.swing.text.rtf.RTFEditorKit"); } } Hashtable ht = new Hashtable(); SwingUtilities.appContextPut(kitTypeRegistryKey, ht); ht = new Hashtable(); SwingUtilities.appContextPut(kitLoaderRegistryKey, ht); for (String key : defaultEditorKitMap.keySet()) { registerEditorKitForContentType(key,defaultEditorKitMap.get(key)); } } } // --- java.awt.Component methods -------------------------- /** * Returns the preferred size for the <code>JEditorPane</code>. * The preferred size for <code>JEditorPane</code> is slightly altered * from the preferred size of the superclass. If the size * of the viewport has become smaller than the minimum size * of the component, the scrollable definition for tracking * width or height will turn to false. The default viewport * layout will give the preferred size, and that is not desired * in the case where the scrollable is tracking. In that case * the <em>normal</em> preferred size is adjusted to the * minimum size. This allows things like HTML tables to * shrink down to their minimum size and then be laid out at * their minimum size, refusing to shrink any further. * * @return a <code>Dimension</code> containing the preferred size */ public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); JViewport port = SwingUtilities.getParentViewport(this); if (port != null) { TextUI ui = getUI(); int prefWidth = d.width; int prefHeight = d.height; if (! getScrollableTracksViewportWidth()) { int w = port.getWidth(); Dimension min = ui.getMinimumSize(this); if (w != 0 && w < min.width) { // Only adjust to min if we have a valid size prefWidth = min.width; } } if (! getScrollableTracksViewportHeight()) { int h = port.getHeight(); Dimension min = ui.getMinimumSize(this); if (h != 0 && h < min.height) { // Only adjust to min if we have a valid size prefHeight = min.height; } } if (prefWidth != d.width || prefHeight != d.height) { d = new Dimension(prefWidth, prefHeight); } } return d; } // --- JTextComponent methods ----------------------------- /** * Sets the text of this <code>TextComponent</code> to the specified * content, * which is expected to be in the format of the content type of * this editor. For example, if the type is set to <code>text/html</code> * the string should be specified in terms of HTML. * <p> * This is implemented to remove the contents of the current document, * and replace them by parsing the given string using the current * <code>EditorKit</code>. This gives the semantics of the * superclass by not changing * out the model, while supporting the content type currently set on * this component. The assumption is that the previous content is * relatively * small, and that the previous content doesn't have side effects. * Both of those assumptions can be violated and cause undesirable results. * To avoid this, create a new document, * <code>getEditorKit().createDefaultDocument()</code>, and replace the * existing <code>Document</code> with the new one. You are then assured the * previous <code>Document</code> won't have any lingering state. * <ol> * <li> * Leaving the existing model in place means that the old view will be * torn down, and a new view created, where replacing the document would * avoid the tear down of the old view. * <li> * Some formats (such as HTML) can install things into the document that * can influence future contents. HTML can have style information embedded * that would influence the next content installed unexpectedly. * </ol> * <p> * An alternative way to load this component with a string would be to * create a StringReader and call the read method. In this case the model * would be replaced after it was initialized with the contents of the * string. * * @param t the new text to be set; if <code>null</code> the old * text will be deleted * @see #getText * @beaninfo * description: the text of this component */ public void setText(String t) { try { Document doc = getDocument(); doc.remove(0, doc.getLength()); if (t == null || t.equals("")) { return; } Reader r = new StringReader(t); EditorKit kit = getEditorKit(); kit.read(r, doc, 0); } catch (IOException ioe) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } } /** * Returns the text contained in this <code>TextComponent</code> * in terms of the * content type of this editor. If an exception is thrown while * attempting to retrieve the text, <code>null</code> will be returned. * This is implemented to call <code>JTextComponent.write</code> with * a <code>StringWriter</code>. * * @return the text * @see #setText */ public String getText() { String txt; try { StringWriter buf = new StringWriter(); write(buf); txt = buf.toString(); } catch (IOException ioe) { txt = null; } return txt; } // --- Scrollable ---------------------------------------- /** * Returns true if a viewport should always force the width of this * <code>Scrollable</code> to match the width of the viewport. * * @return true if a viewport should force the Scrollables width to * match its own, false otherwise */ public boolean getScrollableTracksViewportWidth() { JViewport port = SwingUtilities.getParentViewport(this); if (port != null) { TextUI ui = getUI(); int w = port.getWidth(); Dimension min = ui.getMinimumSize(this); Dimension max = ui.getMaximumSize(this); if ((w >= min.width) && (w <= max.width)) { return true; } } return false; } /** * Returns true if a viewport should always force the height of this * <code>Scrollable</code> to match the height of the viewport. * * @return true if a viewport should force the * <code>Scrollable</code>'s height to match its own, * false otherwise */ public boolean getScrollableTracksViewportHeight() { JViewport port = SwingUtilities.getParentViewport(this); if (port != null) { TextUI ui = getUI(); int h = port.getHeight(); Dimension min = ui.getMinimumSize(this); if (h >= min.height) { Dimension max = ui.getMaximumSize(this); if (h <= max.height) { return true; } } } return false; } // --- Serialization ------------------------------------ /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } // --- variables --------------------------------------- private SwingWorker<URL, Object> pageLoader; /** * Current content binding of the editor. */ private EditorKit kit; private boolean isUserSetEditorKit; private Hashtable<String, Object> pageProperties; /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */ final static String PostDataProperty = "javax.swing.JEditorPane.postdata"; /** * Table of registered type handlers for this editor. */ private Hashtable<String, EditorKit> typeHandlers; /* * Private AppContext keys for this class's static variables. */ private static final Object kitRegistryKey = new StringBuffer("JEditorPane.kitRegistry"); private static final Object kitTypeRegistryKey = new StringBuffer("JEditorPane.kitTypeRegistry"); private static final Object kitLoaderRegistryKey = new StringBuffer("JEditorPane.kitLoaderRegistry"); /** * @see #getUIClassID * @see #readObject */ private static final String uiClassID = "EditorPaneUI"; /** * Key for a client property used to indicate whether * <a href="http://www.w3.org/TR/CSS21/syndata.html#length-units"> * w3c compliant</a> length units are used for html rendering. * <p> * By default this is not enabled; to enable * it set the client {@link #putClientProperty property} with this name * to <code>Boolean.TRUE</code>. * * @since 1.5 */ public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits"; /** * Key for a client property used to indicate whether * the default font and foreground color from the component are * used if a font or foreground color is not specified in the styled * text. * <p> * The default varies based on the look and feel; * to enable it set the client {@link #putClientProperty property} with * this name to <code>Boolean.TRUE</code>. * * @since 1.5 */ public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties"; static final Map<String, String> defaultEditorKitMap = new HashMap<String, String>(0); /** * Returns a string representation of this <code>JEditorPane</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JEditorPane</code> */ protected String paramString() { String kitString = (kit != null ? kit.toString() : ""); String typeHandlersString = (typeHandlers != null ? typeHandlers.toString() : ""); return super.paramString() + ",kit=" + kitString + ",typeHandlers=" + typeHandlersString; } ///////////////// // Accessibility support //////////////// /** * Gets the AccessibleContext associated with this JEditorPane. * For editor panes, the AccessibleContext takes the form of an * AccessibleJEditorPane. * A new AccessibleJEditorPane instance is created if necessary. * * @return an AccessibleJEditorPane that serves as the * AccessibleContext of this JEditorPane */ public AccessibleContext getAccessibleContext() { if (getEditorKit() instanceof HTMLEditorKit) { if (accessibleContext == null || accessibleContext.getClass() != AccessibleJEditorPaneHTML.class) { accessibleContext = new AccessibleJEditorPaneHTML(); } } else if (accessibleContext == null || accessibleContext.getClass() != AccessibleJEditorPane.class) { accessibleContext = new AccessibleJEditorPane(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JEditorPane</code> class. It provides an implementation of the * Java Accessibility API appropriate to editor pane user-interface * elements. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ protected class AccessibleJEditorPane extends AccessibleJTextComponent { /** * Gets the accessibleDescription property of this object. If this * property isn't set, returns the content type of this * <code>JEditorPane</code> instead (e.g. "plain/text", "html/text"). * * @return the localized description of the object; <code>null</code> * if this object does not have a description * * @see #setAccessibleName */ public String getAccessibleDescription() { String description = accessibleDescription; // fallback to client property if (description == null) { description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY); } if (description == null) { description = JEditorPane.this.getContentType(); } return description; } /** * Gets the state set of this object. * * @return an instance of AccessibleStateSet describing the states * of the object * @see AccessibleStateSet */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = super.getAccessibleStateSet(); states.add(AccessibleState.MULTI_LINE); return states; } } /** * This class provides support for <code>AccessibleHypertext</code>, * and is used in instances where the <code>EditorKit</code> * installed in this <code>JEditorPane</code> is an instance of * <code>HTMLEditorKit</code>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane { private AccessibleContext accessibleContext; public AccessibleText getAccessibleText() { return new JEditorPaneAccessibleHypertextSupport(); } protected AccessibleJEditorPaneHTML () { HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit(); accessibleContext = kit.getAccessibleContext(); } /** * Returns the number of accessible children of the object. * * @return the number of accessible children of the object. */ public int getAccessibleChildrenCount() { if (accessibleContext != null) { return accessibleContext.getAccessibleChildrenCount(); } else { return 0; } } /** * Returns the specified Accessible child of the object. The Accessible * children of an Accessible object are zero-based, so the first child * of an Accessible child is at index 0, the second child is at index 1, * and so on. * * @param i zero-based index of child * @return the Accessible child of the object * @see #getAccessibleChildrenCount */ public Accessible getAccessibleChild(int i) { if (accessibleContext != null) { return accessibleContext.getAccessibleChild(i); } else { return null; } } /** * Returns the Accessible child, if one exists, contained at the local * coordinate Point. * * @param p The point relative to the coordinate system of this object. * @return the Accessible, if it exists, at the specified location; * otherwise null */ public Accessible getAccessibleAt(Point p) { if (accessibleContext != null && p != null) { try { AccessibleComponent acomp = accessibleContext.getAccessibleComponent(); if (acomp != null) { return acomp.getAccessibleAt(p); } else { return null; } } catch (IllegalComponentStateException e) { return null; } } else { return null; } } } /** * What's returned by * <code>AccessibleJEditorPaneHTML.getAccessibleText</code>. * * Provides support for <code>AccessibleHypertext</code> in case * there is an HTML document being displayed in this * <code>JEditorPane</code>. * */ protected class JEditorPaneAccessibleHypertextSupport extends AccessibleJEditorPane implements AccessibleHypertext { public class HTMLLink extends AccessibleHyperlink { Element element; public HTMLLink(Element e) { element = e; } /** * Since the document a link is associated with may have * changed, this method returns whether this Link is valid * anymore (with respect to the document it references). * * @return a flag indicating whether this link is still valid with * respect to the AccessibleHypertext it belongs to */ public boolean isValid() { return JEditorPaneAccessibleHypertextSupport.this.linksValid; } /** * Returns the number of accessible actions available in this Link * If there are more than one, the first one is NOT considered the * "default" action of this LINK object (e.g. in an HTML imagemap). * In general, links will have only one AccessibleAction in them. * * @return the zero-based number of Actions in this object */ public int getAccessibleActionCount() { return 1; } /** * Perform the specified Action on the object * * @param i zero-based index of actions * @return true if the the action was performed; else false. * @see #getAccessibleActionCount */ public boolean doAccessibleAction(int i) { if (i == 0 && isValid() == true) { URL u = (URL) getAccessibleActionObject(i); if (u != null) { HyperlinkEvent linkEvent = new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u); JEditorPane.this.fireHyperlinkUpdate(linkEvent); return true; } } return false; // link invalid or i != 0 } /** * Return a String description of this particular * link action. The string returned is the text * within the document associated with the element * which contains this link. * * @param i zero-based index of the actions * @return a String description of the action * @see #getAccessibleActionCount */ public String getAccessibleActionDescription(int i) { if (i == 0 && isValid() == true) { Document d = JEditorPane.this.getDocument(); if (d != null) { try { return d.getText(getStartIndex(), getEndIndex() - getStartIndex()); } catch (BadLocationException exception) { return null; } } } return null; } /** * Returns a URL object that represents the link. * * @param i zero-based index of the actions * @return an URL representing the HTML link itself * @see #getAccessibleActionCount */ public Object getAccessibleActionObject(int i) { if (i == 0 && isValid() == true) { AttributeSet as = element.getAttributes(); AttributeSet anchor = (AttributeSet) as.getAttribute(HTML.Tag.A); String href = (anchor != null) ? (String) anchor.getAttribute(HTML.Attribute.HREF) : null; if (href != null) { URL u; try { u = new URL(JEditorPane.this.getPage(), href); } catch (MalformedURLException m) { u = null; } return u; } } return null; // link invalid or i != 0 } /** * Return an object that represents the link anchor, * as appropriate for that link. E.g. from HTML: * <a href="http://www.sun.com/access">Accessibility</a> * this method would return a String containing the text: * 'Accessibility'. * * Similarly, from this HTML: * &lt;a HREF="#top"&gt;&lt;img src="top-hat.gif" alt="top hat"&gt;&lt;/a&gt; * this might return the object ImageIcon("top-hat.gif", "top hat"); * * @param i zero-based index of the actions * @return an Object representing the hypertext anchor * @see #getAccessibleActionCount */ public Object getAccessibleActionAnchor(int i) { return getAccessibleActionDescription(i); } /** * Get the index with the hypertext document at which this * link begins * * @return index of start of link */ public int getStartIndex() { return element.getStartOffset(); } /** * Get the index with the hypertext document at which this * link ends * * @return index of end of link */ public int getEndIndex() { return element.getEndOffset(); } } private class LinkVector extends Vector<HTMLLink> { public int baseElementIndex(Element e) { HTMLLink l; for (int i = 0; i < elementCount; i++) { l = elementAt(i); if (l.element == e) { return i; } } return -1; } } LinkVector hyperlinks; boolean linksValid = false; /** * Build the private table mapping links to locations in the text */ private void buildLinkTable() { hyperlinks.removeAllElements(); Document d = JEditorPane.this.getDocument(); if (d != null) { ElementIterator ei = new ElementIterator(d); Element e; AttributeSet as; AttributeSet anchor; String href; while ((e = ei.next()) != null) { if (e.isLeaf()) { as = e.getAttributes(); anchor = (AttributeSet) as.getAttribute(HTML.Tag.A); href = (anchor != null) ? (String) anchor.getAttribute(HTML.Attribute.HREF) : null; if (href != null) { hyperlinks.addElement(new HTMLLink(e)); } } } } linksValid = true; } /** * Make one of these puppies */ public JEditorPaneAccessibleHypertextSupport() { hyperlinks = new LinkVector(); Document d = JEditorPane.this.getDocument(); if (d != null) { d.addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent theEvent) { linksValid = false; } public void insertUpdate(DocumentEvent theEvent) { linksValid = false; } public void removeUpdate(DocumentEvent theEvent) { linksValid = false; } }); } } /** * Returns the number of links within this hypertext doc. * * @return number of links in this hypertext doc. */ public int getLinkCount() { if (linksValid == false) { buildLinkTable(); } return hyperlinks.size(); } /** * Returns the index into an array of hyperlinks that * is associated with this character index, or -1 if there * is no hyperlink associated with this index. * * @param charIndex index within the text * @return index into the set of hyperlinks for this hypertext doc. */ public int getLinkIndex(int charIndex) { if (linksValid == false) { buildLinkTable(); } Element e = null; Document doc = JEditorPane.this.getDocument(); if (doc != null) { for (e = doc.getDefaultRootElement(); ! e.isLeaf(); ) { int index = e.getElementIndex(charIndex); e = e.getElement(index); } } // don't need to verify that it's an HREF element; if // not, then it won't be in the hyperlinks Vector, and // so indexOf will return -1 in any case return hyperlinks.baseElementIndex(e); } /** * Returns the index into an array of hyperlinks that * index. If there is no hyperlink at this index, it returns * null. * * @param linkIndex into the set of hyperlinks for this hypertext doc. * @return string representation of the hyperlink */ public AccessibleHyperlink getLink(int linkIndex) { if (linksValid == false) { buildLinkTable(); } if (linkIndex >= 0 && linkIndex < hyperlinks.size()) { return hyperlinks.elementAt(linkIndex); } else { return null; } } /** * Returns the contiguous text within the document that * is associated with this hyperlink. * * @param linkIndex into the set of hyperlinks for this hypertext doc. * @return the contiguous text sharing the link at this index */ public String getLinkText(int linkIndex) { if (linksValid == false) { buildLinkTable(); } Element e = (Element) hyperlinks.elementAt(linkIndex); if (e != null) { Document d = JEditorPane.this.getDocument(); if (d != null) { try { return d.getText(e.getStartOffset(), e.getEndOffset() - e.getStartOffset()); } catch (BadLocationException exception) { return null; } } } return null; } } static class PlainEditorKit extends DefaultEditorKit implements ViewFactory { /** * Fetches a factory that is suitable for producing * views of any models that are produced by this * kit. The default is to have the UI produce the * factory, so this method has no implementation. * * @return the view factory */ public ViewFactory getViewFactory() { return this; } /** * Creates a view from the given structural element of a * document. * * @param elem the piece of the document to build a view of * @return the view * @see View */ public View create(Element elem) { Document doc = elem.getDocument(); Object i18nFlag = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/); if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) { // build a view that support bidi return createI18N(elem); } else { return new WrappedPlainView(elem); } } View createI18N(Element elem) { String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new PlainParagraph(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)){ return new BoxView(elem, View.Y_AXIS); } } return null; } /** * Paragraph for representing plain-text lines that support * bidirectional text. */ static class PlainParagraph extends javax.swing.text.ParagraphView { PlainParagraph(Element elem) { super(elem); layoutPool = new LogicalView(elem); layoutPool.setParent(this); } protected void setPropertiesFromAttributes() { Component c = getContainer(); if ((c != null) && (! c.getComponentOrientation().isLeftToRight())) { setJustification(StyleConstants.ALIGN_RIGHT); } else { setJustification(StyleConstants.ALIGN_LEFT); } } /** * Fetch the constraining span to flow against for * the given child index. */ public int getFlowSpan(int index) { Component c = getContainer(); if (c instanceof JTextArea) { JTextArea area = (JTextArea) c; if (! area.getLineWrap()) { // no limit if unwrapped return Integer.MAX_VALUE; } } return super.getFlowSpan(index); } protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) { SizeRequirements req = super.calculateMinorAxisRequirements(axis, r); Component c = getContainer(); if (c instanceof JTextArea) { JTextArea area = (JTextArea) c; if (! area.getLineWrap()) { // min is pref if unwrapped req.minimum = req.preferred; } } return req; } /** * This class can be used to represent a logical view for * a flow. It keeps the children updated to reflect the state * of the model, gives the logical child views access to the * view hierarchy, and calculates a preferred span. It doesn't * do any rendering, layout, or model/view translation. */ static class LogicalView extends CompositeView { LogicalView(Element elem) { super(elem); } protected int getViewIndexAtPosition(int pos) { Element elem = getElement(); if (elem.getElementCount() > 0) { return elem.getElementIndex(pos); } return 0; } protected boolean updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) { return false; } protected void loadChildren(ViewFactory f) { Element elem = getElement(); if (elem.getElementCount() > 0) { super.loadChildren(f); } else { View v = new GlyphView(elem); append(v); } } public float getPreferredSpan(int axis) { if( getViewCount() != 1 ) throw new Error("One child view is assumed."); View v = getView(0); //((GlyphView)v).setGlyphPainter(null); return v.getPreferredSpan(axis); } /** * Forward the DocumentEvent to the given child view. This * is implemented to reparent the child to the logical view * (the children may have been parented by a row in the flow * if they fit without breaking) and then execute the * superclass behavior. * * @param v the child view to forward the event to. * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has * children * @see #forwardUpdate * @since 1.3 */ protected void forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) { v.setParent(this); super.forwardUpdateToView(v, e, a, f); } // The following methods don't do anything useful, they // simply keep the class from being abstract. public void paint(Graphics g, Shape allocation) { } protected boolean isBefore(int x, int y, Rectangle alloc) { return false; } protected boolean isAfter(int x, int y, Rectangle alloc) { return false; } protected View getViewAtPoint(int x, int y, Rectangle alloc) { return null; } protected void childAllocation(int index, Rectangle a) { } } } } /* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers * sensibly: * From a String like: 'timeout=15, max=5' * create an array of Strings: * { {"timeout", "15"}, * {"max", "5"} * } * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"' * create one like (no quotes in literal): * { {"basic", null}, * {"realm", "FuzzFace"} * {"foo", "Biz Bar Baz"} * } * keys are converted to lower case, vals are left as is.... * * author Dave Brown */ static class HeaderParser { /* table of key/val pairs - maxes out at 10!!!!*/ String raw; String[][] tab; public HeaderParser(String raw) { this.raw = raw; tab = new String[10][2]; parse(); } private void parse() { if (raw != null) { raw = raw.trim(); char[] ca = raw.toCharArray(); int beg = 0, end = 0, i = 0; boolean inKey = true; boolean inQuote = false; int len = ca.length; while (end < len) { char c = ca[end]; if (c == '=') { // end of a key tab[i][0] = new String(ca, beg, end-beg).toLowerCase(); inKey = false; end++; beg = end; } else if (c == '\"') { if (inQuote) { tab[i++][1]= new String(ca, beg, end-beg); inQuote=false; do { end++; } while (end < len && (ca[end] == ' ' || ca[end] == ',')); inKey=true; beg=end; } else { inQuote=true; end++; beg=end; } } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in if (inQuote) { end++; continue; } else if (inKey) { tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase(); } else { tab[i++][1] = (new String(ca, beg, end-beg)); } while (end < len && (ca[end] == ' ' || ca[end] == ',')) { end++; } inKey = true; beg = end; } else { end++; } } // get last key/val, if any if (--end > beg) { if (!inKey) { if (ca[end] == '\"') { tab[i++][1] = (new String(ca, beg, end-beg)); } else { tab[i++][1] = (new String(ca, beg, end-beg+1)); } } else { tab[i][0] = (new String(ca, beg, end-beg+1)).toLowerCase(); } } else if (end == beg) { if (!inKey) { if (ca[end] == '\"') { tab[i++][1] = String.valueOf(ca[end-1]); } else { tab[i++][1] = String.valueOf(ca[end]); } } else { tab[i][0] = String.valueOf(ca[end]).toLowerCase(); } } } } public String findKey(int i) { if (i < 0 || i > 10) return null; return tab[i][0]; } public String findValue(int i) { if (i < 0 || i > 10) return null; return tab[i][1]; } public String findValue(String key) { return findValue(key, null); } public String findValue(String k, String Default) { if (k == null) return Default; k = k.toLowerCase(); for (int i = 0; i < 10; ++i) { if (tab[i][0] == null) { return Default; } else if (k.equals(tab[i][0])) { return tab[i][1]; } } return Default; } public int findInt(String k, int Default) { try { return Integer.parseInt(findValue(k, String.valueOf(Default))); } catch (Throwable t) { return Default; } } } }
gpl-2.0
deyami/dbstorm
dbstorm-zookeeper/src/main/java/com/reform/dbstorm/zookeeper/ZKClient.java
25943
package com.reform.dbstorm.zookeeper; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import com.reform.dbstorm.zookeeper.exception.ZKTimeoutException; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.ConnectionLossException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.SessionExpiredException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.reform.dbstorm.zookeeper.exception.ZKException; import com.reform.dbstorm.zookeeper.exception.ZKInterruptedException; import com.reform.dbstorm.zookeeper.exception.ZKKeeperException; /** * zookeeper客户端,封装zookeeper的多数操作. * <br> * <ol> * <li>用listener的概念取代了watcher,解决了同一客户端对节点进行多次watch只能收到一次通知的限制.</li> * <li>保证客户端的高可用性,封装了在连接断开或session超时等情况下的等待和重连过程.</li> * <li>封装了zookeeper的异常,将部分的checked异常重新包装为runtime异常.</li> * <li>提供了一个同步版本的syncReadData方法,保证数据的实时性.</li> * </ol> * * @author huaiyu.du@opi-corp.com 2012-1-16 下午2:41:20 * */ public class ZKClient implements Watcher { private static final Logger log = LoggerFactory .getLogger(ZKClient.class); /** * 默认超时时间,以millsecond为单位. */ public static final int DEFAULT_CONNECTION_TIMEOUT = 10000; /** * zookeeper连接. */ private ZKConnection connection; /** * 服务器端点列表. */ private final String zkServers; /** * 连接zookeeper超时时间. */ private final long connectionTimeout; /** * 事件分发线程. */ private final EventThread eventThread; /** * 事件处理锁. */ private final ZKLock eventLock = new ZKLock(); /** * 监听客户端状态的listener. */ private final Set<StateListener> stateListeners = new HashSet<StateListener>(); /** * 监听client节点的listener. */ private final ConcurrentHashMap<String, Set<DataListener>> dataListeners = new ConcurrentHashMap<String, Set<DataListener>>(); /** * 监听db配置信息的listener. */ private final ConcurrentHashMap<String, Set<NodeListener>> nodeListeners = new ConcurrentHashMap<String, Set<NodeListener>>(); /** * 客户端关闭标记. */ private volatile boolean shutdownTriggered; /** * 客户端当前的状态,比较重要的是syncconnect和expired两个状态. */ private volatile KeeperState currentState; /** * 当前进入process方法的线程标记. */ private volatile Thread zookeeperEventThread; /** * 工具类 */ private final ZKHelper helper = new ZKHelper(); //====================构造函数=========================// /** * 创建一个客户端实例. * * @param zkServers 服务器端点地址,比如:10.6.39.74:2181,10.6.39.80:2181,10.6.33.105:2181. * 但zkServers不能包含任何chroot路径.去掉chroot路径是因为在zookeeper中还不能真正做到对chroot透明,很难统一api. * * @throws com.reform.dbstorm.zookeeper.exception.ZKTimeoutException 当链接等待时间超过<code>DEFAULT_CONNECTION_TIMEOUT</code>后 */ public ZKClient(final String zkServers) { this.zkServers = zkServers; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; connection = new ZKConnection(zkServers); eventThread = new EventThread(zkServers); connect(connectionTimeout, this); } /** * 创建一个客户端实例. * @param zkServers 服务器端点地址,比如:10.6.39.74:2181,10.6.39.80:2181,10.6.33.105:2181. * @param sessionTimeout 会话超时时间,客户端断开超过此时间后,服务端将会清除掉所有的相关信息,包括watcher和临时节点 */ public ZKClient(final String zkServers, final int sessionTimeout) { this.zkServers = zkServers; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; connection = new ZKConnection(zkServers, sessionTimeout); eventThread = new EventThread(zkServers); connect(connectionTimeout, this); } /** * 创建一个客户端实例. * @param zkServers 服务器端点地址,比如:10.6.39.74:2181,10.6.39.80:2181,10.6.33.105:2181. * @param sessionTimeout 会话超时时间 * @param connectionTimeout 连接超时时间 * * @throws com.reform.dbstorm.zookeeper.exception.ZKTimeoutException 当链接等待时间超过connectionTimeout后 */ public ZKClient(final String zkServers, final int sessionTimeout, final long connectionTimeout) { this.zkServers = zkServers; this.connectionTimeout = connectionTimeout; connection = new ZKConnection(zkServers, sessionTimeout); eventThread = new EventThread(zkServers); connect(connectionTimeout, this); } //====================public=========================// /** * 获取一个znode的数据. * * @param path znode路径 * @param serlizer 反序列化器 * @return 经过反序列化的数据值 * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public <T> T readData(final String path, final DataDeserializer<T> serlizer) { final Stat stat = new Stat(); try { byte[] data = retryUntilConnected(new Callable<byte[]>() { public byte[] call() throws Exception { return connection.getData(path, null, stat); } }); return serlizer.deserialize(data); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 强行要求服务端同步,随后获取一个znode的数据. * * @param path znode路径 * @param serlizer 序列化器 * @return 经过反序列化的数据值 */ public <T> T syncReadData(final String path, final DataDeserializer<T> serlizer) { final Stat stat = new Stat(); try { byte[] data = retryUntilConnected(new Callable<byte[]>() { public byte[] call() throws Exception { return connection.submitSyncTask(path, new Callable<byte[]>() { public byte[] call() throws Exception { return connection.getData(path, null, stat); } }); } }); return serlizer.deserialize(data); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 修改一个znode的数据. * * @param path znode路径 * @param obj 待写入的数据对象 * @param serializer 对象序列化器实例 */ public <T> void writeData(final String path, final T obj, final DataSerializer<T> serializer) { writeData(path, obj, serializer, -1); } /** * 修改一个node数据. * * @param path znode路径 * @param obj 待写入的数据对象 * @param serializer 对象序列化器实例 * @param expectedVersion -1表示不限定版本 * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public <T> void writeData(final String path, final T obj, final DataSerializer<T> serializer, final int expectedVersion) { try { retryUntilConnected(new Callable<Stat>() { public Stat call() throws Exception { return connection.setData(path, serializer.serialize(obj), expectedVersion); } }); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 判断一个znode是否存在. * * @param path znode路径 * @return znode状态 * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public Stat exist(final String path) { try { return helper.exist(path, hasDataListener(path)); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 获取某个znode的全部子节点. * * @param path znode路径 * @return 子节点列表 * * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public List<String> getChildren(final String path) { try { return helper.getChildren(path, hasNodeListener(path)); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 删除节点. * * @param path znode路径 * * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public void deleteNode(final String path) { try { retryUntilConnected(new Callable<Object>() { public Object call() throws Exception { connection.delete(path); return null; } }); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 创建一个持久节点. * * @param path znode路径 * @param obj * @param serializer * @param createParents true则创建父节点,false则不创建 * * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public <T> void createPersistent(final String path, final T obj, final DataSerializer<T> serializer, final boolean createParents) { if (obj != null && serializer == null) { throw new IllegalArgumentException("serializer can not be null"); } try { helper.create(path, obj, serializer, CreateMode.PERSISTENT); } catch (NoNodeException e) { String parentDir = path.substring(0, path.lastIndexOf("/")); if (parentDir.length() > 0) { createPersistent(parentDir, null, null, createParents); } createPersistent(path, obj, serializer, createParents); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 创建一个临时节点. * * @param path znode路径 * @param obj * @param serializer * * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ public <T> void createEphemeral(final String path, final T obj, final DataSerializer<T> serializer) { try { helper.create(path, obj, serializer, CreateMode.EPHEMERAL); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 注册一个数据观察者. * * @param watcher */ public void registerDataListener(final DataListener listener) { final String path = listener.getPath(); log.debug("watch for data {}", path); synchronized (dataListeners) { Set<DataListener> listeners = dataListeners.get(path); if (listeners == null) { listeners = new CopyOnWriteArraySet<DataListener>(); dataListeners.put(path, listeners); } listeners.add(listener); watchForData(path); } } public void unRegisterDataListener(final DataListener listener) { final String path = listener.getPath(); log.debug("unwatch for data {}", path); synchronized (dataListeners) { Set<DataListener> listeners = dataListeners.get(path); if (listeners != null) { listeners.remove(listener); } if (listeners == null || listeners.isEmpty()) { dataListeners.remove(path); } } } /** * 注册一个node观察者. * * @param watcher */ public void registerNodeListener(final NodeListener listener) { final String path = listener.getPath(); log.debug("watch for node {}", path); synchronized (nodeListeners) { Set<NodeListener> listeners = nodeListeners.get(path); if (listeners == null) { listeners = new CopyOnWriteArraySet<NodeListener>(); nodeListeners.put(path, listeners); } listeners.add(listener); } watchForNode(path); } public void unRegisterNodeListener(final NodeListener listener) { final String path = listener.getPath(); log.debug("unwatch for node {}", path); synchronized (nodeListeners) { Set<NodeListener> listeners = nodeListeners.get(path); if (listeners != null) { listeners.remove(listener); } if (listeners == null || listeners.isEmpty()) { nodeListeners.remove(path); } } } /** * 不停地尝试执行任务,直到任务执行完毕. * * @param callable * @return 执行任务返回的结果 * @throws InterruptedException * @throws Exception */ public <T> T retryUntilConnected(final Callable<T> callable) throws InterruptedException, Exception { Assertion.isNotInEventThread(zookeeperEventThread);//不能在在zookeeper的通知线程内调用 while (true) { try { return callable.call(); } catch (ConnectionLossException e) { log.debug("caught a ConnectionLossException , do retry", e); Thread.yield();//暂缓一下,出现此异常后客户端可以按照zkservers列表进行切换,只需要等待即可 waitUntilConnected(this.connectionTimeout, TimeUnit.MILLISECONDS); } catch (SessionExpiredException e) { log.debug("caught a SessionExpiredException , do retry", e); Thread.yield();//暂缓一下,出现此异常往往是不可恢复的,需要重新创建连接, //但是我们不在此处进行处理,而是交给process方法来完成 waitUntilConnected(this.connectionTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { log.debug("caught a Exception , do retry"); throw e; } } } /** * zookeeper的回调,需要考虑到四种情况. * 1.节点改变 * 2.数据改变 * 3.连接断开 * 4.session超时 * */ public void process(final WatchedEvent event) { log.debug("receive event {}", event.toString()); zookeeperEventThread = Thread.currentThread();//一个标记,防止死锁 boolean stateChanged = event.getPath() == null; boolean znodeChanged = event.getPath() != null; boolean dataChanged = event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeChildrenChanged; eventLock.lock(); if (isShutdownTriggered()) { log.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered"); return; } try { if (stateChanged) { processStateChange(event); } if (dataChanged) { processDataOrChildChange(event); } } finally { if (stateChanged) { eventLock.getStateCondition().signalAll(); //唤醒当前所有等待连接成功的客户端 // if (event.getState() == KeeperState.Expired) {//超时后,需要进行重连,对于所有的监听者,应当通知他们可能有东西发生改变了 // eventLock.getZnodeCondition().signalAll(); // eventLock.getDataCondition().signalAll(); //TODO 是否需要触发所有事件? // } } if (znodeChanged) { eventLock.getZnodeCondition().signalAll();//唤醒当前所有等待节点创建和删除的客户端 } if (dataChanged) { eventLock.getDataCondition().signalAll();//唤醒当前所有等待节点数据改变的客户端 } eventLock.unlock(); } } //====================private=========================// /** * 建立zookeeper连接 * * @param connectionTimeout 连接超时时间 * @param watcher * @throws com.reform.dbstorm.zookeeper.exception.ZKTimeoutException 当链接等待时间超过connectionTimeout后 */ private void connect(final long connectionTimeout, final Watcher watcher) { log.debug("connect to server"); boolean started = false; try { eventLock.lockInterruptibly(); setShutdownTrigger(false); eventThread.start(); connection.connect(watcher); if (!waitUntilConnected(connectionTimeout, TimeUnit.MILLISECONDS)) { log.debug("wait to connect timeout {}", connectionTimeout); throw new ZKTimeoutException(this.zkServers, connectionTimeout); } started = true; } catch (InterruptedException e) { throw new ZKInterruptedException(e); } finally { eventLock.unlock(); if (!started) { close(); } } } /** * Close the client. * * @throws ZkInterruptedException */ public void close() throws ZKInterruptedException { if (connection == null) { return; } log.debug("closing ZKClient..."); eventLock.lock(); try { setShutdownTrigger(true); eventThread.interrupt(); eventThread.join(2000); connection.close(); connection = null; } catch (InterruptedException e) { throw new ZKInterruptedException(e); } finally { eventLock.unlock(); } log.debug("closing ZKClient...done"); } /** * 在与zookeeper建立连接之前一直等待. * * @param connectionTimeout 连接超时时间 * @param unit 超时时间单位 * @return * @throws InterruptedException 当阻塞被中断 */ private boolean waitUntilConnected(final long connectionTimeout, final TimeUnit unit) throws InterruptedException { return waitForKeeperState(KeeperState.SyncConnected, connectionTimeout, unit); } private boolean waitForKeeperState(final KeeperState exceptedState, final long connectionTimeout, final TimeUnit unit) throws InterruptedException { Assertion.isNotInEventThread(zookeeperEventThread);//不能在在zookeeper的通知线程内调用 Date deadline = new Date(System.currentTimeMillis() + connectionTimeout); try { eventLock.lockInterruptibly(); while (currentState != exceptedState) { return eventLock.getStateCondition().awaitUntil(deadline);//在达到指定时间之前阻塞 } return true; } catch (InterruptedException e) { throw e; } finally { eventLock.unlock(); } } /** * 处理节点数据或子节点的改变. * * @param event */ private void processDataOrChildChange(final WatchedEvent event) { String path = event.getPath(); boolean dataChanged = event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeDataChanged; if (dataChanged) { for (Set<DataListener> listeners : dataListeners.values()) { fireDataChangedEvent(path, listeners); } } boolean nodeChanged = event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated; if (nodeChanged) { for (Set<NodeListener> listeners : nodeListeners.values()) { fireNodeChangedEvent(path, listeners); } } } /** * 引发一个节点改变事件. * * @param path znode路径 * @param listeners 待通知的监听器 */ private void fireNodeChangedEvent(final String path, final Set<NodeListener> listeners) { for (final NodeListener lis : listeners) { eventThread.send(new ZKEvent() { @Override void run() throws Exception { helper.exist(path, true); helper.getChildren(path, true); if (path.equals(lis.getPath())) { lis.onNodeChange(); } } }); } } /** * 引发一个数据改变事件. * * @param path znode路径 * @param listeners 待通知的监听器 */ private void fireDataChangedEvent(final String path, final Set<DataListener> listeners) { for (final DataListener lis : listeners) { eventThread.send(new ZKEvent() { @Override void run() throws Exception { helper.exist(path, true); if (path.equals(lis.getPath())) { lis.onDataChange(); } } }); } } /** * 状态发生变化进行回调. * * @param event zookeeper事件 */ private void processStateChange(final WatchedEvent event) { setCurrentState(event.getState()); if (KeeperState.Expired == currentState) { reconnect();//超时后状态无法恢复,必须进行重连 fireNewSessionEvents(); } } /** * 通知所有statelistener. * */ private void fireNewSessionEvents() { for (final StateListener listener : stateListeners) { eventThread.send(new ZKEvent() { @Override void run() { listener.onNewSession();//必须应对新建立的连接 } }); } } /** * zookeeper重连. * * @throws ZKInterruptedException 连接zookeeper服务时,线程发生中断 */ private void reconnect() { try { eventLock.lockInterruptibly(); connection.close(); connection.connect(this); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } finally { eventLock.unlock(); } } /** * 监视节点数据变化. * * @param path znode路径 * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ private void watchForData(final String path) { try { retryUntilConnected(new Callable<Object>() { public Object call() throws Exception { connection.exist(path, true); return null; } }); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 监视节点变化. * * @param path znode路径 * @throws ZKKeeperException zookeeper发生异常时 * @throws ZKInterruptedException 调用zookeeper服务时,线程发生中断 * @throws ZKException */ private void watchForNode(final String path) { try { retryUntilConnected(new Callable<Object>() { public Object call() throws Exception { helper.exist(path, true); helper.getChildren(path, true); return null; } }); } catch (KeeperException e) { throw new ZKKeeperException(e); } catch (InterruptedException e) { throw new ZKInterruptedException(e); } catch (Exception e) { throw new ZKException(e); } } /** * 检查当前节点是否存在监听器. * * @param path znode路径 * @return true表示已经进行过监听,false表示未进行过监听 */ private boolean hasDataListener(final String path) { return dataListeners.containsKey(path) ? !dataListeners.get(path).isEmpty() : false; } /** * 检查子节点是否存在监听器. * * @param path znode路径 * @return true表示已经进行过监听,false表示未进行过监听 */ private boolean hasNodeListener(final String path) { return nodeListeners.contains(path) ? !nodeListeners.get(path).isEmpty() : false; } /** * 修改客户端的当前状态. * * @param state */ private void setCurrentState(final KeeperState state) { this.currentState = state; } public void setShutdownTrigger(boolean triggerState) { shutdownTriggered = triggerState; } /** * 客户端是否已经被关闭. * @return */ public boolean isShutdownTriggered() { return shutdownTriggered; } /** * 一个工具类,简单地封装了一些方法. * * @author huaiyu.du@opi-corp.com 2012-1-29 下午4:29:23 */ private final class ZKHelper { /** * 带有重试过程的getChildren. * * @param path * @param watch * * @throws KeeperException * @throws InterruptedException * @throws Exception */ private List<String> getChildren(final String path, final boolean watch) throws InterruptedException, Exception { return retryUntilConnected(new Callable<List<String>>() { public List<String> call() throws Exception { return connection.getChildren(path, watch); } }); } /** * 带有重试过程的exist. * * @param path * @param watch * @throws KeeperException * @throws InterruptedException * @throws Exception */ private Stat exist(final String path, final boolean watch) throws InterruptedException, Exception { return retryUntilConnected(new Callable<Stat>() { public Stat call() throws Exception { return connection.exist(path, watch); } }); } /** * 创建节点. * * @param path * @param obj * @param serializer * @param createMode * @throws KeeperException * @throws InterruptedException * @throws Exception */ private <T> void create(final String path, final T obj, final DataSerializer<T> serializer, final CreateMode createMode) throws InterruptedException, Exception { retryUntilConnected(new Callable<String>() { public String call() throws Exception { byte[] data = obj != null ? serializer.serialize(obj) : new byte[0]; return connection.create(path, data, createMode); } }); } } }
gpl-2.0
moriyoshi/quercus-gae
src/main/java/com/caucho/vfs/FileReadStream.java
4914
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.vfs; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.logging.Level; import java.util.logging.Logger; /** * Stream encapsulating FileInputStream */ public class FileReadStream extends StreamImpl implements LockableStream { private static final Logger log = Logger.getLogger(FileRandomAccessStream.class.getName()); private FileInputStream _is; private FileLock _fileLock; private FileChannel _fileChannel; /** * Create a new FileReadStream. */ public FileReadStream() { } /** * Create a new FileReadStream based on the java.io.* stream. * * @param is the underlying input stream. */ public FileReadStream(FileInputStream is) { init(is); } /** * Create a new FileReadStream based on the java.io.* stream. * * @param is the underlying input stream. * @param path the associated Path. */ public FileReadStream(FileInputStream is, Path path) { init(is); setPath(path); } /** * Initializes a VfsStream with an input/output stream pair. Before a * read, the output will be flushed to avoid deadlocks. * * @param is the underlying InputStream. * @param os the underlying OutputStream. */ public void init(FileInputStream is) { _is = is; setPath(null); } /** * Returns true if there's an associated file. */ public boolean hasSkip() { return _is != null; } /** * Skips bytes in the file. * * @param n the number of bytes to skip * * @return the actual bytes skipped. */ public long skip(long n) throws IOException { if (_is != null) return _is.skip(n); else return -1; } /** * Seeks based on the start. */ public void seekStart(long offset) throws IOException { if (_is != null) _is.getChannel().position(offset); } /** * Returns true if there's an associated file. */ public boolean canRead() { return _is != null; } /** * Reads bytes from the file. * * @param buf a byte array receiving the data. * @param offset starting index to receive data. * @param length number of bytes to read. * * @return the number of bytes read or -1 on end of file. */ public int read(byte []buf, int offset, int length) throws IOException { if (_is == null) return -1; int len = _is.read(buf, offset, length); return len; } /** * Returns the number of bytes available for reading. */ public int getAvailable() throws IOException { if (_is == null) return -1; else { return _is.available(); } } /** * Closes the underlying stream. */ public void close() throws IOException { unlock(); _fileChannel = null; InputStream is = _is; _is = null; if (is != null) is.close(); } public boolean lock(boolean shared, boolean block) { unlock(); if (!shared) { // Invalid request for an exclusive "write" lock on a read only stream. return false; } try { if (_fileChannel == null) { _fileChannel = _is.getChannel(); } if (block) _fileLock = _fileChannel.lock(0, Long.MAX_VALUE, true); else _fileLock = _fileChannel.tryLock(0, Long.MAX_VALUE, true); return _fileLock != null; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } } public boolean unlock() { try { FileLock lock = _fileLock; _fileLock = null; if (lock != null) { lock.release(); return true; } return false; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VMObject.java
2093
/* * Copyright 2000-2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ package sun.jvm.hotspot.runtime; import sun.jvm.hotspot.debugger.*; import sun.jvm.hotspot.types.*; /** This is a base class for all VM runtime objects which wrap Addresses. The rationale is that without this in place, every class would have to implement equals() and hashCode() with boilerplate code, a practice which is inherently error-prone. */ public class VMObject { protected Address addr; /** All of the objects have this as their constructor's signature anyway */ public VMObject(Address addr) { this.addr = addr; } public String toString() { return getClass().getName() + "@" + addr; } public boolean equals(Object arg) { if (arg == null) { return false; } if (!getClass().equals(arg.getClass())) { return false; } VMObject obj = (VMObject) arg; if (!addr.equals(obj.addr)) { return false; } return true; } public int hashCode() { return addr.hashCode(); } public Address getAddress() { return addr; } }
gpl-2.0
smarr/Truffle
tools/src/org.graalvm.tools.api.lsp/src/org/graalvm/tools/api/lsp/LSPCommand.java
2393
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.tools.api.lsp; import java.util.List; import com.oracle.truffle.api.instrumentation.TruffleInstrument.Env; /** * Command interface provided by a {@link LSPExtension}. */ public interface LSPCommand { /** * Get the name of the command. */ String getName(); /** * Execute the command. */ Object execute(LSPServerAccessor server, Env env, List<Object> arguments); /** * Define a timeout for the execution of the command. */ default int getTimeoutMillis() { return -1; } /** * Fallback behavior in case the command's execution exceeded the timeout. Only required if * {@link #getTimeoutMillis()} is overridden and returns a value greater zero. */ default Object onTimeout(List<Object> arguments) { String argumentString = String.join(", ", arguments.toArray(new String[0])); if (getTimeoutMillis() > 0) { throw new RuntimeException("onTimeout not overriden. Arguments: " + argumentString); } else { throw new AssertionError("onTimeout triggered on negative or zero timeout. Arguments: " + argumentString); } } }
gpl-2.0
karianna/jdk8_tl
jdk/src/share/classes/sun/misc/Unsafe.java
44500
/* * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.misc; import java.security.*; import java.lang.reflect.*; /** * A collection of methods for performing low-level, unsafe operations. * Although the class and all methods are public, use of this class is * limited because only trusted code can obtain instances of it. * * @author John R. Rose * @see #getUnsafe */ public final class Unsafe { private static native void registerNatives(); static { registerNatives(); sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe"); } private Unsafe() {} private static final Unsafe theUnsafe = new Unsafe(); /** * Provides the caller with the capability of performing unsafe * operations. * * <p> The returned <code>Unsafe</code> object should be carefully guarded * by the caller, since it can be used to read and write data at arbitrary * memory addresses. It must never be passed to untrusted code. * * <p> Most methods in this class are very low-level, and correspond to a * small number of hardware instructions (on typical machines). Compilers * are encouraged to optimize these methods accordingly. * * <p> Here is a suggested idiom for using unsafe operations: * * <blockquote><pre> * class MyTrustedClass { * private static final Unsafe unsafe = Unsafe.getUnsafe(); * ... * private long myCountAddress = ...; * public int getCount() { return unsafe.getByte(myCountAddress); } * } * </pre></blockquote> * * (It may assist compilers to make the local variable be * <code>final</code>.) * * @exception SecurityException if a security manager exists and its * <code>checkPropertiesAccess</code> method doesn't allow * access to the system properties. */ public static Unsafe getUnsafe() { Class<?> cc = sun.reflect.Reflection.getCallerClass(2); if (!VM.isSystemDomainLoader(cc.getClassLoader())) throw new SecurityException("Unsafe"); return theUnsafe; } /// peek and poke operations /// (compilers should optimize these to memory ops) // These work on object fields in the Java heap. // They will not work on elements of packed arrays. /** * Fetches a value from a given Java variable. * More specifically, fetches a field or array element within the given * object <code>o</code> at the given offset, or (if <code>o</code> is * null) from the memory address whose numerical value is the given * offset. * <p> * The results are undefined unless one of the following cases is true: * <ul> * <li>The offset was obtained from {@link #objectFieldOffset} on * the {@link java.lang.reflect.Field} of some Java field and the object * referred to by <code>o</code> is of a class compatible with that * field's class. * * <li>The offset and object reference <code>o</code> (either null or * non-null) were both obtained via {@link #staticFieldOffset} * and {@link #staticFieldBase} (respectively) from the * reflective {@link Field} representation of some Java field. * * <li>The object referred to by <code>o</code> is an array, and the offset * is an integer of the form <code>B+N*S</code>, where <code>N</code> is * a valid index into the array, and <code>B</code> and <code>S</code> are * the values obtained by {@link #arrayBaseOffset} and {@link * #arrayIndexScale} (respectively) from the array's class. The value * referred to is the <code>N</code><em>th</em> element of the array. * * </ul> * <p> * If one of the above cases is true, the call references a specific Java * variable (field or array element). However, the results are undefined * if that variable is not in fact of the type returned by this method. * <p> * This method refers to a variable by means of two parameters, and so * it provides (in effect) a <em>double-register</em> addressing mode * for Java variables. When the object reference is null, this method * uses its offset as an absolute address. This is similar in operation * to methods such as {@link #getInt(long)}, which provide (in effect) a * <em>single-register</em> addressing mode for non-Java variables. * However, because Java variables may have a different layout in memory * from non-Java variables, programmers should not assume that these * two addressing modes are ever equivalent. Also, programmers should * remember that offsets from the double-register addressing mode cannot * be portably confused with longs used in the single-register addressing * mode. * * @param o Java heap object in which the variable resides, if any, else * null * @param offset indication of where the variable resides in a Java heap * object, if any, else a memory address locating the variable * statically * @return the value fetched from the indicated Java variable * @throws RuntimeException No defined exceptions are thrown, not even * {@link NullPointerException} */ public native int getInt(Object o, long offset); /** * Stores a value into a given Java variable. * <p> * The first two parameters are interpreted exactly as with * {@link #getInt(Object, long)} to refer to a specific * Java variable (field or array element). The given value * is stored into that variable. * <p> * The variable must be of the same type as the method * parameter <code>x</code>. * * @param o Java heap object in which the variable resides, if any, else * null * @param offset indication of where the variable resides in a Java heap * object, if any, else a memory address locating the variable * statically * @param x the value to store into the indicated Java variable * @throws RuntimeException No defined exceptions are thrown, not even * {@link NullPointerException} */ public native void putInt(Object o, long offset, int x); /** * Fetches a reference value from a given Java variable. * @see #getInt(Object, long) */ public native Object getObject(Object o, long offset); /** * Stores a reference value into a given Java variable. * <p> * Unless the reference <code>x</code> being stored is either null * or matches the field type, the results are undefined. * If the reference <code>o</code> is non-null, car marks or * other store barriers for that object (if the VM requires them) * are updated. * @see #putInt(Object, int, int) */ public native void putObject(Object o, long offset, Object x); /** @see #getInt(Object, long) */ public native boolean getBoolean(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putBoolean(Object o, long offset, boolean x); /** @see #getInt(Object, long) */ public native byte getByte(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putByte(Object o, long offset, byte x); /** @see #getInt(Object, long) */ public native short getShort(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putShort(Object o, long offset, short x); /** @see #getInt(Object, long) */ public native char getChar(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putChar(Object o, long offset, char x); /** @see #getInt(Object, long) */ public native long getLong(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putLong(Object o, long offset, long x); /** @see #getInt(Object, long) */ public native float getFloat(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putFloat(Object o, long offset, float x); /** @see #getInt(Object, long) */ public native double getDouble(Object o, long offset); /** @see #putInt(Object, int, int) */ public native void putDouble(Object o, long offset, double x); /** * This method, like all others with 32-bit offsets, was native * in a previous release but is now a wrapper which simply casts * the offset to a long value. It provides backward compatibility * with bytecodes compiled against 1.4. * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public int getInt(Object o, int offset) { return getInt(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putInt(Object o, int offset, int x) { putInt(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public Object getObject(Object o, int offset) { return getObject(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putObject(Object o, int offset, Object x) { putObject(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public boolean getBoolean(Object o, int offset) { return getBoolean(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putBoolean(Object o, int offset, boolean x) { putBoolean(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public byte getByte(Object o, int offset) { return getByte(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putByte(Object o, int offset, byte x) { putByte(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public short getShort(Object o, int offset) { return getShort(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putShort(Object o, int offset, short x) { putShort(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public char getChar(Object o, int offset) { return getChar(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putChar(Object o, int offset, char x) { putChar(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public long getLong(Object o, int offset) { return getLong(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putLong(Object o, int offset, long x) { putLong(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public float getFloat(Object o, int offset) { return getFloat(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putFloat(Object o, int offset, float x) { putFloat(o, (long)offset, x); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public double getDouble(Object o, int offset) { return getDouble(o, (long)offset); } /** * @deprecated As of 1.4.1, cast the 32-bit offset argument to a long. * See {@link #staticFieldOffset}. */ @Deprecated public void putDouble(Object o, int offset, double x) { putDouble(o, (long)offset, x); } // These work on values in the C heap. /** * Fetches a value from a given memory address. If the address is zero, or * does not point into a block obtained from {@link #allocateMemory}, the * results are undefined. * * @see #allocateMemory */ public native byte getByte(long address); /** * Stores a value into a given memory address. If the address is zero, or * does not point into a block obtained from {@link #allocateMemory}, the * results are undefined. * * @see #getByte(long) */ public native void putByte(long address, byte x); /** @see #getByte(long) */ public native short getShort(long address); /** @see #putByte(long, byte) */ public native void putShort(long address, short x); /** @see #getByte(long) */ public native char getChar(long address); /** @see #putByte(long, byte) */ public native void putChar(long address, char x); /** @see #getByte(long) */ public native int getInt(long address); /** @see #putByte(long, byte) */ public native void putInt(long address, int x); /** @see #getByte(long) */ public native long getLong(long address); /** @see #putByte(long, byte) */ public native void putLong(long address, long x); /** @see #getByte(long) */ public native float getFloat(long address); /** @see #putByte(long, byte) */ public native void putFloat(long address, float x); /** @see #getByte(long) */ public native double getDouble(long address); /** @see #putByte(long, byte) */ public native void putDouble(long address, double x); /** * Fetches a native pointer from a given memory address. If the address is * zero, or does not point into a block obtained from {@link * #allocateMemory}, the results are undefined. * * <p> If the native pointer is less than 64 bits wide, it is extended as * an unsigned number to a Java long. The pointer may be indexed by any * given byte offset, simply by adding that offset (as a simple integer) to * the long representing the pointer. The number of bytes actually read * from the target address maybe determined by consulting {@link * #addressSize}. * * @see #allocateMemory */ public native long getAddress(long address); /** * Stores a native pointer into a given memory address. If the address is * zero, or does not point into a block obtained from {@link * #allocateMemory}, the results are undefined. * * <p> The number of bytes actually written at the target address maybe * determined by consulting {@link #addressSize}. * * @see #getAddress(long) */ public native void putAddress(long address, long x); /// wrappers for malloc, realloc, free: /** * Allocates a new block of native memory, of the given size in bytes. The * contents of the memory are uninitialized; they will generally be * garbage. The resulting native pointer will never be zero, and will be * aligned for all value types. Dispose of this memory by calling {@link * #freeMemory}, or resize it with {@link #reallocateMemory}. * * @throws IllegalArgumentException if the size is negative or too large * for the native size_t type * * @throws OutOfMemoryError if the allocation is refused by the system * * @see #getByte(long) * @see #putByte(long, byte) */ public native long allocateMemory(long bytes); /** * Resizes a new block of native memory, to the given size in bytes. The * contents of the new block past the size of the old block are * uninitialized; they will generally be garbage. The resulting native * pointer will be zero if and only if the requested size is zero. The * resulting native pointer will be aligned for all value types. Dispose * of this memory by calling {@link #freeMemory}, or resize it with {@link * #reallocateMemory}. The address passed to this method may be null, in * which case an allocation will be performed. * * @throws IllegalArgumentException if the size is negative or too large * for the native size_t type * * @throws OutOfMemoryError if the allocation is refused by the system * * @see #allocateMemory */ public native long reallocateMemory(long address, long bytes); /** * Sets all bytes in a given block of memory to a fixed value * (usually zero). * * <p>This method determines a block's base address by means of two parameters, * and so it provides (in effect) a <em>double-register</em> addressing mode, * as discussed in {@link #getInt(Object,long)}. When the object reference is null, * the offset supplies an absolute base address. * * <p>The stores are in coherent (atomic) units of a size determined * by the address and length parameters. If the effective address and * length are all even modulo 8, the stores take place in 'long' units. * If the effective address and length are (resp.) even modulo 4 or 2, * the stores take place in units of 'int' or 'short'. * * @since 1.7 */ public native void setMemory(Object o, long offset, long bytes, byte value); /** * Sets all bytes in a given block of memory to a fixed value * (usually zero). This provides a <em>single-register</em> addressing mode, * as discussed in {@link #getInt(Object,long)}. * * <p>Equivalent to <code>setMemory(null, address, bytes, value)</code>. */ public void setMemory(long address, long bytes, byte value) { setMemory(null, address, bytes, value); } /** * Sets all bytes in a given block of memory to a copy of another * block. * * <p>This method determines each block's base address by means of two parameters, * and so it provides (in effect) a <em>double-register</em> addressing mode, * as discussed in {@link #getInt(Object,long)}. When the object reference is null, * the offset supplies an absolute base address. * * <p>The transfers are in coherent (atomic) units of a size determined * by the address and length parameters. If the effective addresses and * length are all even modulo 8, the transfer takes place in 'long' units. * If the effective addresses and length are (resp.) even modulo 4 or 2, * the transfer takes place in units of 'int' or 'short'. * * @since 1.7 */ public native void copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes); /** * Sets all bytes in a given block of memory to a copy of another * block. This provides a <em>single-register</em> addressing mode, * as discussed in {@link #getInt(Object,long)}. * * Equivalent to <code>copyMemory(null, srcAddress, null, destAddress, bytes)</code>. */ public void copyMemory(long srcAddress, long destAddress, long bytes) { copyMemory(null, srcAddress, null, destAddress, bytes); } /** * Disposes of a block of native memory, as obtained from {@link * #allocateMemory} or {@link #reallocateMemory}. The address passed to * this method may be null, in which case no action is taken. * * @see #allocateMemory */ public native void freeMemory(long address); /// random queries /** * This constant differs from all results that will ever be returned from * {@link #staticFieldOffset}, {@link #objectFieldOffset}, * or {@link #arrayBaseOffset}. */ public static final int INVALID_FIELD_OFFSET = -1; /** * Returns the offset of a field, truncated to 32 bits. * This method is implemented as follows: * <blockquote><pre> * public int fieldOffset(Field f) { * if (Modifier.isStatic(f.getModifiers())) * return (int) staticFieldOffset(f); * else * return (int) objectFieldOffset(f); * } * </pre></blockquote> * @deprecated As of 1.4.1, use {@link #staticFieldOffset} for static * fields and {@link #objectFieldOffset} for non-static fields. */ @Deprecated public int fieldOffset(Field f) { if (Modifier.isStatic(f.getModifiers())) return (int) staticFieldOffset(f); else return (int) objectFieldOffset(f); } /** * Returns the base address for accessing some static field * in the given class. This method is implemented as follows: * <blockquote><pre> * public Object staticFieldBase(Class c) { * Field[] fields = c.getDeclaredFields(); * for (int i = 0; i < fields.length; i++) { * if (Modifier.isStatic(fields[i].getModifiers())) { * return staticFieldBase(fields[i]); * } * } * return null; * } * </pre></blockquote> * @deprecated As of 1.4.1, use {@link #staticFieldBase(Field)} * to obtain the base pertaining to a specific {@link Field}. * This method works only for JVMs which store all statics * for a given class in one place. */ @Deprecated public Object staticFieldBase(Class<?> c) { Field[] fields = c.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers())) { return staticFieldBase(fields[i]); } } return null; } /** * Report the location of a given field in the storage allocation of its * class. Do not expect to perform any sort of arithmetic on this offset; * it is just a cookie which is passed to the unsafe heap memory accessors. * * <p>Any given field will always have the same offset and base, and no * two distinct fields of the same class will ever have the same offset * and base. * * <p>As of 1.4.1, offsets for fields are represented as long values, * although the Sun JVM does not use the most significant 32 bits. * However, JVM implementations which store static fields at absolute * addresses can use long offsets and null base pointers to express * the field locations in a form usable by {@link #getInt(Object,long)}. * Therefore, code which will be ported to such JVMs on 64-bit platforms * must preserve all bits of static field offsets. * @see #getInt(Object, long) */ public native long staticFieldOffset(Field f); /** * Report the location of a given static field, in conjunction with {@link * #staticFieldBase}. * <p>Do not expect to perform any sort of arithmetic on this offset; * it is just a cookie which is passed to the unsafe heap memory accessors. * * <p>Any given field will always have the same offset, and no two distinct * fields of the same class will ever have the same offset. * * <p>As of 1.4.1, offsets for fields are represented as long values, * although the Sun JVM does not use the most significant 32 bits. * It is hard to imagine a JVM technology which needs more than * a few bits to encode an offset within a non-array object, * However, for consistency with other methods in this class, * this method reports its result as a long value. * @see #getInt(Object, long) */ public native long objectFieldOffset(Field f); /** * Report the location of a given static field, in conjunction with {@link * #staticFieldOffset}. * <p>Fetch the base "Object", if any, with which static fields of the * given class can be accessed via methods like {@link #getInt(Object, * long)}. This value may be null. This value may refer to an object * which is a "cookie", not guaranteed to be a real Object, and it should * not be used in any way except as argument to the get and put routines in * this class. */ public native Object staticFieldBase(Field f); /** * Detect if the given class may need to be initialized. This is often * needed in conjunction with obtaining the static field base of a * class. * @return false only if a call to {@code ensureClassInitialized} would have no effect */ public native boolean shouldBeInitialized(Class<?> c); /** * Ensure the given class has been initialized. This is often * needed in conjunction with obtaining the static field base of a * class. */ public native void ensureClassInitialized(Class<?> c); /** * Report the offset of the first element in the storage allocation of a * given array class. If {@link #arrayIndexScale} returns a non-zero value * for the same class, you may use that scale factor, together with this * base offset, to form new offsets to access elements of arrays of the * given class. * * @see #getInt(Object, long) * @see #putInt(Object, long, int) */ public native int arrayBaseOffset(Class<?> arrayClass); /** The value of {@code arrayBaseOffset(boolean[].class)} */ public static final int ARRAY_BOOLEAN_BASE_OFFSET = theUnsafe.arrayBaseOffset(boolean[].class); /** The value of {@code arrayBaseOffset(byte[].class)} */ public static final int ARRAY_BYTE_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class); /** The value of {@code arrayBaseOffset(short[].class)} */ public static final int ARRAY_SHORT_BASE_OFFSET = theUnsafe.arrayBaseOffset(short[].class); /** The value of {@code arrayBaseOffset(char[].class)} */ public static final int ARRAY_CHAR_BASE_OFFSET = theUnsafe.arrayBaseOffset(char[].class); /** The value of {@code arrayBaseOffset(int[].class)} */ public static final int ARRAY_INT_BASE_OFFSET = theUnsafe.arrayBaseOffset(int[].class); /** The value of {@code arrayBaseOffset(long[].class)} */ public static final int ARRAY_LONG_BASE_OFFSET = theUnsafe.arrayBaseOffset(long[].class); /** The value of {@code arrayBaseOffset(float[].class)} */ public static final int ARRAY_FLOAT_BASE_OFFSET = theUnsafe.arrayBaseOffset(float[].class); /** The value of {@code arrayBaseOffset(double[].class)} */ public static final int ARRAY_DOUBLE_BASE_OFFSET = theUnsafe.arrayBaseOffset(double[].class); /** The value of {@code arrayBaseOffset(Object[].class)} */ public static final int ARRAY_OBJECT_BASE_OFFSET = theUnsafe.arrayBaseOffset(Object[].class); /** * Report the scale factor for addressing elements in the storage * allocation of a given array class. However, arrays of "narrow" types * will generally not work properly with accessors like {@link * #getByte(Object, int)}, so the scale factor for such classes is reported * as zero. * * @see #arrayBaseOffset * @see #getInt(Object, long) * @see #putInt(Object, long, int) */ public native int arrayIndexScale(Class<?> arrayClass); /** The value of {@code arrayIndexScale(boolean[].class)} */ public static final int ARRAY_BOOLEAN_INDEX_SCALE = theUnsafe.arrayIndexScale(boolean[].class); /** The value of {@code arrayIndexScale(byte[].class)} */ public static final int ARRAY_BYTE_INDEX_SCALE = theUnsafe.arrayIndexScale(byte[].class); /** The value of {@code arrayIndexScale(short[].class)} */ public static final int ARRAY_SHORT_INDEX_SCALE = theUnsafe.arrayIndexScale(short[].class); /** The value of {@code arrayIndexScale(char[].class)} */ public static final int ARRAY_CHAR_INDEX_SCALE = theUnsafe.arrayIndexScale(char[].class); /** The value of {@code arrayIndexScale(int[].class)} */ public static final int ARRAY_INT_INDEX_SCALE = theUnsafe.arrayIndexScale(int[].class); /** The value of {@code arrayIndexScale(long[].class)} */ public static final int ARRAY_LONG_INDEX_SCALE = theUnsafe.arrayIndexScale(long[].class); /** The value of {@code arrayIndexScale(float[].class)} */ public static final int ARRAY_FLOAT_INDEX_SCALE = theUnsafe.arrayIndexScale(float[].class); /** The value of {@code arrayIndexScale(double[].class)} */ public static final int ARRAY_DOUBLE_INDEX_SCALE = theUnsafe.arrayIndexScale(double[].class); /** The value of {@code arrayIndexScale(Object[].class)} */ public static final int ARRAY_OBJECT_INDEX_SCALE = theUnsafe.arrayIndexScale(Object[].class); /** * Report the size in bytes of a native pointer, as stored via {@link * #putAddress}. This value will be either 4 or 8. Note that the sizes of * other primitive types (as stored in native memory blocks) is determined * fully by their information content. */ public native int addressSize(); /** The value of {@code addressSize()} */ public static final int ADDRESS_SIZE = theUnsafe.addressSize(); /** * Report the size in bytes of a native memory page (whatever that is). * This value will always be a power of two. */ public native int pageSize(); /// random trusted operations from JNI: /** * Tell the VM to define a class, without security checks. By default, the * class loader and protection domain come from the caller's class. */ public native Class<?> defineClass(String name, byte[] b, int off, int len, ClassLoader loader, ProtectionDomain protectionDomain); public native Class<?> defineClass(String name, byte[] b, int off, int len); /** * Define a class but do not make it known to the class loader or system dictionary. * <p> * For each CP entry, the corresponding CP patch must either be null or have * the a format that matches its tag: * <ul> * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang * <li>Utf8: a string (must have suitable syntax if used as signature or name) * <li>Class: any java.lang.Class object * <li>String: any object (not just a java.lang.String) * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments * </ul> * @params hostClass context for linkage, access control, protection domain, and class loader * @params data bytes of a class file * @params cpPatches where non-null entries exist, they replace corresponding CP entries in data */ public native Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches); /** Allocate an instance but do not run any constructor. Initializes the class if it has not yet been. */ public native Object allocateInstance(Class<?> cls) throws InstantiationException; /** Lock the object. It must get unlocked via {@link #monitorExit}. */ public native void monitorEnter(Object o); /** * Unlock the object. It must have been locked via {@link * #monitorEnter}. */ public native void monitorExit(Object o); /** * Tries to lock the object. Returns true or false to indicate * whether the lock succeeded. If it did, the object must be * unlocked via {@link #monitorExit}. */ public native boolean tryMonitorEnter(Object o); /** Throw the exception without telling the verifier. */ public native void throwException(Throwable ee); /** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x); /** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x); /** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapLong(Object o, long offset, long expected, long x); /** * Fetches a reference value from a given Java variable, with volatile * load semantics. Otherwise identical to {@link #getObject(Object, long)} */ public native Object getObjectVolatile(Object o, long offset); /** * Stores a reference value into a given Java variable, with * volatile store semantics. Otherwise identical to {@link #putObject(Object, long, Object)} */ public native void putObjectVolatile(Object o, long offset, Object x); /** Volatile version of {@link #getInt(Object, long)} */ public native int getIntVolatile(Object o, long offset); /** Volatile version of {@link #putInt(Object, long, int)} */ public native void putIntVolatile(Object o, long offset, int x); /** Volatile version of {@link #getBoolean(Object, long)} */ public native boolean getBooleanVolatile(Object o, long offset); /** Volatile version of {@link #putBoolean(Object, long, boolean)} */ public native void putBooleanVolatile(Object o, long offset, boolean x); /** Volatile version of {@link #getByte(Object, long)} */ public native byte getByteVolatile(Object o, long offset); /** Volatile version of {@link #putByte(Object, long, byte)} */ public native void putByteVolatile(Object o, long offset, byte x); /** Volatile version of {@link #getShort(Object, long)} */ public native short getShortVolatile(Object o, long offset); /** Volatile version of {@link #putShort(Object, long, short)} */ public native void putShortVolatile(Object o, long offset, short x); /** Volatile version of {@link #getChar(Object, long)} */ public native char getCharVolatile(Object o, long offset); /** Volatile version of {@link #putChar(Object, long, char)} */ public native void putCharVolatile(Object o, long offset, char x); /** Volatile version of {@link #getLong(Object, long)} */ public native long getLongVolatile(Object o, long offset); /** Volatile version of {@link #putLong(Object, long, long)} */ public native void putLongVolatile(Object o, long offset, long x); /** Volatile version of {@link #getFloat(Object, long)} */ public native float getFloatVolatile(Object o, long offset); /** Volatile version of {@link #putFloat(Object, long, float)} */ public native void putFloatVolatile(Object o, long offset, float x); /** Volatile version of {@link #getDouble(Object, long)} */ public native double getDoubleVolatile(Object o, long offset); /** Volatile version of {@link #putDouble(Object, long, double)} */ public native void putDoubleVolatile(Object o, long offset, double x); /** * Version of {@link #putObjectVolatile(Object, long, Object)} * that does not guarantee immediate visibility of the store to * other threads. This method is generally only useful if the * underlying field is a Java volatile (or if an array cell, one * that is otherwise only accessed using volatile accesses). */ public native void putOrderedObject(Object o, long offset, Object x); /** Ordered/Lazy version of {@link #putIntVolatile(Object, long, int)} */ public native void putOrderedInt(Object o, long offset, int x); /** Ordered/Lazy version of {@link #putLongVolatile(Object, long, long)} */ public native void putOrderedLong(Object o, long offset, long x); /** * Unblock the given thread blocked on <tt>park</tt>, or, if it is * not blocked, cause the subsequent call to <tt>park</tt> not to * block. Note: this operation is "unsafe" solely because the * caller must somehow ensure that the thread has not been * destroyed. Nothing special is usually required to ensure this * when called from Java (in which there will ordinarily be a live * reference to the thread) but this is not nearly-automatically * so when calling from native code. * @param thread the thread to unpark. * */ public native void unpark(Object thread); /** * Block current thread, returning when a balancing * <tt>unpark</tt> occurs, or a balancing <tt>unpark</tt> has * already occurred, or the thread is interrupted, or, if not * absolute and time is not zero, the given time nanoseconds have * elapsed, or if absolute, the given deadline in milliseconds * since Epoch has passed, or spuriously (i.e., returning for no * "reason"). Note: This operation is in the Unsafe class only * because <tt>unpark</tt> is, so it would be strange to place it * elsewhere. */ public native void park(boolean isAbsolute, long time); /** * Gets the load average in the system run queue assigned * to the available processors averaged over various periods of time. * This method retrieves the given <tt>nelem</tt> samples and * assigns to the elements of the given <tt>loadavg</tt> array. * The system imposes a maximum of 3 samples, representing * averages over the last 1, 5, and 15 minutes, respectively. * * @params loadavg an array of double of size nelems * @params nelems the number of samples to be retrieved and * must be 1 to 3. * * @return the number of samples actually retrieved; or -1 * if the load average is unobtainable. */ public native int getLoadAverage(double[] loadavg, int nelems); // The following contain CAS-based Java implementations used on // platforms not supporting native instructions /** * Atomically adds the given value to the current value of a field * or array element within the given object <code>o</code> * at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param delta the value to add * @return the previous value * @since 1.8 */ public final int getAndAddInt(Object o, long offset, int delta) { int v; do { v = getIntVolatile(o, offset); } while (!compareAndSwapInt(o, offset, v, v + delta)); return v; } /** * Atomically adds the given value to the current value of a field * or array element within the given object <code>o</code> * at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param delta the value to add * @return the previous value * @since 1.8 */ public final long getAndAddLong(Object o, long offset, long delta) { long v; do { v = getLongVolatile(o, offset); } while (!compareAndSwapLong(o, offset, v, v + delta)); return v; } /** * Atomically exchanges the given value with the current value of * a field or array element within the given object <code>o</code> * at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param newValue new value * @return the previous value * @since 1.8 */ public final int getAndSetInt(Object o, long offset, int newValue) { int v; do { v = getIntVolatile(o, offset); } while (!compareAndSwapInt(o, offset, v, newValue)); return v; } /** * Atomically exchanges the given value with the current value of * a field or array element within the given object <code>o</code> * at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param newValue new value * @return the previous value * @since 1.8 */ public final long getAndSetLong(Object o, long offset, long newValue) { long v; do { v = getLongVolatile(o, offset); } while (!compareAndSwapLong(o, offset, v, newValue)); return v; } /** * Atomically exchanges the given reference value with the current * reference value of a field or array element within the given * object <code>o</code> at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param newValue new value * @return the previous value * @since 1.8 */ public final Object getAndSetObject(Object o, long offset, Object newValue) { Object v; do { v = getObjectVolatile(o, offset); } while (!compareAndSwapObject(o, offset, v, newValue)); return v; } /** * Ensures lack of reordering of loads before the fence * with loads or stores after the fence. * @since 1.8 */ public native void loadFence(); /** * Ensures lack of reordering of stores before the fence * with loads or stores after the fence. * @since 1.8 */ public native void storeFence(); /** * Ensures lack of reordering of loads or stores before the fence * with loads or stores after the fence. * @since 1.8 */ public native void fullFence(); }
gpl-2.0
J-Keeper/LocalGitRepositories
batchSql-master/src/com/wangboo/batchSql/util/DataUtil.java
8701
package com.wangboo.batchSql.util; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ArrayHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.log4j.Logger; import com.mysql.jdbc.DatabaseMetaData; import com.wangboo.batchSql.comp.SqlResultView; public class DataUtil { private static Logger log = Logger.getLogger(DataUtil.class); private static Connection conn; private static String dbName = "data"; public static String driverName = "com.mysql.jdbc.Driver"; public static String sqlPath = "/temp.sql"; public static void init() throws Exception { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite:" + dbName); createTable(); } /** * 创建数据库文件 */ private static void createTable() throws Exception { log.debug("创建数据库文件"); Statement stmt = conn.createStatement(); try { log.debug("创建数据库:servers"); stmt.executeUpdate(FileUtils.readConfig("servers.sql")); } catch (Exception e) { log.error("需要创建数据库" + dbName, e); throw e; } finally { stmt.close(); } } /** * 加载服务器配置列表 * * @return */ public static List<Map<String, Object>> loadServers() { MapListHandler handler = new MapListHandler(); QueryRunner q = new QueryRunner(); try { log.debug("----目前存在的配置-----"); List<Map<String, Object>> list = q.query(conn, "select * from servers", handler); if (list == null) { return null; } for (Map<String, Object> map : list) { if (map == null) { continue; } log.debug(map.toString()); } return list; } catch (Exception e) { log.error("loadServers error", e); return null; } } /** * 增加意向服务器连接配置 * * @param name * @param ip * @param port * @param db * @param user * @param pwd */ public static void addServer(String name, String host, int port, String db, String user, String pwd) { Statement stmt = null; try { stmt = conn.createStatement(); String sql = String .format("insert into servers(name,host,port,user,pwd,db) values ('%s','%s',%d,'%s','%s','%s')", name, host, port, user, pwd, db); log.debug("sql:" + sql); stmt.execute(sql); } catch (SQLException e) { log.error("addServer error : ", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /** * 查询最大的服务器id * * @return int * @throws * @author YXY */ public static int getMaxId() { int maxId = -1; Statement stmt = null; QueryRunner q = new QueryRunner(); try { stmt = conn.createStatement(); String sql = "select MAX(id) idmax from servers"; Object[] objects = q.query(conn, sql, new ArrayHandler()); maxId = (int) objects[0]; log.debug("idmax:" + maxId); } catch (SQLException e) { log.error(e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } return maxId; } /** * 删除服务器 * * @param index * void * @throws * @author YXY */ public static void deleteServer(int id) { Statement stmt = null; try { stmt = conn.createStatement(); String sql = "delete from servers where id=" + id; log.debug("sql:" + sql); stmt.execute(sql); } catch (SQLException e) { log.error("deleteServer error : ", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /** * 更新服务器数据 * * @param id * @param name * @param host * @param port * @param db * @param user * @param pwd * void * @throws * @author YXY */ public static void updateServer(int id, String name, String host, int port, String db, String user, String pwd) { Statement stmt = null; try { stmt = conn.createStatement(); String sql = String .format("update servers set name='%s', host='%s',port=%d,user='%s',pwd='%s',db='%s' where id=" + id, name, host, port, user, pwd, db); log.debug("sql:" + sql); stmt.execute(sql); } catch (SQLException e) { log.error("addServer error : ", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /** * 获取数据库所有数据表 * * @param server * @return List<String> * @throws * @author YXY */ public static List<String> getTables(Map<String, Object> server) { List<String> tables = new ArrayList<>(); // 解析配置 String url = StringUtils.getSqlUrl(server); String user = (String) server.get("user"); String pwd = (String) server.get("pwd"); ResultSet rs = null; Connection myconn = null; try { Class.forName(driverName); myconn = DriverManager.getConnection(url, user, pwd); DatabaseMetaData meta = (DatabaseMetaData) myconn.getMetaData(); rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { tables.add(rs.getString(3)); } } catch (Exception e) { log.error("数据" + url + "连接出错"); e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (myconn != null) { myconn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return tables; } /** * 导出数据库脚本 * * @param sv * @param config * @param tables * void * @throws * @author YXY */ public static void exportSqlData(SqlResultView srv, Map<String, Object> config, List<String> tables, boolean allSelected) { StringBuilder sql = new StringBuilder(); String user = (String) config.get("user"); String pwd = (String) config.get("pwd"); String host = (String) config.get("host"); String port = String.valueOf(config.get("port")); String db = (String) config.get("db"); sql.append("mysqldump -u").append(user).append(" -p").append(pwd) .append(" -h").append(host).append(" -P").append(port) .append(" --set-charset=utf8 ").append(db); if (!allSelected) { for (String tname : tables) { sql.append(" ").append(tname); } } try { Runtime rt = Runtime.getRuntime(); srv.getSqlArea().removeAll(); srv.getSqlArea().append("生成指令:" + sql.toString() + "\r\n"); srv.getSqlArea().append("开始生成脚本......\r\n"); log.debug("生成指令:" + sql.toString()); // 调用 mysql-cmd Process child = rt.exec(sql.toString()); InputStream in = child.getInputStream(); InputStreamReader isr = new InputStreamReader(in, "utf8"); StringBuffer sb = new StringBuffer(""); // 捕获控制台输出信息字符串 BufferedReader br = new BufferedReader(isr); String inStr; while ((inStr = br.readLine()) != null) { sb.append(inStr + "\r\n"); } String outStr = sb.toString(); // 导出sql脚本 FileOutputStream fout = new FileOutputStream(sqlPath); OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8"); writer.write(outStr); writer.flush(); // 关闭输入输出流 in.close(); isr.close(); br.close(); writer.close(); fout.close(); srv.getSqlArea().append("脚本生成完成,准备同步数据.....\r\n"); srv.getSqlArea().setCaretPosition( srv.getSqlArea().getText().length()); } catch (Exception e) { e.printStackTrace(); srv.getSqlArea().append("脚本生成失败,请检查源数据库连接及配置\r\n"); srv.getSqlArea().setCaretPosition( srv.getSqlArea().getText().length()); } } /** * ---- test blow ------- */ public static void test() { QueryRunner q = new QueryRunner(); MapListHandler rsh = new MapListHandler(); try { List<Map<String, Object>> list = q.query(conn, "select * from servers", rsh); System.out.println("list = " + list.size()); for (Map<String, Object> item : list) { log.debug("item : " + item); } } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { // init(); // addServer("1", "192.168.1.182", 3033, "jiyu", "root", "root"); // getTables(null); } }
gpl-2.0
mihangram/Source
TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenu.java
7471
package org.telegram.ui.ActionBar; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.ui.Supergram.Theming.MihanTheme; public class ActionBarMenu extends LinearLayout { protected ActionBar parentActionBar; public ActionBarMenu(Context paramContext) { super(paramContext); } public ActionBarMenu(Context paramContext, ActionBar paramActionBar) { super(paramContext); setOrientation(0); this.parentActionBar = paramActionBar; } public ActionBarMenuItem addItem(int paramInt1, int paramInt2) { return addItem(paramInt1, paramInt2, this.parentActionBar.itemsBackgroundColor); } public ActionBarMenuItem addItem(int paramInt1, int paramInt2, int paramInt3) { return addItem(paramInt1, paramInt2, paramInt3, null, AndroidUtilities.dp(48.0F)); } public ActionBarMenuItem addItem(int paramInt1, int paramInt2, int paramInt3, Drawable paramDrawable, int paramInt4) { ActionBarMenuItem localActionBarMenuItem = new ActionBarMenuItem(getContext(), this, paramInt3); localActionBarMenuItem.setTag(Integer.valueOf(paramInt1)); if (paramDrawable != null) { localActionBarMenuItem.iconView.setImageDrawable(paramDrawable); } for (;;) { addView(localActionBarMenuItem); paramInt1 = MihanTheme.contrastColor(MihanTheme.getThemeColor(ApplicationLoader.applicationContext.getSharedPreferences("Mihantheme", 0))); MihanTheme.setColorFilter(localActionBarMenuItem.iconView.getDrawable(), paramInt1); paramDrawable = (LinearLayout.LayoutParams)localActionBarMenuItem.getLayoutParams(); paramDrawable.height = -1; paramDrawable.width = paramInt4; localActionBarMenuItem.setLayoutParams(paramDrawable); localActionBarMenuItem.setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { ActionBarMenuItem localActionBarMenuItem = (ActionBarMenuItem)paramAnonymousView; if (localActionBarMenuItem.hasSubMenu()) { if (ActionBarMenu.this.parentActionBar.actionBarMenuOnItemClick.canOpenMenu()) { localActionBarMenuItem.toggleSubMenu(); } return; } if (localActionBarMenuItem.isSearchField()) { ActionBarMenu.this.parentActionBar.onSearchFieldVisibilityChanged(localActionBarMenuItem.toggleSearch(true)); return; } ActionBarMenu.this.onItemClick(((Integer)paramAnonymousView.getTag()).intValue()); } }); return localActionBarMenuItem; localActionBarMenuItem.iconView.setImageResource(paramInt2); } } public ActionBarMenuItem addItem(int paramInt, Drawable paramDrawable) { return addItem(paramInt, 0, this.parentActionBar.itemsBackgroundColor, paramDrawable, AndroidUtilities.dp(48.0F)); } public View addItemResource(int paramInt1, int paramInt2) { View localView = ((LayoutInflater)getContext().getSystemService("layout_inflater")).inflate(paramInt2, null); localView.setTag(Integer.valueOf(paramInt1)); addView(localView); LinearLayout.LayoutParams localLayoutParams = (LinearLayout.LayoutParams)localView.getLayoutParams(); localLayoutParams.height = -1; localView.setBackgroundDrawable(Theme.createBarSelectorDrawable(this.parentActionBar.itemsBackgroundColor)); localView.setLayoutParams(localLayoutParams); localView.setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { ActionBarMenu.this.onItemClick(((Integer)paramAnonymousView.getTag()).intValue()); } }); return localView; } public ActionBarMenuItem addItemWithWidth(int paramInt1, int paramInt2, int paramInt3) { return addItem(paramInt1, paramInt2, this.parentActionBar.itemsBackgroundColor, null, paramInt3); } public void clearItems() { removeAllViews(); } public void closeSearchField() { int j = getChildCount(); int i = 0; for (;;) { if (i < j) { Object localObject = getChildAt(i); if ((localObject instanceof ActionBarMenuItem)) { localObject = (ActionBarMenuItem)localObject; if (((ActionBarMenuItem)localObject).isSearchField()) { this.parentActionBar.onSearchFieldVisibilityChanged(((ActionBarMenuItem)localObject).toggleSearch(false)); } } } else { return; } i += 1; } } public ActionBarMenuItem getItem(int paramInt) { View localView = findViewWithTag(Integer.valueOf(paramInt)); if ((localView instanceof ActionBarMenuItem)) { return (ActionBarMenuItem)localView; } return null; } public void hideAllPopupMenus() { int j = getChildCount(); int i = 0; while (i < j) { View localView = getChildAt(i); if ((localView instanceof ActionBarMenuItem)) { ((ActionBarMenuItem)localView).closeSubMenu(); } i += 1; } } public void onItemClick(int paramInt) { if (this.parentActionBar.actionBarMenuOnItemClick != null) { this.parentActionBar.actionBarMenuOnItemClick.onItemClick(paramInt); } } public void onMenuButtonPressed() { int j = getChildCount(); int i = 0; Object localObject; if (i < j) { localObject = getChildAt(i); if ((localObject instanceof ActionBarMenuItem)) { localObject = (ActionBarMenuItem)localObject; if (((ActionBarMenuItem)localObject).getVisibility() == 0) { break label44; } } } label44: do { i += 1; break; if (((ActionBarMenuItem)localObject).hasSubMenu()) { ((ActionBarMenuItem)localObject).toggleSubMenu(); return; } } while (!((ActionBarMenuItem)localObject).overrideMenuClick); onItemClick(((Integer)((ActionBarMenuItem)localObject).getTag()).intValue()); } public void openSearchField(boolean paramBoolean, String paramString) { int j = getChildCount(); int i = 0; for (;;) { if (i < j) { Object localObject = getChildAt(i); if ((localObject instanceof ActionBarMenuItem)) { localObject = (ActionBarMenuItem)localObject; if (((ActionBarMenuItem)localObject).isSearchField()) { if (paramBoolean) { this.parentActionBar.onSearchFieldVisibilityChanged(((ActionBarMenuItem)localObject).toggleSearch(true)); } ((ActionBarMenuItem)localObject).getSearchField().setText(paramString); ((ActionBarMenuItem)localObject).getSearchField().setSelection(paramString.length()); } } } else { return; } i += 1; } } } /* Location: C:\Users\Armandl\Downloads\Compressed\dex2jar-2.0\classes-dex2jar.jar!\org\telegram\ui\ActionBar\ActionBarMenu.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
gpl-2.0
miguel-gr/currency-converter
src/main/java/org/currconv/entities/user/UserLogin.java
569
package org.currconv.entities.user; /** * Entity for user login */ public class UserLogin { private String username; private String password; public UserLogin() { } public UserLogin(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
gpl-2.0
hajunho/Android-OpenGL-ES
examples/2/app/src/main/java/com/example/android/opengl/Square.java
5712
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.opengl; import android.opengl.GLES20; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; /** * A two-dimensional square for use as a drawn object in OpenGL ES 2.0. */ public class Square { private final String vertexShaderCode = // This matrix member variable provides a hook to manipulate // the coordinates of the objects that use this vertex shader "uniform mat4 uMVPMatrix;" + "attribute vec4 vPosition;" + "void main() {" + // The matrix must be included as a modifier of gl_Position. // Note that the uMVPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. " gl_Position = uMVPMatrix * vPosition;" + "}"; private final String fragmentShaderCode = "precision mediump float;" + "uniform vec4 vColor;" + "void main() {" + " gl_FragColor = vColor;" + "}"; private final FloatBuffer vertexBuffer; private final ShortBuffer drawListBuffer; private final int mProgram; private int mPositionHandle; private int mColorHandle; private int mMVPMatrixHandle; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float squareCoords[] = { -0.5f, 0.5f, 0.0f, // top left -0.5f, -0.5f, 0.0f, // bottom left 0.5f, -0.5f, 0.0f, // bottom right 0.5f, 0.5f, 0.0f }; // top right private final short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex float color[] = { 0.2f, 0.709803922f, 0.898039216f, 1.0f }; /** * Sets up the drawing object data for use in an OpenGL ES context. */ public Square() { // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float) squareCoords.length * 4); bb.order(ByteOrder.nativeOrder()); vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(squareCoords); vertexBuffer.position(0); // initialize byte buffer for the draw list ByteBuffer dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short) drawOrder.length * 2); dlb.order(ByteOrder.nativeOrder()); drawListBuffer = dlb.asShortBuffer(); drawListBuffer.put(drawOrder); drawListBuffer.position(0); // prepare shaders and OpenGL program int vertexShader = MyGLRenderer.loadShader( GLES20.GL_VERTEX_SHADER, vertexShaderCode); int fragmentShader = MyGLRenderer.loadShader( GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode); mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program GLES20.glLinkProgram(mProgram); // create OpenGL program executables } /** * Encapsulates the OpenGL ES instructions for drawing this shape. * * @param mvpMatrix - The Model View Project matrix in which to draw * this shape. */ public void draw(float[] mvpMatrix) { // Add program to OpenGL environment GLES20.glUseProgram(mProgram); // get handle to vertex shader's vPosition member mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition"); // Enable a handle to the triangle vertices GLES20.glEnableVertexAttribArray(mPositionHandle); // Prepare the triangle coordinate data GLES20.glVertexAttribPointer( mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer); // get handle to fragment shader's vColor member mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); // Set color for drawing the triangle GLES20.glUniform4fv(mColorHandle, 1, color, 0); // get handle to shape's transformation matrix mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); MyGLRenderer.checkGlError("glGetUniformLocation"); // Apply the projection and view transformation GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0); MyGLRenderer.checkGlError("glUniformMatrix4fv"); // Draw the square GLES20.glDrawElements( GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer); // Disable vertex array GLES20.glDisableVertexAttribArray(mPositionHandle); } }
gpl-2.0
teamflat/enflatme
livrables/obde-gwt/target/.generated/fr/insarouen/teamflat/client/GreetingService_Proxy.java
2538
package fr.insarouen.teamflat.client; import com.google.gwt.user.client.rpc.impl.RemoteServiceProxy; import com.google.gwt.user.client.rpc.impl.ClientSerializationStreamWriter; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.ResponseReader; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.RpcToken; import com.google.gwt.user.client.rpc.RpcTokenException; import com.google.gwt.core.client.impl.Impl; import com.google.gwt.user.client.rpc.impl.RpcStatsContext; public class GreetingService_Proxy extends RemoteServiceProxy implements fr.insarouen.teamflat.client.GreetingServiceAsync { private static final String REMOTE_SERVICE_INTERFACE_NAME = "fr.insarouen.teamflat.client.GreetingService"; private static final String SERIALIZATION_POLICY ="C69ECA74996A72E40A1E5057D4C2F191"; private static final fr.insarouen.teamflat.client.GreetingService_TypeSerializer SERIALIZER = new fr.insarouen.teamflat.client.GreetingService_TypeSerializer(); public GreetingService_Proxy() { super(GWT.getModuleBaseURL(), "greet", SERIALIZATION_POLICY, SERIALIZER); } public void greetServer(java.lang.String name, com.google.gwt.user.client.rpc.AsyncCallback callback) { com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.ServiceHelper helper = new com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.ServiceHelper("GreetingService_Proxy", "greetServer"); try { SerializationStreamWriter streamWriter = helper.start(REMOTE_SERVICE_INTERFACE_NAME, 1); streamWriter.writeString("java.lang.String/2004016611"); streamWriter.writeString(name); helper.finish(callback, ResponseReader.STRING); } catch (SerializationException ex) { callback.onFailure(ex); } } @Override public SerializationStreamWriter createStreamWriter() { ClientSerializationStreamWriter toReturn = (ClientSerializationStreamWriter) super.createStreamWriter(); if (getRpcToken() != null) { toReturn.addFlags(ClientSerializationStreamWriter.FLAG_RPC_TOKEN_INCLUDED); } return toReturn; } @Override protected void checkRpcTokenType(RpcToken token) { if (!(token instanceof com.google.gwt.user.client.rpc.XsrfToken)) { throw new RpcTokenException("Invalid RpcToken type: expected 'com.google.gwt.user.client.rpc.XsrfToken' but got '" + token.getClass() + "'"); } } }
gpl-2.0
developerdong/finalspeed
src/net/fs/rudp/ClientProcessorInterface.java
131
// Copyright (c) 2015 D1SM.net package net.fs.rudp; public interface ClientProcessorInterface { void onMapClientClose(); }
gpl-2.0
myhongkongzhen/pro-study-jdk
src/main/java/z/z/w/jdk/collections/Collection.java
36065
/********************************************************************************************************************** * Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * * Vestibulum commodo. Ut rhoncus gravida arcu. * **********************************************************************************************************************/ package z.z.w.jdk.collections; import java.util.Iterator; /********************************************************************************************* * <pre> * FileName: z.z.w.collections.Collection * Desc: * author: Z_Z.W - myhongkongzhen@gmail.com * version: 2015-11-27 16:43 * LastChange: 2015-11-27 16:43 * History: * </pre> *********************************************************************************************/ /** * The root interface in the <i>collection hierarchy</i>. A collection * 在集合層級中屬於root接口. * represents a group of objects, known as its <i>elements</i>. Some * 一個集合描述了一組對象,并指導它的元素. * collections allow duplicate elements and others do not. Some are ordered * 一些集合允許重複的元素,一些則不允許. * and others unordered. The JDK does not provide any <i>direct</i> * 一些是排序的另一些是非排序的. * implementations of this interface: it provides implementations of more * JDK不提供這個接口的任何一個直接實現: * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface * JDK提供了更多的特定子接口的實現例如Set\List. * is typically used to pass collections around and manipulate them where * 這個接口遍歷集合和操作他們擁有最大限度的通用性的特色. * maximum generality is desired. * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain * 包或者多重集合(非排序的集合可以包含重複的元素) * duplicate elements) should implement this interface directly. * 可以即刻的實現這個接口. * <p>All general-purpose <tt>Collection</tt> implementation classes (which * 所有的通用集合實現類 * typically implement <tt>Collection</tt> indirectly through one of its * (通過他的子接口間接的實現特色集合) * subinterfaces) should provide two "standard" constructors: a void (no * 將提供連個標準的構造方法: * arguments) constructor, which creates an empty collection, and a * (無慘)void的構造器,用於創建一個空集合, * constructor with a single argument of type <tt>Collection</tt>, which * 和一個擁有單個Collection類型參數的構造器, * creates a new collection with the same elements as its argument. In * 用於創建一個擁有相同元素作為參數的新集合. * effect, the latter constructor allows the user to copy any collection, * 事實上,後面的構造器運行用戶拷貝任何一個集合, * producing an equivalent collection of the desired implementation type. * 產生一個等價的所希望實現類型的集合. * There is no way to enforce this convention (as interfaces cannot contain * (作為一個藉口不能包含構造器)這個問題是沒有辦法實現的 * constructors) but all of the general-purpose <tt>Collection</tt> * 但是所有的通用實現在Java平台庫中上遵循這個規則. * implementations in the Java platform libraries comply. * <p>The "destructive" methods contained in this interface, that is, the * 這個接口中包含了"破壞的"方法, * methods that modify the collection on which they operate, are specified to * 改變集合操作的方法, * throw <tt>UnsupportedOperationException</tt> if this collection does not * 如果集合不支持這個操作,會拋出一個UnsupportedOperationException. * support the operation. If this is the case, these methods may, but are not * required to, throw an <tt>UnsupportedOperationException</tt> if the * 這些方法也許按照這種方式不必須的, * invocation would have no effect on the collection. For example, invoking * 如果在集合中不受期望的調用了,則會拋出一個異常. * the {@link #addAll(Collection)} method on an unmodifiable collection may, * 例如:調用addAll方法,在一個無法改變的集合中, * but is not required to, throw the exception if the collection to be added * 但是這個調用是不需要的,如果向集合中添加一個empty的集合就會拋出一個異常. * is empty. * <p><a name="optional-restrictions"/> * Some collection implementations have restrictions on the elements that * 一些集合實現存在限制在他們所包含的元素中. * they may contain. For example, some implementations prohibit null elements, * 例如:一些實現禁止null元素, * and some have restrictions on the types of their elements. Attempting to * 並且一些實現在他們元素的類型上是有限制條件的. * add an ineligible element throws an unchecked exception, typically * 試圖添加一個不合適的元素會拋出一個未檢查異常, * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * 以NullPointerException,ClassCastExcetpion為代表. * to query the presence of an ineligible element may throw an exception, * 試圖查詢不合適元素的存在也許會拋出一個異常, * or it may simply return false; some implementations will exhibit the former * 或者僅僅返回false; * behavior and some will exhibit the latter. More generally, attempting an * 一些實現會顯示之前的行為一些則顯示後續的行為. 更加通用的, * operation on an ineligible element whose completion would not result in * 試圖操作一個不合適的元素 * the insertion of an ineligible element into the collection may throw an * 不會有結果的在一個不合適元素添加集合可能會拋出一個異常 * exception or it may succeed, at the option of the implementation. * 或者會成功,在實現可選時. * Such exceptions are marked as "optional" in the specification for this * 例如異常為這個接口特指的標記為可選. * interface. * <p>It is up to each collection to determine its own synchronization * 由每一個集合自身決定並發政策 * policy. In the absence of a stronger guarantee by the * 實現在一個強保證的出現中 * implementation, undefined behavior may result from the invocation * 未定義行為使得結果從在集合中由另一個線程操作的任意個方法返回. * of any method on a collection that is being mutated by another * thread; this includes direct invocations, passing the collection to * 這包含了直接的調用關係, * a method that might perform invocations, and using an existing * 通過集合中的可執行的方法, * iterator to examine the collection. * 通過一個存在的迭代器測試集合. * <p>Many methods in Collections Framework interfaces are defined in * 許多集合框架接口的方法有明確的定義依據equals方法. * terms of the {@link Object#equals(Object) equals} method. For example, * the specification for the {@link #contains(Object) contains(Object o)} * 例如: contains(Object o)這個方法詳細說明: * method says: "returns <tt>true</tt> if and only if this collection * 返回true,當且僅當集合包含至少一個元素時,判斷(o == null ? e == null : o.equals(e)) * contains at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt> * 這個說明將會不包含Collection.contains方法調用一個null的參數進行o.equals(e)判斷 * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be * invoked for any element <tt>e</tt>. Implementations are free to implement * 對於任何元素. * optimizations whereby the <tt>equals</tt> invocation is avoided, for * 實現最佳化的實現了無效的equals方法調用, * example, by first comparing the hash codes of the two elements. (The * 例如,兩個元素受限進行hash code比較 * {@link Object#hashCode()} specification guarantees that two objects with * (Object.hashCode()方法描述保證了兩個對象hash code不等是不會相等的). * unequal hash codes cannot be equal.) More generally, implementations of * 通常的說, * the various Collections Framework interfaces are free to take advantage of * 集合框架接口多樣的實現能夠自由的針對特定的行為增益. * the specified behavior of underlying {@link Object} methods wherever the * 這些增益使得實現者認為是適當的後續方法. * implementor deems it appropriate. * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements in this collection * * @author Josh Bloch * @author Neal Gafter * @see java.util.Set * @see java.util.List * @see java.util.Map * @see java.util.SortedSet * @see java.util.SortedMap * @see java.util.HashSet * @see java.util.TreeSet * @see java.util.ArrayList * @see java.util.LinkedList * @see java.util.Vector * @see java.util.Collections * @see java.util.Arrays * @see java.util.AbstractCollection * @since 1.2 */ public interface Collection<E> extends Iterable<E> { // Query Operations /** * Returns the number of elements in this collection. If this collection * 返回集合中元素的個數. * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * 如果集合中包含了多餘Integer.MAX_VALUE個元素, * <tt>Integer.MAX_VALUE</tt>. * 則返回Integer.MAX_VALUE. * * @return the number of elements in this collection */ int size(); /** * Returns <tt>true</tt> if this collection contains no elements. * 如果集合中沒有包含元素則返回true * * @return <tt>true</tt> if this collection contains no elements */ boolean isEmpty(); /** * Returns <tt>true</tt> if this collection contains the specified element. * 如果集合包含了指定的元素,則返回true * More formally, returns <tt>true</tt> if and only if this collection * 更正式的講:當且僅當集合包含了至少一個元素存在(o == null ? e == null : o.equals(s)) * contains at least one element <tt>e</tt> such that * 時返回true * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this collection is to be tested * 集合中測試的元素 * * @return <tt>true</tt> if this collection contains the specified * 如果集合中包含這個指定的元素返回true * element * * @throws ClassCastException if the type of the specified element * 如果指定的元素類型與集合不相兼容,會拋出此異常 * is incompatible with this collection * (<a href="#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * 如果指定的元素為null並且這個集合不允許null元素, * collection does not permit null elements * 則會拋出異常 * (<a href="#optional-restrictions">optional</a>) */ boolean contains( Object o ); /** * Returns an iterator over the elements in this collection. There are no * 返回這個集合的迭代器. * guarantees concerning the order in which the elements are returned * 這個方法關於元素的返回是不保證順序的. * (unless this collection is an instance of some class that provides a * (除非這個集合是一個一些提供保證的類的實現). * guarantee). * * @return an <tt>Iterator</tt> over the elements in this collection */ Iterator<E> iterator(); /** * Returns an array containing all of the elements in this collection. * 返回一個數組包含了這個集合中的所有元素 * If this collection makes any guarantees as to what order its elements * 如果這個集合提供了由他的迭代器返回元素的順序的保證 * are returned by its iterator, this method must return the elements in * 那麼這個方法必須返回相同元素順序 * the same order. * <p>The returned array will be "safe" in that no references to it are * 這個返回的數組是安全的由這個集合維護的沒有引用的情況下 * maintained by this collection. (In other words, this method must * (換句話說,這個方法必須分配一個新的數組當這個集合依賴一個數組的時候). * allocate a new array even if this collection is backed by an array). * The caller is thus free to modify the returned array. * 調用者因此可以自由更改返回的數組. * <p>This method acts as bridge between array-based and collection-based * 這個方法作為兩個數組基礎和集合基礎的橋樑 * APIs. * * @return an array containing all of the elements in this collection */ Object[] toArray(); /** * Returns an array containing all of the elements in this collection; * 返回一個包含集合中所有元素的數組 * the runtime type of the returned array is that of the specified array. * 返回的數組運行時類型是那個指定的數組. * If the collection fits in the specified array, it is returned therein. * 如果集合適合這個指定的數組,則返回其中的數組. * Otherwise, a new array is allocated with the runtime type of the * 另外,由指定的數組的運行時類型和集合的大小分配一個新的數組 * specified array and the size of this collection. * <p>If this collection fits in the specified array with room to spare * 如果這個集合適合指定數組分配的空間 * (i.e., the array has more elements than this collection), the element * (比如:數組有多餘集合個數的元素), * in the array immediately following the end of the collection is set to * 數組中的跟隨在集合尾部的元素會設置為null * <tt>null</tt>. (This is useful in determining the length of this * (這對於決定集合長度是有用的,如果調用者知道這個集合不能包含任何null元素). * collection <i>only</i> if the caller knows that this collection does * not contain any <tt>null</tt> elements.) * <p>If this collection makes any guarantees as to what order its elements * 如果這個集合提供了任何保證他的迭代器返回元素的順序, * are returned by its iterator, this method must return the elements in * 這個方法必須返回相同的元素順序. * the same order. * <p>Like the {@link #toArray()} method, this method acts as bridge between * 同toArray()方法一樣, * array-based and collection-based APIs. Further, this method allows * 這個方法作為基礎數組與基礎集合的橋樑. * precise control over the runtime type of the output array, and may, * 進一步的,這個方法允許精確的控制輸出數組的運行時類型, * under certain circumstances, be used to save allocation costs. * 也許,在某一個情況下,可以用於保存分配消耗. * <p>Suppose <tt>x</tt> is a collection known to contain only strings. * 支持X是一個僅僅包含string的一直集合 * The following code can be used to dump the collection into a newly * 跟隨的代碼可以用於傾倒集合到一個新的分配的string數組中 * allocated array of <tt>String</tt>: * <pre> * String[] y = x.toArray(new String[0]);</pre> * Note that <tt>toArray(new Object[0])</tt> is identical in function to * 注意toArray(new Object[0])與toArray()方法功能完全相同. * <tt>toArray()</tt>. * * @param a the array into which the elements of this collection are to be * 用於存儲集合中的元素的足夠大的數組. * stored, if it is big enough; otherwise, a new array of the same * 另外,一個新的相同運行時類型的數組為此目的而得到分配. * runtime type is allocated for this purpose. * * @return an array containing all of the elements in this collection * * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * 如果指定數組的運行時類型不是集合中每個元素的運行時類型的子類型 * this collection * 則會拋出一個異常 * @throws NullPointerException if the specified array is null * 如果指定的數組為null */ <T> T[] toArray( T[] a ); // Modification Operations /** * Ensures that this collection contains the specified element (optional * 保證集合包含特定的元素(可選的操作) * operation). Returns <tt>true</tt> if this collection changed as a * 如果集合由於這個調用而改變了,則返回true * result of the call. (Returns <tt>false</tt> if this collection does * not permit duplicates and already contains the specified element.)<p> * (如果集合不允許重複的操作並且已經包含了指定的元素則返回false.) * Collections that support this operation may place limitations on what * 支持向集合中添加元素不瘦邊界限制的操作. * elements may be added to this collection. In particular, some * collections will refuse to add <tt>null</tt> elements, and others will * 詳細來講,一些集合會拒絕添加null元素, * impose restrictions on the type of elements that may be added. * 另一些將收到可添加元素的類型的限制條件. * Collection classes should clearly specify in their documentation any * 集合類會明確的在文檔中指定元素添加的任意限制條件. * restrictions on what elements may be added.<p> * If a collection refuses to add a particular element for any reason * 如果一個集合拒絕添加一個特定元素除了他已包含元素之外的原因, * other than that it already contains the element, it <i>must</i> throw * an exception (rather than returning <tt>false</tt>). This preserves * 他會拋出一個異常(而不是返回false). * the invariant that a collection always contains the specified element * 一個結合總是包含特定的元素在這個方法調用返回后是保持不便的. * after this call returns. * * @param e element whose presence in this collection is to be ensured * 集合中出現的元素將是確定的. * * @return <tt>true</tt> if this collection changed as a result of the * 調用后的結果改變了結合,則會返回true * call * * @throws UnsupportedOperationException if the <tt>add</tt> operation * 如果集合不支持add操作,則會拋出這個異常 * is not supported by this collection * @throws ClassCastException if the class of the specified element * 如果指定元素的類型阻止添加進這個集合,則會拋出一個異常 * prevents it from being added to this collection * @throws NullPointerException if the specified element is null and this * 如果指定的元素為null這個結合不允許null元素 * collection does not permit null elements * 則會拋出一個異常 * @throws IllegalArgumentException if some property of the element * 如果元素的一些屬性組織添加進這個集合 * prevents it from being added to this collection * 則會拋出一個異常 * @throws IllegalStateException if the element cannot be added at this * 如果元素不允許時間超時的插入限制 * time due to insertion restrictions * 則會拋出一個異常 */ boolean add( E e ); /** * Removes a single instance of the specified element from this * 從集合中移出一個指定的元素實例 * collection, if it is present (optional operation). More formally, * removes an element <tt>e</tt> such that * 更嚴格的說,移出一個(o == null ? e == null : o.equals(e))的元素, * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if * this collection contains one or more such elements. Returns * 如果集合包含了一個或更多的這個元素. * <tt>true</tt> if this collection contained the specified element (or * 如果集合包含指定的元素則返回true * equivalently, if this collection changed as a result of the call). * (或者相同的,如果集合因為這個調用的結果而改變了). * * @param o element to be removed from this collection, if present * 如果存在,從集合中移出這個元素. * * @return <tt>true</tt> if an element was removed as a result of this call * 如果因為方法的調用的結果移出了元素,則返回true * * @throws ClassCastException if the type of the specified element * is incompatible with this collection * 如果指定的元素的類型與這個集合互不相容,則拋出一個異常 * (<a href="#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements * 如果指定的元素為null並且結婚不允許null元素,則拋出一個異常 * (<a href="#optional-restrictions">optional</a>) * @throws UnsupportedOperationException if the <tt>remove</tt> operation * 如果這個集合不支持移除操作則會拋出一個異常 * is not supported by this collection */ boolean remove( Object o ); // Bulk Operations /** * Returns <tt>true</tt> if this collection contains all of the elements * 如果集合包含指定集合中的所有元素,則返回true * in the specified collection. * * @param c collection to be checked for containment in this collection * 在集合中要檢查的集合內容 * * @return <tt>true</tt> if this collection contains all of the elements * 如果集合包含了指定集合的所有元素,則返回true * in the specified collection * * @throws ClassCastException if the types of one or more elements * 如果在指定的集合中的一個或者更多的元素的類型與這個集合不匹配 * in the specified collection are incompatible with this * 則會拋出一個異常 * collection * (<a href="#optional-restrictions">optional</a>) * @throws NullPointerException if the specified collection contains one * 如果指定集合包含一個或多個null元素並且這個集合是不允許null元素時 * or more null elements and this collection does not permit null * 拋出一個異常 * elements * (<a href="#optional-restrictions">optional</a>), * or if the specified collection is null. * @see #contains(Object) */ boolean containsAll( Collection<?> c ); /** * Adds all of the elements in the specified collection to this collection * 添加指定集合的所有元素到這個集合中 * (optional operation). The behavior of this operation is undefined if * (可選的操作). * the specified collection is modified while the operation is in progress. * 這個操作的行為是不明確的,如果在操作過程中指定的集合改變了. * (This implies that the behavior of this call is undefined if the * (這就意味著調用的行為是未明確的如果指定的集合是這個集合,並且這個集合是非空的集合.) * specified collection is this collection, and this collection is * nonempty.) * * @param c collection containing elements to be added to this collection * 集合包含添加進的集合的元素 * * @return <tt>true</tt> if this collection changed as a result of the call * 如果這個調用的結果改變了集合,那麼返回true * * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * 如果集合不支持addAll操作 * is not supported by this collection * @throws ClassCastException if the class of an element of the specified * 如果指定集合的元素的類型阻止從這個集合中添加 * collection prevents it from being added to this collection * @throws NullPointerException if the specified collection contains a * 如果指定的集合包含null元素並且集合不允許null元素 * null element and this collection does not permit null elements, * or if the specified collection is null * 或者指定的集合為null. * @throws IllegalArgumentException if some property of an element of the * 如果指定集合的元素的某些熟悉阻止向這個集合中添加 * specified collection prevents it from being added to this * collection * @throws IllegalStateException if not all the elements can be added at * 如果在運行的時間超時的限制下沒有將所有元素添加進入集合 * this time due to insertion restrictions * @see #add(Object) */ boolean addAll( Collection<? extends E> c ); /** * Removes all of this collection's elements that are also contained in the * 移出所有的包含在指定集合中的元素 * specified collection (optional operation). After this call returns, * (可選的操作). * this collection will contain no elements in common with the specified * 這個調用返回之後,集合將不包含任何指定集合中的元素 * collection. * * @param c collection containing elements to be removed from this collection * 從這個集合中移出集合包含的元素 * * @return <tt>true</tt> if this collection changed as a result of the * 如果這個調用的結果改變了這個集合,則返回true * call * * @throws UnsupportedOperationException if the <tt>removeAll</tt> method * 如果集合不支持removeAll操作 * is not supported by this collection * @throws ClassCastException if the types of one or more elements * 如果這個集合中的一個或多個元素的類型與制定集合不匹配 * in this collection are incompatible with the specified * collection * (<a href="#optional-restrictions">optional</a>) * @throws NullPointerException if this collection contains one or more * 如果集合包含一個或多個null元素並且制定集合不支持null * null elements and the specified collection does not support * null elements * (<a href="#optional-restrictions">optional</a>), * or if the specified collection is null * 或者指定集合為null * @see #remove(Object) * @see #contains(Object) */ boolean removeAll( Collection<?> c ); /** * Retains only the elements in this collection that are contained in the * 保證集合中的元素包含在指定集合中 * specified collection (optional operation). In other words, removes from * (可選的操作). * this collection all of its elements that are not contained in the * 換句話說,就是移出所有不在指定集合中的這個集合中的元素 * specified collection. * * @param c collection containing elements to be retained in this collection * 保證這個集合中的包含的元素 * * @return <tt>true</tt> if this collection changed as a result of the call * * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation * 如果集合不支持retainAll操作 * is not supported by this collection * @throws ClassCastException if the types of one or more elements * 如果集合中的一個或多個元素的類型與指定集合不匹配 * in this collection are incompatible with the specified * collection * (<a href="#optional-restrictions">optional</a>) * @throws NullPointerException if this collection contains one or more * 如果集合包含一個或多個null元素並且指定集合不允許null元素 * null elements and the specified collection does not permit null * elements * (<a href="#optional-restrictions">optional</a>), * or if the specified collection is null * 或者指定集合為null * @see #remove(Object) * @see #contains(Object) */ boolean retainAll( Collection<?> c ); /** * Removes all of the elements from this collection (optional operation). * 移出集合中的所有元素(可選的操作) * The collection will be empty after this method returns. * 這個方法調用返回之後集合將會是empty的 * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * 如果這個集合不支持clear操作 * is not supported by this collection */ void clear(); // Comparison and hashing /** * Compares the specified object with this collection for equality. <p> * 將指定obj與當前集合比較相等. * While the <tt>Collection</tt> interface adds no stipulations to the * 集合接口由Object.equals()方法添加未規定的通用的方法. * general contract for the <tt>Object.equals</tt>, programmers who * implement the <tt>Collection</tt> interface "directly" (in other words, * 實現集合接口的程序員分派 * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt> * (換句話說,這是一個Collection而不是一個Set或者List) * or a <tt>List</tt>) must exercise care if they choose to override the * 如果選擇複寫Object.equals必須小心使用. * <tt>Object.equals</tt>. It is not necessary to do so, and the simplest * 這是非必須的, * course of action is to rely on <tt>Object</tt>'s implementation, but * 最簡單的行為過程依賴於Object的實現, * the implementor may wish to implement a "value comparison" in place of * 但是實現者可以在默認比較中實現值的比較. * the default "reference comparison." (The <tt>List</tt> and * <tt>Set</tt> interfaces mandate such value comparisons.)<p> * (List與Set接口都有類似的值比較.) * The general contract for the <tt>Object.equals</tt> method states that * 對於Object.equals方法陳述的通用的契約必須是對等的 * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and * (換句話說,a.equals(b)當且僅當b.equals(a)) * only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt> * and <tt>Set.equals</tt> state that lists are only equal to other lists, * 對於List與Set的equals描述的契約僅僅是list等於其他的list, * and sets to other sets. Thus, a custom <tt>equals</tt> method for a * set等於另外的set. * collection class that implements neither the <tt>List</tt> nor * 因此對於實現既不是List也不是set接口的集合類的通用的equals方法 * <tt>Set</tt> interface must return <tt>false</tt> when this collection * 必須返回false當這個集合與另外的list或者set相比較時. * is compared to any list or set. (By the same logic, it is not possible * to write a class that correctly implements both the <tt>Set</tt> and * (相同的邏輯,寫一個正確的實現Set與List接口的類是不可能的.) * <tt>List</tt> interfaces.) * * @param o object to be compared for equality with this collection * 一個對象與這個集合比較相等性 * * @return <tt>true</tt> if the specified object is equal to this * 如果指定的obj與這個集合相等,返回true * collection * * @see Object#equals(Object) * @see java.util.Set#equals(Object) * @see java.util.List#equals(Object) */ boolean equals( Object o ); /** * Returns the hash code value for this collection. While the * 返回這個集合的hashcode * <tt>Collection</tt> interface adds no stipulations to the general * 當這個集合接口添加了沒有約定的Object.hashCode方法通用的契約, * contract for the <tt>Object.hashCode</tt> method, programmers should * take note that any class that overrides the <tt>Object.equals</tt> * 程序員應該標記任何複寫了Object.equals方法的列必須複寫hashcode方法, * method must also override the <tt>Object.hashCode</tt> method in order * to satisfy the general contract for the <tt>Object.hashCode</tt> method. * 在安全的hashcode方法中的公共契約中. * In particular, <tt>c1.equals(c2)</tt> implies that * 特別說明,c1.equals(c2)意味著c1.hashCode() == c2.hashCode(); * <tt>c1.hashCode()==c2.hashCode()</tt>. * * @return the hash code value for this collection * 返回這個集合的hash code值 * * @see Object#hashCode() * @see Object#equals(Object) */ int hashCode(); }
gpl-2.0
TruckMuncher/TruckMuncher-Android
testlib/src/main/java/com/truckmuncher/testlib/ReadableRobolectricTestRunner.java
1043
package com.truckmuncher.testlib; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.robolectric.AndroidManifest; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.res.Fs; public class ReadableRobolectricTestRunner extends RobolectricTestRunner { public ReadableRobolectricTestRunner(Class<?> testClass) throws InitializationError { super(testClass); } @Override protected String testName(FrameworkMethod method) { return StringUtils.humanize(method.getName()); } @Override protected AndroidManifest getAppManifest(Config config) { String manifestProperty = "src/main/AndroidManifest.xml"; String resProperty = "src/main/res"; return new AndroidManifest(Fs.fileFromPath(manifestProperty), Fs.fileFromPath(resProperty)) { @Override public int getTargetSdkVersion() { return 18; } }; } }
gpl-2.0
beemsoft/techytax
techytax-xbrl/src/main/java/nl/nltaxonomie/nt13/bd/_20181212_b/dictionary/bd_types/Anstring6FItemType.java
1159
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.04.10 at 11:10:53 AM CEST // package nl.nltaxonomie.nt13.bd._20181212_b.dictionary.bd_types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import org.xbrl._2003.instance.TokenItemType; /** * <p>Java class for anstring6FItemType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="anstring6FItemType"> * &lt;simpleContent> * &lt;restriction base="&lt;http://www.xbrl.org/2003/instance>tokenItemType"> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "anstring6FItemType") public class Anstring6FItemType extends TokenItemType { }
gpl-2.0
huangyaoming/wxtest
src/com/byhealth/wechat/mysdk/process/ServiceExecutor.java
312
package com.byhealth.wechat.mysdk.process; /** * 服务执行器 * @author jie.hua@alipay.com * @version $Id: ServiceExecutor.java, v 0.1 2014-1-9 上午2:45:59 jie.hua Exp $ */ public interface ServiceExecutor { /** * 业务执行方法 */ public String execute() throws Exception; }
gpl-2.0
locatlang/Compiler
src/io/github/locatlang/compiler/FileManager.java
2086
package io.github.locatlang.compiler; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by creeps on 02/05/15. */ public class FileManager { File path; public FileManager(String folderPath) { path = new File(folderPath); } private List<File> lcfiles = new ArrayList<File>(); private boolean searchRunning = false; private void searchInDir(File dir) { File[] objects = dir.listFiles(); for( File f : objects ) { if( f.isFile() ) { //checks if the file extension is .lcat int lastIndexOfDot = f.getName().lastIndexOf("."); //can't be 0, else the file would be named ".lcat" if( lastIndexOfDot > 0 ) { if ( f.getName().substring( lastIndexOfDot ).equalsIgnoreCase(".lcat") ) { lcfiles.add(f.getAbsoluteFile()); } } } else if( f.isDirectory() ) { if ( searchRunning ) { searchInDir(f.getAbsoluteFile()); } } } } public List<File> initSearch() { searchRunning = true; searchInDir(path); return lcfiles; } public void cancelSearch() { searchRunning = false; } public String[] readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; List<String> lines = new ArrayList<String>(); while ((line = reader.readLine()) != null) { lines.add(line); } return lines.toArray(new String[lines.size()]); } public String[] readFile(String fpath) throws IOException { return readFile(new File(fpath)); } public void writeFile(String path, String[] data, String encoding) throws IOException { PrintWriter writer = new PrintWriter(path, encoding); for( String line : data ) { writer.println(line); } writer.close(); } public void writeFile(String path, String[] data) throws IOException { writeFile(path, data, "UTF-8"); } public void writeFile(File file, String[] data, String encoding) throws IOException { writeFile(file.getAbsolutePath(), data, encoding); } public void writeFile(File file, String[] data) throws IOException { writeFile(file, data, "UTF-8"); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest05614.java
2476
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest05614") public class BenchmarkTest05614 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(param); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo", bar}; ProcessBuilder pb = new ProcessBuilder(); pb.command(args); try { Process p = pb.start(); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case"); throw new ServletException(e); } } }
gpl-2.0
Supreme85/VIQAUITestingTool
Java/src/main/java/ru/viqa/ui_testing/common/alertings/ScreenshotAlert.java
2881
package ru.viqa.ui_testing.common.alertings; import org.testng.Assert; import ru.viqa.ui_testing.common.interfaces.IAlerting; import ru.viqa.ui_testing.page_objects.VISite; import org.openqa.selenium.TakesScreenshot; import java.io.File; import java.io.IOException; import static org.apache.commons.io.FileUtils.copyFile; import static org.openqa.selenium.OutputType.FILE; import static org.testng.Assert.assertTrue; import static ru.viqa.ui_testing.common.loggers.DefaultLogger.getValidUrl; import static org.testng.Assert.fail; import static ru.viqa.ui_testing.page_objects.VISite.*; /** * Created by 12345 on 03.10.2014. */ public class ScreenshotAlert implements IAlerting { private VISite site; public String LogDirectory; private String fileName; public String getDefaultFileName() { return "_fail_" + getRunId(); } public ScreenshotAlert(VISite site) { this.site = site; this.fileName = "fail_" + getRunId(); } public Exception throwError(String errorMsg) throws Exception { Logger.error(errorMsg); takeScreenshot(); assertTrue(false, errorMsg); throw new Exception(errorMsg); } public void takeScreenshot() throws Exception { takeScreenshot(null, null); } public void takeScreenshot(String path, String outputFileName) throws Exception { Logger.event("Add Screenshot: " + path + ": " + outputFileName); if (outputFileName == null || outputFileName.equals("")) outputFileName = fillFileName(); path = new File(".").getCanonicalPath() + getValidUrl(path != null ? path : fillPath()); String screensFilePath = getFileName(path + outputFileName); new File(screensFilePath).getParentFile().mkdirs(); File screensFile = ((TakesScreenshot)site.getWebDriver()).getScreenshotAs(FILE); copyFile(screensFile, new File(screensFilePath)); Logger.event("Add Screenshot: " + screensFilePath); } private String getFileName(String fileName) { int num = 1; String newName = fileName; while (new File(newName + ".jpg").exists()) newName = fileName + "_" + num ++; return newName + ".jpg"; } private String fillPath() throws IOException { String imgRoot = getValidUrl(getProperty("vi.screenshot.path")); return (imgRoot != null && !imgRoot.equals("")) ? imgRoot : LogDirectory != null ? LogDirectory : "/../.logs/" + getRunId(); } private String fillFileName() throws IOException { if (fileName != null) return fileName; String outputFileName = getValidUrl(getProperty("vi.screenshot.fileName")); if (outputFileName == null || outputFileName.equals("")) return getDefaultFileName(); return outputFileName; } }
gpl-2.0
taopmindray/server
data/src/main/java/com/youthclub/scheduler/SessionDataCleaner.java
910
package com.youthclub.scheduler; import com.youthclub.lookup.LookUp; import com.youthclub.model.Session; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.persistence.EntityManager; import java.util.Calendar; import java.util.List; /** * @author Frank */ @Singleton @Startup public class SessionDataCleaner { @PostConstruct public void run() { final EntityManager entityManager = LookUp.getEntityManager(); final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); final List<Session> sessions = entityManager.createNamedQuery("Session.beforeDate") .setParameter("date", calendar.getTime()) .getResultList(); for (final Session session : sessions) { entityManager.remove(session); } entityManager.flush(); } }
gpl-2.0
ksmaheshkumar/ache
src/main/java/focusedCrawler/util/DataNotFoundException.java
1367
/* ############################################################################ ## ## Copyright (C) 2006-2009 University of Utah. All rights reserved. ## ## This file is part of DeepPeep. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL included in the packaging of ## this file. Please review the following to ensure GNU General Public ## Licensing requirements will be met: ## http://www.opensource.org/licenses/gpl-license.php ## ## If you are unsure which license is appropriate for your use (for ## instance, you are interested in developing a commercial derivative ## of DeepPeep), please contact us at deeppeep@sci.utah.edu. ## ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ## ############################################################################ */ package focusedCrawler.util; public class DataNotFoundException extends DetailException { public DataNotFoundException() { super(); } public DataNotFoundException(String message) { super(message); } public DataNotFoundException(String message,Throwable detail) { super(message,detail); } }
gpl-2.0
ncdesouza/xstream
backend/test/unit/RecordTest.java
975
package unit; import backend.transaction.Record; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static junit.framework.TestCase.assertEquals; /** * unit.UserTest: * <brief description of class> */ @RunWith(Parameterized.class) public class RecordTest { private int code; private Record record; public RecordTest(int code) { this.code = code; this.record = new Record(code); } @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {0}, {1}, {2}, {3}, {4}, {5}, {6}, }); } @Test public void testRecordConstruct() throws Exception { assertEquals(code, record.getCode()); } }
gpl-2.0
Min3CraftDud3/Realm-of-the-Mad-Kings
src/me/faris/rotmk/helpers/utils/Utilities.java
6170
package me.faris.rotmk.helpers.utils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.entity.Player; import java.io.*; import java.util.Random; public class Utilities { private static Random random = new Random(); /** * Check if a location is the same as another (in terms of block locations) * * @param loc1 - Location 1. * @param loc2 - Location 2. * @return True if the locations are the same, false if not. */ public static boolean compareLocations(Location loc1, Location loc2) { if (loc1 == null || loc2 == null) return false; int x1 = (int) loc1.getX(), y1 = (int) loc1.getY(), z1 = (int) loc1.getZ(); int x2 = (int) loc2.getX(), y2 = (int) loc2.getY(), z2 = (int) loc2.getZ(); return x1 == x2 && y1 == y2 && z1 == z2; } /** * Convert a location into a string. * * @param location - The string in the location format: {world} {x} {y} {z} * @param roundedValues - If the x, y and z values should be rounded. * @param containsYawAndPitch - The location contains a yaw and a pitch. * @return A string with the data of a location. */ public static String convertLocationToString(Location location, boolean roundedValues, boolean containsYawAndPitch) { if (location == null) return "world " + 0D + " " + 50D + " " + 0D + (containsYawAndPitch ? " " + 0F + " " + 0F : ""); String strLoc = (location.getWorld() != null ? location.getWorld().getName() : "world") + " "; if (roundedValues) strLoc += (double) ((int) location.getX()) + " " + (double) ((int) location.getY()) + " " + (double) ((int) location.getZ()); else strLoc += location.getX() + " " + location.getY() + " " + location.getZ(); if (containsYawAndPitch) strLoc += " " + location.getPitch() + " " + location.getYaw(); return strLoc; } /** * Convert a string into a location. * * @param strLocation - The location as a string. * @param containsYawAndPitch - The location contains a yaw and a pitch. * @return A location with data from the string. */ public static Location convertStringToLocation(String strLocation, boolean containsYawAndPitch) { if (strLocation == null) return null; try { if (strLocation.contains(" ")) { String[] locSplit = strLocation.split(" "); World w = Bukkit.getWorld(locSplit[0]); if (w == null) Bukkit.createWorld(WorldCreator.name(locSplit[0])); double x = Double.parseDouble(locSplit[1]), y = Double.parseDouble(locSplit[2]), z = Double.parseDouble(locSplit[3]); float yaw = 0F, pitch = 0F; if (containsYawAndPitch) { yaw = Float.parseFloat(locSplit[4]); pitch = Float.parseFloat(locSplit[5]); } return new Location(w, x, y, z, yaw, pitch); } } catch (Exception ex) { } return null; } /** * Copy a folder from one location to another. * * @param src - The source folder. * @param dest - The destination. * @throws java.io.IOException */ public static void copyFolder(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { dest.mkdir(); } String files[] = src.list(); for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file); copyFolder(srcFile, destFile); } } else { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } } /** * Delete a world. * * @param world - The world to delete. */ public static void deleteWorld(World world) { try { File worldFolder = world.getWorldFolder(); Bukkit.getServer().unloadWorld(world, false); deleteDirectory(worldFolder); } catch (Exception ex) { } } public static boolean deleteDirectory(File path) { if (path.exists()) { File files[] = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } public static void feedPlayer(Player player, int amount) { if (amount < 0) amount *= -1; if (player.getFoodLevel() + amount > 20) player.setFoodLevel(20); else player.setFoodLevel(player.getFoodLevel() + amount); } /** * Get a Random object. * * @return The Random instance. */ public static Random getRandom() { return random; } public static void healPlayer(Player player, int amount) { if (amount < 0) amount *= -1; if (player.getHealth() + amount > player.getMaxHealth()) player.setHealth(player.getMaxHealth()); else player.setHealth(player.getHealth() + amount); } /** * Check whether a String has a numeric value above Integer.MIN_VALUE and above Integer.MAX_VALUE * * @param aString - A String * @return True if the String is an integer, false if not. */ public static boolean isInteger(String aString) { try { Integer.parseInt(aString); return true; } catch (Exception ex) { return false; } } public static void resetPlayer(Player player) { player.setHealth(player.getMaxHealth()); player.setFoodLevel(20); } }
gpl-2.0
evgs/Bombus
src/Client/Groups.java
6657
/* * Groups.java * * Created on 8.05.2005, 0:36 * * Copyright (c) 2005-2007, Eugene Stahov (evgs), http://bombus-im.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package Client; import com.alsutton.jabber.JabberBlockListener; import com.alsutton.jabber.JabberDataBlock; import com.alsutton.jabber.datablocks.Iq; import images.RosterIcons; import java.util.*; import locale.SR; import ui.ImageList; import ui.VirtualList; /** * * @author Evg_S */ public class Groups implements JabberBlockListener{ Vector groups; public final static int TYPE_SELF=1; public final static int TYPE_NO_GROUP=2; public final static int TYPE_COMMON=3; public final static int TYPE_IGNORE=4; public final static int TYPE_NOT_IN_LIST=5; public final static int TYPE_TRANSP=6; public final static int TYPE_MUC=7; public final static int TYPE_SEARCH_RESULT=8; public final static String COMMON_GROUP=SR.MS_GENERAL; private final static String GROUPSTATE_NS="http://bombus-im.org/groups"; public Groups(){ groups=new Vector(); addGroup(SR.MS_TRANSPORTS, Groups.TYPE_TRANSP); addGroup(SR.MS_SELF_CONTACT, Groups.TYPE_SELF); addGroup(SR.MS_SEARCH_RESULTS, Groups.TYPE_SEARCH_RESULT); addGroup(SR.MS_NOT_IN_LIST, Groups.TYPE_NOT_IN_LIST); addGroup(SR.MS_IGNORE_LIST, Groups.TYPE_IGNORE); addGroup(Groups.COMMON_GROUP, Groups.TYPE_NO_GROUP); } private int rosterContacts; private int rosterOnline; public void resetCounters(){ for (Enumeration e=groups.elements();e.hasMoreElements();){ Group grp=(Group)e.nextElement(); grp.startCount(); } rosterContacts=rosterOnline=0; } public void addToVector(Vector d, int index){ Group gr=(Group)groups.elementAt(index); if (!gr.visible) return; if (gr.contacts.size()>0){ d.addElement(gr); if (!gr.collapsed) for (Enumeration e=gr.contacts.elements();e.hasMoreElements();){ d.addElement(e.nextElement()); } } gr.finishCount(); if (gr.type==Groups.TYPE_SEARCH_RESULT) return; ;//don't count this contacts if (gr.type==Groups.TYPE_NOT_IN_LIST) return; ;//don't count this contacts rosterContacts+=gr.getNContacts(); rosterOnline+=gr.getOnlines(); } public Group getGroup(int type) { for (Enumeration e=groups.elements();e.hasMoreElements();){ Group grp=(Group)e.nextElement(); if (grp.type==type) return grp; } return null; } public Enumeration elements(){ return groups.elements(); } public Group getGroup(String name) { for (Enumeration e=groups.elements();e.hasMoreElements();){ Group grp=(Group)e.nextElement(); if (name.equals(grp.name)) return grp; } return null; } public Group addGroup(String name, int type) { Group ng=new Group(name); ng.type=type; return addGroup(ng); } public Group addGroup(Group ng) { groups.addElement(ng); VirtualList.sort(groups); return ng; } public Vector getRosterGroupNames(){ Vector s=new Vector(); for (int i=0; i<groups.size(); i++) { Group grp=(Group) groups.elementAt(i); if (grp.type<TYPE_NO_GROUP) continue; if (grp.type>TYPE_IGNORE) continue; s.addElement(grp.name); } return s; } public int getCount() {return groups.size();} public int getRosterContacts() { return rosterContacts; } public int getRosterOnline() { return rosterOnline; } void removeGroup(Group g) { groups.removeElement(g); } public int blockArrived(JabberDataBlock data) { if (data instanceof Iq) if (data.getTypeAttribute().equals("result")) { JabberDataBlock query=data.findNamespace("query", "jabber:iq:private"); if (query==null) return BLOCK_REJECTED; JabberDataBlock gs=query.findNamespace("gs", GROUPSTATE_NS); if (gs==null) return BLOCK_REJECTED; for (Enumeration e=gs.getChildBlocks().elements(); e.hasMoreElements();) { JabberDataBlock item=(JabberDataBlock)e.nextElement(); String groupName=item.getText(); boolean collapsed=item.getAttribute("state").equals("collapsed"); Group grp=getGroup(groupName); if (grp==null) continue; grp.collapsed=collapsed; } StaticData.getInstance().roster.reEnumRoster(); return NO_MORE_BLOCKS; } return BLOCK_REJECTED; } public void queryGroupState(boolean get) { Roster roster=StaticData.getInstance().roster; if (!roster.isLoggedIn()) return; JabberDataBlock iq=new Iq(null, (get)? Iq.TYPE_GET : Iq.TYPE_SET, (get)? "queryGS" : "setGS"); JabberDataBlock query=iq.addChildNs("query", "jabber:iq:private"); JabberDataBlock gs=query.addChildNs("gs", GROUPSTATE_NS); if (get) { roster.theStream.addBlockListener(this); } else { for (Enumeration e=groups.elements(); e.hasMoreElements();) { Group grp=(Group)e.nextElement(); if (grp.collapsed) { gs.addChild("item", grp.getName()).setAttribute("state", "collapsed"); } } } //System.out.println(iq.toString()); roster.theStream.send(iq); } }
gpl-2.0
CarlosAgon/ILP-UPMC
Java/src/com/paracamplus/ilp2/compiler/ast/ASTCprogram.java
963
/* ***************************************************************** * ILP9 - Implantation d'un langage de programmation. * by Christian.Queinnec@paracamplus.com * See http://mooc.paracamplus.com/ilp9 * GPL version 3 ***************************************************************** */ package com.paracamplus.ilp2.compiler.ast; import com.paracamplus.ilp1.interfaces.IASTexpression; import com.paracamplus.ilp2.compiler.interfaces.IASTCfunctionDefinition; public class ASTCprogram extends com.paracamplus.ilp1.compiler.ast.ASTCprogram implements com.paracamplus.ilp2.compiler.interfaces.IASTCprogram { public ASTCprogram (IASTCfunctionDefinition[] functions, IASTexpression expression) { super(expression); this.functions = functions; } protected IASTCfunctionDefinition[] functions; @Override public IASTCfunctionDefinition[] getFunctionDefinitions() { return functions; } }
gpl-2.0
hkaj/CoFITS
server/src/DocumentAgent/RemoveProjectSeqBehaviour.java
146
package DocumentAgent; import jade.core.behaviours.SequentialBehaviour; public class RemoveProjectSeqBehaviour extends SequentialBehaviour { }
gpl-2.0
btrzcinski/netchat
j-client/testing/confReadTest.java
783
import java.util.*; import java.io.*; public class confReadTest { public static void main(String[] argss) { Scanner in = null; try { in = new Scanner(new File("etc/modules.conf")); } catch (FileNotFoundException e) {} while(in.hasNext()) { String s = in.nextLine(); int poundIndex = s.indexOf('#'); if(poundIndex != -1) s = s.substring(0, poundIndex); if(s.equals("")) continue; String[] args = s.split("\\s+", 0); if(args.length != 2) { System.out.println("Reached invalid conf statement: " + s + "." + "Ignoring..."); for(int i = 0; i < args.length; i++) System.out.println(args[i]); continue; } System.out.println("Adding " + args[0] + ":" + args[1] + " to module classname map..."); } } }
gpl-2.0
wordpress-mobile/MediaPicker-Android
mediapicker/src/main/java/org/wordpress/mediapicker/CheckableFrameLayout.java
1090
package org.wordpress.mediapicker; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.FrameLayout; /** * Frame layout that manages a checked state. */ public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mIsChecked; public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); mIsChecked = false; } @Override public void setChecked(boolean checked) { mIsChecked = checked; refreshDrawableState(); } @Override public boolean isChecked() { return mIsChecked; } @Override public void toggle() { mIsChecked = !mIsChecked; } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, new int[] { android.R.attr.state_checked }); } return drawableState; } }
gpl-2.0
sk19871216/Yilife
app/src/main/java/com/jiuan/android/app/yilife/bean/geiallapps/GetAllAppsResponse.java
401
package com.jiuan.android.app.yilife.bean.geiallapps; import com.google.gson.annotations.SerializedName; /** * Created by Administrator on 2015/1/6. */ public class GetAllAppsResponse { @SerializedName("Datas") private AllappsBean[] datas; public AllappsBean[] getDatas() { return datas; } public void setDatas(AllappsBean[] datas) { this.datas = datas; } }
gpl-2.0
plaice/Intense
libintense-java/src/intense/aep/AETPClient.java
16405
// **************************************************************************** // // AETPClient.java : AEP 2.0 textual (AETP) streamed client, compatible with // the both the C++ and Java AETPServer. // // Copyright 2001, 2002, 2004 Paul Swoboda. // // This file is part of the Intense project. // // Intense 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. // // Intense 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 Intense; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. // // **************************************************************************** package intense.aep; import java.lang.*; import java.util.*; import java.util.concurrent.locks.*; import java.io.*; import intense.*; import intense.log.*; public class AETPClient extends AEPStreamClient { protected static class LexerToken extends Context.Token { // Context.Token types (preserving enum sequence): public static final int VOID = 0; public static final int DIMENSION = 1; public static final int BASEVALUE = 2; public static final int DASH = 3; public static final int DASHDASH = 4; public static final int DASHDASHDASH = 5; public static final int PLUS = 6; public static final int LANGLE = 7; public static final int RANGLE = 8; public static final int LSQUARE = 9; public static final int RSQUARE = 10; public static final int ERROR = 11; public static final int ENDOFFILE = 12; // Extra AETPClient.LexerToken types: public static final int BREAK = 13; public static final int SERVER_DISCONNECT = 14; public static final int NOTIFY = 15; public static final int ASSIGN = 16; public static final int APPLY = 17; public static final int CLEAR = 18; public static final int KICK = 19; public static final int ACK = 20; public static final int DENY = 21; public static final int COUNT = 22; public static final int ID_KEYWORD = 23; public static final int ID = 24; public static final int SEQUENCE = 25; public static final int TEXT = 26; public static final int DIM_KEYWORD = 27; public static final int ROOT_KEYWORD = 28; public static final int COMPOUND_DIMENSION = 29; public static final int EXT_KEYWORD = 30; public static final int INT_KEYWORD = 31; public static final String[] typeStrings = { "VOID", "DIMENSION", "BASEVALUE", "DASH", "DASHDASH", "DASHDASHDASH", "PLUS", "LANGLE", "RANGLE", "LSQUARE", "RSQUARE", "ERROR", "ENDOFFILE", "BREAK", "SERVER_DISCONNECT", "NOTIFY", "ASSIGN", "APPLY", "CLEAR", "KICK", "ACK", "DENY", "COUNT", "ID_KEYWORD", "ID", "SEQUENCE", "TEXT", "DIM_KEYWORD", "ROOT_KEYWORD", "COMPOUND_DIMENSION", "EXT_KEYWORD", "INT_KEYWORD" }; private int type; public int getType () { return type; } public String getTypeString () { return typeStrings[type]; } public static String getTypeString (int type) { return typeStrings[type]; } public LexerToken () { super(); } int setBreak () { return type = BREAK; } int setServerDisconnect () { return type = SERVER_DISCONNECT; } int setNotify () { return type = NOTIFY; } int setAssign () { return type = ASSIGN; } int setApply () { return type = APPLY; } int setClear () { return type = CLEAR; } int setKick () { return type = KICK; } int setAck () { return type = ACK; } int setDeny () { return type = DENY; } int setCount (int count) { value = new Integer(count); return type = COUNT; } int setIdKeyword () { return type = ID_KEYWORD; } int setId (long id) { value = new Long(id); return type = ID; } int setSequence (long sequence) { value = new Long(sequence); return type = SEQUENCE; } int setText (String text) { value = text; return type = TEXT; } int setDimKeyword () { return type = DIM_KEYWORD; } int setRootKeyword () { return type = ROOT_KEYWORD; } int setCompoundDimension (CompoundDimension compoundDimension) { value = compoundDimension; return type = COMPOUND_DIMENSION; } int setExternalKeyword () { return type = EXT_KEYWORD; } int setInternalKeyword () { return type = INT_KEYWORD; } }; protected Reader is; protected PrintStream os; AETPLexer lexer; protected void construct () { this.is = new InputStreamReader(inputStream); this.os = new PrintStream(outputStream, true); lexer = new AETPLexer(is); lexer.setClientType(); } public AETPClient (InputStream is, OutputStream os) throws AEPException { super(is, os, null, Log.NOTICE, true, false, 0); construct(); } public AETPClient (InputStream is, OutputStream os, Log log) throws AEPException { super(is, os, log, Log.NOTICE, true, false, 0); construct(); } public AETPClient (InputStream is, OutputStream os, Log log, int logLevel) throws AEPException { super(is, os, log, logLevel, true, false, 0); construct(); } public AETPClient (InputStream is, OutputStream os, Log log, int logLevel, boolean errorTolerant) throws AEPException { super(is, os, log, logLevel, errorTolerant, false, 0); construct(); } public AETPClient (InputStream is, OutputStream os, Log log, int logLevel, boolean errorTolerant, boolean useReceiverThread) throws AEPException { super(is, os, log, logLevel, errorTolerant, useReceiverThread, 0); construct(); } public AETPClient (InputStream is, OutputStream os, Log log, int logLevel, boolean errorTolerant, boolean useReceiverThread, int maxReceiveSize) throws AEPException { super( is, os, log, logLevel, errorTolerant, useReceiverThread, maxReceiveSize ); construct(); } protected void send (AEPServer.Token token) throws IOException, AEPException { token.aetpPrint(os); os.flush(); outputStream.flush(); } protected Token receive () throws IOException, IntenseException, AEPException { Token token = null; LexerToken lexerToken = new LexerToken(); int type; type = lexer.getToken(lexerToken); switch (type) { case LexerToken.VOID: throw new AEPException("Received VOID AETPClient.LexerToken"); case LexerToken.SERVER_DISCONNECT: { long serverSequence; // Server sequence: serverSequence = readSequence(lexerToken, "server sequence", type); // Break: if (lexer.getToken(lexerToken) != LexerToken.BREAK) { throwBadLexerToken(lexerToken, type); } token = new ServerDisconnectToken(serverSequence); } break; case LexerToken.NOTIFY: { long serverSequence; int targetsSize; int nodesSize; boolean haveSeenAssign = false; boolean haveSeenApply = false; serverSequence = readSequence(lexerToken, "server sequence", type); token = new NotifyToken(serverSequence); // Number of targets: ((AETPLexer)lexer).setCountIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.COUNT) { throwBadLexerToken(lexerToken, type); } targetsSize = ((Integer)lexerToken.getValue()).intValue(); // Number of nodes: ((AETPLexer)lexer).setCountIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.COUNT) { throwBadLexerToken(lexerToken, type); } nodesSize = ((Integer)lexerToken.getValue()).intValue(); for (int i = 0; i < targetsSize; i++) { long participantId; int nodeIndex; CompoundDimension dimension = null; boolean dimensionIsExternal = false; int targetType; switch (targetType = lexer.getToken(lexerToken)) { case LexerToken.ASSIGN: case LexerToken.APPLY: ((AETPLexer)lexer).setIdIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.ID) { throwBadLexerToken(lexerToken, type); } participantId = ((Long)lexerToken.getValue()).longValue(); // nodeIndex: ((AETPLexer)lexer).setCountIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.COUNT) { throwBadLexerToken(lexerToken, type); } nodeIndex = ((Integer)lexerToken.getValue()).intValue(); if (lexer.getToken(lexerToken) == LexerToken.DIM_KEYWORD) { if (lexer.getToken(lexerToken) != LexerToken.COMPOUND_DIMENSION) { throwBadLexerToken(lexerToken, type); } dimension = (CompoundDimension)lexerToken.getValue(); lexer.getToken(lexerToken); if (lexerToken.getType() == LexerToken.EXT_KEYWORD) { dimensionIsExternal = true; } else if (lexerToken.getType() == LexerToken.INT_KEYWORD) { dimensionIsExternal = false; } else { throwBadLexerToken(lexerToken, type); } } else if (lexerToken.getType() != LexerToken.ROOT_KEYWORD) { throwBadLexerToken(lexerToken, type); } if (targetType == LexerToken.ASSIGN) { haveSeenAssign = true; if (dimension != null) { ((NotifyToken)token).addTarget(new NotifyToken.AssignTarget( participantId, nodeIndex, dimension, dimensionIsExternal )); } else { ((NotifyToken)token).addTarget( new NotifyToken.AssignTarget(participantId, nodeIndex) ); } } else { // targetType == LexerToken.APPLY haveSeenApply = true; if (dimension != null) { ((NotifyToken)token).addTarget( new NotifyToken.ApplyTarget( participantId, nodeIndex, dimension, dimensionIsExternal )); } else { ((NotifyToken)token).addTarget( new NotifyToken.ApplyTarget(participantId, nodeIndex) ); } } // Assign/ApplyTarget constructor does NOT copy dimensions. break; case LexerToken.CLEAR: ((AETPLexer)lexer).setIdIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.ID) { throwBadLexerToken(lexerToken, type); } participantId = ((Long)lexerToken.getValue()).longValue(); if (lexer.getToken(lexerToken) == LexerToken.DIM_KEYWORD) { if (lexer.getToken(lexerToken) != LexerToken.COMPOUND_DIMENSION) { throwBadLexerToken(lexerToken, type); } dimension = (CompoundDimension)lexerToken.getValue(); } else if (lexerToken.getType() != LexerToken.ROOT_KEYWORD) { throwBadLexerToken(lexerToken, type); } if (dimension != null) { ((NotifyToken)token).addTarget( new NotifyToken.ClearTarget(participantId, dimension) ); } else { ((NotifyToken)token).addTarget( new NotifyToken.ClearTarget(participantId) ); } break; case LexerToken.KICK: ((AETPLexer)lexer).setIdIntegersType(); if (lexer.getToken(lexerToken) != LexerToken.ID) { throwBadLexerToken(lexerToken, type); } participantId = ((Long)lexerToken.getValue()).longValue(); ((NotifyToken)token).addTarget( new NotifyToken.KickTarget(participantId) ); break; default: throwBadLexerToken(lexerToken, type); } } for (int i = 0; i < nodesSize; i++) { Context node; if (haveSeenAssign) { node = new Context(); } else if (haveSeenApply) { node = new ContextOp(); } else { throw new AEPException( "Received NOTIFY with non-zero node count but no assign or " + "apply targets" ); } lexer.beginInContext(); node.recogniseNode(lexer); lexer.beginInToken(); ((NotifyToken)token).addNode(node); } } if (lexer.getToken(lexerToken) != LexerToken.BREAK) { throwBadLexerToken(lexerToken, type); } break; case LexerToken.ACK: case LexerToken.DENY: { long clientSequence; long serverSequence; String message = null; serverSequence = readSequence(lexerToken, "server sequence", type); clientSequence = readSequence(lexerToken, "client sequence", type); // Message or break: if (lexer.getToken(lexerToken) == LexerToken.TEXT) { message = lexerToken.getValue().toString(); lexer.getToken(lexerToken); if (lexer.getToken(lexerToken) != LexerToken.BREAK) { throwBadLexerToken(lexerToken, type); } } else if (lexerToken.getType() != LexerToken.BREAK) { throwBadLexerToken(lexerToken, type); } switch (type) { case LexerToken.ACK: token = new AckToken(serverSequence, clientSequence, message); break; case LexerToken.DENY: token = new DenyToken(serverSequence, clientSequence, message); break; case LexerToken.ERROR: token = new ErrorToken(serverSequence, clientSequence, message); break; } } break; case LexerToken.ERROR: { throw new AEPException( "Parsed error token in AETPClient.receive: \"" + lexerToken.getValue() + "\"" ); } default: { throw new AEPException( "INTERNAL ERROR: Parsed bad token type " + lexerToken.getTypeString() + " in AETPClient.receive", Log.FATAL ); } } return token; } long readSequence (LexerToken lexerToken, String sequenceName, int inTokenType) throws IOException, AEPException { long returnValue = -1; ((AETPLexer)lexer).setSequenceIntegersType(); switch (lexer.getToken(lexerToken)) { case LexerToken.SEQUENCE: returnValue = ((Long)lexerToken.getValue()).longValue(); break; case LexerToken.BREAK: { String inTokenName = LexerToken.getTypeString(inTokenType); throw new AEPException( "Missing " + sequenceName + " in " + inTokenName ); } default: { String inTokenName = LexerToken.getTypeString(inTokenType); throwBadLexerToken(lexerToken, inTokenType); } } return returnValue; } void throwBadLexerToken (LexerToken token, int inTokenType) throws AEPException { throw new AEPException( "Unexpected token of type " + token.getTypeString() + " in " + LexerToken.getTypeString(inTokenType) ); } protected String getName () { return "AETPClient"; } protected boolean locksReception () { return false; } /** * The AETP input stream is obtained from (and buffered by!) the * JFlex-generated AETPLexer. */ protected boolean blockForAvailableData () throws IOException { return false; } }
gpl-2.0
intfloat/CoreNLP
src/edu/stanford/nlp/classify/LinearClassifier.java
48581
// Stanford Classifier - a multiclass maxent classifier // LinearClassifier // Copyright (c) 2003-2007 The Board of Trustees of // The Leland Stanford Junior University. All Rights Reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information, bug reports, fixes, contact: // Christopher Manning // Dept of Computer Science, Gates 1A // Stanford CA 94305-9010 // USA // Support/Questions: java-nlp-user@lists.stanford.edu // Licensing: java-nlp-support@lists.stanford.edu // http://www-nlp.stanford.edu/software/classifier.shtml package edu.stanford.nlp.classify; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.ling.BasicDatum; import edu.stanford.nlp.ling.Datum; import edu.stanford.nlp.ling.RVFDatum; import edu.stanford.nlp.util.*; import edu.stanford.nlp.stats.ClassicCounter; import edu.stanford.nlp.stats.Counter; import edu.stanford.nlp.stats.Distribution; import edu.stanford.nlp.stats.Counters; import java.io.*; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; import java.util.function.Function; import edu.stanford.nlp.util.logging.Redwood; /** * Implements a multiclass linear classifier. At classification time this * can be any generalized linear model classifier (such as a perceptron, * a maxent classifier (softmax logistic regression), or an SVM). * * @author Dan Klein * @author Jenny Finkel * @author Galen Andrew (converted to arrays and indices) * @author Christopher Manning (most of the printing options) * @author Eric Yeh (save to text file, new constructor w/thresholds) * @author Sarah Spikes (sdspikes@cs.stanford.edu) (Templatization) * @author {@literal nmramesh@cs.stanford.edu} {@link #weightsAsMapOfCounters()} * @author Angel Chang (Add functions to get top features, and number of features with weights above a certain threshold) * * @param <L> The type of the labels in the Classifier * @param <F> The type of the features in the Classifier */ public class LinearClassifier<L, F> implements ProbabilisticClassifier<L, F>, RVFClassifier<L, F> { /** A logger for this class */ private static Redwood.RedwoodChannels log = Redwood.channels(LinearClassifier.class); /** Classifier weights. First index is the featureIndex value and second index is the labelIndex value. */ private double[][] weights; private Index<L> labelIndex; private Index<F> featureIndex; public boolean intern = false; // variable should be deleted when breaking serialization anyway.... private double[] thresholds; // = null; private static final long serialVersionUID = 8499574525453275255L; private static final int MAX_FEATURE_ALIGN_WIDTH = 50; public static final String TEXT_SERIALIZATION_DELIMITER = "\t"; static final Redwood.RedwoodChannels logger = Redwood.channels(LinearClassifier.class); @Override public Collection<L> labels() { return labelIndex.objectsList(); } public Collection<F> features() { return featureIndex.objectsList(); } public Index<L> labelIndex() { return labelIndex; } public Index<F> featureIndex() { return featureIndex; } private double weight(int iFeature, int iLabel) { if (iFeature < 0) { //logger.info("feature not seen "); return 0.0; } assert iFeature < weights.length; assert iLabel < weights[iFeature].length; return weights[iFeature][iLabel]; } private double weight(F feature, int iLabel) { int f = featureIndex.indexOf(feature); return weight(f, iLabel); } public double weight(F feature, L label) { int f = featureIndex.indexOf(feature); int iLabel = labelIndex.indexOf(label); return weight(f, iLabel); } /* --- obsolete method from before this class was rewritten using arrays public Counter scoresOf(Datum example) { Counter scores = new Counter(); for (L l : labels()) { scores.setCount(l, scoreOf(example, l)); } return scores; } --- */ /** Construct a counter with keys the labels of the classifier and * values the score (unnormalized log probability) of each class. */ @Override public Counter<L> scoresOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return scoresOfRVFDatum((RVFDatum<L,F>)example); Collection<F> feats = example.asFeatures(); int[] features = new int[feats.size()]; int i = 0; for (F f : feats) { int index = featureIndex.indexOf(f); if (index >= 0) { features[i++] = index; // } else { //logger.info("FEATURE LESS THAN ZERO: " + f); } } int[] activeFeatures = new int[i]; synchronized (System.class) { System.arraycopy(features, 0, activeFeatures, 0, i); } Counter<L> scores = new ClassicCounter<>(); for (L lab : labels()) { scores.setCount(lab, scoreOf(activeFeatures, lab)); } return scores; } /** Given a datum's features, construct a counter with keys * the labels and values the score (unnormalized log probability) * for each class. */ public Counter<L> scoresOf(int[] features) { Counter<L> scores = new ClassicCounter<>(); for (L label : labels()) scores.setCount(label, scoreOf(features, label)); return scores; } /** Returns of the score of the Datum for the specified label. * Ignores the true label of the Datum. */ public double scoreOf(Datum<L, F> example, L label) { if (example instanceof RVFDatum<?, ?>) { return scoreOfRVFDatum((RVFDatum<L,F>)example, label); } int iLabel = labelIndex.indexOf(label); double score = 0.0; for (F f : example.asFeatures()) { score += weight(f, iLabel); } return score + thresholds[iLabel]; } /** Construct a counter with keys the labels of the classifier and * values the score (unnormalized log probability) of each class * for an RVFDatum. */ @Override @Deprecated public Counter<L> scoresOf(RVFDatum<L, F> example) { Counter<L> scores = new ClassicCounter<>(); for (L l : labels()) { scores.setCount(l, scoreOfRVFDatum(example, l)); } //System.out.println("Scores are: " + scores + " (gold: " + example.label() + ")"); return scores; } /** Construct a counter with keys the labels of the classifier and * values the score (unnormalized log probability) of each class * for an RVFDatum. */ private Counter<L> scoresOfRVFDatum(RVFDatum<L, F> example) { Counter<L> scores = new ClassicCounter<>(); // Index the features in the datum Counter<F> asCounter = example.asFeaturesCounter(); Counter<Integer> asIndexedCounter = new ClassicCounter<>(asCounter.size()); for (Map.Entry<F, Double> entry : asCounter.entrySet()) { asIndexedCounter.setCount(featureIndex.indexOf(entry.getKey()), entry.getValue()); } // Set the scores appropriately for (L l : labels()) { scores.setCount(l, scoreOfRVFDatum(asIndexedCounter, l)); } //System.out.println("Scores are: " + scores + " (gold: " + example.label() + ")"); return scores; } /** Returns the score of the RVFDatum for the specified label. * Ignores the true label of the RVFDatum. * * @param example Used to get the observed x value. Its label is ignored. * @param label The label y that the observed value is scored with. * @return A linear classifier score */ private double scoreOfRVFDatum(RVFDatum<L, F> example, L label) { int iLabel = labelIndex.indexOf(label); double score = 0.0; Counter<F> features = example.asFeaturesCounter(); for (Map.Entry<F, Double> entry : features.entrySet()) { score += weight(entry.getKey(), iLabel) * entry.getValue(); } return score + thresholds[iLabel]; } /** Returns the score of the RVFDatum for the specified label. * Ignores the true label of the RVFDatum. */ private double scoreOfRVFDatum(Counter<Integer> features, L label) { int iLabel = labelIndex.indexOf(label); double score = 0.0; for (Map.Entry<Integer, Double> entry : features.entrySet()) { score += weight(entry.getKey(), iLabel) * entry.getValue(); } return score + thresholds[iLabel]; } /** Returns of the score of the Datum as internalized features for the * specified label. Ignores the true label of the Datum. * Doesn't consider a value for each feature. */ private double scoreOf(int[] feats, L label) { int iLabel = labelIndex.indexOf(label); assert iLabel >= 0; double score = 0.0; for (int feat : feats) { score += weight(feat, iLabel); } return score + thresholds[iLabel]; } /** * Returns a counter mapping from each class name to the probability of * that class for a certain example. * Looking at the the sum of each count v, should be 1.0. */ @Override public Counter<L> probabilityOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return probabilityOfRVFDatum((RVFDatum<L,F>)example); Counter<L> scores = logProbabilityOf(example); for (L label : scores.keySet()) { scores.setCount(label, Math.exp(scores.getCount(label))); } return scores; } /** * Returns a counter mapping from each class name to the probability of * that class for a certain example. * Looking at the the sum of each count v, should be 1.0. */ private Counter<L> probabilityOfRVFDatum(RVFDatum<L, F> example) { // NB: this duplicate method is needed so it calls the scoresOf method // with a RVFDatum signature Counter<L> scores = logProbabilityOfRVFDatum(example); for (L label : scores.keySet()) { scores.setCount(label, Math.exp(scores.getCount(label))); } return scores; } /** * Returns a counter mapping from each class name to the probability of * that class for a certain example. * Looking at the the sum of each count v, should be 1.0. */ @Deprecated public Counter<L> probabilityOf(RVFDatum<L, F> example) { // NB: this duplicate method is needed so it calls the scoresOf method // with a RVFDatum signature Counter<L> scores = logProbabilityOf(example); for (L label : scores.keySet()) { scores.setCount(label, Math.exp(scores.getCount(label))); } return scores; } /** * Returns a counter mapping from each class name to the log probability of * that class for a certain example. * Looking at the the sum of e^v for each count v, should be 1.0. */ @Override public Counter<L> logProbabilityOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return logProbabilityOfRVFDatum((RVFDatum<L,F>)example); Counter<L> scores = scoresOf(example); Counters.logNormalizeInPlace(scores); return scores; } /** * Given a datum's features, returns a counter mapping from each * class name to the log probability of that class. * Looking at the the sum of e^v for each count v, should be 1. */ public Counter<L> logProbabilityOf(int[] features) { Counter<L> scores = scoresOf(features); Counters.logNormalizeInPlace(scores); return scores; } public Counter<L> probabilityOf(int [] features) { Counter<L> scores = logProbabilityOf(features); for (L label : scores.keySet()) { scores.setCount(label, Math.exp(scores.getCount(label))); } return scores; } /** * Returns a counter for the log probability of each of the classes * looking at the the sum of e^v for each count v, should be 1 */ private Counter<L> logProbabilityOfRVFDatum(RVFDatum<L, F> example) { // NB: this duplicate method is needed so it calls the scoresOf method // with an RVFDatum signature!! Don't remove it! // JLS: type resolution of method parameters is static Counter<L> scores = scoresOfRVFDatum(example); Counters.logNormalizeInPlace(scores); return scores; } /** * Returns a counter for the log probability of each of the classes. * Looking at the the sum of e^v for each count v, should give 1. */ @Deprecated public Counter<L> logProbabilityOf(RVFDatum<L, F> example) { // NB: this duplicate method is needed so it calls the scoresOf method // with an RVFDatum signature!! Don't remove it! // JLS: type resolution of method parameters is static Counter<L> scores = scoresOf(example); Counters.logNormalizeInPlace(scores); return scores; } /** * Returns indices of labels * @param labels - Set of labels to get indices * @return Set of indices */ protected Set<Integer> getLabelIndices(Set<L> labels) { Set<Integer> iLabels = Generics.newHashSet(); for (L label:labels) { int iLabel = labelIndex.indexOf(label); iLabels.add(iLabel); if (iLabel < 0) throw new IllegalArgumentException("Unknown label " + label); } return iLabels; } /** * Returns number of features with weight above a certain threshold * (across all labels). * * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @return number of features satisfying the specified conditions */ public int getFeatureCount(double threshold, boolean useMagnitude) { int n = 0; for (double[] weightArray : weights) { for (double weight : weightArray) { double thisWeight = (useMagnitude) ? Math.abs(weight) : weight; if (thisWeight > threshold) { n++; } } } return n; } /** * Returns number of features with weight above a certain threshold. * * @param labels Set of labels we care about when counting features * Use null to get counts across all labels * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @return number of features satisfying the specified conditions */ public int getFeatureCount(Set<L> labels, double threshold, boolean useMagnitude) { if (labels != null) { Set<Integer> iLabels = getLabelIndices(labels); return getFeatureCountLabelIndices(iLabels, threshold, useMagnitude); } else { return getFeatureCount(threshold, useMagnitude); } } /** * Returns number of features with weight above a certain threshold. * * @param iLabels Set of label indices we care about when counting features * Use null to get counts across all labels * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @return number of features satisfying the specified conditions */ protected int getFeatureCountLabelIndices(Set<Integer> iLabels, double threshold, boolean useMagnitude) { int n = 0; for (double[] weightArray : weights) { for (int labIndex : iLabels) { double thisWeight = (useMagnitude) ? Math.abs(weightArray[labIndex]) : weightArray[labIndex]; if (thisWeight > threshold) { n++; } } } return n; } /** * Returns list of top features with weight above a certain threshold * (list is descending and across all labels). * * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @param numFeatures How many top features to return (-1 for unlimited) * @return List of triples indicating feature, label, weight */ public List<Triple<F,L,Double>> getTopFeatures(double threshold, boolean useMagnitude, int numFeatures) { return getTopFeatures(null, threshold, useMagnitude, numFeatures, true); } /** * Returns list of top features with weight above a certain threshold * @param labels Set of labels we care about when getting features * Use null to get features across all labels * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @param numFeatures How many top features to return (-1 for unlimited) * @param descending Return weights in descending order * @return List of triples indicating feature, label, weight */ public List<Triple<F,L,Double>> getTopFeatures(Set<L> labels, double threshold, boolean useMagnitude, int numFeatures, boolean descending) { if (labels != null) { Set<Integer> iLabels = getLabelIndices(labels); return getTopFeaturesLabelIndices(iLabels, threshold, useMagnitude, numFeatures, descending); } else { return getTopFeaturesLabelIndices(null, threshold, useMagnitude, numFeatures, descending); } } /** * Returns list of top features with weight above a certain threshold * @param iLabels Set of label indices we care about when getting features * Use null to get features across all labels * @param threshold Threshold above which we will count the feature * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @param numFeatures How many top features to return (-1 for unlimited) * @param descending Return weights in descending order * @return List of triples indicating feature, label, weight */ protected List<Triple<F,L,Double>> getTopFeaturesLabelIndices(Set<Integer> iLabels, double threshold, boolean useMagnitude, int numFeatures, boolean descending) { edu.stanford.nlp.util.PriorityQueue<Pair<Integer,Integer>> biggestKeys = new FixedPrioritiesPriorityQueue<>(); // locate biggest keys for (int feat = 0; feat < weights.length; feat++) { for (int lab = 0; lab < weights[feat].length; lab++) { if (iLabels != null && !iLabels.contains(lab)) { continue; } double thisWeight; if (useMagnitude) { thisWeight = Math.abs(weights[feat][lab]); } else { thisWeight = weights[feat][lab]; } if (thisWeight > threshold) { // reverse the weight, so get smallest first thisWeight = -thisWeight; if (biggestKeys.size() == numFeatures) { // have enough features, add only if bigger double lowest = biggestKeys.getPriority(); if (thisWeight < lowest) { // remove smallest biggestKeys.removeFirst(); biggestKeys.add(new Pair<>(feat, lab), thisWeight); } } else { // always add it if don't have enough features yet biggestKeys.add(new Pair<>(feat, lab), thisWeight); } } } } List<Triple<F,L,Double>> topFeatures = new ArrayList<>(biggestKeys.size()); while (!biggestKeys.isEmpty()) { Pair<Integer,Integer> p = biggestKeys.removeFirst(); double weight = weights[p.first()][p.second()]; F feat = featureIndex.get(p.first()); L label = labelIndex.get(p.second()); topFeatures.add(new Triple<>(feat, label, weight)); } if (descending) { Collections.reverse(topFeatures); } return topFeatures; } /** * Returns string representation of a list of top features * @param topFeatures List of triples indicating feature, label, weight * @return String representation of the list of features */ public String topFeaturesToString(List<Triple<F,L,Double>> topFeatures) { // find longest key length (for pretty printing) with a limit int maxLeng = 0; for (Triple<F,L,Double> t : topFeatures) { String key = "(" + t.first + "," + t.second + ")"; int leng = key.length(); if (leng > maxLeng) { maxLeng = leng; } } maxLeng = Math.min(64, maxLeng); // set up pretty printing of weights NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(4); if (nf instanceof DecimalFormat) { ((DecimalFormat) nf).setPositivePrefix(" "); } //print high weight features to a String StringBuilder sb = new StringBuilder(); for (Triple<F,L,Double> t : topFeatures) { String key = "(" + t.first + "," + t.second + ")"; sb.append(StringUtils.pad(key, maxLeng)); sb.append(" "); double cnt = t.third(); if (Double.isInfinite(cnt)) { sb.append(cnt); } else { sb.append(nf.format(cnt)); } sb.append("\n"); } return sb.toString(); } /** Return a String that prints features with large weights. * * @param useMagnitude Whether the notion of "large" should ignore * the sign of the feature weight. * @param numFeatures How many top features to print * @param printDescending Print weights in descending order * @return The String representation of features with large weights */ public String toBiggestWeightFeaturesString(boolean useMagnitude, int numFeatures, boolean printDescending) { // this used to try to use a TreeSet, but that was WRONG.... edu.stanford.nlp.util.PriorityQueue<Pair<Integer,Integer>> biggestKeys = new FixedPrioritiesPriorityQueue<>(); // locate biggest keys for (int feat = 0; feat < weights.length; feat++) { for (int lab = 0; lab < weights[feat].length; lab++) { double thisWeight; // reverse the weight, so get smallest first if (useMagnitude) { thisWeight = -Math.abs(weights[feat][lab]); } else { thisWeight = -weights[feat][lab]; } if (biggestKeys.size() == numFeatures) { // have enough features, add only if bigger double lowest = biggestKeys.getPriority(); if (thisWeight < lowest) { // remove smallest biggestKeys.removeFirst(); biggestKeys.add(new Pair<>(feat, lab), thisWeight); } } else { // always add it if don't have enough features yet biggestKeys.add(new Pair<>(feat, lab), thisWeight); } } } // Put in List either reversed or not // (Note: can't repeatedly iterate over PriorityQueue.) int actualSize = biggestKeys.size(); Pair<Integer, Integer>[] bigArray = ErasureUtils.<Pair<Integer, Integer>>mkTArray(Pair.class,actualSize); // logger.info("biggestKeys is " + biggestKeys); if (printDescending) { for (int j = actualSize - 1; j >= 0; j--) { bigArray[j] = biggestKeys.removeFirst(); } } else { for (int j = 0; j < actualSize; j--) { bigArray[j] = biggestKeys.removeFirst(); } } List<Pair<Integer, Integer>> bigColl = Arrays.asList(bigArray); // logger.info("bigColl is " + bigColl); // find longest key length (for pretty printing) with a limit int maxLeng = 0; for (Pair<Integer,Integer> p : bigColl) { String key = "(" + featureIndex.get(p.first) + "," + labelIndex.get(p.second) + ")"; int leng = key.length(); if (leng > maxLeng) { maxLeng = leng; } } maxLeng = Math.min(64, maxLeng); // set up pretty printing of weights NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(4); if (nf instanceof DecimalFormat) { ((DecimalFormat) nf).setPositivePrefix(" "); } //print high weight features to a String StringBuilder sb = new StringBuilder("LinearClassifier [printing top " + numFeatures + " features]\n"); for (Pair<Integer, Integer> p : bigColl) { String key = "(" + featureIndex.get(p.first) + "," + labelIndex.get(p.second) + ")"; sb.append(StringUtils.pad(key, maxLeng)); sb.append(" "); double cnt = weights[p.first][p.second]; if (Double.isInfinite(cnt)) { sb.append(cnt); } else { sb.append(nf.format(cnt)); } sb.append("\n"); } return sb.toString(); } /** * Similar to histogram but exact values of the weights * to see whether there are many equal weights. * * @return A human readable string about the classifier distribution. */ public String toDistributionString(int threshold) { Counter<Double> weightCounts = new ClassicCounter<>(); StringBuilder s = new StringBuilder(); s.append("Total number of weights: ").append(totalSize()); for (double[] weightArray : weights) { for (double weight : weightArray) { weightCounts.incrementCount(weight); } } s.append("Counts of weights\n"); Set<Double> keys = Counters.keysAbove(weightCounts, threshold); s.append(keys.size()).append(" keys occur more than ").append(threshold).append(" times "); return s.toString(); } public int totalSize() { return labelIndex.size() * featureIndex.size(); } public String toHistogramString() { // big classifiers double[][] hist = new double[3][202]; Object[][] histEg = new Object[3][202]; int num = 0; int pos = 0; int neg = 0; int zero = 0; double total = 0.0; double x2total = 0.0; double max = 0.0, min = 0.0; for (int f = 0; f < weights.length; f++) { for (int l = 0; l < weights[f].length; l++) { Pair<F, L> feat = new Pair<>(featureIndex.get(f), labelIndex.get(l)); num++; double wt = weights[f][l]; total += wt; x2total += wt * wt; if (wt > max) { max = wt; } if (wt < min) { min = wt; } if (wt < 0.0) { neg++; } else if (wt > 0.0) { pos++; } else { zero++; } int index; index = bucketizeValue(wt); hist[0][index]++; if (histEg[0][index] == null) { histEg[0][index] = feat; } if (wt < 0.1 && wt >= -0.1) { index = bucketizeValue(wt * 100.0); hist[1][index]++; if (histEg[1][index] == null) { histEg[1][index] = feat; } if (wt < 0.001 && wt >= -0.001) { index = bucketizeValue(wt * 10000.0); hist[2][index]++; if (histEg[2][index] == null) { histEg[2][index] = feat; } } } } } double ave = total / num; double stddev = (x2total / num) - ave * ave; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Linear classifier with " + num + " f(x,y) features"); pw.println("Average weight: " + ave + "; std dev: " + stddev); pw.println("Max weight: " + max + " min weight: " + min); pw.println("Weights: " + neg + " negative; " + pos + " positive; " + zero + " zero."); printHistCounts(0, "Counts of lambda parameters between [-10, 10)", pw, hist, histEg); printHistCounts(1, "Closeup view of [-0.1, 0.1) depicted * 10^2", pw, hist, histEg); printHistCounts(2, "Closeup view of [-0.001, 0.001) depicted * 10^4", pw, hist, histEg); pw.close(); return sw.toString(); } /** Print out a partial representation of a linear classifier. * This just calls toString("WeightHistogram", 0) */ @Override public String toString() { return toString("WeightHistogram", 0); } /** * Print out a partial representation of a linear classifier in one of * several ways. * * @param style Options are: * HighWeight: print out the param parameters with largest weights; * HighMagnitude: print out the param parameters for which the absolute * value of their weight is largest; * AllWeights: print out the weights of all features; * WeightHistogram: print out a particular hard-coded textual histogram * representation of a classifier; * WeightDistribution; * * @param param Determines the number of things printed in certain styles * @throws IllegalArgumentException if the style name is unrecognized */ public String toString(String style, int param) { if (style == null || style.isEmpty()) { return "LinearClassifier with " + featureIndex.size() + " features, " + labelIndex.size() + " classes, and " + labelIndex.size() * featureIndex.size() + " parameters.\n"; } else if (style.equalsIgnoreCase("HighWeight")) { return toBiggestWeightFeaturesString(false, param, true); } else if (style.equalsIgnoreCase("HighMagnitude")) { return toBiggestWeightFeaturesString(true, param, true); } else if (style.equalsIgnoreCase("AllWeights")) { return toAllWeightsString(); } else if (style.equalsIgnoreCase("WeightHistogram")) { return toHistogramString(); } else if (style.equalsIgnoreCase("WeightDistribution")) { return toDistributionString(param); } else { throw new IllegalArgumentException("Unknown style: " + style); } } /** * Convert parameter value into number between 0 and 201 */ private static int bucketizeValue(double wt) { int index; if (wt >= 0.0) { index = ((int) (wt * 10.0)) + 100; } else { index = ((int) (Math.floor(wt * 10.0))) + 100; } if (index < 0) { index = 201; } else if (index > 200) { index = 200; } return index; } /** * Print histogram counts from hist and examples over a certain range */ private static void printHistCounts(int ind, String title, PrintWriter pw, double[][] hist, Object[][] histEg) { pw.println(title); for (int i = 0; i < 200; i++) { int intPart, fracPart; if (i < 100) { intPart = 10 - ((i + 9) / 10); fracPart = (10 - (i % 10)) % 10; } else { intPart = (i / 10) - 10; fracPart = i % 10; } pw.print("[" + ((i < 100) ? "-" : "") + intPart + "." + fracPart + ", " + ((i < 100) ? "-" : "") + intPart + "." + fracPart + "+0.1): " + hist[ind][i]); if (histEg[ind][i] != null) { pw.print(" [" + histEg[ind][i] + ((hist[ind][i] > 1) ? ", ..." : "") + "]"); } pw.println(); } } //TODO: Sort of assumes that Labels are Strings... public String toAllWeightsString() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Linear classifier with the following weights"); Datum<L, F> allFeatures = new BasicDatum<>(features(), (L) null); justificationOf(allFeatures, pw); return sw.toString(); } /** * Print all features in the classifier and the weight that they assign * to each class. Print to stderr. */ public void dump() { Datum<L, F> allFeatures = new BasicDatum<>(features(), (L) null); justificationOf(allFeatures); } /** * Print all features in the classifier and the weight that they assign * to each class. Print to the given PrintWriter. */ public void dump(PrintWriter pw) { Datum<L, F> allFeatures = new BasicDatum<>(features(), (L) null); justificationOf(allFeatures, pw); } /** * Print all features in the classifier and the weight that they assign * to each class. The feature names are printed in sorted order. */ public void dumpSorted() { Datum<L, F> allFeatures = new BasicDatum<>(features(), (L) null); justificationOf(allFeatures, new PrintWriter(System.err, true), true); } /** * Print all features active for a particular datum and the weight that * the classifier assigns to each class for those features. */ private void justificationOfRVFDatum(RVFDatum<L, F> example, PrintWriter pw) { int featureLength = 0; int labelLength = 6; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); if (nf instanceof DecimalFormat) { ((DecimalFormat) nf).setPositivePrefix(" "); } Counter<F> features = example.asFeaturesCounter(); for (F f : features.keySet()) { featureLength = Math.max(featureLength, f.toString().length() + 2 + nf.format(features.getCount(f)).length()); } // make as wide as total printout featureLength = Math.max(featureLength, "Total:".length()); // don't make it ridiculously wide featureLength = Math.min(featureLength, MAX_FEATURE_ALIGN_WIDTH); for (L l : labels()) { labelLength = Math.max(labelLength, l.toString().length()); } StringBuilder header = new StringBuilder(); for (int s = 0; s < featureLength; s++) { header.append(' '); } for (L l : labels()) { header.append(' '); header.append(StringUtils.pad(l, labelLength)); } pw.println(header); for (F f : features.keySet()) { String fStr = f.toString(); StringBuilder line = new StringBuilder(fStr); line.append("[").append(nf.format(features.getCount(f))).append("]"); fStr = line.toString(); for (int s = fStr.length(); s < featureLength; s++) { line.append(' '); } for (L l : labels()) { String lStr = nf.format(weight(f, l)); line.append(' '); line.append(lStr); for (int s = lStr.length(); s < labelLength; s++) { line.append(' '); } } pw.println(line); } Counter<L> scores = scoresOfRVFDatum(example); StringBuilder footer = new StringBuilder("Total:"); for (int s = footer.length(); s < featureLength; s++) { footer.append(' '); } for (L l : labels()) { footer.append(' '); String str = nf.format(scores.getCount(l)); footer.append(str); for (int s = str.length(); s < labelLength; s++) { footer.append(' '); } } pw.println(footer); Distribution<L> distr = Distribution.distributionFromLogisticCounter(scores); footer = new StringBuilder("Prob:"); for (int s = footer.length(); s < featureLength; s++) { footer.append(' '); } for (L l : labels()) { footer.append(' '); String str = nf.format(distr.getCount(l)); footer.append(str); for (int s = str.length(); s < labelLength; s++) { footer.append(' '); } } pw.println(footer); } public void justificationOf(Datum<L, F> example) { PrintWriter pw = new PrintWriter(System.err, true); justificationOf(example, pw); } /** * Print all features active for a particular datum and the weight that * the classifier assigns to each class for those features. */ public void justificationOf(Datum<L, F> example, PrintWriter pw) { justificationOf(example, pw, null); } /** * Print all features active for a particular datum and the weight that * the classifier assigns to each class for those features. Sorts by feature * name if 'sorted' is true. */ public void justificationOf(Datum<L, F> example, PrintWriter pw, boolean sorted) { if(example instanceof RVFDatum<?, ?>) justificationOf(example, pw, null, sorted); } public <T> void justificationOf(Datum<L, F> example, PrintWriter pw, Function<F, T> printer) { justificationOf(example, pw, printer, false); } /** Print all features active for a particular datum and the weight that * the classifier assigns to each class for those features. * * @param example The datum for which features are to be printed * @param pw Where to print it to * @param printer If this is non-null, then it is applied to each * feature to convert it to a more readable form * @param sortedByFeature Whether to sort by feature names */ public <T> void justificationOf(Datum<L, F> example, PrintWriter pw, Function<F, T> printer, boolean sortedByFeature) { if(example instanceof RVFDatum<?, ?>) { justificationOfRVFDatum((RVFDatum<L,F>)example,pw); return; } NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); if (nf instanceof DecimalFormat) { ((DecimalFormat) nf).setPositivePrefix(" "); } // determine width for features, making it at least total's width int featureLength = 0; //TODO: not really sure what this Printer is supposed to spit out... for (F f : example.asFeatures()) { int length = f.toString().length(); if (printer != null) { length = printer.apply(f).toString().length(); } featureLength = Math.max(featureLength, length); } // make as wide as total printout featureLength = Math.max(featureLength, "Total:".length()); // don't make it ridiculously wide featureLength = Math.min(featureLength, MAX_FEATURE_ALIGN_WIDTH); // determine width for labels int labelLength = 6; for (L l : labels()) { labelLength = Math.max(labelLength, l.toString().length()); } // print header row of output listing classes StringBuilder header = new StringBuilder(""); for (int s = 0; s < featureLength; s++) { header.append(' '); } for (L l : labels()) { header.append(' '); header.append(StringUtils.pad(l, labelLength)); } pw.println(header); // print active features and weights per class Collection<F> featColl = example.asFeatures(); if (sortedByFeature){ featColl = ErasureUtils.sortedIfPossible(featColl); } for (F f : featColl) { String fStr; if (printer != null) { fStr = printer.apply(f).toString(); } else { fStr = f.toString(); } StringBuilder line = new StringBuilder(fStr); for (int s = fStr.length(); s < featureLength; s++) { line.append(' '); } for (L l : labels()) { String lStr = nf.format(weight(f, l)); line.append(' '); line.append(lStr); for (int s = lStr.length(); s < labelLength; s++) { line.append(' '); } } pw.println(line); } // Print totals, probs, etc. Counter<L> scores = scoresOf(example); StringBuilder footer = new StringBuilder("Total:"); for (int s = footer.length(); s < featureLength; s++) { footer.append(' '); } for (L l : labels()) { footer.append(' '); String str = nf.format(scores.getCount(l)); footer.append(str); for (int s = str.length(); s < labelLength; s++) { footer.append(' '); } } pw.println(footer); Distribution<L> distr = Distribution.distributionFromLogisticCounter(scores); footer = new StringBuilder("Prob:"); for (int s = footer.length(); s < featureLength; s++) { footer.append(' '); } for (L l : labels()) { footer.append(' '); String str = nf.format(distr.getCount(l)); footer.append(str); for (int s = str.length(); s < labelLength; s++) { footer.append(' '); } } pw.println(footer); } /** * This method returns a map from each label to a counter of feature weights for that label. * Useful for feature analysis. * * @return a map of counters */ public Map<L,Counter<F>> weightsAsMapOfCounters() { Map<L,Counter<F>> mapOfCounters = Generics.newHashMap(); for(L label : labelIndex){ int labelID = labelIndex.indexOf(label); Counter<F> c = new ClassicCounter<>(); mapOfCounters.put(label, c); for (F f : featureIndex) { c.incrementCount(f, weights[featureIndex.indexOf(f)][labelID]); } } return mapOfCounters; } public Counter<L> scoresOf(Datum<L, F> example, Collection<L> possibleLabels) { Counter<L> scores = new ClassicCounter<>(); for (L l : possibleLabels) { if (labelIndex.indexOf(l) == -1) { continue; } double score = scoreOf(example, l); scores.setCount(l, score); } return scores; } /* -- looks like a failed attempt at micro-optimization -- public L experimentalClassOf(Datum<L,F> example) { if(example instanceof RVFDatum<?, ?>) { throw new UnsupportedOperationException(); } int labelCount = weights[0].length; //System.out.printf("labelCount: %d\n", labelCount); Collection<F> features = example.asFeatures(); int[] featureInts = new int[features.size()]; int fI = 0; for (F feature : features) { featureInts[fI++] = featureIndex.indexOf(feature); } //System.out.println("Features: "+features); double bestScore = Double.NEGATIVE_INFINITY; int bestI = 0; for (int i = 0; i < labelCount; i++) { double score = 0; for (int j = 0; j < featureInts.length; j++) { if (featureInts[j] < 0) continue; score += weights[featureInts[j]][i]; } if (score > bestScore) { bestI = i; bestScore = score; } //System.out.printf("Score: %s(%d): %e\n", labelIndex.get(i), i, score); } //System.out.printf("label(%d): %s\n", bestI, labelIndex.get(bestI));; return labelIndex.get(bestI); } -- */ @Override public L classOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return classOfRVFDatum((RVFDatum<L,F>)example); Counter<L> scores = scoresOf(example); return Counters.argmax(scores); } private L classOfRVFDatum(RVFDatum<L, F> example) { Counter<L> scores = scoresOfRVFDatum(example); return Counters.argmax(scores); } @Override @Deprecated public L classOf(RVFDatum<L, F> example) { Counter<L> scores = scoresOf(example); return Counters.argmax(scores); } /** For Kryo -- can be private */ private LinearClassifier() { } /** Make a linear classifier from the parameters. The parameters are used, not copied. * * @param weights The parameters of the classifier. The first index is the * featureIndex value and second index is the labelIndex value. * @param featureIndex An index from F to integers used to index the features in the weights array * @param labelIndex An index from L to integers used to index the labels in the weights array */ public LinearClassifier(double[][] weights, Index<F> featureIndex, Index<L> labelIndex) { this.featureIndex = featureIndex; this.labelIndex = labelIndex; this.weights = weights; thresholds = new double[labelIndex.size()]; Arrays.fill(thresholds, 0.0); } // todo: This is unused and seems broken (ignores passed in thresholds) public LinearClassifier(double[][] weights, Index<F> featureIndex, Index<L> labelIndex, double[] thresholds) throws Exception { this.featureIndex = featureIndex; this.labelIndex = labelIndex; this.weights = weights; if (thresholds.length != labelIndex.size()) throw new Exception("Number of thresholds and number of labels do not match."); thresholds = new double[thresholds.length]; int curr = 0; for (double tval : thresholds) { thresholds[curr++] = tval; } Arrays.fill(thresholds, 0.0); } private static <F, L> Counter<Pair<F, L>> makeWeightCounter(double[] weights, Index<Pair<F, L>> weightIndex) { Counter<Pair<F,L>> weightCounter = new ClassicCounter<>(); for (int i = 0; i < weightIndex.size(); i++) { if (weights[i] == 0) { continue; // no need to save 0 weights } weightCounter.setCount(weightIndex.get(i), weights[i]); } return weightCounter; } public LinearClassifier(double[] weights, Index<Pair<F, L>> weightIndex) { this(makeWeightCounter(weights, weightIndex)); } public LinearClassifier(Counter<? extends Pair<F, L>> weightCounter) { this(weightCounter, new ClassicCounter<>()); } public LinearClassifier(Counter<? extends Pair<F, L>> weightCounter, Counter<L> thresholdsC) { Collection<? extends Pair<F, L>> keys = weightCounter.keySet(); featureIndex = new HashIndex<>(); labelIndex = new HashIndex<>(); for (Pair<F, L> p : keys) { featureIndex.add(p.first()); labelIndex.add(p.second()); } thresholds = new double[labelIndex.size()]; for (L label : labelIndex) { thresholds[labelIndex.indexOf(label)] = thresholdsC.getCount(label); } weights = new double[featureIndex.size()][labelIndex.size()]; Pair<F, L> tempPair = new Pair<>(); for (int f = 0; f < weights.length; f++) { for (int l = 0; l < weights[f].length; l++) { tempPair.first = featureIndex.get(f); tempPair.second = labelIndex.get(l); weights[f][l] = weightCounter.getCount(tempPair); } } } public void adaptWeights(Dataset<L, F> adapt,LinearClassifierFactory<L, F> lcf) { logger.info("before adapting, weights size="+weights.length); weights = lcf.adaptWeights(weights,adapt); logger.info("after adapting, weights size=" + weights.length); } public double[][] weights() { return weights; } public void setWeights(double[][] newWeights) { weights = newWeights; } /** * Loads a classifier from a file. * Simple convenience wrapper for IOUtils.readFromString. */ public static <L, F> LinearClassifier<L, F> readClassifier(String loadPath) { log.info("Deserializing classifier from " + loadPath + "..."); try { ObjectInputStream ois = IOUtils.readStreamFromString(loadPath); LinearClassifier<L, F> classifier = ErasureUtils.<LinearClassifier<L, F>>uncheckedCast(ois.readObject()); ois.close(); return classifier; } catch (Exception e) { throw new RuntimeException("Deserialization failed: "+e.getMessage(), e); } } /** * Convenience wrapper for IOUtils.writeObjectToFile */ public static void writeClassifier(LinearClassifier<?, ?> classifier, String writePath) { try { IOUtils.writeObjectToFile(classifier, writePath); } catch (Exception e) { throw new RuntimeException("Serialization failed: "+e.getMessage(), e); } } /** * Saves this out to a standard text file, instead of as a serialized Java object. * NOTE: this currently assumes feature and weights are represented as Strings. * @param file String filepath to write out to. */ public void saveToFilename(String file) { try { File tgtFile = new File(file); BufferedWriter out = new BufferedWriter(new FileWriter(tgtFile)); // output index first, blank delimiter, outline feature index, then weights labelIndex.saveToWriter(out); featureIndex.saveToWriter(out); int numLabels = labelIndex.size(); int numFeatures = featureIndex.size(); for (int featIndex=0; featIndex<numFeatures; featIndex++) { for (int labelIndex=0;labelIndex<numLabels;labelIndex++) { out.write(String.valueOf(featIndex)); out.write(TEXT_SERIALIZATION_DELIMITER); out.write(String.valueOf(labelIndex)); out.write(TEXT_SERIALIZATION_DELIMITER); out.write(String.valueOf(weight(featIndex, labelIndex))); out.write("\n"); } } // write out thresholds: first item after blank is the number of thresholds, after is the threshold array values. out.write("\n"); out.write(String.valueOf(thresholds.length)); out.write("\n"); for (double val : thresholds) { out.write(String.valueOf(val)); out.write("\n"); } out.close(); } catch (Exception e) { logger.info("Error attempting to save classifier to file=" + file); e.printStackTrace(); } } }
gpl-2.0
snookle/browseforspeed
website/src/net/whatsbeef/client/screenshots.java
265
package net.whatsbeef.client; import java.util.ArrayList; import com.google.gwt.user.client.ui.*; public class screenshots { public static HTML getHTML () { String html = "<div class='page'><img src='img/screenshot.png' /></div>"; return new HTML(html); } }
gpl-2.0