answer
stringlengths
17
10.2M
package com.eyekabob; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.eyekabob.util.DocumentTask; import com.eyekabob.util.JSONTask; import com.eyekabob.util.LastFMUtil; import com.eyekabob.util.NiceNodeList; import com.phonegap.api.LOG; public class EventResults extends EyekabobActivity { private Dialog alertDialog; ArrayAdapter<String> adapter; private Map<String, String> eventMap; private OnItemClickListener listItemListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String event = ((TextView) view).getText().toString(); Intent intent = new Intent(getApplicationContext(), Event.class); Map<String, String> params = new HashMap<String, String>(); params.put("event", eventMap.get(event)); intent.setData(EyekabobHelper.LastFM.getUri("event.getInfo", params)); startActivity(intent); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.eventlistactivity); adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item); ListView lv = (ListView)findViewById(R.id.eventsList); lv.setAdapter(adapter); Uri uri = this.getIntent().getData(); if (getIntent().hasExtra("zip")) { // Search by zip. String zip = getIntent().getExtras().getString("zip"); if (EyekabobHelper.zipToNameMap.containsKey(zip)) { LOG.d(getClass().getName(), "Using cached zip"); Uri lastFMURI = getLastFMURI(EyekabobHelper.zipToNameMap.get("zip")); sendDocumentRequest(lastFMURI.toString()); } else { LOG.d(getClass().getName(), "Getting zip from geonames service"); sendJSONRequest(uri.toString()); } } else { LOG.d(getClass().getName(), "Searching for events using current location"); sendDocumentRequest(uri.toString()); } lv.setTextFilterEnabled(true); lv.setOnItemClickListener(listItemListener); } // TODO: use dialogfragment to show dialog protected void createDialog() { Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.searching); builder.setCancelable(false); alertDialog = builder.create(); alertDialog.setOwnerActivity(this); } protected void loadEvents(Document doc) { if (doc == null) { Toast.makeText(getApplicationContext(), R.string.no_results, Toast.LENGTH_LONG).show(); return; } NodeList events = doc.getElementsByTagName("event"); if (events.getLength() == 0) { Toast.makeText(getApplicationContext(), R.string.no_results, Toast.LENGTH_LONG).show(); return; } eventMap = new HashMap<String, String>(); for (int i = 0; i < events.getLength(); i++) { Node eventNode = events.item(i); NiceNodeList eventNodeList = new NiceNodeList(eventNode.getChildNodes()); Map<String, Node> eventNodes = eventNodeList.get("title", "id", "venue", "startDate"); NiceNodeList venueNodeList = new NiceNodeList(eventNodes.get("venue").getChildNodes()); Map<String, Node> venueNodes = venueNodeList.get("name", "location"); NiceNodeList locationNodeList = new NiceNodeList(venueNodes.get("location").getChildNodes()); Map<String, Node> locationNodes = locationNodeList.get("city", "geo:point"); long distance = -1; if (!getIntent().hasExtra("showDistance") || getIntent().getExtras().getBoolean("showDistance", true)) { NiceNodeList geoNodeList = new NiceNodeList(locationNodes.get("geo:point").getChildNodes()); Map<String, Node> geoNodes = geoNodeList.get("geo:lat", "geo:long"); Node lat = geoNodes.get("geo:lat"); Node lon = geoNodes.get("geo:long"); if (lat != null && lon != null) { String latStr = lat.getTextContent(); String lonStr = lon.getTextContent(); if (!"".equals(latStr) && !"".equals(lonStr)) { distance = EyekabobHelper.getDistance(Double.parseDouble(latStr), Double.parseDouble(lonStr), this); } } } String distanceStr = ""; if (distance != -1) { distanceStr = "\n" + distance + " mi"; } String title = eventNodes.get("title").getTextContent() + "\n"; String startDate = LastFMUtil.toReadableDate(eventNodes.get("startDate").getTextContent()); String venue = ""; if (!getIntent().hasExtra("showVenue") || getIntent().getExtras().getBoolean("showVenue", true)) { venue = venueNodes.get("name").getTextContent() + "\n"; } String city = ""; if (!getIntent().hasExtra("showCity") || getIntent().getExtras().getBoolean("showCity", true)) { city = locationNodes.get("city").getTextContent() + "\n"; } adapter.add(title + venue + city + startDate + distanceStr); eventMap.put(title + venue + city + startDate + distanceStr, eventNodes.get("id").getTextContent()); } } protected void sendJSONRequest(String uri) { new JSONRequestTask().execute(uri); } protected void sendDocumentRequest(String uri) { new DocumentRequestTask().execute(uri); } protected Uri getLastFMURI(String location) { Map<String, String> params = new HashMap<String, String>(); params.put("location", location); params.put("distance", (String)getIntent().getExtras().get("distance")); return EyekabobHelper.LastFM.getUri("geo.getEvents", params); } private class JSONRequestTask extends JSONTask { protected void onPreExecute() { if (alertDialog == null) { EventResults.this.createDialog(); } if (!alertDialog.isShowing()) { alertDialog.show(); } } protected void onPostExecute(JSONObject result) { String location = null; try { JSONArray locations = (JSONArray)result.get("postalcodes"); JSONObject jsonLocation = (JSONObject)locations.get(0); location = (String)jsonLocation.get("placeName"); } catch (JSONException e) { e.printStackTrace(); } Uri uri = EventResults.this.getLastFMURI(location); EventResults.this.sendDocumentRequest(uri.toString()); } } // Handles the asynchronous request, away from the UI thread. private class DocumentRequestTask extends DocumentTask { protected void onPreExecute() { if (alertDialog == null) { EventResults.this.createDialog(); } if (!alertDialog.isShowing()) { alertDialog.show(); } } protected void onPostExecute(Document result) { alertDialog.dismiss(); EventResults.this.loadEvents(result); } } }
package com.github.kevinsawicki.http; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * A fluid interface for making HTTP requests using an underlying * {@link HttpURLConnection} (or sub-class). */ public class HttpRequest { /** * 'UTF-8' charset name */ public static final String CHARSET_UTF8 = "UTF-8"; /** * 'Accept' header name */ public static final String HEADER_ACCEPT = "Accept"; /** * 'Accept-Charset' header name */ public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; /** * 'Accept-Encoding' header name */ public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; /** * 'Authentication' header name */ public static final String HEADER_AUTHENTICATION = "Authentication"; /** * 'Cache-Control' header name */ public static final String HEADER_CACHE_CONTROL = "Cache-Control"; /** * 'Content-Encoding' header name */ public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; /** * 'Content-Length' header name */ public static final String HEADER_CONTENT_LENGTH = "Content-Length"; /** * 'Content-Type' header name */ public static final String HEADER_CONTENT_TYPE = "Content-Type"; /** * 'Date' header name */ public static final String HEADER_DATE = "Date"; /** * 'ETag' header name */ public static final String HEADER_ETAG = "ETag"; /** * 'Expires' header name */ public static final String HEADER_EXPIRES = "Expires"; /** * 'Host' header name */ public static final String HEADER_HOST = "Host"; /** * 'Last-Modified' header name */ public static final String HEADER_LAST_MODIFIED = "Last-Modified"; /** * 'Location' header name */ public static final String HEADER_LOCATION = "Location"; /** * 'Server' header name */ public static final String HEADER_SERVER = "Server"; /** * 'User-Agent' header name */ public static final String HEADER_USER_AGENT = "User-Agent"; /** * 'GET' request method */ public static final String METHOD_GET = "GET"; /** * 'HEAD' request method */ public static final String METHOD_HEAD = "HEAD"; /** * 'DELETE' request method */ public static final String METHOD_DELETE = "DELETE"; /** * 'OPTIONS' options method */ public static final String METHOD_OPTIONS = "OPTIONS"; /** * 'POST' request method */ public static final String METHOD_POST = "POST"; /** * 'PUT' request method */ public static final String METHOD_PUT = "PUT"; /** * 'TRACE' request method */ public static final String METHOD_TRACE = "TRACE"; /** * 'charset' header value parameter */ public static final String PARAM_CHARSET = "charset"; private static final String BOUNDARY = "----1010101010"; private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=" + BOUNDARY; private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; public static class Base64 { /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; /** The 64 valid Base64 values. */ /* * Host platform me be something funny like EBCDIC, so we hardcode these * values. */ private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; /** Defeats instantiation. */ private Base64() { } /** * <p> * Encodes up to three bytes of the array <var>source</var> and writes * the resulting four Base64 bytes to <var>destination</var>. The source * and destination arrays can be manipulated anywhere along their length * by specifying <var>srcOffset</var> and <var>destOffset</var>. This * method does not check to make sure your arrays are large enough to * accomodate <var>srcOffset</var> + 3 for the <var>source</var> array * or <var>destOffset</var> + 4 for the <var>destination</var> array. * The actual number of significant bytes in your array is given by * <var>numSigBytes</var>. * </p> * <p> * This is the lowest level of the encoding methods with all possible * parameters. * </p> * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param numSigBytes * the number of significant bytes in your array * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { byte[] ALPHABET = _STANDARD_ALPHABET; // 1 2 3 // 01234567890123456789012345678901 Bit position // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that // appear // when Java treats a value as negative that is cast from a byte to // an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } } /** * Encode string as a byte array in Base64 annotation. * * @param string * @return The Base64-encoded data as a string */ public static String encode(String string) { byte[] bytes; try { bytes = string.getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { bytes = string.getBytes(); } return encodeBytes(bytes); } public static String encodeBytes(byte[] source) { return encodeBytes(source, 0, source.length); } public static String encodeBytes(byte[] source, int off, int len) { byte[] encoded = encodeBytesToBytes(source, off, len); // Return value according to relevant encoding. try { return new String(encoded, PREFERRED_ENCODING); } catch (UnsupportedEncodingException uue) { return new String(encoded); } } // end encodeBytes public static byte[] encodeBytesToBytes(byte[] source, int off, int len) { if (source == null) throw new NullPointerException("Cannot serialize a null array."); if (off < 0) throw new IllegalArgumentException( "Cannot have negative offset: " + off); if (len < 0) throw new IllegalArgumentException( "Cannot have length offset: " + len); if (off + len > source.length) throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); // Bytes needed for actual encoding int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); byte[] outBuff = new byte[encLen]; int d = 0; int e = 0; int len2 = len - 2; for (; d < len2; d += 3, e += 4) encode3to4(source, d + off, 3, outBuff, e); if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } // Only resize array if we didn't guess it right. if (e <= outBuff.length - 1) { // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff, 0, finalOut, 0, e); return finalOut; } else return outBuff; } } /** * Request exception */ public static class RequestException extends RuntimeException { /** serialVersionUID */ private static final long serialVersionUID = -1170466989781746231L; /** * @param message * @param cause */ public RequestException(String message, Throwable cause) { super(message, cause); } /** * @param message */ public RequestException(String message) { super(message); } /** * @param cause */ public RequestException(Throwable cause) { super(cause); } } /** * Request output stream */ public static class RequestOutputStream extends BufferedOutputStream { private final Charset charset; /** * Create request output stream * * @param stream * @param charsetName */ public RequestOutputStream(OutputStream stream, String charsetName) { super(stream); if (charsetName == null) charsetName = CHARSET_UTF8; charset = Charset.forName(charsetName); } /** * Write string to stream * * @param value * @return this stream * @throws IOException */ public RequestOutputStream write(String value) throws IOException { super.write(value.getBytes(charset)); return this; } } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest get(String url) throws RequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest get(URL url) throws RequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest post(String url) throws RequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest post(URL url) throws RequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest put(String url) throws RequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest put(URL url) throws RequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest delete(String url) throws RequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest delete(URL url) throws RequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest head(String url) throws RequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest head(URL url) throws RequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'OPTIONS' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest options(String url) throws RequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start a 'OPTIONS' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest options(URL url) throws RequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest trace(String url) throws RequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws RequestException */ public static HttpRequest trace(URL url) throws RequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Set the 'http.keepAlive' property to the given value. * <p> * This setting will apply to requests. * * @param keepAlive */ public static void keepAlive(boolean keepAlive) { System.setProperty("http.keepAlive", Boolean.toString(keepAlive)); } private final HttpURLConnection connection; private RequestOutputStream output; private boolean multipart; private boolean form; private int bufferSize = 8192; /** * Create HTTP connection wrapper * * @param url * @param method * @throws RequestException */ public HttpRequest(final String url, final String method) throws RequestException { try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(method); } catch (IOException e) { throw new RequestException(e); } } /** * Create HTTP connection wrapper * * @param url * @param method * @throws RequestException */ public HttpRequest(final URL url, final String method) throws RequestException { try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); } catch (IOException e) { throw new RequestException(e); } } public String toString() { return connection.getRequestMethod() + " " + connection.getURL(); } /** * Get underlying connection * * @return connection */ public HttpURLConnection getConnection() { return connection; } /** * Get the status code of the response * * @return this request * @throws RequestException */ public int code() throws RequestException { try { closeOutput(); return connection.getResponseCode(); } catch (IOException e) { throw new RequestException(e); } } /** * Is the response code a 200 OK? * * @return true if 200, false otherwise * @throws RequestException */ public boolean ok() throws RequestException { return HttpURLConnection.HTTP_OK == code(); } /** * Is the response code a 201 Created? * * @return true if 201, false otherwise * @throws RequestException */ public boolean created() throws RequestException { return HttpURLConnection.HTTP_CREATED == code(); } /** * Get status message of the response * * @return message * @throws RequestException */ public String message() throws RequestException { try { closeOutput(); return connection.getResponseMessage(); } catch (IOException e) { throw new RequestException(e); } } /** * Disconnect the connection * * @return this request */ public HttpRequest disconnect() { connection.disconnect(); return this; } /** * Set chunked streaming mode to the given size * * @param size * @return this request */ public HttpRequest chunk(final int size) { connection.setChunkedStreamingMode(size); return this; } /** * Set the buffer size used when copying between streams * * @param size * @return this request */ public HttpRequest bufferSize(final int size) { if (size < 1) throw new IllegalArgumentException("Size must be greater than zero"); bufferSize = size; return this; } /** * Get response as String in given charset. * <p> * This will fallback to using the platform's default character if the given * charset is null. * * @param charset * @return string * @throws RequestException */ public String body(final String charset) throws RequestException { final ByteArrayOutputStream output = new ByteArrayOutputStream( contentLength()); copy(buffer(), output); if (charset != null) try { return output.toString(charset); } catch (UnsupportedEncodingException e) { throw new RequestException(e); } else return output.toString(); } /** * Get response as String using character returned from {@link #charset()} * * @return string * @throws RequestException */ public String body() throws RequestException { return body(charset()); } /** * Get response as byte array * * @return byte array * @throws RequestException */ public byte[] bytes() throws RequestException { final ByteArrayOutputStream output = new ByteArrayOutputStream( contentLength()); copy(buffer(), output); return output.toByteArray(); } /** * Get response in a buffered stream * * @return stream * @throws RequestException */ public BufferedInputStream buffer() throws RequestException { return new BufferedInputStream(stream()); } /** * Get stream to response body * * @return stream * @throws RequestException */ public InputStream stream() throws RequestException { try { return connection.getInputStream(); } catch (IOException e) { throw new RequestException(e); } } /** * Get reader to response body using given character set. * <p> * This will fallback to using the platform's default character if the given * charset is null. * * @param charset * @return reader * @throws RequestException */ public InputStreamReader reader(final String charset) throws RequestException { final InputStream stream = stream(); if (charset != null) try { return new InputStreamReader(stream, charset); } catch (UnsupportedEncodingException e) { throw new RequestException(e); } else return new InputStreamReader(stream); } /** * Get response to response body using the character set returned from * {@link #charset()} * * @return reader * @throws RequestException */ public InputStreamReader reader() throws RequestException { return reader(charset()); } /** * Stream response body to file * * @param file * @return this request */ public HttpRequest body(final File file) { final OutputStream output; try { output = new BufferedOutputStream(new FileOutputStream(file)); } catch (FileNotFoundException e) { throw new RequestException(e); } try { return stream(output); } finally { try { output.close(); } catch (IOException e) { throw new RequestException(e); } } } /** * Stream response to given output stream * * @param output * @return this request */ public HttpRequest stream(final OutputStream output) { return copy(buffer(), output); } /** * Get error stream to response * * @return stream */ public InputStream errorStream() { return connection.getErrorStream(); } /** * Get error stream as string * * @return error string * @throws RequestException */ public String errorString() throws RequestException { final InputStream stream = errorStream(); if (stream == null) return ""; final ByteArrayOutputStream output = new ByteArrayOutputStream( contentLength()); copy(buffer(), output); final String charset = charset(); if (charset == null) return output.toString(); try { return output.toString(charset); } catch (UnsupportedEncodingException e) { throw new RequestException(e); } } /** * Set read timeout on connection to value * * @param timeout * @return this request */ public HttpRequest readTimeout(final int timeout) { connection.setReadTimeout(timeout); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final String value) { connection.setRequestProperty(name, value); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final Number value) { return header(name, value.toString()); } /** * Set header names to given values. * <p> * Each name should be followed by the corresponding value and the number of * arguments must be divisible by 2. * * @param headers * @return this request */ public HttpRequest headers(final String... headers) { if (headers == null || headers.length == 0 || headers.length % 2 != 0) throw new IllegalArgumentException( "Headers must be non-null, non-empty and divisible by two"); for (int i = 0; i < headers.length; i += 2) header(headers[i], headers[i + 1]); return this; } /** * Get a response header * * @param name * @return response header */ public String header(final String name) { return connection.getHeaderField(name); } /** * Get a date header from the response * * @param name * @return date, -1 on failures */ public long dateHeader(final String name) { return connection.getHeaderFieldDate(name, -1L); } /** * Get an integer header from the response * * @param name * @return integer, -1 on failures */ public int intHeader(final String name) { return connection.getHeaderFieldInt(name, -1); } /** * Get parameter value from header * * @param value * @param paramName * @return parameter value or null if none */ protected String getParam(final String value, final String paramName) { if (value == null || value.length() == 0) return null; int postSemi = value.indexOf(';') + 1; if (postSemi > 0 && postSemi == value.length()) return null; String[] params = value.substring(postSemi).trim().split(";"); for (String param : params) { String[] split = param.split("="); if (split.length != 2) continue; if (!paramName.equals(split[0])) continue; String charset = split[1]; int length = charset.length(); if (length == 0) continue; if (length > 2 && '"' == charset.charAt(0) && '"' == charset.charAt(length - 1)) charset = charset.substring(1, length - 1); return charset; } return null; } /** * Get 'charset' parameter from 'Content-Type' response header * * @return charset or null if none */ public String charset() { return getParam(contentType(), PARAM_CHARSET); } /** * Set the 'User-Agent' header to given value * * @param value * @return this request */ public HttpRequest userAgent(final String value) { return header(HEADER_USER_AGENT, value); } /** * Set the 'Host' header to given value * * @param value * @return this request */ public HttpRequest host(final String value) { return header(HEADER_HOST, value); } /** * Set the 'Accept-Encoding' header to given value * * @param value * @return this request */ public HttpRequest acceptEncoding(final String value) { return header(HEADER_ACCEPT_ENCODING, value); } /** * Set the 'Accept-Charset' header to given value * * @param value * @return this request */ public HttpRequest acceptCharset(final String value) { return header(HEADER_ACCEPT_CHARSET, value); } /** * Get the 'Content-Encoding' header from the response * * @return this request */ public String contentEncoding() { return header(HEADER_CONTENT_ENCODING); } /** * Get the 'Server' header from the response * * @return server */ public String server() { return header(HEADER_SERVER); } /** * Get the 'Date' header from the response * * @return date value, -1 on failures */ public long date() { return dateHeader(HEADER_DATE); } /** * Get the 'Cache-Control' header from the response * * @return cache control */ public String cacheControl() { return header(HEADER_CACHE_CONTROL); } /** * Get the 'ETag' header from the response * * @return entity tag */ public String eTag() { return header(HEADER_ETAG); } /** * Get the 'Expires' header from the response * * @return expires value, -1 on failures */ public long expires() { return dateHeader(HEADER_EXPIRES); } /** * Get the 'Last-Modified' header from the response * * @return last modified value, -1 on failures */ public long lastModified() { return dateHeader(HEADER_LAST_MODIFIED); } /** * Get the 'Location' header from the response * * @return location */ public String location() { return header(HEADER_LOCATION); } /** * Set the 'Authentication' header to given value * * @param value * @return this request */ public HttpRequest authentication(final String value) { return header(HEADER_AUTHENTICATION, value); } /** * Set the 'Authentication' header to given values in Basic authentication * format * * @param name * @param password * @return this request */ public HttpRequest basic(final String name, final String password) { return authentication("Basic " + Base64.encode(name + ":" + password)); } /** * Set the 'Content-Type' request header to the given value * * @param value * @return this request */ public HttpRequest contentType(final String value) { return header(HEADER_CONTENT_TYPE, value); } /** * Get the 'Content-Type' header from the response * * @return response header value */ public String contentType() { return header(HEADER_CONTENT_TYPE); } /** * Get the 'Content-Type' header from the response * * @return response header value */ public int contentLength() { return intHeader(HEADER_CONTENT_LENGTH); } /** * Set the 'Content-Length' request header to the given value * * @param value * @return this request */ public HttpRequest contentLength(final String value) { final int length = Integer.parseInt(value); return contentLength(length); } /** * Set the 'Content-Length' request header to the given value * * @param value * @return this request */ public HttpRequest contentLength(final int value) { connection.setFixedLengthStreamingMode(value); return this; } /** * Set the 'Accept' header to given value * * @param value * @return this request */ public HttpRequest accept(final String value) { return header(HEADER_ACCEPT, value); } /** * Copy between streams * * @param input * @param output * @return this request * @throws RequestException */ protected HttpRequest copy(final InputStream input, final OutputStream output) throws RequestException { final byte[] buffer = new byte[bufferSize]; int read; try { while ((read = input.read(buffer)) != -1) output.write(buffer, 0, read); } catch (IOException e) { throw new RequestException(e); } finally { try { input.close(); } catch (IOException e) { throw new RequestException(e); } } return this; } /** * Close output stream * * @return this request * @throws RequestException * @throws IOException */ protected HttpRequest closeOutput() throws IOException { if (output == null) return this; if (multipart) output.write("\r\n--" + BOUNDARY + "--\r\n"); output.close(); output = null; return this; } /** * Open output stream * * @return this request * @throws IOException */ protected HttpRequest openOutput() throws IOException { if (output != null) return this; connection.setDoOutput(true); final String charset = getParam( connection.getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET); output = new RequestOutputStream(connection.getOutputStream(), charset); return this; } /** * Start part of a multipart * * @return this request * @throws IOException */ protected HttpRequest startPart() throws IOException { if (!multipart) { multipart = true; contentType(CONTENT_TYPE_MULTIPART).openOutput(); output.write("--" + BOUNDARY + "\r\n"); } else output.write("\r\n--" + BOUNDARY + "\r\n"); return this; } /** * Write part header * * @param name * @param filename * @return this request * @throws IOException */ protected HttpRequest writePartHeader(final String name, final String filename) throws IOException { StringBuilder partBuffer = new StringBuilder(); partBuffer.append("Content-Disposition: form-data; name=\""); partBuffer.append(name); if (filename != null) { partBuffer.append("\";filename=\""); partBuffer.append(filename); } partBuffer.append("\"\r\n\r\n"); output.write(partBuffer.toString()); return this; } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request */ public HttpRequest part(final String name, final String part) { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final String filename, final String part) throws RequestException { try { startPart(); writePartHeader(name, filename); output.write(part); } catch (IOException e) { throw new RequestException(e); } return this; } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final Number part) throws RequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final String filename, final Number part) throws RequestException { try { startPart(); writePartHeader(name, filename); output.write(part.toString()); } catch (IOException e) { throw new RequestException(e); } return this; } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final File part) throws RequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final String filename, final File part) throws RequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(part)); } catch (IOException e) { throw new RequestException(e); } return part(name, filename, stream); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final InputStream part) throws RequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws RequestException */ public HttpRequest part(final String name, final String filename, final InputStream part) throws RequestException { try { startPart(); writePartHeader(name, filename); copy(part, output); } catch (IOException e) { throw new RequestException(e); } return this; } /** * Write a multipart header to the response body * * @param name * @param value * @return this request * @throws RequestException */ public HttpRequest partHeader(String name, String value) throws RequestException { return send(name).send(": ").send(value).send("\r\n\r\n"); } /** * Write contents of file to request body * * @param input * @return this request * @throws RequestException */ public HttpRequest send(final File input) throws RequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(input)); } catch (FileNotFoundException e) { throw new RequestException(e); } return send(stream); } /** * Write byte array to request body * * @param input * @return this request * @throws RequestException */ public HttpRequest send(final byte[] input) throws RequestException { return send(new ByteArrayInputStream(input)); } /** * Write stream to request body * * @param input * @return this request * @throws RequestException */ public HttpRequest send(final InputStream input) throws RequestException { try { openOutput(); copy(input, output); } catch (IOException e) { throw new RequestException(e); } return this; } /** * Write string to request body * <p> * The charset configured via {@link #contentType(String)} will be used and * UTF-8 will be used if it is unset. * * @param value * @return this request * @throws RequestException */ public HttpRequest send(final String value) throws RequestException { try { openOutput(); output.write(value); } catch (IOException e) { throw new RequestException(e); } return this; } /** * Write the values in the map as form data to the request body * <p> * The pair specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param values * @return this request * @throws RequestException */ public HttpRequest form(final Map<?, ?> values) throws RequestException { return form(values, CHARSET_UTF8); } /** * Write the name/value pair as form data to the request body * <p> * The pair specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @return this request * @throws RequestException */ public HttpRequest form(final Object name, final Object value) { return form(name, value, null); } /** * Write the name/value pair as form data to the request body * <p> * The values specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @param charset * @return this request * @throws RequestException */ public HttpRequest form(final Object name, final Object value, final String charset) { return form(Collections.singletonMap(name, value), charset); } /** * Write the values in the map as encoded form data to the request body * * @param values * @param charset * @return this request * @throws RequestException */ public HttpRequest form(final Map<?, ?> values, final String charset) throws RequestException { if (!form) { contentType(CONTENT_TYPE_FORM + ";" + PARAM_CHARSET + "=" + charset); form = true; } if (values.isEmpty()) return this; final Set<?> set = values.entrySet(); @SuppressWarnings({ "unchecked", "rawtypes" }) final Iterator<Entry> entries = (Iterator<Entry>) set.iterator(); try { openOutput(); @SuppressWarnings("rawtypes") Entry entry = entries.next(); output.write(URLEncoder.encode(entry.getKey().toString(), charset)); output.write('='); Object value = entry.getValue(); if (value != null) output.write(URLEncoder.encode(value.toString(), charset)); while (entries.hasNext()) { entry = entries.next(); output.write('&'); output.write(URLEncoder.encode(entry.getKey().toString(), charset)); output.write('='); value = entry.getValue(); if (value != null) output.write(URLEncoder.encode(value.toString(), charset)); } } catch (IOException e) { throw new RequestException(e); } return this; } /** * Configure HTTPS connection to trust all certificates * * @return this request * @throws RequestException */ public HttpRequest trustAllCerts() throws RequestException { if (!(connection instanceof HttpsURLConnection)) return this; final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; final SSLContext context; try { context = SSLContext.getInstance("TLS"); context.init(null, trustAllCerts, new SecureRandom()); } catch (KeyManagementException e) { throw new RequestException(e); } catch (NoSuchAlgorithmException e) { throw new RequestException(e); } ((HttpsURLConnection) connection).setSSLSocketFactory(context .getSocketFactory()); return this; } /** * Configured HTTPS connection to trust all hosts * * @return this request */ public HttpRequest trustAllHosts() { if (!(connection instanceof HttpsURLConnection)) return this; ((HttpsURLConnection) connection) .setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return this; } }
package org.wings.plaf.css; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.plaf.Update; import org.wings.*; import org.wings.event.SRequestListener; import org.wings.event.SRequestEvent; import org.wings.util.SStringBuilder; import org.wings.dnd.DragAndDropManager; import org.wings.header.*; import org.wings.io.Device; import org.wings.plaf.CGManager; import org.wings.plaf.css.script.OnPageRenderedScript; import org.wings.resource.ClassPathResource; import org.wings.resource.ReloadResource; import org.wings.resource.UpdateResource; import org.wings.resource.ResourceNotFoundException; import org.wings.script.*; import org.wings.session.*; import javax.swing.*; import java.io.IOException; import java.util.*; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; /** * PLAF renderer for SFrames. * Does quite many abritriray things i.e. registering diverse service scripts, etc. */ public class FrameCG implements org.wings.plaf.FrameCG { private static final long serialVersionUID = 1L; private final static Log log = LogFactory.getLog(FrameCG.class); public final static String STRICT_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " + "\"http: /** * The HTML DOCTYPE setting all browsers to Quirks mode. We need this to force IE to use the correct box * rendering model. It's the only browser you cannot reconfigure via a CSS tag. */ public final static String QUIRKS_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"; /** * Lookup for a property Stylesheet.BROWSERNAME to know fitting stylesheets */ private static final String PROPERTY_STYLESHEET = "Stylesheet."; private static final String BROWSER_DEFAULT = "default"; private ClassPathResource formbutton; private String documentType = STRICT_DOCTYPE; protected final List headers = new ArrayList(); /** * Should the returned HTML page start with the &lt;?xml version="1.0" encoding="..."&gt;. * This has effects which rendering mode the browsers will choose (quirks/strict) */ private Boolean renderXmlDeclaration = Boolean.FALSE; /** * Initialize properties from config */ public FrameCG() { final CGManager manager = SessionManager.getSession().getCGManager(); final String userDocType = (String) manager.getObject("FrameCG.userDocType", String.class); final Boolean userRenderXmlDecl = (Boolean) manager.getObject("FrameCG.renderXmlDeclaration", Boolean.class); if (userDocType != null) { setDocumentType(userDocType); } if (userRenderXmlDecl != null) { setRenderXmlDeclaration(userRenderXmlDecl); } // Externalize JavaScript headers // JS_YUI_UTILITIES = aggregate: yahoo, dom, event, connection, animation, dragdrop // headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_UTILITIES)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_YAHOO_DOM_EVENT)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_CONNECTION)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_ANIMATION)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_DRAGDROP)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_CONTAINER)); headers.add(Utils.createExternalizedCSSHeaderFromProperty(Utils.CSS_EXT_CORE)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_EXT)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_DOM_QUERY)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_YUI_BRIDGE)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_OBSERVABLE)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_EVENT_MANAGER)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_DOM_HELPER)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_EXT_ELEMENT)); headers.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_WINGS_ALL)); headers.add(new JavaScriptHeader("../dwr/engine.js")); headers.add(new JavaScriptHeader("../dwr/util.js")); formbutton = new ClassPathResource("org/wings/plaf/css/formbutton.htc", "text/x-component"); formbutton.getId(); // externalize } public void installCG(final SComponent comp) { final SFrame component = (SFrame) comp; // Add dynamic resources to the frame ReloadResource reloadResource = new ReloadResource(component); component.addDynamicResource(reloadResource); UpdateResource updateResource = new UpdateResource(component); component.addDynamicResource(updateResource); // Externalize update resource component.getDynamicResource(UpdateResource.class).getId(); final JavaScriptDOMListener handleClicks = new JavaScriptDOMListener( JavaScriptEvent.ON_CLICK, "wingS.util.handleBodyClick", comp); final JavaScriptDOMListener storeFocusFF = new JavaScriptDOMListener( JavaScriptEvent.ON_FOCUS, "wingS.util.storeFocus", comp); final JavaScriptDOMListener storeFocusIE = new JavaScriptDOMListener( JavaScriptEvent.ON_ACTIVATE, "wingS.util.storeFocus", comp); // Add script listeners to the frame component.addScriptListener(handleClicks); component.addScriptListener(Utils.isMSIE(component) ? storeFocusIE : storeFocusFF); SessionHeaders.getInstance().registerHeaders(headers); SessionHeaders.getInstance().registerHeaders(getBrowserStylesheets()); new InputMapRequestListener(component); } class InputMapRequestListener { SFrame frame; public InputMapRequestListener(SFrame frame) { this.frame = frame; frame.putClientProperty("InputMapRequestListener", this); frame.getSession().addRequestListener(new SRequestListener() { public void processRequest(SRequestEvent e) { if (e.getType() == SRequestEvent.DELIVER_START && InputMapRequestListener.this.frame.getDynamicResources().contains(e.getRequestedResource().getObject())) { boolean changeDetected = false; List<SComponent> components = InputMapRequestListener.this.frame.getGlobalInputMapComponents(); for (SComponent component : components) { boolean visible = component.isRecursivelyVisible(); if (!Boolean.valueOf(visible).equals(component.getClientProperty("visible"))) { component.putClientProperty("visible", visible); changeDetected |= true; } } for (SComponent component : components) { if (checkForChange(component, SComponent.WHEN_FOCUSED_OR_ANCESTOR_OF_FOCUSED_COMPONENT)) { changeDetected |= true; } if (checkForChange(component, SComponent.WHEN_IN_FOCUSED_FRAME)) { changeDetected |= true; } } if (changeDetected) { String script = strokes(components); InputMapRequestListener.this.frame.getSession().getScriptManager().addScriptListener(new JavaScriptListener(null, null, script)); } } } }); } private boolean checkForChange(SComponent component, int condition) { InputMap inputMap = component.getInputMap(condition); if (inputMap != null && inputMap.size() > 0) { if (!(inputMap instanceof VersionedInputMap)) { inputMap = new VersionedInputMap(inputMap); component.setInputMap(condition, inputMap); component.putClientProperty("inputMapVersion" + condition, -1); } final VersionedInputMap versionedInputMap = (VersionedInputMap)inputMap; final Integer inputMapVersion = (Integer) component.getClientProperty("inputMapVersion" + condition); if (inputMapVersion == null || versionedInputMap.getVersion() != inputMapVersion) { component.putClientProperty("inputMapVersion" + condition, versionedInputMap.getVersion()); return true; } } return false; } } private String strokes(List<SComponent> components) { if (components == null) return null; StringBuilder builder = new StringBuilder(); builder.append("wingS.keyboard.keyStrokes = new Array();"); for (SComponent component : components) { if (component.isRecursivelyVisible()) { appendStrokes(builder, component, SComponent.WHEN_FOCUSED_OR_ANCESTOR_OF_FOCUSED_COMPONENT, component.getInputMap(SComponent.WHEN_FOCUSED_OR_ANCESTOR_OF_FOCUSED_COMPONENT)); appendStrokes(builder, component, SComponent.WHEN_IN_FOCUSED_FRAME, component.getInputMap(SComponent.WHEN_IN_FOCUSED_FRAME)); } } return builder.toString(); } private void appendStrokes(StringBuilder builder, SComponent component, int condition, InputMap inputMap) { KeyStroke[] keyStrokes = inputMap.keys(); if (keyStrokes != null) { for (int i = 0; i < keyStrokes.length; i++) { KeyStroke keyStroke = keyStrokes[i]; Object binding = inputMap.get(keyStroke); switch (keyStroke.getKeyEventType()) { case KeyEvent.KEY_PRESSED: builder.append("wingS.keyboard.keyStrokes.push(new wingS.keyboard.KeyStroke('"); builder.append(component.getName()); builder.append("',"); builder.append(condition == SComponent.WHEN_FOCUSED_OR_ANCESTOR_OF_FOCUSED_COMPONENT ? "true" : "false"); builder.append(",'"); builder.append(binding); builder.append("',"); builder.append(keyStroke.getKeyCode()); builder.append(','); builder.append((keyStroke.getModifiers() & InputEvent.SHIFT_DOWN_MASK) != 0); builder.append(','); builder.append((keyStroke.getModifiers() & InputEvent.CTRL_DOWN_MASK) != 0); builder.append(','); builder.append((keyStroke.getModifiers() & InputEvent.ALT_DOWN_MASK) != 0); builder.append("));\n"); break; case KeyEvent.KEY_TYPED: break; case KeyEvent.KEY_RELEASED: break; } } } } /** * Externalizes the style sheet(s) for this session. Look up according style sheet file name in * org.wings.plaf.css.properties file under Stylesheet.BROWSERNAME. The style sheet is loaded from * the class path. * * @return a list of externalized browser specific stylesheet headers */ private List getBrowserStylesheets() { Session session = SessionManager.getSession(); final CGManager cgManager = session.getCGManager(); final String browserName = session.getUserAgent().getBrowserType().getShortName(); String cssClassPaths = (String) cgManager.getObject(PROPERTY_STYLESHEET + browserName, String.class); if (cssClassPaths == null) { cssClassPaths = (String) cgManager.getObject(PROPERTY_STYLESHEET + BROWSER_DEFAULT, String.class); } ArrayList browserStylesheets = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(cssClassPaths, ","); while (tokenizer.hasMoreTokens()) { browserStylesheets.add(Utils.createExternalizedCSSHeader(tokenizer.nextToken())); } return browserStylesheets; } /** * Uninstall renderer (i.e. other to apply other renderer). */ public void uninstallCG(final SComponent comp) { final SFrame component = (SFrame) comp; component.removeDynamicResource(ReloadResource.class); component.removeDynamicResource(UpdateResource.class); SessionHeaders.getInstance().deregisterHeaders(headers); } public void componentChanged(SComponent c) { } public void write(final Device device, final SComponent component) throws IOException { final SFrame frame = (SFrame) component; String strokes = strokes(frame.getGlobalInputMapComponents()); if (strokes != null) component.getSession().getScriptManager().addScriptListener(new JavaScriptListener(null, null, strokes)); if (!frame.isVisible()) return; else frame.fireRenderEvent(SComponent.START_RENDERING); Session session = SessionManager.getSession(); final String language = session.getLocale().getLanguage(); final String title = frame.getTitle(); final String encoding = session.getCharacterEncoding(); // <?xml version="1.0" encoding="..."> if (renderXmlDeclaration == null || renderXmlDeclaration) { device.print("<?xml version=\"1.0\" encoding=\""); Utils.write(device, encoding); device.print("\"?>\n"); } // <!DOCTYPE HTML PUBLIC ... > Utils.writeRaw(device, documentType); device.print("\n"); // <html> tag device.print("<html xmlns=\"http: Utils.write(device, language); device.print("\" lang=\""); Utils.write(device, language); device.print("\">\n"); // <head> tag device.print("<head>"); if (title != null) { device.print("<title>"); Utils.write(device, title); device.print("</title>\n"); } // Character set encoding, the default is typically utf-8. device.print("<meta http-equiv=\"Content-type\" content=\"text/html; charset="); Utils.write(device, encoding); device.print("\"/>\n"); /* Insert version and compile time. Since the Version Class is generated on compile time, * build errors in SDK's are quite normal. Just run the Version.java ant task. */ device.print("<meta http-equiv=\"Generator\" content=\"wingS (http://wingsframework.org) v"); device.print(Version.getVersion()); device.print(" built on: "); device.print(Version.getCompileTime()); device.print("\" />\n"); // Render all headers for (Object next : frame.getHeaders()) { if (next instanceof Renderable) { try { ((Renderable) next).write(device); } catch (ResourceNotFoundException e) { log.error("Unable to deliver inlined renderable", e); } } else { Utils.write(device, next.toString()); } device.print("\n"); } // Focus management. Put focus in selected object. if (frame.getFocus() != null) { String script = "wingS.util.requestFocus('" + frame.getFocus().getName() + "');"; ScriptManager.getInstance().addScriptListener(new OnPageRenderedScript(script)); } device.print("</head>\n"); device.print("<body"); Utils.writeEvents(device, frame, null); Utils.writeAllAttributes(device, frame); device.print(">\n"); // Write contents of the frame if (frame.isVisible()) { Utils.createExternalizedJSHeaderFromProperty(Utils.JS_ETC_WZ_TOOLTIP).write(device); device.print("\n"); // Write components frame.getLayout().write(device); // Write menus device.print("\n\n<div id=\"wings_menues\">\n"); Set menues = frame.getSession().getMenuManager().getMenues(frame); for (Iterator i = menues.iterator(); i.hasNext();) { SComponent menuItem = (SComponent) i.next(); menuItem.putClientProperty("popup", Boolean.TRUE); menuItem.write(device); menuItem.putClientProperty("popup", null); } device.print("\n</div>\n\n"); DragAndDropManager dndManager = frame.getSession().getDragAndDropManager(); dndManager.getCG().write(device, dndManager); handleScripts(device, frame); } device.print("</body>\n</html>\n"); component.fireRenderEvent(SComponent.DONE_RENDERING); } protected void handleScripts(Device device, SComponent component) throws IOException { final SFrame frame = (SFrame) component; final ScriptManager scriptManager = frame.getSession().getScriptManager(); final SToolTipManager tooltipManager = SToolTipManager.sharedInstance(); // hand script listeners of frame to script manager scriptManager.addScriptListeners(frame.getScriptListeners()); device.print("<script type=\"text/javascript\">\n"); // print all scripts device.print(getGlobalInitScript(frame)).print("\n"); device.print(getTooltipInitScript(tooltipManager)).print("\n"); ScriptListener[] scriptListeners = scriptManager.getScriptListeners(); for (int i = 0; i < scriptListeners.length; ++i) { if (scriptListeners[i].getScript() != null) { device.print(scriptListeners[i].getScript()).print("\n"); } } scriptManager.clearScriptListeners(); device.print("</script>\n"); } private String getGlobalInitScript(SFrame frame) throws IOException { Map<String, Object> initConfig = new HashMap<String, Object>(); initConfig.put("eventEpoch", frame.getEventEpoch()); initConfig.put("reloadResource", frame.getDynamicResource(ReloadResource.class).getURL().toString()); initConfig.put("updateResource", frame.getDynamicResource(UpdateResource.class).getURL().toString()); initConfig.put("updateEnabled", frame.isUpdateEnabled()); initConfig.put("updateCursor", Utils.mapToJsObject(frame.getUpdateCursor())); initConfig.put("autoAdjustLayout", Utils.mapToJsObject(frame.getAutoAdjustLayout())); SStringBuilder script = new SStringBuilder(); script.append("wingS.global.init(").append(Utils.mapToJsObject(initConfig)).append(");"); return script.toString(); } private String getTooltipInitScript(SToolTipManager tooltipManager) throws IOException { SStringBuilder script = new SStringBuilder(); script.append("wingS.component.initTooltips("); script.append(tooltipManager.getInitialDelay()).append(","); script.append(tooltipManager.getDismissDelay()).append(","); script.append(tooltipManager.isFollowMouse()).append(");"); return script.toString(); } public String getDocumentType() { return documentType; } public void setDocumentType(String documentType) { this.documentType = documentType; } /** * @return The current rendered DOCTYPE of this document. {@link #STRICT_DOCTYPE} */ public Boolean getRenderXmlDeclaration() { return renderXmlDeclaration; } /** * Sets should the returned HTML page start with the &lt;?xml version="1.0" encoding="..."&gt;. * This has effects which rendering mode the browsers will choose (quirks/strict) * * @param renderXmlDeclaration should the returned HTML page start with the &lt;?xml version="1.0" encoding="..."&gt;. */ public void setRenderXmlDeclaration(Boolean renderXmlDeclaration) { this.renderXmlDeclaration = renderXmlDeclaration; } public Update getComponentUpdate(SComponent component) { return null; } public Update getAddHeaderUpdate(SFrame frame, int index, Object header) { if (header instanceof Script) return new HeaderScriptUpdate(frame, true, (Script) header, index); else if (header instanceof Link) return new HeaderLinkUpdate(frame, true, (Link) header, index); else return null; } public Update getAddHeaderUpdate(SFrame frame, Object header) { if (header instanceof Script) return new HeaderScriptUpdate(frame, true, (Script) header); else if (header instanceof Link) return new HeaderLinkUpdate(frame, true, (Link) header); else return null; } public Update getRemoveHeaderUpdate(SFrame frame, Object header) { if (header instanceof Script) // Removing script headers asynchronously would indeed // detach the according header, however, the functions // contained in the according files are not unloaded. // If unloading functions is desired, it might be a good // idea to RETURN 'NULL' here. This would create a // component update of the frame which in turn would // force a complete page reload and function unloading. return new HeaderScriptUpdate(frame, false, (Script) header); else if (header instanceof Link) return new HeaderLinkUpdate(frame, false, (Link) header); else return null; } public Update getEpochUpdate(SFrame frame, String epoch) { return new EpochUpdate(frame, epoch); } public Update getFocusUpdate(SFrame frame, SComponent focus) { return new FocusUpdate(frame, focus); } public Update getUpdateEnabledUpdate(SFrame frame, boolean enabled) { return new UpdateEnabledUpdate(frame, enabled); } protected class HeaderScriptUpdate extends AbstractUpdate { private Boolean add; private Script script; private Integer index; public HeaderScriptUpdate(SComponent component, boolean add, Script script) { super(component); this.add = add; this.script = script; } public HeaderScriptUpdate(SComponent component, boolean add, Script script, int index) { this(component, add, script); this.index = index; } public int getPriority() { return 5; } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("headerScript"); handler.addParameter(add); handler.addParameter(script.getURL().toString()); handler.addParameter(script.getType()); if (index != null) handler.addParameter(index); return handler; } public boolean equals(Object object) { if (this == object) return true; if (!super.equals(object)) return false; if (!script.equals(((HeaderScriptUpdate) object).script)) return false; return true; } } protected class HeaderLinkUpdate extends AbstractUpdate { private Boolean add; private Link link; private Integer index; public HeaderLinkUpdate(SComponent component, boolean add, Link link) { super(component); this.add = add; this.link = link; } public HeaderLinkUpdate(SComponent component, boolean add, Link link, int index) { this(component, add, link); this.index = index; } public int getPriority() { return 5; } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("headerLink"); handler.addParameter(add); handler.addParameter(link.getURL().toString()); handler.addParameter(link.getType()); if (link.getRel() != null || link.getRev() != null || link.getTarget() != null || index != null) handler.addParameter(link.getRel()); if (link.getRev() != null || link.getTarget() != null || index != null) handler.addParameter(link.getRev()); if (link.getTarget() != null || index != null) handler.addParameter(link.getTarget()); if (index != null) handler.addParameter(index); return handler; } public boolean equals(Object object) { if (this == object) return true; if (!super.equals(object)) return false; if (!link.equals(((HeaderLinkUpdate) object).link)) return false; return true; } } protected class EpochUpdate extends AbstractUpdate { private String epoch; public EpochUpdate(SComponent component, String epoch) { super(component); this.epoch = epoch; } public int getPriority() { return 0; } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("epoch"); handler.addParameter(epoch); return handler; } } protected class FocusUpdate extends AbstractUpdate { private SComponent focus; public FocusUpdate(SComponent component, SComponent focus) { super(component); this.focus = focus; } public int getPriority() { return 0; } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("focus"); handler.addParameter(focus.getName()); return handler; } } protected class UpdateEnabledUpdate extends AbstractUpdate { private Boolean enabled; public UpdateEnabledUpdate(SComponent component, boolean enabled) { super(component); this.enabled = Boolean.valueOf(enabled); } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("updateEnabled"); handler.addParameter(enabled); return handler; } } }
package net.sf.jailer.ui.util; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import net.sf.jailer.database.Session; import net.sf.jailer.ui.UIUtil; public class AWTWatchdog { private static final long MAX_DELAY = 10000; public static void start() { try { Thread watchdog = new Thread(new Runnable() { @Override public void run() { boolean issueSent = false; for (;;) { try { long t = System.currentTimeMillis(); Thread.sleep(1000); if (t + 5000 < System.currentTimeMillis()) { setStarttime(0); continue; } } catch (InterruptedException e) { // ignore } long st = getStarttime(); if (st != 0 && st + MAX_DELAY < System.currentTimeMillis()) { if (!issueSent) { String dump; try { dump = sendThreadDump(); } catch (Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); dump = sw.toString(); } dump = "AWT-Thread hanging: " + dump; Session._log.error(dump); final int MAX_CL = 1000; String iMsg = dump; if (iMsg.length() > MAX_CL) { iMsg = iMsg.substring(0, MAX_CL); } UIUtil.sendIssue("AWTHanging", iMsg); issueSent = true; } } else { if (issueSent) { String iMsg = "AWT-Thread working"; Session._log.info(iMsg); UIUtil.sendIssue("AWTHanging", iMsg); return; } } } } }, "AWT-WD"); watchdog.setDaemon(true); watchdog.start(); } catch (Exception e) { e.printStackTrace(); } } // TODO: show latest "net..jailer" + use invokelater-probes instead protected static String sendThreadDump() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) { if (ti.getThreadName() != null && ti.getThreadName().toLowerCase().startsWith("awt-ev")) { StringBuilder sb = new StringBuilder( "\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " " + ti.getThreadState()); if (ti.getLockName() != null) { sb.append(" on " + ti.getLockName()); } if (ti.getLockOwnerName() != null) { sb.append(" owned by \"" + ti.getLockOwnerName() + "\" Id=" + ti.getLockOwnerId()); } if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; for (; i < ti.getStackTrace().length && i < 100; i++) { StackTraceElement ste = ti.getStackTrace()[i]; sb.append("\tat " + ste.toString()); sb.append('\n'); if (i == 0 && ti.getLockInfo() != null) { Thread.State ts = ti.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on " + ti.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked " + mi); sb.append('\n'); } } } if (i < ti.getStackTrace().length) { sb.append("\t..."); sb.append('\n'); } LockInfo[] locks = ti.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); System.err.print("Error: AWT-Thread hanging: " + sb.toString()); return sb.toString(); } } return "no awt-thread?"; } private static long starttime = 0; private synchronized static long getStarttime() { return starttime; } public synchronized static void setStarttime(long starttime) { AWTWatchdog.starttime = starttime; } }
package annotatedspring.episodes; import org.hibernate.validator.constraints.NotBlank; import org.pegdown.PegDownProcessor; import javax.persistence.*; import javax.validation.constraints.NotNull; @Entity public class Episode { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @NotBlank private String title; private String summary; @Lob private String notes; private String youtubeId; private Integer duration; private String sourcecodeUrl; private boolean published; public Integer getId() { return id; } public String getTitle() { return title; } public String getNotes() { return notes; } public String getNotesHtml() { return new PegDownProcessor().markdownToHtml(notes); } public void setId(Integer id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setNotes(String notes) { this.notes = notes; } public String getYoutubeId() { return youtubeId; } public void setYoutubeId(String youtubeId) { this.youtubeId = youtubeId; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public String getSourcecodeUrl() { return sourcecodeUrl; } public void setSourcecodeUrl(String sourcecodeUrl) { this.sourcecodeUrl = sourcecodeUrl; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public boolean isPublished() { return published; } public void setPublished(boolean published) { this.published = published; } }
package at.spardat.xma.xdelta; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.zip.ZipException; import org.apache.commons.compress.archivers.zip.ExtraFieldUtils; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipFile; import com.nothome.delta.GDiffPatcher; import com.nothome.delta.PatchException; /** * This class applys a zip file containing deltas created with {@link JarDelta} using * {@link com.nothome.delta.GDiffPatcher} on the files contained in the jar file. * The result of this operation is not binary equal to the original target zip file. * Timestamps of files and directories are not reconstructed. But the contents of all * files in the reconstructed target zip file are complely equal to their originals. * * @author s2877 */ public class JarPatcher { /** The patch name. */ private final String patchName; /** The source name. */ private final String sourceName; /** The buffer len. */ private final int BUFFER_LEN = 8 * 1024; /** The buffer. */ private final byte[] buffer = new byte[BUFFER_LEN]; /** The next. */ private String next = null; public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list) throws IOException { applyDelta(patch, source, output, list, ""); patch.close(); } /** * Apply delta. * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException(fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream.read(sourceBytes); erg < sourceBytes.length; erg += sourceStream.read(sourceBytes, erg, sourceBytes.length - erg)); } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } } /** * Gets the entry. * * @param source the source * @param name the name * @param crc the crc * @return the entry */ private ZipArchiveEntry getEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { if (next.getCrc() == crc) return next; } if (!JarDelta.zipFilesPattern.matcher(name).matches()) { return null; } else { return source.getEntry(name); } } /** * Gets the patch entry. * * @param source the source * @param name the name * @param crc the crc * @return the patch entry */ private ZipArchiveEntry getPatchEntry(ZipFile source, String name, long crc) { for (ZipArchiveEntry next : source.getEntries(name)) { long nextCrc = Long.valueOf(next.getComment()); if (nextCrc == crc) return next; } return null; } /** * Close entry. * * @param output the output * @param outEntry the out entry * @param crc the crc * @throws IOException Signals that an I/O exception has occurred. */ private void closeEntry(ZipArchiveOutputStream output, ZipArchiveEntry outEntry, long crc) throws IOException { output.flush(); output.closeArchiveEntry(); if (outEntry.getCrc() != crc) throw new IOException("CRC mismatch for " + outEntry.getName()); } /** * Instantiates a new jar patcher. * * @param patchName the patch name * @param sourceName the source name */ public JarPatcher(String patchName, String sourceName) { this.patchName = patchName; this.sourceName = sourceName; } /** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br> * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (").append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (").append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); } /** * Entry to new name. * * @param source the source * @param name the name * @return the zip archive entry * @throws ZipException the zip exception */ private ZipArchiveEntry copyEntry(ZipArchiveEntry source) throws ZipException { ZipArchiveEntry ret = new ZipArchiveEntry(source.getName()); byte[] extra = source.getExtra(); if (extra != null) { ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ)); } else { ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true))); } ret.setInternalAttributes(source.getInternalAttributes()); ret.setExternalAttributes(source.getExternalAttributes()); ret.setExtraFields(source.getExtraFields(true)); return ret; } }
package br.ufrn.ceres.bsi.questions; import java.util.List; import br.ufrn.ceres.bsi.questions.dao.UserService; import br.ufrn.ceres.bsi.questions.dao.util.JPAUtil; import br.ufrn.ceres.bsi.questions.model.Endereco; import br.ufrn.ceres.bsi.questions.model.Alternativa; import br.ufrn.ceres.bsi.questions.model.Questao; import br.ufrn.ceres.bsi.questions.model.Usuario; public class Main { public static void main(String[] args) { Endereco endereco = new Endereco(); endereco.setCity("Caicó"); endereco.setCountry("Brasil"); endereco.setStreet("Presidente Kennedy"); endereco.setSuburb("Acampamento"); Usuario user1 = new Usuario(); user1.setUsername("tacianosilva"); user1.setFirstname("Taciano"); user1.setLastname("Silva"); user1.setEmail("tacianosilva@gmail.com"); user1.setPassword("12345"); user1.setAddress(endereco); Usuario user2 = new Usuario(); user2.setUsername("xuxa"); user2.setFirstname("Xuxa"); user2.setLastname("????"); user2.setEmail("xuxa@gmail.com"); user2.setPassword("12345"); user2.setAddress(endereco); UserService service = new UserService(JPAUtil.EMF); service.create(user1); service.create(user2); System.out.println(service.find(user1.getId())); System.out.println(service.find(user2.getId())); //service.delete(user1.getId()); System.out.println(service.find(user1.getId())); System.out.println(service.find(user2.getId())); List<Usuario> lista = service.findByQuery("SELECT u FROM Usuario u"); for (Usuario usuario : lista) { System.out.println(usuario); } } }
package com.amplitude.api; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = DatabaseHelper.class.getName(); static final Map<String, DatabaseHelper> instances = new HashMap<String, DatabaseHelper>(); protected static final String STORE_TABLE_NAME = "store"; protected static final String LONG_STORE_TABLE_NAME = "long_store"; private static final String KEY_FIELD = "key"; private static final String VALUE_FIELD = "value"; protected static final String EVENT_TABLE_NAME = "events"; protected static final String IDENTIFY_TABLE_NAME = "identifys"; private static final String ID_FIELD = "id"; private static final String EVENT_FIELD = "event"; private static final String CREATE_STORE_TABLE = "CREATE TABLE IF NOT EXISTS " + STORE_TABLE_NAME + " (" + KEY_FIELD + " TEXT PRIMARY KEY NOT NULL, " + VALUE_FIELD + " TEXT);"; private static final String CREATE_LONG_STORE_TABLE = "CREATE TABLE IF NOT EXISTS " + LONG_STORE_TABLE_NAME + " (" + KEY_FIELD + " TEXT PRIMARY KEY NOT NULL, " + VALUE_FIELD + " INTEGER);"; private static final String CREATE_EVENTS_TABLE = "CREATE TABLE IF NOT EXISTS " + EVENT_TABLE_NAME + " (" + ID_FIELD + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EVENT_FIELD + " TEXT);"; private static final String CREATE_IDENTIFYS_TABLE = "CREATE TABLE IF NOT EXISTS " + IDENTIFY_TABLE_NAME + " (" + ID_FIELD + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EVENT_FIELD + " TEXT);"; File file; private String instanceName; private boolean callResetListenerOnDatabaseReset = true; private DatabaseResetListener databaseResetListener; private static final AmplitudeLog logger = AmplitudeLog.getLogger(); @Deprecated static DatabaseHelper getDatabaseHelper(Context context) { return getDatabaseHelper(context, null); } static synchronized DatabaseHelper getDatabaseHelper(Context context, String instance) { instance = Utils.normalizeInstanceName(instance); DatabaseHelper dbHelper = instances.get(instance); if (dbHelper == null) { dbHelper = new DatabaseHelper(context.getApplicationContext(), instance); instances.put(instance, dbHelper); } return dbHelper; } private static String getDatabaseName(String instance) { return (Utils.isEmptyString(instance) || instance.equals(Constants.DEFAULT_INSTANCE)) ? Constants.DATABASE_NAME : Constants.DATABASE_NAME + "_" + instance; } protected DatabaseHelper(Context context) { this(context, null); } protected DatabaseHelper(Context context, String instance) { super(context, getDatabaseName(instance), null, Constants.DATABASE_VERSION); file = context.getDatabasePath(getDatabaseName(instance)); instanceName = Utils.normalizeInstanceName(instance); } void setDatabaseResetListener(DatabaseResetListener databaseResetListener) { this.databaseResetListener = databaseResetListener; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_STORE_TABLE); db.execSQL(CREATE_LONG_STORE_TABLE); // INTEGER PRIMARY KEY AUTOINCREMENT guarantees that all generated values // for the field will be monotonically increasing and unique over the // lifetime of the table, even if rows get removed db.execSQL(CREATE_EVENTS_TABLE); db.execSQL(CREATE_IDENTIFYS_TABLE); // NOTE: the database file can become corrupted between interactions // getWriteableDatabase and getReadableDatabase will test for corruption // and actually delete the database file and call onCreate again if it's corrupted // Our normal catch exception and delete database does not get triggered in this scenario // Therefore we are also calling the reset callback inside onCreate if (databaseResetListener != null && callResetListenerOnDatabaseReset) { try { callResetListenerOnDatabaseReset = false; // guards against stack overflow databaseResetListener.onDatabaseReset(db); } catch (SQLiteException e) { logger.e(TAG, String.format("databaseReset callback failed during onCreate"), e); } finally { callResetListenerOnDatabaseReset = true; } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion > newVersion) { logger.e(TAG, "onUpgrade() with invalid oldVersion and newVersion"); resetDatabase(db); return; } if (newVersion <= 1) { return; } switch (oldVersion) { case 1: db.execSQL(CREATE_STORE_TABLE); if (newVersion <= 2) break; case 2: db.execSQL(CREATE_IDENTIFYS_TABLE); db.execSQL(CREATE_LONG_STORE_TABLE); if (newVersion <= 3) break; case 3: break; default: logger.e(TAG, "onUpgrade() with unknown oldVersion " + oldVersion); resetDatabase(db); } } private void resetDatabase(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + LONG_STORE_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + EVENT_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + IDENTIFY_TABLE_NAME); onCreate(db); } synchronized long insertOrReplaceKeyValue(String key, String value) { return value == null ? deleteKeyFromTable(STORE_TABLE_NAME, key) : insertOrReplaceKeyValueToTable(STORE_TABLE_NAME, key, value); } synchronized long insertOrReplaceKeyLongValue(String key, Long value) { return value == null ? deleteKeyFromTable(LONG_STORE_TABLE_NAME, key) : insertOrReplaceKeyValueToTable(LONG_STORE_TABLE_NAME, key, value); } synchronized long insertOrReplaceKeyValueToTable(String table, String key, Object value) { long result = -1; SQLiteDatabase db = null; try { db = getWritableDatabase(); result = insertOrReplaceKeyValueToTable(db, table, key, value); } catch (SQLiteException e) { logger.e(TAG, String.format("insertOrReplaceKeyValue in %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("insertOrReplaceKeyValue in %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } finally { if (db != null && db.isOpen()) { close(); } } return result; } synchronized long insertOrReplaceKeyValueToTable(SQLiteDatabase db, String table, String key, Object value) throws SQLiteException, StackOverflowError { long result = -1; ContentValues contentValues = new ContentValues(); contentValues.put(KEY_FIELD, key); if (value instanceof Long) { contentValues.put(VALUE_FIELD, (Long) value); } else { contentValues.put(VALUE_FIELD, (String) value); } result = insertKeyValueContentValuesIntoTable(db, table, contentValues); if (result == -1) { logger.w(TAG, "Insert failed"); } return result; } synchronized long insertKeyValueContentValuesIntoTable(SQLiteDatabase db, String table, ContentValues contentValues) throws SQLiteException, StackOverflowError { return db.insertWithOnConflict( table, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE ); } synchronized long deleteKeyFromTable(String table, String key) { long result = -1; try { SQLiteDatabase db = getWritableDatabase(); result = db.delete(table, KEY_FIELD + "=?", new String[]{key}); } catch (SQLiteException e) { logger.e(TAG, String.format("deleteKey from %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("deleteKey from %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } finally { close(); } return result; } synchronized long addEvent(String event) { return addEventToTable(EVENT_TABLE_NAME, event); } synchronized long addIdentify(String identifyEvent) { return addEventToTable(IDENTIFY_TABLE_NAME, identifyEvent); } private synchronized long addEventToTable(String table, String event) { long result = -1; try { SQLiteDatabase db = getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(EVENT_FIELD, event); result = insertEventContentValuesIntoTable(db, table, contentValues); if (result == -1) { logger.w(TAG, String.format("Insert into %s failed", table)); } } catch (SQLiteException e) { logger.e(TAG, String.format("addEvent to %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("addEvent to %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } finally { close(); } return result; } synchronized long insertEventContentValuesIntoTable(SQLiteDatabase db, String table, ContentValues contentValues) throws SQLiteException, StackOverflowError { return db.insert(table, null, contentValues); } synchronized String getValue(String key) { return (String) getValueFromTable(STORE_TABLE_NAME, key); } synchronized Long getLongValue(String key) { return (Long) getValueFromTable(LONG_STORE_TABLE_NAME, key); } protected synchronized Object getValueFromTable(String table, String key) { Object value = null; Cursor cursor = null; try { SQLiteDatabase db = getReadableDatabase(); cursor = queryDb( db, table, new String[]{KEY_FIELD, VALUE_FIELD}, KEY_FIELD + " = ?", new String[]{key}, null, null, null, null ); if (cursor.moveToFirst()) { value = table.equals(STORE_TABLE_NAME) ? cursor.getString(1) : cursor.getLong(1); } } catch (SQLiteException e) { logger.e(TAG, String.format("getValue from %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getValue from %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } catch (IllegalStateException e) { // cursor window row too big exception handleIfCursorRowTooLargeException(e); } catch (RuntimeException e) { // cursor window allocation exception convertIfCursorWindowException(e); } finally { if (cursor != null) { cursor.close(); } close(); } return value; } synchronized List<JSONObject> getEvents(long upToId, long limit) throws JSONException { return getEventsFromTable(EVENT_TABLE_NAME, upToId, limit); } synchronized List<JSONObject> getIdentifys( long upToId, long limit) throws JSONException { return getEventsFromTable(IDENTIFY_TABLE_NAME, upToId, limit); } protected synchronized List<JSONObject> getEventsFromTable( String table, long upToId, long limit) throws JSONException { List<JSONObject> events = new LinkedList<JSONObject>(); Cursor cursor = null; try { SQLiteDatabase db = getReadableDatabase(); cursor = queryDb( db, table, new String[] { ID_FIELD, EVENT_FIELD }, upToId >= 0 ? ID_FIELD + " <= " + upToId : null, null, null, null, ID_FIELD + " ASC", limit >= 0 ? "" + limit : null ); while (cursor.moveToNext()) { long eventId = cursor.getLong(0); String event = cursor.getString(1); if (Utils.isEmptyString(event)) { continue; } JSONObject obj = new JSONObject(event); obj.put("event_id", eventId); events.add(obj); } } catch (SQLiteException e) { logger.e(TAG, String.format("getEvents from %s failed", table), e); delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getEvents from %s failed", table), e); delete(); } catch (IllegalStateException e) { handleIfCursorRowTooLargeException(e); } catch (RuntimeException e) { convertIfCursorWindowException(e); } finally { if (cursor != null) { cursor.close(); } close(); } return events; } synchronized long getEventCount() { return getEventCountFromTable(EVENT_TABLE_NAME); } synchronized long getIdentifyCount() { return getEventCountFromTable(IDENTIFY_TABLE_NAME); } synchronized long getTotalEventCount() { return getEventCount() + getIdentifyCount(); } private synchronized long getEventCountFromTable(String table) { long numberRows = 0; SQLiteStatement statement = null; try { SQLiteDatabase db = getReadableDatabase(); String query = "SELECT COUNT(*) FROM " + table; statement = db.compileStatement(query); numberRows = statement.simpleQueryForLong(); } catch (SQLiteException e) { logger.e(TAG, String.format("getNumberRows for %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getNumberRows for %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } finally { if (statement != null) { statement.close(); } close(); } return numberRows; } synchronized long getNthEventId(long n) { return getNthEventIdFromTable(EVENT_TABLE_NAME, n); } synchronized long getNthIdentifyId(long n) { return getNthEventIdFromTable(IDENTIFY_TABLE_NAME, n); } private synchronized long getNthEventIdFromTable(String table, long n) { long nthEventId = -1; SQLiteStatement statement = null; try { SQLiteDatabase db = getReadableDatabase(); String query = "SELECT " + ID_FIELD + " FROM " + table + " LIMIT 1 OFFSET " + (n - 1); statement = db.compileStatement(query); nthEventId = -1; try { nthEventId = statement.simpleQueryForLong(); } catch (SQLiteDoneException e) { logger.w(TAG, e); } } catch (SQLiteException e) { logger.e(TAG, String.format("getNthEventId from %s failed", table), e); // Hard to recover from SQLiteExceptions, just start fresh delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getNthEventId from %s failed", table), e); // potential stack overflow error when getting database on custom Android versions delete(); } finally { if (statement != null) { statement.close(); } close(); } return nthEventId; } synchronized void removeEvents(long maxId) { removeEventsFromTable(EVENT_TABLE_NAME, maxId); } synchronized void removeIdentifys(long maxId) { removeEventsFromTable(IDENTIFY_TABLE_NAME, maxId); } private synchronized void removeEventsFromTable(String table, long maxId) { try { SQLiteDatabase db = getWritableDatabase(); db.delete(table, ID_FIELD + " <= " + maxId, null); } catch (SQLiteException e) { logger.e(TAG, String.format("removeEvents from %s failed", table), e); delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("removeEvents from %s failed", table), e); delete(); } finally { close(); } } synchronized void removeEvent(long id) { removeEventFromTable(EVENT_TABLE_NAME, id); } synchronized void removeIdentify(long id) { removeEventFromTable(IDENTIFY_TABLE_NAME, id); } private synchronized void removeEventFromTable(String table, long id) { try { SQLiteDatabase db = getWritableDatabase(); db.delete(table, ID_FIELD + " = " + id, null); } catch (SQLiteException e) { logger.e(TAG, String.format("removeEvent from %s failed", table), e); delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("removeEvent from %s failed", table), e); delete(); } finally { close(); } } private void delete() { // This only gets called if the database somehow gets corrupted AFTER being fetched // ie after the call to getWriteableDatabase / getReadableDatabase // or if a SQL exception occurs during the interaction try { close(); file.delete(); } catch (SecurityException e) { logger.e(TAG, "delete failed", e); } finally { if (databaseResetListener != null && callResetListenerOnDatabaseReset) { callResetListenerOnDatabaseReset = false; // guards against stack overflow SQLiteDatabase db = null; try { db = getWritableDatabase(); databaseResetListener.onDatabaseReset(db); } catch (SQLiteException e) { logger.e(TAG, String.format("databaseReset callback failed during delete"), e); } finally { callResetListenerOnDatabaseReset = true; if (db != null && db.isOpen()) { close(); } } } } } boolean dbFileExists() { return file.exists(); } // add level of indirection to facilitate mocking during unit tests Cursor queryDb( SQLiteDatabase db, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit ) { return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); } private void handleIfCursorRowTooLargeException(IllegalStateException e) { String message = e.getMessage(); if (!Utils.isEmptyString(message) && message.contains("Couldn't read") && message.contains("CursorWindow")) { delete(); } else { throw e; } } /* Checks if the RuntimeException is an android.database.CursorWindowAllocationException. If it is, then wrap the message in Amplitude's CursorWindowAllocationException so the AmplitudeClient can handle it. If not then rethrow. */ private static void convertIfCursorWindowException(RuntimeException e) { String message = e.getMessage(); if (!Utils.isEmptyString(message) && (message.startsWith("Cursor window allocation of") || message.startsWith("Could not allocate CursorWindow"))) { throw new CursorWindowAllocationException(message); } else { throw e; } } }
package com.android.yj.viewlib; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class SelectBar extends View { private static final String TAG = SelectBar.class.getSimpleName(); private static final String ERROR_LABEL_ARRAY_NUM = "label array length should match specific item num"; private static final String ERROR_SELECTED_ITEM_INDEX = "selected item index out of bounds"; private Paint mUnClickedRectPaint; private Paint mClickedRectPaint; private Paint mUnClickedCirclePaint; private Paint mClickedCirclePaint; private Paint mTextPaint; private int mUnSelectedLineColor; private int mSelectedLineColor; private int mUnSelectedItemColor; private int mSelectedItemColor; private int mLabelColor; private int mItemNum; private int mSelectedItemIndex; private String[] mLabelArray; /* View */ private int mMeasuredViewWidth; /* View */ private int mMeasuredViewHeight; private int mMidRectHeightY; private int mRectHeight; private int mRectWidth; /* Padding */ private int mRectLRPadding; private int mCircleRadius; private int mCircleGap; private OnItemClickedListener mOicListener; public SelectBar(Context context) { this(context, null); } public SelectBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SelectBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initAttrs(context, attrs); initPaints(); } private void initAttrs(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectBar); int attrCount = attrs.getAttributeCount(); for (int i = 0; i < attrCount; i++) { String attrName = attrs.getAttributeName(i); String attrValue = attrs.getAttributeValue(i); Log.i(TAG, attrName + " : " + attrValue); } mUnSelectedLineColor = typedArray.getColor(R.styleable.SelectBar_unselected_line_color, Color.LTGRAY); mSelectedLineColor = typedArray.getColor(R.styleable.SelectBar_selected_line_color, Color.DKGRAY); mUnSelectedItemColor = typedArray.getColor(R.styleable.SelectBar_unselected_item_color, Color.LTGRAY); mSelectedItemColor = typedArray.getColor(R.styleable.SelectBar_selected_item_color, Color.DKGRAY); mLabelColor = typedArray.getColor(R.styleable.SelectBar_label_color, Color.BLACK); mItemNum = typedArray.getInt(R.styleable.SelectBar_item_num, 1); mLabelArray = new String[mItemNum]; CharSequence[] csArr = typedArray.getTextArray(R.styleable.SelectBar_label_array); if (csArr == null) { for (int i = 0; i < mItemNum; i++) { mLabelArray[i] = String.valueOf(i + 1); } } else { if (mItemNum == csArr.length) { for (int i = 0; i < mItemNum; i++) { mLabelArray[i] = String.valueOf(csArr[i]); } } else { throw new RuntimeException(ERROR_LABEL_ARRAY_NUM); } } mSelectedItemIndex = typedArray.getInt(R.styleable.SelectBar_selected_item_index, 0); if (mSelectedItemIndex < 0 || mSelectedItemIndex > mItemNum - 1) { throw new RuntimeException(ERROR_SELECTED_ITEM_INDEX); } typedArray.recycle(); } public void setOnItemClickedListener(OnItemClickedListener listener) { mOicListener = listener; } public void setUnSelectLineColor(int color) { mUnSelectedLineColor = color; } public void setSelectLineColor(int color) { mSelectedLineColor = color; } public void setUnSelectItemColor(int color) { mUnSelectedItemColor = color; } public void setSelectItemColor(int color) { mSelectedItemColor = color; } public void setLabelColor(int color) { mLabelColor = color; } public void setItemNum(int num) { mItemNum = num; /* Itemcrashitem0 */ mSelectedItemIndex = 0; invalidate(); } public void setSelectedItemIndex(int index) { mSelectedItemIndex = index; invalidate(); } public void setLabelArray(String[] array) { mLabelArray = array; invalidate(); } private void initAttrs() { mItemNum = 5; mLabelArray = new String[mItemNum]; for (int i = 0; i < mItemNum; i++) { mLabelArray[i] = String.valueOf(i + 1); } } private void initPaints() { mUnClickedRectPaint = new Paint(); mUnClickedRectPaint.setStyle(Paint.Style.FILL); mClickedRectPaint = new Paint(); mClickedRectPaint.setStyle(Paint.Style.FILL); mUnClickedCirclePaint = new Paint(); mUnClickedCirclePaint.setStyle(Paint.Style.FILL); mClickedCirclePaint = new Paint(); mClickedCirclePaint.setStyle(Paint.Style.FILL); mTextPaint = new Paint(); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setAntiAlias(true); mTextPaint.setTextAlign(Paint.Align.CENTER); mTextPaint.setFakeBoldText(true); } private void updatePaintsColor() { if (mUnSelectedLineColor == 0) { mUnClickedRectPaint.setColor(Color.LTGRAY); } else { mUnClickedRectPaint.setColor(mUnSelectedLineColor); } if (mSelectedLineColor == 0) { mClickedRectPaint.setColor(Color.DKGRAY); } else { mClickedRectPaint.setColor(mSelectedLineColor); } if (mUnSelectedItemColor == 0) { mUnClickedCirclePaint.setColor(Color.BLUE); } else { mUnClickedCirclePaint.setColor(mUnSelectedItemColor); } if (mSelectedItemColor == 0) { mClickedCirclePaint.setColor(Color.MAGENTA); } else { mClickedCirclePaint.setColor(mSelectedItemColor); } if (mLabelColor == 0) { mTextPaint.setColor(Color.BLACK); } else { mTextPaint.setColor(mLabelColor); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mMeasuredViewWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); mMeasuredViewHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(mMeasuredViewWidth, mMeasuredViewHeight); mMidRectHeightY = mMeasuredViewHeight / 3; mTextPaint.setTextSize(mMeasuredViewHeight / 3); mCircleRadius = mMeasuredViewHeight / 6; mCircleGap = mMeasuredViewWidth / (mItemNum + 1); mRectLRPadding = mCircleGap / 3; mRectHeight = mMeasuredViewHeight / 10; mRectWidth = mMeasuredViewWidth - mRectLRPadding * 2; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); updatePaintsColor(); if (mSelectedItemIndex < 0 || mSelectedItemIndex > mItemNum - 1) { throw new RuntimeException(ERROR_SELECTED_ITEM_INDEX); } canvas.drawRect(mRectLRPadding, mMidRectHeightY - mRectHeight / 2, mCircleGap * (mSelectedItemIndex + 1), mMidRectHeightY + mRectHeight / 2, mClickedRectPaint); canvas.drawRect(mCircleGap * (mSelectedItemIndex + 1), mMidRectHeightY - mRectHeight / 2, mRectLRPadding + mRectWidth, mMidRectHeightY + mRectHeight / 2, mUnClickedRectPaint); if (mSelectedItemIndex + 1 == mItemNum) { canvas.drawRect(mRectLRPadding, mMidRectHeightY - mRectHeight / 2, mRectLRPadding + mRectWidth, mMidRectHeightY + mRectHeight / 2, mClickedRectPaint); } for (int i = 0; i < mItemNum; i++) { if (i <= mSelectedItemIndex) { canvas.drawCircle((i + 1) * mCircleGap, mMidRectHeightY, mCircleRadius, mClickedCirclePaint); } else { canvas.drawCircle((i + 1) * mCircleGap, mMidRectHeightY, mCircleRadius, mUnClickedCirclePaint); } canvas.drawText(mLabelArray[i], (i + 1) * mCircleGap, mMidRectHeightY + mCircleRadius * 3, mTextPaint); } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); float x = event.getX(); float y = event.getY(); switch (action) { case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_DOWN: for (int i = 0; i < mItemNum; i++) { if (y >= mMidRectHeightY - mCircleRadius && y <= mMidRectHeightY + mCircleRadius) { if (x >= (i + 1) * mCircleGap - mCircleRadius && x <= (i + 1) * mCircleGap + mCircleRadius) { mSelectedItemIndex = i; invalidate(); if (mOicListener != null) { mOicListener.onItemClick(mSelectedItemIndex, mLabelArray[mSelectedItemIndex], event); } return true; } } } break; case MotionEvent.ACTION_UP: break; default: break; } return super.onTouchEvent(event); } public interface OnItemClickedListener { void onItemClick(int index, String label, MotionEvent event); } }
package com.arturmkrtchyan.sizeof4j; public class Main { public static void main(String[] args) { JvmUtil.printAll(); System.out.println("\n\nSizeOf"); System.out.println("================================="); System.out.println("byte: " + SizeOf.byteSize()); System.out.println("boolean: " + SizeOf.booleanSize()); System.out.println("short: " + SizeOf.shortSize()); System.out.println("char: " + SizeOf.charSize()); System.out.println("int: " + SizeOf.intSize()); System.out.println("float: " + SizeOf.floatSize()); System.out.println("long: " + SizeOf.longSize()); System.out.println("double: " + SizeOf.doubleSize()); System.out.println(" System.out.println("Object: " + SizeOf.objectShallowSize(new Object())); System.out.println("Integer: " + SizeOf.objectShallowSize(new Integer(2))); System.out.println("String: " + SizeOf.objectShallowSize(new String("aaa"))); System.out.println(" System.out.println("A: " + SizeOf.objectShallowSize(new A())); System.out.println("B: " + SizeOf.objectShallowSize(new B())); System.out.println("C: " + SizeOf.objectShallowSize(new C())); } private static class A { private int i; } private static class B { private int i; private java.util.Locale l = java.util.Locale.US; } private static class C { private int i; private java.util.HashMap hm = new java.util.HashMap(); } }
package com.emc.ecs.smart; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.filter.ClientFilter; import org.apache.log4j.LogMF; import org.apache.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; /** * Computes the MD5 of the upload body and validates the server's checksum on response. */ public class MD5CheckFilter extends ClientFilter { private static final Logger l4j = Logger.getLogger(MD5CheckFilter.class); @Override public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { if(clientRequest.getEntity() == null) { return getNext().handle(clientRequest); } // First, calculate the entity's MD5 String md5hex; Object entity = clientRequest.getEntity(); if(entity instanceof byte[]) { md5hex = MD5Utils.byteArrayMD5((byte[]) entity); } else if(entity instanceof ByteBuffer) { md5hex = MD5Utils.byteBufferMD5((ByteBuffer) entity); } else if(entity instanceof InputStream) { md5hex = MD5Utils.inputStreamMD5((InputStream) entity); } else { throw new ClientHandlerException("Could not handle entity of type " + entity.getClass()); } ClientResponse response = getNext().handle(clientRequest); // Extract MD5 from Etag header. String responseMd5Hex = getResponseMD5(response); if(responseMd5Hex == null) { LogMF.warn(l4j, "Could not extract MD5 from response. Request MD5={0}", md5hex); return response; } // Compare if(!responseMd5Hex.toLowerCase().equals(md5hex.toLowerCase())) { LogMF.warn(l4j, "MD5 Mismatch! Request: {0} Response: {1}", md5hex, responseMd5Hex); // Wrap in ClientHandlerException so the RetryFilter can catch it. throw new ClientHandlerException( new IOException(String.format("MD5 Mismatch! Request: %s Response: %s", md5hex, responseMd5Hex))); } LogMF.debug(l4j, "MD5 check ok: {0} = {1}", md5hex, responseMd5Hex); return response; } /** * Extracts the MD5 out of the response Etag header. * @param response response to parse * @return Etag parsed from the response or null if no MD5 could be found. */ private String getResponseMD5(ClientResponse response) { // First look for x-emc-content-md5 String contentMd5 = response.getHeaders().getFirst("x-emc-content-md5"); if(contentMd5 != null) { return contentMd5.toUpperCase(); } // Else, it might be in the Etag. String etag = response.getHeaders().getFirst("etag"); if(etag == null) { return null; } LogMF.debug(l4j, "Response Etag: {0}", etag); if(etag.startsWith("\"")) { etag = stripQuotes(etag); } if(etag.endsWith("-")) { LogMF.info(l4j, "Etag does not look like an MD5: {0}", etag); return null; } return etag.toUpperCase(); } private String stripQuotes(String etag) { return etag.substring(1, etag.length()-1); } }
package com.fundynamic.d2tm.game.map; import com.fundynamic.d2tm.game.entities.structures.Structure; import com.fundynamic.d2tm.game.entities.units.Unit; import com.fundynamic.d2tm.game.terrain.Terrain; import com.fundynamic.d2tm.game.terrain.TerrainFactory; import com.fundynamic.d2tm.graphics.Shroud; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.SlickException; public class Map { private static final int TILE_SIZE = 32; // If possible, get rid of this! private final TerrainFactory terrainFactory; private Shroud shroud; private final int height, width; private final int heightWithInvisibleBorder, widthWithInvisibleBorder; private Cell[][] cells; public Map(TerrainFactory terrainFactory, Shroud shroud, int width, int height) throws SlickException { this.terrainFactory = terrainFactory; this.shroud = shroud; this.height = height; this.width = width; this.heightWithInvisibleBorder = height + 2; this.widthWithInvisibleBorder = width + 2; initializeEmptyMap(); } public static Map generateRandom(TerrainFactory terrainFactory, Shroud shroud, int width, int height) { try { System.out.println("Generating random map sized " + width + "x" + height); Map map = new Map(terrainFactory, shroud, width, height); map.putTerrainOnMap(); map.smooth(); return map; } catch (SlickException e) { System.err.println("Exception while creating map with terrainFactory: " + terrainFactory + ", width: " + width + ", height: " + height + ". return null; } } public int getWidth() { return width; } public int getHeight() { return height; } /** * Get the exact cell on x,y directly from the internals. Only should be used for drawing (not for game logic). * The map class has an 'invisible border'. So a map of 64x64 is actually 66x66. * * @param x * @param y * @return */ public Cell getCell(int x, int y) { try { return cells[x][y]; } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("You're going out of bounds!\n" + "Parameters given: x = " + x + ", y = " + y + ".\n" + "You must keep within the dimensions:\n" + "Width: 0 to (not on or over!) " + widthWithInvisibleBorder + "\n" + "Height: 0 to (not on or over!) " + heightWithInvisibleBorder); } } public Cell getCellProtected(int x, int y) { int correctedX = x; if (correctedX < 0) correctedX = 0; if (correctedX >= widthWithInvisibleBorder) correctedX = widthWithInvisibleBorder - 1; int correctedY = y; if (correctedY < 0) correctedY = 0; if (correctedY >= heightWithInvisibleBorder) correctedY = heightWithInvisibleBorder - 1; return getCell(correctedX, correctedY); } private void initializeEmptyMap() { this.cells = new Cell[widthWithInvisibleBorder][heightWithInvisibleBorder]; for (int x = 0; x < widthWithInvisibleBorder; x++) { for (int y = 0; y < heightWithInvisibleBorder; y++) { Cell cell = new Cell(this, terrainFactory.createEmptyTerrain(), x, y); cell.setShrouded(false); cells[x][y] = cell; // This is quirky, but I think Cell will become part of a list and Map will no longer be an array then. } } } // @TODO: move this to a MapLoader / MapCreator / MapFactory / MapRepository private void putTerrainOnMap() { System.out.println("Putting terrain on map"); for (int x = 1; x <= this.width; x++) { for (int y = 1; y <= this.height; y++) { final Cell cell = getCell(x, y); final Terrain terrain = terrainFactory.create((int) (Math.random() * 7), cell); cell.setShrouded((int) (Math.random() * 2) == 0); cell.changeTerrain(terrain); } } } // TODO: This is more of a MapEditor method public void smooth() { System.out.println("Smoothing all cells"); for (int x = 1; x <= this.width; x++) { for (int y = 1; y <= this.height; y++) { Cell cell = getCell(x, y); final Terrain terrain = cell.getTerrain(); TerrainFacing facing = getFacing( terrain.isSame(cell.getCellAbove().getTerrain()), terrain.isSame(cell.getCellRight().getTerrain()), terrain.isSame(cell.getCellBeneath().getTerrain()), terrain.isSame(cell.getCellLeft().getTerrain())); terrain.setFacing(facing); } } } public int getWidthInPixels(int tileWidth) { return this.width * tileWidth; } public int getHeightInPixels(int tileHeight) { return this.height * tileHeight; } public Perimeter createViewablePerimeter(Vector2D screenResolution, int tileWidth, int tileHeight) { return new Perimeter(tileWidth, (getWidthInPixels(tileWidth) - tileWidth) - screenResolution.getX(), tileHeight, (getHeightInPixels(tileHeight) - tileHeight) - screenResolution.getY()); } public Shroud getShroud() { return shroud; } public Cell getCellByAbsolutePixelCoordinates(int pixelX, int pixelY) { return getCell(pixelX / TILE_SIZE, pixelY / TILE_SIZE); } // the reference to StructuresRepository.StructureData is a bit awkward public Unit placeUnit(Unit unit) { Vector2D mapCoordinates = unit.getMapCoordinates(); getCell(mapCoordinates).setEntity(unit); return unit; } // the reference to StructuresRepository.StructureData is a bit awkward // TODO: Add test for this method! public Structure placeStructure(Structure structure) { Vector2D topLeftMapCoordinates = structure.getMapCoordinates(); for (int x = 0; x < structure.getWidthInCells(); x++) { for (int y = 0; y < structure.getHeightInCells(); y++) { getCell(topLeftMapCoordinates.getXAsInt() + x, topLeftMapCoordinates.getYAsInt() + y).setEntity(structure); } } return structure; } public Cell getCell(Vector2D mapCoordinates) { return getCell(mapCoordinates.getXAsInt(), mapCoordinates.getYAsInt()); } private static final int BIT_MASK_NONE = 0; private static final int BIT_MASK_TOP = 0x0008; private static final int BIT_MASK_RIGHT = 0x0004; private static final int BIT_MASK_BOTTOM = 0x0002; private static final int BIT_MASK_LEFT = 0x0001; private static final TerrainFacing[] FACINGS = { TerrainFacing.MIDDLE, // 0x0000 TerrainFacing.TOP_RIGHT_BOTTOM, // 0x0001 TerrainFacing.TOP_RIGHT_LEFT, // 0x0010 TerrainFacing.TOP_RIGHT, // 0x0011 TerrainFacing.TOP_BOTTOM_LEFT, // 0x0100 TerrainFacing.TOP_BOTTOM, // 0x0101 TerrainFacing.TOP_LEFT, // 0x0110 TerrainFacing.TOP, // 0x0111 TerrainFacing.RIGHT_BOTTOM_LEFT, // 0x1000 TerrainFacing.RIGHT_BOTTOM, // 0x1001 TerrainFacing.RIGHT_LEFT, // 0x1010 TerrainFacing.RIGHT, // 0x1011 TerrainFacing.BOTTOM_LEFT, // 0x1100 TerrainFacing.BOTTOM, // 0x1101 TerrainFacing.LEFT, // 0x1110 TerrainFacing.FULL, // 0x1111 }; public static TerrainFacing getFacing(boolean isTopSame, boolean isRightSame, boolean isBottomSame, boolean isLeftSame) { int value = 0; value |= isTopSame ? BIT_MASK_TOP : BIT_MASK_NONE; value |= isRightSame ? BIT_MASK_RIGHT : BIT_MASK_NONE; value |= isBottomSame ? BIT_MASK_BOTTOM : BIT_MASK_NONE; value |= isLeftSame ? BIT_MASK_LEFT : BIT_MASK_NONE; return FACINGS[value]; } /** * This enum has types for all kind of facing for a specific TerrainType. (non-walls) * <p/> * The types are explained by looking at the graphical representation, and then pointing out * at what sides the terrain type is drawn. * <p/> * Example: * TerrainType = Rock * Looking at spritesheet, of rock. * The very first tile is a full rock tile, so the first type in the enum is FULL * The second tile (one to the right), is a tile with sand on the left, rock on the top, right, bottom. * (we go clockwise), so the enum is TOP_RIGHT_BOTTOM */ public static enum TerrainFacing { FULL, LEFT, RIGHT, TOP, BOTTOM, TOP_LEFT, RIGHT_BOTTOM, TOP_RIGHT, BOTTOM_LEFT, MIDDLE, TOP_BOTTOM, TOP_RIGHT_BOTTOM, TOP_BOTTOM_LEFT, RIGHT_BOTTOM_LEFT, TOP_RIGHT_LEFT, RIGHT_LEFT } }
package com.genesys.workspace; import com.genesys.internal.common.ApiClient; import com.genesys.internal.common.ApiException; import com.genesys.internal.common.ApiResponse; import com.genesys.internal.common.StringUtil; import com.genesys.workspace.models.targets.TargetsSearchOptions; import com.genesys.internal.workspace.model.ApiSuccessResponse; import com.genesys.internal.workspace.model.PersonalFavoriteData; import com.genesys.internal.workspace.model.RecentData; import com.genesys.internal.workspace.model.RecentTargetData; import com.genesys.internal.workspace.model.TargetsResponse; import com.genesys.internal.workspace.model.TargetsResponseData; import com.genesys.internal.workspace.model.TargetInformation; import com.genesys.internal.workspace.model.TargetspersonalfavoritessaveData; import com.genesys.internal.workspace.model.TargetsrecentsaddData; import com.genesys.workspace.common.WorkspaceApiException; import com.genesys.workspace.models.targets.AgentTarget; import com.genesys.workspace.models.targets.Target; import com.genesys.workspace.models.targets.SearchResult; import com.genesys.workspace.models.targets.TargetType; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TargetsApi { private com.genesys.internal.workspace.api.TargetsApi targetsApi; void initialize(ApiClient client) { this.targetsApi = new com.genesys.internal.workspace.api.TargetsApi(client); } void setTargetsApi(com.genesys.internal.workspace.api.TargetsApi targetsApi) { this.targetsApi = targetsApi; } /** * Search for targets by the specified search term. * @param searchTerm The text to search for in targets. * @return SearchResult<Target> */ public SearchResult<Target> search(String searchTerm) throws WorkspaceApiException { return search(searchTerm, new TargetsSearchOptions()); } /** * Search for targets by the specified search term. * @param searchTerm The text to search for in targets. * @param options Options used to refine the search. (optional) * @return SearchResult<Target> */ public SearchResult<Target> search(String searchTerm, TargetsSearchOptions options) throws WorkspaceApiException { try { String types = null; List<String> typesArray = null; if(options.getTypes() != null){ typesArray = new ArrayList<>(10); for(TargetType targetType: options.getTypes()){ typesArray.add(targetType.getValue()); } types = StringUtil.join(typesArray.toArray(new String[typesArray.size()]),","); } String excludeGroups = options.getExcludeGroups() !=null? StringUtil.join(options.getExcludeGroups(),","):null; String excludeFromGroups = options.getExcludeFromGroups() !=null? StringUtil.join(options.getExcludeFromGroups(),","): null; String restrictToGroups = options.getRestrictToGroups() !=null? StringUtil.join (options.getRestrictToGroups(),","): null; TargetsResponse response = this.targetsApi.getTargets(searchTerm, options.getFilterName(), types, excludeGroups, excludeFromGroups, restrictToGroups, options.isDesc()? "desc": null, options.getLimit() < 1? null: new BigDecimal(options.getLimit()), options.isExact()? "exact": null); TargetsResponseData data = response.getData(); List<Target> targets = new ArrayList<>(); if (data.getTargets() != null) { for (com.genesys.internal.workspace.model.Target t : data.getTargets()) { Target target = Target.fromTarget(t); targets.add(target); } } return new SearchResult<>(data.getTotalMatches(), targets); } catch (ApiException e) { throw new WorkspaceApiException("searchTargets failed.", e); } } /** * Add a target that the agent recently used. * @param target The target to add. * @param media The media channel on which the target was used. */ public void addRecentTarget(Target target, String media) throws WorkspaceApiException { addRecentTarget(target,media,System.currentTimeMillis()); } /** * Add a target that the agent recently used. * @param target The target to add. * @param media The media channel the where the target was recently used. * @param timestamp The timestamp for when the target was used. This value should be a number representing the milliseconds elapsed since the UNIX epoch. (optional) */ public void addRecentTarget(Target target, String media, long timestamp) throws WorkspaceApiException { try { TargetsrecentsaddData data = new TargetsrecentsaddData(); data.setTarget(toInformation(target)); RecentData recentData = new RecentData(); recentData.setMedia(media); recentData.setTimeStamp(new BigDecimal(timestamp)); data.setRecentInformation(recentData); RecentTargetData recentTargetData = new RecentTargetData(); recentTargetData.setData(data); ApiSuccessResponse resp = targetsApi.addRecentTarget(recentTargetData); Util.throwIfNotOk(resp); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot add recent target", ex); } } private TargetInformation toInformation(Target target) { TargetInformation information = new TargetInformation(); if(target instanceof AgentTarget) { information.setFirstName(((AgentTarget)target).getFirstName()); information.setLastName(((AgentTarget)target).getLastName()); information.setEmailAddresses(Arrays.asList(((AgentTarget)target).getEmailAddress())); } information.setNumbers(Arrays.asList(target.getNumber())); information.setType(target.getType().getValue()); return information; } /** * Get recently used targets for the current agent. * @return SearchResult<Target> */ public SearchResult<Target> getRecentTargets() throws WorkspaceApiException { return getRecentTargets(0); } /** * Get recently used targets for the current agent. * @param limit The number of results to return. The default value is 50. (optional) * @return SearchResult<Target> */ public SearchResult<Target> getRecentTargets(int limit) throws WorkspaceApiException { try { TargetsResponse resp = targetsApi.getRecentTargets(limit > 0? new BigDecimal(limit): null); Util.throwIfNotOk(resp.getStatus()); TargetsResponseData data = resp.getData(); int total = 0; List<Target> list = new ArrayList<>(); if(data != null) { total = data.getTotalMatches(); if(data.getTargets() != null) { for (com.genesys.internal.workspace.model.Target t : data.getTargets()) { Target target = Target.fromTarget(t); list.add(target); } } } return new SearchResult<>(total, list); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot get recent targets", ex); } } /** * Get a specific target by type and ID. Targets can be agents, agent groups, queues, route points, skills, and custom contacts. * @param id The ID of the target. * @param type The type of target to retrieve. The possible values are AGENT, AGENT_GROUP, ACD_QUEUE, ROUTE_POINT, SKILL, and CUSTOM_CONTACT. * @return Target */ public Target getTarget(long id, TargetType type) throws WorkspaceApiException { try { TargetsResponse resp = targetsApi.getTarget(new BigDecimal(id), type.getValue()); Util.throwIfNotOk(resp.getStatus()); Target target = null; if(resp.getData() != null) { List<com.genesys.internal.workspace.model.Target> targets = resp.getData().getTargets(); if(targets != null && targets.size() > 0) { target = Target.fromTarget(targets.get(0)); } } return target; } catch(ApiException ex) { throw new WorkspaceApiException("Cannot get target", ex); } } /** * Delete the target from the agent's personal favorites. * @param target The target to delete. */ public void deletePersonalFavorite(Target target) throws WorkspaceApiException { try { ApiSuccessResponse resp = targetsApi.deletePersonalFavorite(String.valueOf(target.getId()), target.getType().getValue()); Util.throwIfNotOk(resp); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot delete personal favorite", ex); } } /** * Get the agent's personal favorites. * @return SearchResult<Target> */ public SearchResult<Target> getPersonalFavorites() throws WorkspaceApiException { return getPersonalFavorites(0); } /** * Get the agent's personal favorites. * @param limit Number of results to return. The default value is 50. (optional) * @return SearchResult<Target> */ public SearchResult<Target> getPersonalFavorites(int limit) throws WorkspaceApiException { try { TargetsResponse resp = targetsApi.getPersonalFavorites(limit > 0? new BigDecimal(limit): null); Util.throwIfNotOk(resp.getStatus()); TargetsResponseData data = resp.getData(); int total = 0; List<Target> list = new ArrayList<>(); if(data != null) { total = data.getTotalMatches(); if(data.getTargets() != null) { for (com.genesys.internal.workspace.model.Target t : data.getTargets()) { Target target = Target.fromTarget(t); list.add(target); } } } return new SearchResult<>(total, list); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot personal favorites", ex); } } /** * Save a target to the agent's personal favorites in the specified category. * @param target The target to save. * @param category The agent's personal favorites category. */ public void savePersonalFavorite(Target target, String category) throws WorkspaceApiException { TargetspersonalfavoritessaveData data = new TargetspersonalfavoritessaveData(); data.setCategory(category); data.setTarget(toInformation(target)); PersonalFavoriteData favData = new PersonalFavoriteData(); favData.setData(data); try { ApiSuccessResponse resp = targetsApi.savePersonalFavorite(favData); Util.throwIfNotOk(resp); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot save personal favorites", ex); } } /** * Acknowledge missed calls in the list of recent targets. */ public void ackRecentMissedCalls() throws WorkspaceApiException { try { ApiSuccessResponse resp = targetsApi.ackRecentMissedCalls(); Util.throwIfNotOk(resp); } catch(ApiException ex) { throw new WorkspaceApiException("Cannot ack recent missed calls", ex); } } }
package com.github.davidmoten.rx; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import com.github.davidmoten.rx.internal.operators.OnSubscribeReader; import rx.Observable; import rx.functions.Action1; import rx.functions.Action2; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func2; public final class Strings { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); /** * Returns null if input is null otherwise returns input.toString().trim(). */ private static Func1<Object, String> TRIM = new Func1<Object, String>() { @Override public String call(Object input) { if (input == null) return null; else return input.toString().trim(); } }; @SuppressWarnings("unchecked") public static <T> Func1<T, String> trim() { return (Func1<T, String>) TRIM; } public static Observable<String> from(Reader reader, int bufferSize) { return Observable.create(new OnSubscribeReader(reader, bufferSize)); } public static Observable<String> from(Reader reader) { return from(reader, 8192); } public static Observable<String> from(InputStream is) { return from(new InputStreamReader(is)); } public static Observable<String> from(InputStream is, Charset charset) { return from(new InputStreamReader(is, charset)); } public static Observable<String> from(InputStream is, Charset charset, int bufferSize) { return from(new InputStreamReader(is, charset), bufferSize); } public static Observable<String> split(Observable<String> source, String pattern) { return source.compose(Transformers.split(pattern)); } public static Observable<String> concat(Observable<String> source) { return concat(source, ""); } public static Observable<String> concat(Observable<String> source, final String delimiter) { return strings(source.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() { @Override public StringBuilder call(StringBuilder a, String b) { if (a.length() > 0) a.append(delimiter); return a.append(b); } })); } public static Observable<String> strings(Observable<?> source) { return source.map(new Func1<Object, String>() { @Override public String call(Object t) { return String.valueOf(t); } }); } public static Observable<String> from(File file) { return from(file, DEFAULT_CHARSET); } public static Observable<String> from(final File file, final Charset charset) { Func0<Reader> resourceFactory = new Func0<Reader>() { @Override public Reader call() { try { return new InputStreamReader(new FileInputStream(file), charset); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }; Func1<Reader, Observable<String>> observableFactory = new Func1<Reader, Observable<String>>() { @Override public Observable<String> call(Reader is) { return from(is); } }; Action1<Reader> disposeAction = new Action1<Reader>() { @Override public void call(Reader is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } }; return Observable.using(resourceFactory, observableFactory, disposeAction, true); } public Observable<String> join(Observable<String> source) { return join(source, ""); } public Observable<String> join(Observable<String> source, final String delimiter) { return source.collect(new Func0<StringBuilder>() { @Override public StringBuilder call() { return new StringBuilder(); } }, new Action2<StringBuilder, String>() { @Override public void call(StringBuilder b, String s) { b.append(delimiter); b.append(s); } }).map(new Func1<StringBuilder, String>() { @Override public String call(StringBuilder b) { return b.toString(); } }); } }
package com.github.lstephen.ootp.ai; import com.github.lstephen.ootp.ai.config.Config; import com.github.lstephen.ootp.ai.data.Id; import com.github.lstephen.ootp.ai.draft.DraftReport; import com.github.lstephen.ootp.ai.io.Printables; import com.github.lstephen.ootp.ai.ootp5.report.SpringTraining; import com.github.lstephen.ootp.ai.player.Player; import com.github.lstephen.ootp.ai.player.ratings.PlayerRatings; import com.github.lstephen.ootp.ai.regression.BattingPrediction; import com.github.lstephen.ootp.ai.regression.Predictor; import com.github.lstephen.ootp.ai.regression.Predictor$; import com.github.lstephen.ootp.ai.report.DevelopmentReport; import com.github.lstephen.ootp.ai.report.FreeAgents; import com.github.lstephen.ootp.ai.report.GenericValueReport; import com.github.lstephen.ootp.ai.report.HistorialDevelopmentReport; import com.github.lstephen.ootp.ai.report.HittingSelectionReport; import com.github.lstephen.ootp.ai.report.LeagueBattingReport; import com.github.lstephen.ootp.ai.report.PitchingStrategyReport; import com.github.lstephen.ootp.ai.report.PotentialVsActualReport; import com.github.lstephen.ootp.ai.report.SalaryReport; import com.github.lstephen.ootp.ai.report.TeamPositionReport; import com.github.lstephen.ootp.ai.report.TeamReport; import com.github.lstephen.ootp.ai.roster.Changes; import com.github.lstephen.ootp.ai.roster.Changes.ChangeType; import com.github.lstephen.ootp.ai.roster.FourtyManRoster; import com.github.lstephen.ootp.ai.roster.Moves; import com.github.lstephen.ootp.ai.roster.Roster; import com.github.lstephen.ootp.ai.roster.Roster.Status; import com.github.lstephen.ootp.ai.roster.RosterSelection; import com.github.lstephen.ootp.ai.roster.Team; import com.github.lstephen.ootp.ai.selection.BestStartersSelection; import com.github.lstephen.ootp.ai.selection.Mode; import com.github.lstephen.ootp.ai.selection.Selections; import com.github.lstephen.ootp.ai.selection.bench.Bench; import com.github.lstephen.ootp.ai.selection.depthchart.AllDepthCharts; import com.github.lstephen.ootp.ai.selection.depthchart.DepthChartSelection; import com.github.lstephen.ootp.ai.selection.lineup.AllLineups; import com.github.lstephen.ootp.ai.selection.lineup.LineupSelection; import com.github.lstephen.ootp.ai.selection.rotation.Rotation; import com.github.lstephen.ootp.ai.selection.rotation.RotationSelection; import com.github.lstephen.ootp.ai.site.SingleTeam; import com.github.lstephen.ootp.ai.site.Site; import com.github.lstephen.ootp.ai.site.SiteDefinition; import com.github.lstephen.ootp.ai.site.SiteHolder; import com.github.lstephen.ootp.ai.site.impl.SiteDefinitionFactory; import com.github.lstephen.ootp.ai.stats.SplitPercentages; import com.github.lstephen.ootp.ai.stats.SplitPercentagesHolder; import com.github.lstephen.ootp.ai.stats.SplitStats; import com.github.lstephen.ootp.ai.value.JavaAdapter; import com.github.lstephen.ootp.ai.value.PlayerValue; import com.github.lstephen.ootp.ai.value.ReplacementLevels$; import com.github.lstephen.ootp.extract.html.Page; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Stopwatch; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.joda.time.DateTimeConstants; /** @author lstephen */ public class Main { private static final Logger LOG = Logger.getLogger(Main.class.getName()); private static final SiteDefinition TWML = SiteDefinitionFactory.ootp6( "TWML", "http: Id.<Team>valueOf(15), "Splendid Splinter", 16); private static final SiteDefinition CBL = SiteDefinitionFactory.ootp5( "CBL", "http: private static final SiteDefinition HFTC = SiteDefinitionFactory.ootp5( "HFTC", "http: private static final SiteDefinition OLD_BTH_CHC = SiteDefinitionFactory.ootp6( "BTH", "http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/", Id.<Team>valueOf(20), "National", 30); private static final SiteDefinition OLD_BTH_NYY = SiteDefinitionFactory.ootp6( "OLD_BTH_NYY", "http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/", Id.<Team>valueOf(3), "American", 30); private static final SiteDefinition BTHUSTLE = SiteDefinitionFactory.ootp6( "BTHUSTLE", "http://bthbaseball.allsimbaseball10.com/game/lgreports/", Id.<Team>valueOf(14), "National", 16); private static final SiteDefinition SAVOY = SiteDefinitionFactory.ootp5( "SAVOY", "http: private static final SiteDefinition LBB = SiteDefinitionFactory.ootp5( "LBB", "http://longballer2.x10host.com/LBB.lg/leaguesite/", Id.<Team>valueOf(3), "AL", 20); private static final SiteDefinition GABL = SiteDefinitionFactory.ootp5( "GABL", "http: Id.<Team>valueOf(22), "National", 30); private static final SiteDefinition TFMS = SiteDefinitionFactory.ootp5("TFMS", "tfms5-2004/", Id.<Team>valueOf(3), "League 2", 16); private static final ImmutableMap<String, SiteDefinition> SITES = ImmutableMap.<String, SiteDefinition>builder() .put("TWML", TWML) .put("CBL", CBL) .put("HFTC", HFTC) .put("OLD_BTH_CHC", OLD_BTH_CHC) .put("OLD_BTH_NYY", OLD_BTH_NYY) .put("BTHUSTLE", BTHUSTLE) .put("LBB", LBB) .put("SAVOY", SAVOY) .put("GABL", GABL) .build(); private static ImmutableSet<SiteDefinition> LOOK_TO_NEXT_SEASON = ImmutableSet.of(); private static ImmutableSet<SiteDefinition> INAUGURAL_DRAFT = ImmutableSet.of(); public static void main(String[] args) throws IOException { new Main().run(); } public void run() throws IOException { String site = System.getenv("OOTPAI_SITE"); if (site == null) { throw new IllegalStateException("OOTPAI_SITE is required"); } run(SITES.get(site)); } private void run(SiteDefinition def) throws IOException { Preconditions.checkNotNull(def, "SiteDefinition not found"); File outputDirectory = new File(Config.createDefault().getValue("output.dir").or("c:/ootp")); try (FileOutputStream out = new FileOutputStream(new File(outputDirectory, def.getName() + ".txt"), false)) { run(def, out); } } private void run(SiteDefinition def, OutputStream out) throws IOException { LOG.log(Level.INFO, "Running for {0}...", def.getName()); String clearCache = System.getenv("OOTPAI_CLEAR_CACHE"); if ("true".equals(clearCache)) { LOG.log(Level.INFO, "Clearing cache..."); def.getSite().clearCache(); } Boolean isLookToNextSeason = Boolean.FALSE; if (LOOK_TO_NEXT_SEASON.contains(def)) { isLookToNextSeason = Boolean.TRUE; } final Site site = def.getSite(); SiteHolder.set(site); LOG.log(Level.INFO, "Warming team cache..."); site.getTeamIds() .parallelStream() .flatMap( id -> Stream.of("team%s.html", "team%spr.html", "team%ssa.html") .map(s -> String.format(s, id.get()))) .map(site::getPage) .forEach(Page::load); LOG.log(Level.INFO, "Warming player cache..."); site.getAllPlayers(); Printables.print(LeagueBattingReport.create(site)).to(out); LOG.log(Level.INFO, "Extracting current roster and team..."); Roster oldRoster = site.extractRoster(); Context$.MODULE$.oldRoster_$eq(oldRoster); Team team = site.extractTeam(); LOG.log(Level.INFO, "Calculating SplitPercentages..."); SplitPercentages pcts = SplitPercentages.create(site); SplitPercentagesHolder.set(pcts); SplitStats.setPercentages(pcts); PlayerRatings.setPercentages(pcts); BestStartersSelection.setPercentages(pcts); Bench.setPercentages(pcts); pcts.print(out); LOG.info("Training regressions and running predictions..."); final Predictor predictor = Predictor$.MODULE$.train(site); Printables.print(predictor.correlationReport()).to(out); Context$.MODULE$.currentPredictor_$eq(predictor); LOG.info("Loading manual changes..."); Changes changes = Changes.load(site); team.processManualChanges(changes); boolean isPreseason = site.getDate().getMonthOfYear() < DateTimeConstants.APRIL; boolean isExpandedRosters = site.getDate().getMonthOfYear() == DateTimeConstants.SEPTEMBER; boolean isPlayoffs = site.getDate().getMonthOfYear() >= DateTimeConstants.OCTOBER || "true".equals(System.getenv("OOTPAI_PLAYOFFS")); int month = site.getDate().getMonthOfYear(); Mode mode = Mode.REGULAR_SEASON; if (isPreseason) { mode = Mode.PRESEASON; } else if (isExpandedRosters) { mode = Mode.EXPANDED; } else if (isPlayoffs) { mode = Mode.PLAYOFFS; } LOG.info("Loading FAS..."); FreeAgents fas = FreeAgents.create(site, changes, predictor); RosterSelection selection = new RosterSelection(team, predictor); selection.setPrevious(oldRoster); LOG.log(Level.INFO, "Selecting ideal roster..."); Context$.MODULE$.idealRoster_$eq(selection.select(Mode.IDEAL)); LOG.info("Calculating top FA targets..."); Iterable<Player> topFaTargets = fas.getTopTargets(mode); Integer minRosterSize = 70; Integer maxRosterSize = 75; ImmutableSet<Player> futureFas = ImmutableSet.of(); if (isLookToNextSeason) { futureFas = ImmutableSet.copyOf(Iterables.filter(team, site.isFutureFreeAgent())); System.out.print("Removing (FA):"); for (Player p : Player.byShortName().immutableSortedCopy(futureFas)) { System.out.print(p.getShortName() + "/"); } System.out.println(); team.remove(futureFas); } LOG.log(Level.INFO, "Selecting new rosters..."); Stopwatch sw = Stopwatch.createStarted(); Mode selectionMode = mode; if (isPlayoffs) { selectionMode = Mode.PLAYOFFS; } Roster newRoster = selection.select(selectionMode, changes); newRoster.setTargetMinimum(minRosterSize); newRoster.setTargetMaximum(maxRosterSize); Context$.MODULE$.newRoster_$eq(newRoster); sw.stop(); LOG.log(Level.INFO, "Roster selection time: " + sw); Printables.print(new HittingSelectionReport(newRoster, predictor, site.getTeamBatting())) .to(out); selection.printPitchingSelectionTable(out, newRoster, site.getTeamPitching()); Printables.print(newRoster).to(out); LOG.info("Calculating roster changes..."); Printables.print(newRoster.getChangesFrom(oldRoster)).to(out); LOG.log(Level.INFO, "Choosing rotation..."); Rotation rotation = RotationSelection.forMode(selectionMode, predictor) .useAllAvailable() .selectRotation( ImmutableSet.<Player>of(), Selections.onlyPitchers(newRoster.getPlayers(Status.ML))); Printables.print(rotation).to(out); Printables.print(new PitchingStrategyReport(rotation, predictor)).to(out); LOG.log(Level.INFO, "Choosing lineups..."); BattingPrediction pitcherHitting = rotation.getPitcherHitting(predictor); LOG.log( Level.INFO, "Pitcher Hitting: vsL:" + pitcherHitting.vsLeft().getSlashLine() + " vsR:" + pitcherHitting.vsRight().getSlashLine()); AllLineups lineups = new LineupSelection(predictor) .select(Selections.onlyHitters(newRoster.getPlayers(Status.ML))); LOG.log(Level.INFO, "Choosing Depth Charts..."); AllDepthCharts depthCharts = new DepthChartSelection(predictor).select(lineups, newRoster.getPlayers(Status.ML)); Printables.print(depthCharts).to(out); Printables.print(lineups).to(out); LOG.info("Salary report..."); SalaryReport salary = new SalaryReport(team, site.getSalary(), site.getFinancials(), predictor); final GenericValueReport generic = new GenericValueReport(team, predictor, salary); generic.setReverse(false); LOG.log(Level.INFO, "Strategy..."); generic.setTitle("Bunt for Hit"); generic.setPlayers( newRoster .getPlayers(Status.ML) .stream() .filter(p -> p.getBuntForHitRating().normalize().get() > 80) .collect(Collectors.toSet())); generic.print(out); double stealingBreakEven = 0.590 + 3.33 * lineups.getHomeRunsPerPlateAppearance(predictor); generic.setTitle("Stealing @ " + String.format("%.1f", stealingBreakEven * 100.0)); generic.setPlayers( newRoster .getPlayers(Status.ML) .stream() .filter(p -> p.getStealingRating().normalize().get() > stealingBreakEven * 100.0) .collect(Collectors.toSet())); generic.print(out); if (def.getName().equals("BTHUSTLE")) { LOG.info("40 man roster reports..."); FourtyManRoster fourtyMan = new FourtyManRoster(team, newRoster, predictor); fourtyMan.setChanges(changes); Printables.print(fourtyMan).to(out); generic.setTitle("+40"); generic.setPlayers( ImmutableSet.<Player>builder() .addAll(fourtyMan.getPlayersToAdd()) .addAll( FluentIterable.from(changes.get(ChangeType.FOURTY_MAN)) .filter(Predicates.in(newRoster.getAllPlayers()))) .build()); generic.print(out); generic.setTitle("-40"); generic.setPlayers(fourtyMan.getPlayersToRemove()); generic.print(out); generic.setTitle("Waive"); generic.setPlayers(isExpandedRosters ? ImmutableSet.of() : fourtyMan.getPlayersToWaive()); generic.print(out); LOG.info("Waviers report..."); generic.setTitle("Waivers"); generic.setPlayers(site.getWaiverWire()); generic.print(out); if (site.getDate().getMonthOfYear() < DateTimeConstants.APRIL) { LOG.info("AFL..."); generic.setTitle("AFL"); generic.setPlayers(Iterables.filter(newRoster.getAllPlayers(), Player::isAflEligible)); generic.print(out); LOG.info("Winter ball..."); generic.setTitle("Winter ball"); generic.setPlayers(Iterables.filter(newRoster.getAllPlayers(), Player::isWinterEligible)); generic.print(out); LOG.info("Rule 5..."); generic.setTitle("Rule 5"); generic.setPlayers( Iterables.filter( site.getRuleFiveDraft(), new Predicate<Player>() { public boolean apply(Player p) { return JavaAdapter.nowValue(p, predictor).vsReplacement().get().toLong() >= 0; } })); generic.print(out); } LOG.info("T=O..."); generic.setTitle("T=O"); generic.setPlayers( Iterables.filter( newRoster.getAllPlayers(), p -> { if (!p.isTOEligible()) { return false; } Long current = JavaAdapter.nowValue(p, predictor).vsReplacement().get().toLong(); Long future = JavaAdapter.futureValue(p, predictor).vsReplacement().isEmpty() ? 0 : JavaAdapter.futureValue(p, predictor).vsReplacement().get().toLong(); if (p.getAge() <= 25 && future > 0) { return true; } return false; })); generic.print(out); LOG.info("SP to MR..."); generic.setTitle("SP to MR"); generic.setPlayers(Iterables.filter(newRoster.getAllPlayers(), Player::isSpToMrEligible)); generic.print(out); } Moves moves = new Moves(newRoster, changes, predictor); generic.setTitle("Release"); generic.setPlayers(moves.getRelease()); generic.print(out); generic.setTitle("Sign"); generic.setPlayers(moves.getSign()); generic.print(out); if (site.getDate().getMonthOfYear() == DateTimeConstants.MARCH) { LOG.log(Level.INFO, "Spring training..."); Printables.print(SpringTraining.create(site.getType(), newRoster.getAllPlayers())).to(out); } Printables.print(ReplacementLevels$.MODULE$.getForIdeal(predictor)).to(out); LOG.info("Development Report..."); Printables.print(new DevelopmentReport(site, predictor)).to(out); LOG.info("Historial Development Report..."); Printables.print(new HistorialDevelopmentReport(site, predictor)).to(out); LOG.info("Potential vs actual Report..."); Printables.print(new PotentialVsActualReport(site)).to(out); LOG.info("Draft..."); ImmutableSet<Player> drafted = ImmutableSet.copyOf(changes.get(Changes.ChangeType.PICKED)); Iterable<Player> remaining = Sets.difference( ImmutableSet.copyOf(FluentIterable.from(site.getDraft()).filter(Predicates.notNull())), drafted); if (!Iterables.isEmpty(remaining)) { generic.setTitle("Drafted"); generic.setPlayers(drafted); generic.print(out); generic.setTitle("Remaining"); generic.setPlayers(remaining); generic.print(out); } DraftReport.create(site, predictor).print(out); Printables.print(salary).to(out); LOG.info("Extensions report..."); generic.setTitle("Extensions"); generic.setPlayers( Iterables.concat( Iterables.filter(newRoster.getAllPlayers(), site.isFutureFreeAgent()), futureFas)); generic.print(out); LOG.info("Arbitration report..."); generic.setTitle("Arbitration"); generic.setPlayers( Iterables.filter( newRoster.getAllPlayers(), new Predicate<Player>() { public boolean apply(Player p) { return p.getSalary().endsWith("a"); } })); generic.print(out); LOG.info("FA report..."); generic.setTitle("Top Targets"); generic.setPlayers(topFaTargets); generic.print(out); generic.setTitle("Free Agents"); generic.setPlayers(site.getFreeAgents()); generic.setLimit(50); generic.print(out); Printables.print(new TeamPositionReport(newRoster, predictor)).to(out); generic.setTitle("Trade Values"); generic.setPlayers(Iterables.concat(newRoster.getAllPlayers(), futureFas)); generic.setLimit(200); generic.print(out); Set<Player> all = Sets.newHashSet(); Set<Player> minorLeaguers = Sets.newHashSet(); LOG.log(Level.INFO, "Team reports..."); generic.setLimit(50); int n = Iterables.size(site.getTeamIds()); int count = 1; for (Id<Team> id : site.getTeamIds()) { SingleTeam t = site.getSingleTeam(id); LOG.log(Level.INFO, "{0} ({1}/{2})...", new Object[] {t.getName(), count, n}); generic.setTitle(t.getName()); Roster r = t.getRoster(); Iterables.addAll(all, r.getAllPlayers()); Iterables.addAll(minorLeaguers, r.getPlayers(Status.AAA)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.AA)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.A)); generic.setPlayers(r.getAllPlayers()); generic.print(out); count++; } TeamReport now = TeamReport.create("Now", predictor, site, new PlayerValue(predictor).getNowValue()); LOG.info("Team Now Report..."); now.sortByEndOfSeason(); Printables.print(now).to(out); generic.useDefaultValueFunction(); LOG.log(Level.INFO, "Non Top 10 prospects..."); ImmutableSet<Player> nonTopTens = ImmutableSet.copyOf( Iterables.filter( all, new Predicate<Player>() { public boolean apply(Player p) { return !p.getTeamTopProspectPosition().isPresent() && p.getAge() <= 25 && site.getCurrentSalary(p) == 0; } })); generic.setTitle("Non Top prospects"); generic.setLimit(50); generic.setPlayers(nonTopTens); generic.print(out); LOG.log(Level.INFO, "Minor league non-prospects..."); ImmutableSet<Player> mlNonProspects = ImmutableSet.copyOf( Iterables.filter( minorLeaguers, new Predicate<Player>() { public boolean apply(Player p) { return p.getAge() > 25; } })); generic.setTitle("ML non-prospects"); generic.setPlayers(mlNonProspects); generic.print(out); if (def.getName().equals("BTHUSTLE")) { LOG.info("SP to MR..."); generic.setTitle("SP to MR"); generic.setPlayers(Iterables.filter(Iterables.concat(all, site.getFreeAgents()), Player::isSpToMrEligible)); generic.print(out); } LOG.log(Level.INFO, "Done."); } }
package com.afollestad.silk.fragments; import android.os.Bundle; import android.view.View; import com.afollestad.silk.Silk; import com.afollestad.silk.caching.SilkComparable; import com.afollestad.silk.views.list.SilkListView; import java.util.List; /** * @author Aidan Follestad (afollestad) */ public abstract class SilkFeedFragment<ItemType extends SilkComparable> extends SilkListFragment<ItemType> { private boolean mBlockPaginate = false; public static class OfflineException extends Exception { public OfflineException() { super("You are currently offline."); } } protected int getAddIndex() { return -1; } protected void onPreLoad() { } protected void onPostLoad(List<ItemType> results, boolean paginated) { if (results != null) { if (paginated || getAddIndex() < 0) { getAdapter().add(results); } else { getAdapter().add(getAddIndex(), results); } } setLoadComplete(false); } protected abstract List<ItemType> refresh() throws Exception; protected abstract List<ItemType> paginate() throws Exception; protected abstract void onError(Exception e); public void performRefresh(boolean showProgress) { if (isLoading()) return; setLoading(showProgress); onPreLoad(); Thread t = new Thread(new Runnable() { @Override public void run() { try { if (!Silk.isOnline(getActivity())) throw new OfflineException(); final List<ItemType> items = refresh(); runOnUiThread(new Runnable() { @Override public void run() { onPostLoad(items, false); } }); } catch (final Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { onError(e); setLoadComplete(true); } }); } } }); t.setPriority(Thread.MAX_PRIORITY); t.start(); } public void performPaginate(boolean showProgress) { if (isLoading()) return; else if (mBlockPaginate) return; setLoading(showProgress); Thread t = new Thread(new Runnable() { @Override public void run() { try { if (!Silk.isOnline(getActivity())) throw new OfflineException(); final List<ItemType> items = paginate(); if (items == null || items.size() == 0) mBlockPaginate = true; runOnUiThread(new Runnable() { @Override public void run() { int beforeCount = getAdapter().getCount(); onPostLoad(items, true); if (items != null) getListView().smoothScrollToPosition(beforeCount); } }); } catch (final Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { onError(e); setLoadComplete(true); } }); } } }); t.setPriority(Thread.MAX_PRIORITY); t.start(); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); performRefresh(true); if (getListView() instanceof SilkListView) { ((SilkListView)getListView()).setOnSilkScrollListener(new SilkListView.OnSilkScrollListener() { @Override public void onScrollToTop() { } @Override public void onScrollToBottom() { performPaginate(false); } }); } } }
package com.digi.xbee.api; import java.io.IOException; import java.net.Inet6Address; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import com.digi.xbee.api.utils.srp.SrpUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import com.digi.xbee.api.connection.IConnectionInterface; import com.digi.xbee.api.connection.DataReader; import com.digi.xbee.api.connection.android.AndroidUSBPermissionListener; import com.digi.xbee.api.connection.serial.SerialPortParameters; import com.digi.xbee.api.exceptions.ATCommandException; import com.digi.xbee.api.exceptions.InterfaceNotOpenException; import com.digi.xbee.api.exceptions.InvalidOperatingModeException; import com.digi.xbee.api.exceptions.OperationNotSupportedException; import com.digi.xbee.api.exceptions.TimeoutException; import com.digi.xbee.api.exceptions.TransmitException; import com.digi.xbee.api.exceptions.XBeeException; import com.digi.xbee.api.io.IOLine; import com.digi.xbee.api.io.IOMode; import com.digi.xbee.api.io.IOSample; import com.digi.xbee.api.io.IOValue; import com.digi.xbee.api.listeners.IExplicitDataReceiveListener; import com.digi.xbee.api.listeners.IIOSampleReceiveListener; import com.digi.xbee.api.listeners.IModemStatusReceiveListener; import com.digi.xbee.api.listeners.IIPDataReceiveListener; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.IDataReceiveListener; import com.digi.xbee.api.listeners.ISMSReceiveListener; import com.digi.xbee.api.listeners.IUserDataRelayReceiveListener; import com.digi.xbee.api.models.ATCommand; import com.digi.xbee.api.models.ATCommandResponse; import com.digi.xbee.api.models.ATCommandStatus; import com.digi.xbee.api.models.AssociationIndicationStatus; import com.digi.xbee.api.models.HardwareVersion; import com.digi.xbee.api.models.PowerLevel; import com.digi.xbee.api.models.RemoteATCommandOptions; import com.digi.xbee.api.models.RestFulStatusEnum; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBeeProtocol; import com.digi.xbee.api.models.XBeeTransmitStatus; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ATCommandPacket; import com.digi.xbee.api.packet.common.ATCommandQueuePacket; import com.digi.xbee.api.packet.common.ATCommandResponsePacket; import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket; import com.digi.xbee.api.packet.common.RemoteATCommandPacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.common.TransmitStatusPacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.TXStatusPacket; import com.digi.xbee.api.packet.thread.CoAPRxResponsePacket; import com.digi.xbee.api.packet.thread.CoAPTxRequestPacket; import com.digi.xbee.api.packet.thread.IPv6RemoteATCommandRequestPacket; import com.digi.xbee.api.packet.thread.IPv6RemoteATCommandResponsePacket; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; /** * This class provides common functionality for all XBee devices. * * @see XBeeDevice * @see RemoteXBeeDevice */ public abstract class AbstractXBeeDevice { // Constants. /** * Default receive timeout used to wait for a response in synchronous * operations: {@value} ms. * * @see XBeeDevice#getReceiveTimeout() * @see XBeeDevice#setReceiveTimeout(int) */ protected final static int DEFAULT_RECEIVE_TIMETOUT = 2000; // 2.0 seconds of timeout to receive packet and command responses. /** * Timeout to wait before entering in command mode: {@value} ms. * * <p>It is used to determine the operating mode of the module (this * library only supports API modes, not transparent mode).</p> * * <p>This value depends on the {@code GT}, {@code AT} and/or {@code BT} * parameters.</p> * * @see XBeeDevice#determineOperatingMode() */ protected final static int TIMEOUT_BEFORE_COMMAND_MODE = 1200; /** * Timeout to wait after entering in command mode: {@value} ms. * * <p>It is used to determine the operating mode of the module (this * library only supports API modes, not transparent mode).</p> * * <p>This value depends on the {@code GT}, {@code AT} and/or {@code BT} * parameters.</p> * * @see XBeeDevice#determineOperatingMode() */ protected final static int TIMEOUT_ENTER_COMMAND_MODE = 1500; // Variables. protected IConnectionInterface connectionInterface; protected DataReader dataReader = null; protected XBeeProtocol xbeeProtocol = XBeeProtocol.UNKNOWN; protected OperatingMode operatingMode = OperatingMode.UNKNOWN; protected XBee16BitAddress xbee16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; protected XBee64BitAddress xbee64BitAddress = XBee64BitAddress.UNKNOWN_ADDRESS; protected Inet6Address ipv6Address = null; protected int currentFrameID = 0xFF; protected int receiveTimeout = DEFAULT_RECEIVE_TIMETOUT; protected AbstractXBeeDevice localXBeeDevice; protected Logger logger; private String nodeID; private String firmwareVersion; private HardwareVersion hardwareVersion; private Object ioLock = new Object(); private boolean ioPacketReceived = false; private boolean applyConfigurationChanges = true; private byte[] ioPacketPayload; public AbstractXBeeDevice(String port, int baudRate) { this(XBee.createConnectiontionInterface(port, baudRate)); } public AbstractXBeeDevice(String port, int baudRate, int dataBits, int stopBits, int parity, int flowControl) { this(port, new SerialPortParameters(baudRate, dataBits, stopBits, parity, flowControl)); } public AbstractXBeeDevice(String port, SerialPortParameters serialPortParameters) { this(XBee.createConnectiontionInterface(port, serialPortParameters)); } public AbstractXBeeDevice(Context context, int baudRate) { this(XBee.createConnectiontionInterface(context, baudRate)); } public AbstractXBeeDevice(Context context, int baudRate, AndroidUSBPermissionListener permissionListener) { this(XBee.createConnectiontionInterface(context, baudRate, permissionListener)); } public AbstractXBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; this.logger = LoggerFactory.getLogger(this.getClass()); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName()); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress addr64) { this(localXBeeDevice, addr64, null, null); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress addr64, XBee16BitAddress addr16, String id) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (addr64 == null) throw new NullPointerException("XBee 64-bit address of the device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = addr64; this.xbee16BitAddress = addr16; if (addr16 == null) xbee16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; this.nodeID = id; this.logger = LoggerFactory.getLogger(this.getClass()); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName()); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, Inet6Address ipv6Addr) { this(localXBeeDevice, ipv6Addr, null); } public AbstractXBeeDevice(XBeeDevice localXBeeDevice, Inet6Address ipv6Addr, String id) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (ipv6Addr == null) throw new NullPointerException("XBee IPv6 address of the device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.ipv6Address = ipv6Addr; this.nodeID = id; this.logger = LoggerFactory.getLogger(this.getClass()); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName()); } /** * Returns the connection interface associated to this XBee device. * * @return XBee device's connection interface. * * @see com.digi.xbee.api.connection.IConnectionInterface */ public IConnectionInterface getConnectionInterface() { return connectionInterface; } /** * Returns whether this XBee device is a remote device. * * @return {@code true} if this XBee device is a remote device, * {@code false} otherwise. */ abstract public boolean isRemote(); /** * Reads some parameters from this device and obtains its protocol. * * <p>This method refresh the values of:</p> * <ul> * <li>64-bit address only if it is not initialized.</li> * <li>Node Identifier.</li> * <li>Hardware version if it is not initialized.</li> * <li>Firmware version.</li> * <li>XBee device protocol.</li> * <li>16-bit address (not for DigiMesh/DigiPoint modules).</li> * </ul> * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout reading the parameters. * @throws XBeeException if there is any error trying to read the device information or * if there is any other XBee related exception. * * @see #get16BitAddress() * @see #get64BitAddress() * @see #getHardwareVersion() * @see #getNodeID() * @see #getFirmwareVersion() * @see #getXBeeProtocol() * @see #setNodeID(String) */ public void readDeviceInfo() throws TimeoutException, XBeeException { byte[] response = null; // Get the 64-bit address. if (xbee64BitAddress == null || xbee64BitAddress.equals(XBee64BitAddress.UNKNOWN_ADDRESS)) { String addressHigh; String addressLow; response = getParameter("SH"); addressHigh = HexUtils.byteArrayToHexString(response); response = getParameter("SL"); addressLow = HexUtils.byteArrayToHexString(response); while(addressLow.length() < 8) addressLow = "0" + addressLow; xbee64BitAddress = new XBee64BitAddress(addressHigh + addressLow); } // Get the Node ID. response = getParameter("NI"); nodeID = new String(response); // Get the hardware version. if (hardwareVersion == null) { response = getParameter("HV"); hardwareVersion = HardwareVersion.get(response[0]); } // Get the firmware version. response = getParameter("VR"); firmwareVersion = HexUtils.byteArrayToHexString(response); // Original value of the protocol. XBeeProtocol origProtocol = getXBeeProtocol(); // Obtain the device protocol. xbeeProtocol = XBeeProtocol.determineProtocol(hardwareVersion, firmwareVersion); if (origProtocol != XBeeProtocol.UNKNOWN && origProtocol != xbeeProtocol) { throw new XBeeException("Error reading device information: " + "Your module seems to be " + xbeeProtocol + " and NOT " + origProtocol + ". Check if you are using" + " the appropriate device class."); } // Get the 16-bit address. This must be done after obtaining the protocol because // DigiMesh and Point-to-Multipoint protocols don't have 16-bit addresses. XBeeProtocol protocol = getXBeeProtocol(); if (protocol == XBeeProtocol.ZIGBEE || protocol == XBeeProtocol.RAW_802_15_4 || protocol == XBeeProtocol.XTEND || protocol == XBeeProtocol.SMART_ENERGY || protocol == XBeeProtocol.ZNET) { response = getParameter("MY"); xbee16BitAddress = new XBee16BitAddress(response); } } /** * Returns the 16-bit address of this XBee device. * * <p>To refresh this value use the {@link #readDeviceInfo()} method.</p> * * @return The 16-bit address of this XBee device. * * @see com.digi.xbee.api.models.XBee16BitAddress */ public XBee16BitAddress get16BitAddress() { return xbee16BitAddress; } /** * Returns the 64-bit address of this XBee device. * * <p>If this value is {@code null} or * {@code XBee64BitAddress.UNKNOWN_ADDRESS}, use the * {@link #readDeviceInfo()} method to get its value.</p> * * @return The 64-bit address of this XBee device. * * @see com.digi.xbee.api.models.XBee64BitAddress */ public XBee64BitAddress get64BitAddress() { return xbee64BitAddress; } /** * Returns the IPv6 address of this IPv6 device. * * <p>To refresh this value use the {@link #readDeviceInfo()} method.</p> * * @return The IPv6 address of this IPv6 device. * * @see java.net.Inet6Address * * @since 1.2.1 */ public Inet6Address getIPv6Address() { return ipv6Address; } /** * Returns the Operating mode (AT, API or API escaped) of this XBee device * for a local device, and the operating mode of the local device used as * communication interface for a remote device. * * @return The operating mode of the local XBee device. * * @see #isRemote() * @see com.digi.xbee.api.models.OperatingMode */ protected OperatingMode getOperatingMode() { if (isRemote()) return localXBeeDevice.getOperatingMode(); return operatingMode; } /** * Returns the XBee Protocol of this XBee device. * * <p>To refresh this value use the {@link #readDeviceInfo()} method.</p> * * @return The XBee device protocol. * * @see com.digi.xbee.api.models.XBeeProtocol */ public XBeeProtocol getXBeeProtocol() { return xbeeProtocol; } /** * Returns the node identifier of this XBee device. * * <p>To refresh this value use the {@link #readDeviceInfo()} method.</p> * * @return The node identifier of this device. * * @see #setNodeID(String) */ public String getNodeID() { return nodeID; } public void setNodeID(String nodeID) throws TimeoutException, XBeeException { if (nodeID == null) throw new NullPointerException("Node ID cannot be null."); if (nodeID.length() > 20) throw new IllegalArgumentException("Node ID length must be less than 21."); setParameter("NI", nodeID.getBytes()); this.nodeID = nodeID; } /** * Returns the firmware version (hexadecimal string value) of this XBee * device. * * <p>To refresh this value use the {@link #readDeviceInfo()} method.</p> * * @return The firmware version of the XBee device. */ public String getFirmwareVersion() { return firmwareVersion; } /** * Returns the hardware version of this XBee device. * * <p>If this value is {@code null}, use the {@link #readDeviceInfo()} * method to get its value.</p> * * @return The hardware version of the XBee device. * * @see com.digi.xbee.api.models.HardwareVersion * @see com.digi.xbee.api.models.HardwareVersionEnum */ public HardwareVersion getHardwareVersion() { return hardwareVersion; } /** * Updates the current device reference with the data provided for the * given device. * * <p><b>This is only for internal use.</b></p> * * @param device The XBee Device to get the data from. */ public void updateDeviceDataFrom(AbstractXBeeDevice device) { // TODO Should the devices have the same protocol?? // TODO Should be allow to update a local from a remote or viceversa?? Maybe // this must be in the Local/Remote device class(es) and not here... // Only update the Node Identifier if the provided is not null. if (device.getNodeID() != null) this.nodeID = device.getNodeID(); // Only update the 64-bit address if the original is null or unknown. XBee64BitAddress addr64 = device.get64BitAddress(); if (addr64 != null && !addr64.equals(XBee64BitAddress.UNKNOWN_ADDRESS) && !addr64.equals(xbee64BitAddress) && (xbee64BitAddress == null || xbee64BitAddress.equals(XBee64BitAddress.UNKNOWN_ADDRESS))) { xbee64BitAddress = addr64; } // TODO Change here the 16-bit address or maybe in ZigBee and 802.15.4? // TODO Should the 16-bit address be always updated? Or following the same rule as the 64-bit address. XBee16BitAddress addr16 = device.get16BitAddress(); if (addr16 != null && !addr16.equals(xbee16BitAddress)) { xbee16BitAddress = addr16; } //this.deviceType = device.deviceType; // This is not yet done. // The operating mode: only API/API2. Do we need this for a remote device? // The protocol of the device should be the same. // The hardware version should be the same. // The firmware version can change... } /** * Adds the provided listener to the list of listeners to be notified * when new packets are received. * * <p>If the listener has been already included, this method does nothing. * </p> * * @param listener Listener to be notified when new packets are received. * * @throws NullPointerException if {@code listener == null} * * @see #removePacketListener(IPacketReceiveListener) * @see com.digi.xbee.api.listeners.IPacketReceiveListener */ protected void addPacketListener(IPacketReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addPacketReceiveListener(listener); } /** * Removes the provided listener from the list of packets listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addPacketListener(IPacketReceiveListener) * @see com.digi.xbee.api.listeners.IPacketReceiveListener */ protected void removePacketListener(IPacketReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removePacketReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new data is received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new data is received. * * @throws NullPointerException if {@code listener == null} * * @see #removeDataListener(IDataReceiveListener) * @see com.digi.xbee.api.listeners.IDataReceiveListener */ protected void addDataListener(IDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addDataReceiveListener(listener); } /** * Removes the provided listener from the list of data listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addDataListener(IDataReceiveListener) * @see com.digi.xbee.api.listeners.IDataReceiveListener */ protected void removeDataListener(IDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeDataReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new IO samples are received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new IO samples are received. * * @throws NullPointerException if {@code listener == null} * * @see #removeIOSampleListener(IIOSampleReceiveListener) * @see com.digi.xbee.api.listeners.IIOSampleReceiveListener */ protected void addIOSampleListener(IIOSampleReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addIOSampleReceiveListener(listener); } /** * Removes the provided listener from the list of IO samples listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addIOSampleListener(IIOSampleReceiveListener) * @see com.digi.xbee.api.listeners.IIOSampleReceiveListener */ protected void removeIOSampleListener(IIOSampleReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeIOSampleReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new Modem Status events are received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new Modem Status events are * received. * * @throws NullPointerException if {@code listener == null} * * @see #removeModemStatusListener(IModemStatusReceiveListener) * @see com.digi.xbee.api.listeners.IModemStatusReceiveListener */ protected void addModemStatusListener(IModemStatusReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addModemStatusReceiveListener(listener); } /** * Removes the provided listener from the list of Modem Status listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addModemStatusListener(IModemStatusReceiveListener) * @see com.digi.xbee.api.listeners.IModemStatusReceiveListener */ protected void removeModemStatusListener(IModemStatusReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeModemStatusReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new explicit data packets are received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new explicit data packets * are received. * * @throws NullPointerException if {@code listener == null} * * @see #removeExplicitDataListener(IExplicitDataReceiveListener) * @see com.digi.xbee.api.listeners.IExplicitDataReceiveListener */ protected void addExplicitDataListener(IExplicitDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addExplicitDataReceiveListener(listener); } /** * Removes the provided listener from the list of explicit data receive * listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addExplicitDataListener(IExplicitDataReceiveListener) * @see com.digi.xbee.api.listeners.IExplicitDataReceiveListener */ protected void removeExplicitDataListener(IExplicitDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeExplicitDataReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new IP data is received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new IP data is * received. * * @throws NullPointerException if {@code listener == null} * * @see #removeIPDataListener(IIPDataReceiveListener) * @see com.digi.xbee.api.listeners.IIPDataReceiveListener * * @since 1.2.0 */ protected void addIPDataListener(IIPDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addIPDataReceiveListener(listener); } /** * Removes the provided listener from the list of IP data listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addIPDataListener(IIPDataReceiveListener) * @see com.digi.xbee.api.listeners.IIPDataReceiveListener * * @since 1.2.0 */ protected void removeIPDataListener(IIPDataReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeIPDataReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new SMS is received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new SMS is received. * * @throws NullPointerException if {@code listener == null} * * @see #removeSMSListener(ISMSReceiveListener) * @see com.digi.xbee.api.listeners.ISMSReceiveListener * * @since 1.2.0 */ protected void addSMSListener(ISMSReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addSMSReceiveListener(listener); } /** * Removes the provided listener from the list of SMS listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addSMSListener(ISMSReceiveListener) * @see com.digi.xbee.api.listeners.ISMSReceiveListener * * @since 1.2.0 */ protected void removeSMSListener(ISMSReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeSMSReceiveListener(listener); } /** * Adds the provided listener to the list of listeners to be notified * when new User Data Relay message is received. * * <p>If the listener has been already included this method does nothing. * </p> * * @param listener Listener to be notified when new User Data Relay message * is received. * * @throws NullPointerException if {@code listener == null} * * @see #removeUserDataRelayListener(IUserDataRelayReceiveListener) * @see IUserDataRelayReceiveListener * * @since 1.3.0 */ protected void addUserDataRelayListener(IUserDataRelayReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.addUserDataRelayReceiveListener(listener); } /** * Removes the provided listener from the list of User Data Relay listeners. * * <p>If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @throws NullPointerException if {@code listener == null} * * @see #addUserDataRelayListener(IUserDataRelayReceiveListener) * @see IUserDataRelayReceiveListener * * @since 1.3.0 */ protected void removeUserDataRelayListener(IUserDataRelayReceiveListener listener) { if (listener == null) throw new NullPointerException("Listener cannot be null."); if (dataReader == null) return; dataReader.removeUserDataRelayReceiveListener(listener); } /** * Sends the given AT command and waits for answer or until the configured * receive timeout expires. * * <p>The receive timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * @param command AT command to be sent. * @return An {@code ATCommandResponse} object containing the response of * the command or {@code null} if there is no response. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws InvalidOperatingModeException if the operating mode is different * than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the AT command. * @throws NullPointerException if {@code command == null}. * @throws TimeoutException if the configured time expires while waiting * for the command reply. * * @see XBeeDevice#getReceiveTimeout() * @see XBeeDevice#setReceiveTimeout(int) * @see com.digi.xbee.api.models.ATCommand * @see com.digi.xbee.api.models.ATCommandResponse */ protected ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, TimeoutException, IOException { // Check if command is null. if (command == null) throw new NullPointerException("AT command cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Create the corresponding AT command packet depending on if the device is local or remote. XBeePacket packet; if (isRemote()) { int remoteATCommandOptions = RemoteATCommandOptions.OPTION_NONE; if (isApplyConfigurationChangesEnabled()) remoteATCommandOptions |= RemoteATCommandOptions.OPTION_APPLY_CHANGES; if (getXBeeProtocol() == XBeeProtocol.THREAD) { packet = new IPv6RemoteATCommandRequestPacket(getNextFrameID(), ipv6Address, remoteATCommandOptions, command.getCommand(), command.getParameter()); } else{ XBee16BitAddress remote16BitAddress = get16BitAddress(); if (remote16BitAddress == null) remote16BitAddress = XBee16BitAddress.UNKNOWN_ADDRESS; packet = new RemoteATCommandPacket(getNextFrameID(), get64BitAddress(), remote16BitAddress, remoteATCommandOptions, command.getCommand(), command.getParameter()); } } else { if (isApplyConfigurationChangesEnabled()) packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); else packet = new ATCommandQueuePacket(getNextFrameID(), command.getCommand(), command.getParameter()); } if (command.getParameter() == null) logger.debug(toString() + "Sending AT command '{}'.", command.getCommand()); else logger.debug(toString() + "Sending AT command '{} {}'.", command.getCommand(), HexUtils.prettyHexString(command.getParameter())); try { // Send the packet and build the corresponding response depending on if the device is local or remote. XBeePacket answerPacket; if (isRemote()) answerPacket = localXBeeDevice.sendXBeePacket(packet); else answerPacket = sendXBeePacket(packet); if (answerPacket instanceof ATCommandResponsePacket) { ATCommandResponsePacket r = (ATCommandResponsePacket)answerPacket; response = new ATCommandResponse(command, r.getCommandValue(), r.getStatus()); } else if (answerPacket instanceof RemoteATCommandResponsePacket) { RemoteATCommandResponsePacket r = (RemoteATCommandResponsePacket)answerPacket; response = new ATCommandResponse(command, r.getCommandValue(), r.getStatus()); } else if (answerPacket instanceof IPv6RemoteATCommandResponsePacket) { IPv6RemoteATCommandResponsePacket r = (IPv6RemoteATCommandResponsePacket)answerPacket; response = new ATCommandResponse(command, r.getCommandValue(), r.getStatus()); } if (response != null && response.getResponse() != null) logger.debug(toString() + "AT command response: {}.", HexUtils.prettyHexString(response.getResponse())); else logger.debug(toString() + "AT command response: null."); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; } /** * Sends the given XBee packet asynchronously. * * <p>The method will not wait for an answer for the packet.</p> * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws InvalidOperatingModeException if the operating mode is different * than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws NullPointerException if {@code packet == null}. * * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see com.digi.xbee.api.packet.XBeePacket */ protected void sendXBeePacketAsync(XBeePacket packet) throws InvalidOperatingModeException, IOException { sendXBeePacket(packet, null); } /** * Sends the given XBee packet asynchronously and registers the given * packet listener (if not {@code null}) to wait for an answer. * * <p>The method will not wait for an answer for the packet, but the given * listener will be notified when the answer arrives.</p> * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws InvalidOperatingModeException if the operating mode is different * than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws NullPointerException if {@code packet == null}. * * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see com.digi.xbee.api.listeners.IPacketReceiveListener * @see com.digi.xbee.api.packet.XBeePacket */ protected void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws InvalidOperatingModeException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Add the required frame ID and subscribe listener if given. if (packet instanceof XBeeAPIPacket) { insertFrameID(packet); XBeeAPIPacket apiPacket = (XBeeAPIPacket)packet; if (packetReceiveListener != null && apiPacket.needsAPIFrameID()) dataReader.addPacketReceiveListener(packetReceiveListener, apiPacket.getFrameID()); else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } // Write packet data. writePacket(packet); break; } } /** * Sends the given XBee packet synchronously and blocks until response is * received or receive timeout is reached. * * <p>The receive timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * @return An {@code XBeePacket} containing the response of the sent packet * or {@code null} if there is no response. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws InvalidOperatingModeException if the operating mode is different * than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws NullPointerException if {@code packet == null}. * @throws TimeoutException if the configured time expires while waiting for * the packet reply. * * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see XBeeDevice#setReceiveTimeout(int) * @see XBeeDevice#getReceiveTimeout() * @see com.digi.xbee.api.packet.XBeePacket */ protected XBeePacket sendXBeePacket(final XBeePacket packet) throws InvalidOperatingModeException, TimeoutException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Build response container. ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); // If the packet does not need frame ID, send it async. and return null. if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet); return null; } } else { sendXBeePacketAsync(packet); return null; } // Add the required frame ID to the packet if necessary. insertFrameID(packet); // Generate a packet received listener for the packet to be sent. IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); // Add the packet listener to the data reader. addPacketListener(packetReceiveListener); // Write the packet data. writePacket(packet); try { // Wait for response or timeout. synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) {} } // After the wait check if we received any response, if not throw timeout exception. if (responseList.size() < 1) throw new TimeoutException(); // Return the received packet. return responseList.get(0); } finally { // Always remove the packet listener from the list. removePacketListener(packetReceiveListener); } } } /** * Insert (if possible) the next frame ID stored in the device to the * provided packet. * * @param xbeePacket The packet to add the frame ID. * * @see com.digi.xbee.api.packet.XBeePacket */ private void insertFrameID(XBeePacket xbeePacket) { if (xbeePacket instanceof XBeeAPIPacket) return; XBeeAPIPacket apiPacket = (XBeeAPIPacket)xbeePacket; if (apiPacket.needsAPIFrameID() && apiPacket.getFrameID() == XBeeAPIPacket.NO_FRAME_ID) apiPacket.setFrameID(getNextFrameID()); } /** * Returns the packet listener corresponding to the provided sent packet. * * <p>The listener will filter those packets matching with the Frame ID of * the sent packet storing them in the provided responseList array.</p> * * @param sentPacket The packet sent. * @param responseList List of packets received that correspond to the * frame ID of the packet sent. * * @return A packet receive listener that will filter the packets received * corresponding to the sent one. * * @see com.digi.xbee.api.listeners.IPacketReceiveListener * @see com.digi.xbee.api.packet.XBeePacket */ private IPacketReceiveListener createPacketReceivedListener(final XBeePacket sentPacket, final ArrayList<XBeePacket> responseList) { IPacketReceiveListener packetReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Check if it is the packet we are waiting for. if (((XBeeAPIPacket)receivedPacket).checkFrameID((((XBeeAPIPacket)sentPacket).getFrameID()))) { // Security check to avoid class cast exceptions. It has been observed that parallel processes // using the same connection but with different frame index may collide and cause this exception at some point. if (sentPacket instanceof XBeeAPIPacket && receivedPacket instanceof XBeeAPIPacket) { XBeeAPIPacket sentAPIPacket = (XBeeAPIPacket)sentPacket; XBeeAPIPacket receivedAPIPacket = (XBeeAPIPacket)receivedPacket; // If the packet sent is an AT command, verify that the received one is an AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.AT_COMMAND) { if (receivedAPIPacket.getFrameType() != APIFrameType.AT_COMMAND_RESPONSE) return; if (!((ATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((ATCommandResponsePacket)receivedPacket).getCommand())) return; } // If the packet sent is a remote AT command, verify that the received one is a remote AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.REMOTE_AT_COMMAND_REQUEST) { if (receivedAPIPacket.getFrameType() != APIFrameType.REMOTE_AT_COMMAND_RESPONSE) return; if (!((RemoteATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((RemoteATCommandResponsePacket)receivedPacket).getCommand())) return; } } // Verify that the sent packet is not the received one! This can happen when the echo mode is enabled in the // serial port. if (!sentPacket.equals(receivedPacket)) { responseList.add(receivedPacket); synchronized (responseList) { responseList.notify(); } } } } }; return packetReceiveListener; } /** * Writes the given XBee packet in the connection interface of this device. * * @param packet XBee packet to be written. * * @throws IOException if an I/O error occurs while writing the XBee packet * in the connection interface. * * @see com.digi.xbee.api.packet.XBeePacket */ private void writePacket(XBeePacket packet) throws IOException { logger.debug(toString() + "Sending XBee packet: \n{}", packet.toPrettyString()); // Write bytes with the required escaping mode. switch (operatingMode) { case API: default: connectionInterface.writeData(packet.generateByteArray()); break; case API_ESCAPE: connectionInterface.writeData(packet.generateByteArrayEscaped()); break; } } /** * Returns the next Frame ID of this XBee device. * * @return The next Frame ID. */ protected synchronized int getNextFrameID() { if (isRemote()) return localXBeeDevice.getNextFrameID(); if (currentFrameID == 0xff) { // Reset counter. currentFrameID = 1; } else currentFrameID ++; return currentFrameID; } /** * Sends the provided {@code XBeePacket} and determines if the transmission * status is success for synchronous transmissions. * * <p>If the status is not success, an {@code TransmitException} is thrown.</p> * * @param packet The {@code XBeePacket} to be sent. * @param asyncTransmission Determines whether the transmission must be * asynchronous. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code packet == null}. * @throws TransmitException if {@code packet} is not an instance of * {@code TransmitStatusPacket} or * if {@code packet} is not an instance of * {@code TXStatusPacket} or * if its transmit status is different than * {@code XBeeTransmitStatus.SUCCESS}. * @throws XBeeException if there is any other XBee related error. * * @see com.digi.xbee.api.packet.XBeePacket */ protected void sendAndCheckXBeePacket(XBeePacket packet, boolean asyncTransmission) throws TransmitException, XBeeException { XBeePacket receivedPacket = null; // Send the XBee packet. try { if (asyncTransmission) sendXBeePacketAsync(packet); else receivedPacket = sendXBeePacket(packet); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // If the transmission is async. we are done. if (asyncTransmission) return; // Check if the packet received is a valid transmit status packet. if (receivedPacket == null) throw new TransmitException(null); XBeeTransmitStatus status = null; if (receivedPacket instanceof TransmitStatusPacket) status = ((TransmitStatusPacket)receivedPacket).getTransmitStatus(); else if (receivedPacket instanceof TXStatusPacket) status = ((TXStatusPacket)receivedPacket).getTransmitStatus(); if (status != XBeeTransmitStatus.SUCCESS && status != XBeeTransmitStatus.SELF_ADDRESSED) throw new TransmitException(status); } /** * Sends the provided {@code CoAPTxRequestPacket} and determines if the * transmission status and CoAP RX Response are success for synchronous * transmissions. * * <p>If the status or the CoAP response is not successful, an * {@code TransmitException} is thrown.</p> * * @param packet The {@code CoAPTxRequestPacket} to be sent. * @param asyncTransmission Determines whether the transmission must be * asynchronous. * * @return A byte array containing the RfData of the CoAP RX Response * packet, if that field is not empty. In other cases, it will * return {@code null}. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code packet == null}. * @throws TransmitException if {@code packet} is not an instance of * {@code TransmitStatusPacket} or * if {@code packet} is not an instance of * {@code TXStatusPacket} or * if its transmit status is different than * {@code XBeeTransmitStatus.SUCCESS}. * @throws XBeeException if CoAP response packet is not received or it is * not successful or if there is any other XBee * related error. * * @see com.digi.xbee.api.packet.thread.CoAPTxRequestPacket * * @since 1.2.1 */ protected byte[] sendAndCheckCoAPPacket(CoAPTxRequestPacket packet, boolean asyncTransmission) throws TransmitException, XBeeException { // Add listener to read CoAP response (when sending a CoAP transmission, // a transmit status and a CoAP response are received by the sender) ArrayList<CoAPRxResponsePacket> coapResponsePackets = new ArrayList<CoAPRxResponsePacket>(); IPacketReceiveListener listener = createCoAPResponseListener(coapResponsePackets); addPacketListener(listener); // Send the CoAP Tx Request packet. XBeePacket receivedPacket = null; try { if (asyncTransmission) sendXBeePacketAsync(packet); else receivedPacket = sendXBeePacket(packet); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // If the transmission is async. we are done. if (asyncTransmission) return null; if (receivedPacket == null) throw new TransmitException(null); // Verify Transmit status. XBeeTransmitStatus status = null; if (receivedPacket instanceof TXStatusPacket) status = ((TXStatusPacket)receivedPacket).getTransmitStatus(); if (status == null || (status != XBeeTransmitStatus.SUCCESS && status != XBeeTransmitStatus.SELF_ADDRESSED)) throw new TransmitException(status); // Verify CoAP response (only expect one CoAP RX Response packet). CoAPRxResponsePacket coapRxPacket = null; try { coapRxPacket = waitForCoAPRxResponsePacket(coapResponsePackets); } finally { // Always remove the packet listener from the list. removePacketListener(listener); } if (coapRxPacket == null) throw new XBeeException("CoAP response was null."); return coapRxPacket.getData(); } /** * Returns the CoAP packet listener corresponding to the provided sent CoAP * packet. * * <p>The listener will filter CoAP Rx Response packets (0x9C) and storing * them in the provided responseList array.</p> * * @param coapResponsePackets List of CoAP Rx Response packets received. * * @return A CoAP packet receive listener. * * @see com.digi.xbee.api.listeners.IPacketReceiveListener * @see com.digi.xbee.api.packet.thread.CoAPRxResponsePacket * * @since 1.2.1 */ private IPacketReceiveListener createCoAPResponseListener(final ArrayList<CoAPRxResponsePacket> coapResponsePackets) { IPacketReceiveListener listener = new IPacketReceiveListener() { @Override public void packetReceived(XBeePacket receivedPacket) { if (receivedPacket instanceof CoAPRxResponsePacket) { coapResponsePackets.add((CoAPRxResponsePacket)receivedPacket); coapResponsePackets.notifyAll(); } } }; return listener; } /** * Returns the CoAP Rx Response packet that comes in through the serial * port in the given timeout. * * @param coapResponsePackets List of packets where the received packet will be stored. * * @return CoAP Rx Response packet received. * * @throws XBeeException if CoAP response packet is not received or it is * not successful or if there is any other XBee * related error. * * @since 1.2.1 */ private CoAPRxResponsePacket waitForCoAPRxResponsePacket(ArrayList<CoAPRxResponsePacket> coapResponsePackets) throws XBeeException { synchronized (coapResponsePackets) { try { coapResponsePackets.wait(receiveTimeout); } catch (InterruptedException e) {} } if (!coapResponsePackets.isEmpty()) { RestFulStatusEnum responseStatus = coapResponsePackets.get(0).getStatus(); if (responseStatus != RestFulStatusEnum.SUCCESS && responseStatus != RestFulStatusEnum.CREATED && responseStatus != RestFulStatusEnum.ACCEPTED && responseStatus != RestFulStatusEnum.NON_AUTHORITATIVE && responseStatus != RestFulStatusEnum.NO_CONTENT && responseStatus != RestFulStatusEnum.RESET_CONTENT) throw new XBeeException("CoAP response had an unexpected status: " + responseStatus.toString()); } else { throw new XBeeException("CoAP response was not received."); } return coapResponsePackets.get(0); } /** * Sets the configuration of the given IO line of this XBee device. * * @param ioLine The IO line to configure. * @param ioMode The IO mode to set to the IO line. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioMode == null}. * @throws TimeoutException if there is a timeout sending the set * configuration command. * @throws XBeeException if there is any other XBee related exception. * * @see #getIOConfiguration(IOLine) * @see com.digi.xbee.api.io.IOLine * @see com.digi.xbee.api.io.IOMode */ public void setIOConfiguration(IOLine ioLine, IOMode ioMode) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (ioMode == null) throw new NullPointerException("IO mode cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter(ioLine.getConfigurationATCommand(), new byte[]{(byte)ioMode.getID()}); } /** * Returns the configuration mode of the provided IO line of this XBee * device. * * @param ioLine The IO line to get its configuration. * * @return The IO mode (configuration) of the provided IO line. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code ioLine == null}. * @throws TimeoutException if there is a timeout sending the get * configuration command. * @throws XBeeException if there is any other XBee related exception. * * @see #setIOConfiguration(IOLine, IOMode) * @see com.digi.xbee.api.io.IOLine * @see com.digi.xbee.api.io.IOMode */ public IOMode getIOConfiguration(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("DIO pin cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the received configuration mode is valid. int ioModeValue = getParameter(ioLine.getConfigurationATCommand())[0]; IOMode dioMode = IOMode.getIOMode(ioModeValue, ioLine); if (dioMode == null) throw new OperationNotSupportedException("Received configuration mode '" + HexUtils.integerToHexString(ioModeValue, 1) + "' is not valid."); // Return the configuration mode. return dioMode; } /** * Sets the digital value (high or low) to the provided IO line of this * XBee device. * * @param ioLine The IO line to set its value. * @param ioValue The IOValue to set to the IO line ({@code HIGH} or * {@code LOW}). * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioValue == null}. * @throws TimeoutException if there is a timeout sending the set DIO * command. * @throws XBeeException if there is any other XBee related exception. * * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) * @see com.digi.xbee.api.io.IOLine * @see com.digi.xbee.api.io.IOValue * @see com.digi.xbee.api.io.IOMode#DIGITAL_OUT_HIGH * @see com.digi.xbee.api.io.IOMode#DIGITAL_OUT_LOW */ public void setDIOValue(IOLine ioLine, IOValue ioValue) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check IO value. if (ioValue == null) throw new NullPointerException("IO value cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter(ioLine.getConfigurationATCommand(), new byte[]{(byte)ioValue.getID()}); } /** * Returns the digital value of the provided IO line of this XBee device. * * <p>The provided <b>IO line must be previously configured as digital I/O * </b>. To do so, use {@code setIOConfiguration} and the following * {@code IOMode}:</p> * * <ul> * <li>{@code IOMode.DIGITAL_IN} to configure as digital input.</li> * <li>{@code IOMode.DIGITAL_OUT_HIGH} to configure as digital output, high. * </li> * <li>{@code IOMode.DIGITAL_OUT_LOW} to configure as digital output, low. * </li> * </ul> * * @param ioLine The IO line to get its digital value. * * @return The digital value corresponding to the provided IO line. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code ioLine == null}. * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) * @see com.digi.xbee.api.io.IOLine * @see com.digi.xbee.api.io.IOValue * @see com.digi.xbee.api.io.IOMode#DIGITAL_IN * @see com.digi.xbee.api.io.IOMode#DIGITAL_OUT_HIGH * @see com.digi.xbee.api.io.IOMode#DIGITAL_OUT_LOW */ public IOValue getDIOValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Obtain an IO Sample from the XBee device. IOSample ioSample = readIOSample(); // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not contain digital data for " + ioLine.getName() + "."); // Return the digital value. return ioSample.getDigitalValues().get(ioLine); } public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check duty cycle limits. if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Convert the value. int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); setParameter(ioLine.getPWMDutyCycleATCommand(), ByteUtils.intToByteArray(finaldutyCycle)); } public double getPWMDutyCycle(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] value = getParameter(ioLine.getPWMDutyCycleATCommand()); // Return the PWM duty cycle value. int readValue = ByteUtils.byteArrayToInt(value); return Math.round((readValue * 100.0/1023.0) * 100.0) / 100.0; } /** * Returns the analog value of the provided IO line of this XBee device. * * <p>The provided <b>IO line must be previously configured as ADC</b>. To * do so, use {@code setIOConfiguration} and {@code IOMode.ADC}.</p> * * @param ioLine The IO line to get its analog value. * * @return The analog value corresponding to the provided IO line. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code ioLine == null}. * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) * @see com.digi.xbee.api.io.IOLine * @see com.digi.xbee.api.io.IOMode#ADC */ public int getADCValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Obtain an IO Sample from the XBee device. IOSample ioSample = readIOSample(); // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not contain analog data for " + ioLine.getName() + "."); // Return the analog value. return ioSample.getAnalogValues().get(ioLine); } /** * Sets the 64-bit destination extended address of this XBee device. * * <p>{@link XBee64BitAddress#BROADCAST_ADDRESS} is the broadcast address * for the PAN. {@link XBee64BitAddress#COORDINATOR_ADDRESS} can be used to * address the Pan Coordinator.</p> * * @param xbee64BitAddress 64-bit destination address to be configured. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code xbee64BitAddress == null}. * @throws TimeoutException if there is a timeout sending the set * destination address command. * @throws XBeeException if there is any other XBee related exception. * * @see #getDestinationAddress() * @see com.digi.xbee.api.models.XBee64BitAddress */ public void setDestinationAddress(XBee64BitAddress xbee64BitAddress) throws TimeoutException, XBeeException { if (xbee64BitAddress == null) throw new NullPointerException("Address cannot be null."); // This method needs to apply changes after modifying the destination // address, but only if the destination address could be set successfully. boolean applyChanges = isApplyConfigurationChangesEnabled(); if (applyChanges) enableApplyConfigurationChanges(false); byte[] address = xbee64BitAddress.getValue(); try { setParameter("DH", Arrays.copyOfRange(address, 0, 4)); setParameter("DL", Arrays.copyOfRange(address, 4, 8)); applyChanges(); } finally { // Always restore the old value of the AC. enableApplyConfigurationChanges(applyChanges); } } /** * Returns the 64-bit destination extended address of this XBee device. * * <p>{@link XBee64BitAddress#BROADCAST_ADDRESS} is the broadcast address * for the PAN. {@link XBee64BitAddress#COORDINATOR_ADDRESS} can be used to * address the Pan Coordinator.</p> * * @return 64-bit destination address. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout sending the get * destination address command. * @throws XBeeException if there is any other XBee related exception. * * @see #setDestinationAddress(XBee64BitAddress) * @see com.digi.xbee.api.models.XBee64BitAddress */ public XBee64BitAddress getDestinationAddress() throws TimeoutException, XBeeException { byte[] dh = getParameter("DH"); byte[] dl = getParameter("DL"); byte[] address = new byte[dh.length + dl.length]; System.arraycopy(dh, 0, address, 0, dh.length); System.arraycopy(dl, 0, address, dh.length, dl.length); return new XBee64BitAddress(address); } /** * Sets the destination IPv6 address. * * @param ipv6Address Destination IPv6 address. * * @throws NullPointerException if {@code ipv6Address == null}. * @throws TimeoutException if there is a timeout setting the IPv6 * destination address. * @throws XBeeException if there is any other XBee related exception. * * @see #getIPv6DestinationAddress() * @see java.net.Inet6Address * * @since 1.2.1 */ public void setIPv6DestinationAddress(Inet6Address ipv6Address) throws TimeoutException, XBeeException { if (ipv6Address == null) throw new NullPointerException("Destination IPv6 address cannot be null."); setParameter("DL", ipv6Address.getAddress()); } /** * Returns the destination IPv6 address. * * @return The configured destination IPv6 address. * * @throws TimeoutException if there is a timeout reading the IPv6 * destination address. * @throws XBeeException if there is any other XBee related exception. * * @see #setIPv6DestinationAddress(Inet6Address) * @see java.net.Inet6Address * * @since 1.2.1 */ public Inet6Address getIPv6DestinationAddress() throws TimeoutException, XBeeException { try { return (Inet6Address) Inet6Address.getByAddress(getParameter("DL")); } catch (UnknownHostException e) { throw new XBeeException(e); } } public void setIOSamplingRate(int rate) throws TimeoutException, XBeeException { // Check range. if (rate < 0 || rate > 0xFFFF) throw new IllegalArgumentException("Rate must be between 0 and 0xFFFF."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); setParameter("IR", ByteUtils.intToByteArray(rate)); } /** * Returns the IO sampling rate of this XBee device. * * <p>A sample rate of {@code 0} means the IO sampling feature is disabled. * </p> * * <p>Periodic sampling allows this XBee module to take an IO sample and * transmit it to a remote device (configured in the destination address) * at the configured periodic rate (ms).</p> * * @return IO sampling rate in milliseconds. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout sending the get IO * sampling rate command. * @throws XBeeException if there is any other XBee related exception. * * @see #getDestinationAddress() * @see #setDestinationAddress(XBee64BitAddress) * @see #setIOSamplingRate(int) */ public int getIOSamplingRate() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] rate = getParameter("IR"); return ByteUtils.byteArrayToInt(rate); } /** * Sets the digital IO lines of this XBee device to be monitored and * sampled whenever their status changes. * * <p>A {@code null} set of lines disables this feature.</p> * * <p>If a change is detected on an enabled digital IO pin, a digital IO * sample is immediately transmitted to the configured destination address. * </p> * * <p>The destination address can be configured using the * {@code setDestinationAddress(XBee64BitAddress)} method and retrieved by * {@code getDestinationAddress()}.</p> * * @param lines Set of IO lines to be monitored, {@code null} to disable * this feature. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout sending the set DIO * change detection command. * @throws XBeeException if there is any other XBee related exception. * * @see #getDestinationAddress() * @see #getDIOChangeDetection() * @see #setDestinationAddress(XBee64BitAddress) */ public void setDIOChangeDetection(Set<IOLine> lines) throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] bitfield = new byte[2]; if (lines != null) { for (IOLine line : lines) { int i = line.getIndex(); if (i < 8) bitfield[1] = (byte) (bitfield[1] | (1 << i)); else bitfield[0] = (byte) (bitfield[0] | (1 << i - 8)); } } setParameter("IC", bitfield); } /** * Returns the set of IO lines of this device that are monitored for * change detection. * * <p>A {@code null} set means the DIO change detection feature is disabled. * </p> * * <p>Modules can be configured to transmit to the configured destination * address a data sample immediately whenever a monitored digital IO line * changes state.</p> * * @return Set of digital IO lines that are monitored for change detection, * {@code null} if there are no monitored lines. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout sending the get DIO * change detection command. * @throws XBeeException if there is any other XBee related exception. * * @see #getDestinationAddress() * @see #setDestinationAddress(XBee64BitAddress) * @see #setDIOChangeDetection(Set) */ public Set<IOLine> getDIOChangeDetection() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); byte[] bitfield = getParameter("IC"); TreeSet<IOLine> lines = new TreeSet<IOLine>(); int mask = (bitfield[0] << 8) + (bitfield[1] & 0xFF); for (int i = 0; i < 16; i++) { if (ByteUtils.isBitEnabled(mask, i)) lines.add(IOLine.getDIO(i)); } if (lines.size() > 0) return lines; return null; } /** * Applies changes to all command registers causing queued command register * values to be applied. * * <p>This method must be invoked if the 'apply configuration changes' * option is disabled and the changes to this XBee device parameters must * be applied.</p> * * <p>To know if the 'apply configuration changes' option is enabled, use * the {@code isApplyConfigurationChangesEnabled()} method. And to * enable/disable this feature, the method * {@code enableApplyConfigurationChanges(boolean)}.</p> * * <p>Applying changes does not imply the modifications will persist * through subsequent resets. To do so, use the {@code writeChanges()} * method.</p> * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout sending the get Apply * Changes command. * @throws XBeeException if there is any other XBee related exception. * * @see #enableApplyConfigurationChanges(boolean) * @see #isApplyConfigurationChangesEnabled() * @see #setParameter(String, byte[]) * @see #writeChanges() */ public void applyChanges() throws TimeoutException, XBeeException { executeParameter("AC"); } /** * Checks if the provided {@code ATCommandResponse} is valid throwing an * {@code ATCommandException} in case it is not. * * @param response The {@code ATCommandResponse} to check. * * @throws ATCommandException if {@code response == null} or * if {@code response.getResponseStatus() != ATCommandStatus.OK}. * * @see com.digi.xbee.api.models.ATCommandResponse */ protected void checkATCommandResponseIsValid(ATCommandResponse response) throws ATCommandException { if (response == null || response.getResponseStatus() == null) throw new ATCommandException(null); else if (response.getResponseStatus() != ATCommandStatus.OK) throw new ATCommandException(response.getResponseStatus()); } /** * Returns an IO sample from this XBee device containing the value of all * enabled digital IO and analog input channels. * * @return An IO sample containing the value of all enabled digital IO and * analog input channels. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout getting the IO sample. * @throws XBeeException if there is any other XBee related exception. * * @see com.digi.xbee.api.io.IOSample */ public IOSample readIOSample() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Try to build an IO Sample from the sample payload. byte[] samplePayload = null; IOSample ioSample; // The response to the IS command in local 802.15.4 devices is empty, // so we have to create a packet listener to receive the IO sample. if (!isRemote() && getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { executeParameter("IS"); samplePayload = receiveRaw802IOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } else samplePayload = getParameter("IS"); try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; } /** * Returns the latest 802.15.4 IO packet and returns its value. * * @return The value of the latest received 802.15.4 IO packet. */ private byte[] receiveRaw802IOPacket() { ioPacketReceived = false; ioPacketPayload = null; addPacketListener(IOPacketReceiveListener); synchronized (ioLock) { try { ioLock.wait(receiveTimeout); } catch (InterruptedException e) { } } removePacketListener(IOPacketReceiveListener); if (ioPacketReceived) return ioPacketPayload; return null; } /** * Custom listener for 802.15.4 IO packets. It will try to receive an * 802.15.4 IO sample packet. * * <p>When an IO sample packet is received, it saves its payload and * notifies the object that was waiting for the reception.</p> */ private IPacketReceiveListener IOPacketReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Discard non API packets. if (!(receivedPacket instanceof XBeeAPIPacket)) return; // If we already have received an IO packet, ignore this packet. if (ioPacketReceived) return; // Save the packet value (IO sample payload) switch (((XBeeAPIPacket)receivedPacket).getFrameType()) { case IO_DATA_SAMPLE_RX_INDICATOR: ioPacketPayload = ((IODataSampleRxIndicatorPacket)receivedPacket).getRFData(); break; case RX_IO_16: ioPacketPayload = ((RX16IOPacket)receivedPacket).getRFData(); break; case RX_IO_64: ioPacketPayload = ((RX64IOPacket)receivedPacket).getRFData(); break; default: return; } // Set the IO packet received flag. ioPacketReceived = true; // Continue execution by notifying the lock object. synchronized (ioLock) { ioLock.notify(); } } }; /** * Performs a software reset on this XBee device and blocks until the * process is completed. * * @throws TimeoutException if the configured time expires while waiting * for the command reply. * @throws XBeeException if there is any other XBee related exception. */ abstract public void reset() throws TimeoutException, XBeeException; public void setParameter(String parameter, byte[] parameterValue) throws TimeoutException, XBeeException { if (parameterValue == null) throw new NullPointerException("Value of the parameter cannot be null."); sendParameter(parameter, parameterValue); } public byte[] getParameter(String parameter) throws TimeoutException, XBeeException { byte[] parameterValue = sendParameter(parameter, null); // Check if the response is null, if so throw an exception (maybe it was a write-only parameter). if (parameterValue == null) throw new OperationNotSupportedException("Couldn't get the '" + parameter + "' value."); return parameterValue; } public void executeParameter(String parameter) throws TimeoutException, XBeeException { sendParameter(parameter, null); } private byte[] sendParameter(String parameter, byte[] parameterValue) throws TimeoutException, XBeeException { if (parameter == null) throw new NullPointerException("Parameter cannot be null."); if (parameter.length() != 2) throw new IllegalArgumentException("Parameter must contain exactly 2 characters."); ATCommand atCommand = new ATCommand(parameter, parameterValue); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(atCommand); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Return the response value. return response.getResponse(); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return connectionInterface.toString(); } /** * Enables or disables the 'apply configuration changes' option for this * device. * * <p>Enabling this option means that when any parameter of this XBee * device is set, it will be also applied.</p> * * <p>If this option is disabled, the method {@code applyChanges()} must be * used in order to apply the changes in all the parameters that were * previously set.</p> * * @param enabled {@code true} to apply configuration changes when an XBee * parameter is set, {@code false} otherwise. * * @see #applyChanges() * @see #isApplyConfigurationChangesEnabled() */ public void enableApplyConfigurationChanges(boolean enabled) { applyConfigurationChanges = enabled; } /** * Returns whether the 'apply configuration changes' option is enabled in * this device. * * <p>If this option is enabled, when any parameter of this XBee device is * set, it will be also applied.</p> * * <p>If this option is disabled, the method {@code applyChanges()} must be * used in order to apply the changes in all the parameters that were * previously set.</p> * * @return {@code true} if the option is enabled, {@code false} otherwise. * * @see #applyChanges() * @see #enableApplyConfigurationChanges(boolean) */ public boolean isApplyConfigurationChangesEnabled() { return applyConfigurationChanges; } /** * Configures the 16-bit address (network address) of this XBee device with * the provided one. * * @param xbee16BitAddress The new 16-bit address. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code xbee16BitAddress == null}. * @throws TimeoutException if there is a timeout setting the address. * @throws XBeeException if there is any other XBee related exception. * * @see #get16BitAddress() * @see com.digi.xbee.api.models.XBee16BitAddress */ protected void set16BitAddress(XBee16BitAddress xbee16BitAddress) throws TimeoutException, XBeeException { if (xbee16BitAddress == null) throw new NullPointerException("16-bit address canot be null."); setParameter("MY", xbee16BitAddress.getValue()); this.xbee16BitAddress = xbee16BitAddress; } /** * Returns the operating PAN ID (Personal Area Network Identifier) of * this XBee device. * * <p>For modules to communicate they must be configured with the same * identifier. Only modules with matching IDs can communicate with each * other.This parameter allows multiple networks to co-exist on the same * physical channel.</p> * * @return The operating PAN ID of this XBee device. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout getting the PAN ID. * @throws XBeeException if there is any other XBee related exception. * * @see #setPANID(byte[]) */ public byte[] getPANID() throws TimeoutException, XBeeException { switch (getXBeeProtocol()) { case ZIGBEE: return getParameter("OP"); default: return getParameter("ID"); } } public void setPANID(byte[] panID) throws TimeoutException, XBeeException { if (panID == null) throw new NullPointerException("PAN ID cannot be null."); if (panID.length == 0) throw new IllegalArgumentException("Length of the PAN ID cannot be 0."); if (panID.length > 8) throw new IllegalArgumentException("Length of the PAN ID cannot be longer than 8 bytes."); setParameter("ID", panID); } /** * Returns the output power level at which this XBee device transmits * conducted power. * * @return The output power level of this XBee device. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout getting the power level. * @throws XBeeException if there is any other XBee related exception. * * @see #setPowerLevel(PowerLevel) * @see com.digi.xbee.api.models.PowerLevel */ public PowerLevel getPowerLevel() throws TimeoutException, XBeeException { byte[] powerLevelValue = getParameter("PL"); return PowerLevel.get(ByteUtils.byteArrayToInt(powerLevelValue)); } /** * Sets the output power level at which this XBee device transmits * conducted power. * * @param powerLevel The new output power level to be set in this XBee * device. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws NullPointerException if {@code powerLevel == null}. * @throws TimeoutException if there is a timeout setting the power level. * @throws XBeeException if there is any other XBee related exception. * * @see #getPowerLevel() * @see com.digi.xbee.api.models.PowerLevel */ public void setPowerLevel(PowerLevel powerLevel) throws TimeoutException, XBeeException { if (powerLevel == null) throw new NullPointerException("Power level cannot be null."); setParameter("PL", ByteUtils.intToByteArray(powerLevel.getValue())); } /** * Returns the current association status of this XBee device. * * <p>It indicates occurrences of errors during the last association * request.</p> * * @return The association indication status of the XBee device. * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout getting the association * indication status. * @throws XBeeException if there is any other XBee related exception. * * @see #forceDisassociate() * @see com.digi.xbee.api.models.AssociationIndicationStatus */ protected AssociationIndicationStatus getAssociationIndicationStatus() throws TimeoutException, XBeeException { byte[] associationIndicationValue = getParameter("AI"); return AssociationIndicationStatus.get(ByteUtils.byteArrayToInt(associationIndicationValue)); } /** * Forces this XBee device to immediately disassociate from the network and * re-attempt to associate. * * <p>Only valid for End Devices.</p> * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout executing the * disassociation command. * @throws XBeeException if there is any other XBee related exception. * * @see #getAssociationIndicationStatus() */ protected void forceDisassociate() throws TimeoutException, XBeeException { executeParameter("DA"); } /** * Writes configurable parameter values to the non-volatile memory of this * XBee device so that parameter modifications persist through subsequent * resets. * * <p>Parameters values remain in this device's memory until overwritten by * subsequent use of this method.</p> * * <p>If changes are made without writing them to non-volatile memory, the * module reverts back to previously saved parameters the next time the * module is powered-on.</p> * * <p>Writing the parameter modifications does not mean those values are * immediately applied, this depends on the status of the 'apply * configuration changes' option. Use method * {@code isApplyConfigurationChangesEnabled()} to get its status and * {@code enableApplyConfigurationChanges(boolean)} to enable/disable the * option. If it is disable method {@code applyChanges()} can be used in * order to manually apply the changes.</p> * * @throws InterfaceNotOpenException if this device connection is not open. * @throws TimeoutException if there is a timeout executing the write * changes command. * @throws XBeeException if there is any other XBee related exception. * * @see #applyChanges() * @see #enableApplyConfigurationChanges(boolean) * @see #isApplyConfigurationChangesEnabled() * @see #setParameter(String, byte[]) */ public void writeChanges() throws TimeoutException, XBeeException { executeParameter("WR"); } /** * Enables the Bluetooth interface of this XBee device. * * <p>To work with this interface, you must also configure the Bluetooth * password if not done previously. You can use the * {@link #updateBluetoothPassword(String)} method for that purpose.</p> * * <p>Note that your device must have Bluetooth Low Energy support to use * this method.</p> * * @throws TimeoutException if there is a timeout enabling the interface. * @throws XBeeException if there is any other XBee related exception. * * @see #disableBluetooth() * @see #updateBluetoothPassword(String) * * @since 1.3.0 */ public void enableBluetooth() throws TimeoutException, XBeeException { enableBluetooth(true); } /** * Disables the Bluetooth interface of this XBee device. * * <p>Note that your device must have Bluetooth Low Energy support to use * this method.</p> * * @throws TimeoutException if there is a timeout disabling the interface. * @throws XBeeException if there is any other XBee related exception. * * @see #enableBluetooth() * * @since 1.3.0 */ public void disableBluetooth() throws TimeoutException, XBeeException { enableBluetooth(false); } /** * Enables or disables the Bluetooth interface of this XBee device. * * @param enable {@code true} to enable the Bluetooth interface, * {@code false} to disable it. * * @throws TimeoutException if there is a timeout enabling or disabling the * interface. * @throws XBeeException if there is any other XBee related exception. * * @since 1.3.0 */ private void enableBluetooth(boolean enable) throws TimeoutException, XBeeException { setParameter("BT", new byte[] {(byte) (enable ? 0x01 : 0x00)}); writeChanges(); applyChanges(); } /** * Reads and returns the EUI-48 Bluetooth MAC address of this XBee device * in a format such as {@code 00112233AABB}. * * <p>Note that your device must have Bluetooth Low Energy support to use * this method.</p> * * @return The Bluetooth MAC address. * * @throws TimeoutException if there is a timeout reading the MAC address. * @throws XBeeException if there is any other XBee related exception. * * @since 1.3.0 */ public String getBluetoothMacAddress() throws TimeoutException, XBeeException { return HexUtils.byteArrayToHexString(getParameter("BL")); } /** * Changes the password of this Bluetooth device with the new one provided. * * <p>Note that your device must have Bluetooth Low Energy support to use * this method.</p> * * @param newPassword New Bluetooth password. * * @throws TimeoutException if there is a timeout changing the Bluetooth * password. * @throws XBeeException if there is any other XBee related exception. * * @since 1.3.0 */ public void updateBluetoothPassword(String newPassword) throws TimeoutException, XBeeException { // Generate a new salt and verifier. byte[] salt = SrpUtils.generateSalt(); byte[] verifier; try { verifier = SrpUtils.generateVerifier(salt, newPassword); } catch (IOException | NoSuchAlgorithmException e) { throw new XBeeException(e); } // Set the salt. setParameter("$S", salt); // Set the verifier (split in 4 settings). int index = 0; int atLength = verifier.length / 4; setParameter("$V", Arrays.copyOfRange(verifier, index, index + atLength)); index += atLength; setParameter("$W", Arrays.copyOfRange(verifier, index, index + atLength)); index += atLength; setParameter("$X", Arrays.copyOfRange(verifier, index, index + atLength)); index += atLength; setParameter("$Y", Arrays.copyOfRange(verifier, index, index + atLength)); // Write and apply changes. writeChanges(); applyChanges(); } }
package com.hearthsim.card.minion; import com.hearthsim.card.*; import com.hearthsim.event.CharacterFilter; import com.hearthsim.event.CharacterFilterSummon; import com.hearthsim.event.attack.AttackAction; import com.hearthsim.event.effect.CardEffectCharacter; import com.hearthsim.event.effect.CardEffectCharacterSummon; import com.hearthsim.event.effect.CardEffectOnResolveTargetableInterface; import com.hearthsim.exception.HSException; import com.hearthsim.exception.HSInvalidPlayerIndexException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.HearthAction; import com.hearthsim.util.HearthAction.Verb; import com.hearthsim.util.factory.BoardStateFactoryBase; import com.hearthsim.util.tree.HearthTreeNode; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Minion extends Card implements CardEffectOnResolveTargetableInterface, CardEndTurnInterface, CardStartTurnInterface { private static final Logger log = LoggerFactory.getLogger(Card.class); public static enum MinionTribe { NONE, BEAST, MECH, MURLOC, PIRATE, DEMON, DRAGON, TOTEM } public static MinionTribe StringToMinionTribe(String race) { race = race == null ? "" : race.toLowerCase(); switch (race) { case "beast": return MinionTribe.BEAST; case "mech": return MinionTribe.MECH; case "murloc": return MinionTribe.MURLOC; case "pirate": return MinionTribe.PIRATE; case "demon": return MinionTribe.DEMON; case "dragon": return MinionTribe.DRAGON; case "totem": return MinionTribe.TOTEM; default: return MinionTribe.NONE; } } private boolean taunt_; private boolean divineShield_; protected boolean windFury_; private boolean charge_; private boolean immune_ = false; // Ignores damage protected boolean hasAttacked_; protected boolean hasWindFuryAttacked_; private boolean frozen_; protected boolean silenced_; private boolean stealthed_; protected boolean heroTargetable_ = true; protected byte health_; protected byte maxHealth_; private byte auraHealth_; protected byte attack_; private byte extraAttackUntilTurnEnd_; private byte auraAttack_; private boolean destroyOnTurnStart_; private boolean destroyOnTurnEnd_; protected byte spellDamage_; protected boolean cantAttack; public Minion() { super(); } @Override protected void initFromImplementedCard(ImplementedCardList.ImplementedCard implementedCard) { super.initFromImplementedCard(implementedCard); if (implementedCard != null) { // only 'Minion' class is not implemented this.attack_ = implementedCard.attack_ > 0 ? (byte) implementedCard.attack_ : 0; this.health_ = (byte) implementedCard.health_; this.maxHealth_ = health_; this.taunt_ = implementedCard.taunt_; this.divineShield_ = implementedCard.divineShield_; this.windFury_ = implementedCard.windfury_; this.charge_ = implementedCard.charge_; this.stealthed_ = implementedCard.stealth_; this.spellDamage_ = (byte) implementedCard.spellDamage; this.cantAttack = implementedCard.cantAttack; } } public boolean getTaunt() { return taunt_; } public void setTaunt(boolean taunt) { taunt_ = taunt; } public byte getHealth() { return health_; } public void setHealth(byte health) { health_ = health; } public void addHealth(byte value) { health_ += value; } public byte getMaxHealth() { return maxHealth_; } public void setMaxHealth(byte health) { maxHealth_ = health; } public void addMaxHealth(byte value) { maxHealth_ += value; } public byte getBaseHealth() { if (this.implementedCard == null) { return this.getMaxHealth(); } return (byte) this.implementedCard.health_; } public byte getAttack() { return attack_; } public void setAttack(byte attack) { attack_ = attack; } public void addAttack(byte value) { attack_ += value; } public byte getBaseAttack() { if (this.implementedCard == null) { return this.attack_; } return (byte) this.implementedCard.attack_; } public boolean getDivineShield() { return divineShield_; } public void setDivineShield(boolean divineShield) { divineShield_ = divineShield; } public boolean canAttack() { return !this.hasAttacked_ && (this.getTotalAttack()) > 0 && !this.frozen_ && !cantAttack; } public void hasAttacked(boolean hasAttacked) { hasAttacked_ = hasAttacked; } public boolean hasWindFuryAttacked() { return hasWindFuryAttacked_; } public void hasWindFuryAttacked(boolean hasAttacked) { hasWindFuryAttacked_ = hasAttacked; } public boolean getCharge() { return charge_; } public void setCharge(boolean value) { charge_ = value; } public boolean getFrozen() { return frozen_; } public void setFrozen(boolean value) { frozen_ = value; } public boolean getWindfury() { return windFury_; } public void setWindfury(boolean value) { windFury_ = value; if (hasAttacked_) { hasAttacked_ = false; hasWindFuryAttacked_ = true; } } public void addExtraAttackUntilTurnEnd(byte value) { extraAttackUntilTurnEnd_ += value; } public byte getExtraAttackUntilTurnEnd() { return extraAttackUntilTurnEnd_; } public void setExtraAttackUntilTurnEnd(byte value) { extraAttackUntilTurnEnd_ = value; } public boolean getDestroyOnTurnStart() { return destroyOnTurnStart_; } public void setDestroyOnTurnStart(boolean value) { destroyOnTurnStart_ = value; } public boolean getDestroyOnTurnEnd() { return destroyOnTurnEnd_; } public void setDestroyOnTurnEnd(boolean value) { destroyOnTurnEnd_ = value; } public boolean isSilenced() { return silenced_; } protected void setSilenced(boolean silenced) { silenced_ = silenced; } public byte getAuraAttack() { return auraAttack_; } public void setAuraAttack(byte value) { auraAttack_ = value; } public byte getAuraHealth() { return auraHealth_; } public void setAuraHealth(byte value) { auraHealth_ = value; } public byte getTotalAttack() { return (byte) (attack_ + auraAttack_ + extraAttackUntilTurnEnd_); } public byte getTotalHealth() { return (byte) (health_ + auraHealth_); } public byte getTotalMaxHealth() { return (byte) (maxHealth_ + auraHealth_); } public MinionTribe getTribe() { if (this.implementedCard == null) { return MinionTribe.NONE; } return Minion.StringToMinionTribe(this.implementedCard.race); } public void addAuraHealth(byte value) { auraHealth_ += value; } public void removeAuraHealth(byte value) { health_ += value; if (health_ > maxHealth_) health_ = maxHealth_; auraHealth_ -= value; } public boolean getStealthed() { return stealthed_; } public void setStealthed(boolean value) { stealthed_ = value; } public boolean getImmune() { return immune_; } public void setImmune(boolean immune) { immune_ = immune; } // This is a flag to tell the BoardState that it can't cheat on the placement of this minion public boolean getPlacementImportant() { return false; } public boolean isHeroTargetable() { return heroTargetable_; } public void setHeroTargetable(boolean value) { heroTargetable_ = value; } public byte getSpellDamage() { return spellDamage_; } public void setSpellDamage(byte value) { spellDamage_ = value; } public void addSpellDamage(byte value) { spellDamage_ += value; } public void subtractSpellDamage(byte value) { spellDamage_ -= value; } public boolean isAlive() { return getTotalHealth() > 0; } public boolean hasBattlecry() { return this instanceof MinionTargetableBattlecry || this instanceof MinionUntargetableBattlecry; } public boolean isHero() { return false; } /** * Called at the start of the turn * <p> * This function is called at the start of the turn. Any derived class must override it to implement whatever "start of the turn" effect the card has. */ @Override public HearthTreeNode startTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel) throws HSException { if (destroyOnTurnStart_) { // toRet = this.destroyAndNotify(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1); this.setHealth((byte) -99); } return boardModel; } /** * End the turn and resets the card state * <p> * This function is called at the end of the turn. Any derived class must override it and remove any temporary buffs that it has. * <p> * This is not the most efficient implementation... luckily, endTurn only happens once per turn */ @Override public HearthTreeNode endTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel) throws HSException { extraAttackUntilTurnEnd_ = 0; if (destroyOnTurnEnd_) { // toRet = this.destroyAndNotify(thisMinionPlayerIndex, toRet, deckPlayer0, deckPlayer1); this.setHealth((byte) -99); } return boardModel; } /** * Called when this minion takes damage * <p> * Always use this function to take damage... it properly notifies all others of its damage and possibly of its death * * @param damage The amount of damage to take * @param attackPlayerSide The player index of the attacker. This is needed to do things like +spell damage. * @param thisPlayerSide * @param boardState * @param isSpellDamage True if this is a spell damage * @param handleMinionDeath Set this to True if you want the death event to trigger when (if) the minion dies from this damage. Setting this flag to True will also trigger deathrattle immediately. * @throws HSInvalidPlayerIndexException */ public HearthTreeNode takeDamageAndNotify(byte damage, PlayerSide attackPlayerSide, PlayerSide thisPlayerSide, HearthTreeNode boardState, boolean isSpellDamage, boolean handleMinionDeath) { byte damageDealt = this.takeDamage(damage, attackPlayerSide, thisPlayerSide, boardState.data_, isSpellDamage); if (damageDealt > 0) { return boardState.notifyMinionDamaged(thisPlayerSide, this); } return boardState; } public byte takeDamage(byte damage, PlayerSide originSide, PlayerSide thisPlayerSide, BoardModel board, boolean isSpellDamage) { if (this.divineShield_) { if (damage > 0) this.divineShield_ = false; return 0; } if (this.immune_) { return 0; } byte totalDamage = damage; if (isSpellDamage) { totalDamage += board.modelForSide(originSide).getSpellDamage(); } this.health_ = (byte) (this.health_ - totalDamage); return totalDamage; } /** * Called when this minion dies (destroyAndNotify) * <p> * Always use this function to "kill" minions * * @param thisPlayerSide * @param boardState * @throws HSInvalidPlayerIndexException */ public HearthTreeNode destroyAndNotify(PlayerSide thisPlayerSide, HearthTreeNode boardState, boolean singleRealizationOnly) { health_ = 0; HearthTreeNode toRet = boardState; // perform the deathrattle action if there is one if (deathrattleAction_ != null) { toRet = deathrattleAction_.performAction(this, thisPlayerSide, toRet, singleRealizationOnly); } toRet = toRet.notifyMinionDead(thisPlayerSide, this); return toRet; } // Use for bounce (e.g., Brewmaster) or recreate (e.g., Reincarnate) public Minion createResetCopy() { try { Constructor<? extends Minion> ctor = this.getClass().getConstructor(); return ctor.newInstance(); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Called when this minion is silenced * <p> * Always use this function to "silence" minions * * @param thisPlayerSide * @param boardState * @throws HSInvalidPlayerIndexException */ public void silenced(PlayerSide thisPlayerSide, BoardModel boardState) { spellDamage_ = 0; divineShield_ = false; taunt_ = false; charge_ = false; frozen_ = false; windFury_ = false; deathrattleAction_ = null; stealthed_ = false; heroTargetable_ = true; cantAttack = false; // Reset the attack and health to base this.attack_ = this.getBaseAttack(); if (this.maxHealth_ > this.getBaseHealth()) { this.maxHealth_ = this.getBaseHealth(); if (this.health_ > this.maxHealth_) this.health_ = this.maxHealth_; } //Ask the board to clear this minion's aura boardState.removeAuraOfMinion(thisPlayerSide, this); //Set the silenced flag at the end silenced_ = true; } /** * Called when this minion is healed * <p> * Always use this function to heal minions * @param healAmount The amount of healing to take * @param thisPlayerSide * @param boardState */ public HearthTreeNode takeHealAndNotify(byte healAmount, PlayerSide thisPlayerSide, HearthTreeNode boardState) { byte actual = this.takeHeal(healAmount, thisPlayerSide, boardState.data_); if (actual > 0) { return boardState.notifyMinionHealed(thisPlayerSide, this); } return boardState; } public byte takeHeal(byte healAmount, PlayerSide thisPlayerSide, BoardModel board) { int missing = this.maxHealth_ - this.health_; int actual = healAmount > missing ? missing : healAmount; this.health_ += actual; return (byte) actual; } @Override public boolean canBeUsedOn(PlayerSide playerSide, Minion minion, BoardModel boardModel) { if (!super.canBeUsedOn(playerSide, minion, boardModel)) { return false; } return playerSide != PlayerSide.WAITING_PLAYER && !hasBeenUsed; } /** * Use a targetable battlecry. This will add battlecry nodes to boardState as children. * * @param side * @param targetCharacterIndex * @param boardState * @return * @throws HSException */ public HearthTreeNode useTargetableBattlecry(PlayerSide side, int targetCharacterIndex, HearthTreeNode boardState, boolean singleRealizationOnly) { if (this instanceof MinionTargetableBattlecry) { boardState.data_.modelForSide(side); boardState = ((MinionTargetableBattlecry)this).useTargetableBattlecry_core(PlayerSide.CURRENT_PLAYER, this, side, targetCharacterIndex, boardState); if (boardState != null) { int originCharacterIndex = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getIndexForCharacter(this); boardState = BoardStateFactoryBase.handleDeadMinions(boardState, singleRealizationOnly); boardState.setAction(new HearthAction(Verb.TARGETABLE_BATTLECRY, PlayerSide.CURRENT_PLAYER, originCharacterIndex, side, targetCharacterIndex)); } } return boardState; } /** * Use an untargetable battlecry. * * @param minionPlacementIndex * @param boardState * @param singleRealizationOnly * @return * @throws HSException */ public HearthTreeNode useUntargetableBattlecry(int minionPlacementIndex, HearthTreeNode boardState, boolean singleRealizationOnly) { HearthTreeNode toRet = boardState; if (this instanceof MinionUntargetableBattlecry) { MinionUntargetableBattlecry battlecryMinion = (MinionUntargetableBattlecry) this; toRet = battlecryMinion.useUntargetableBattlecry_core(minionPlacementIndex, boardState, singleRealizationOnly); if (toRet != null) { // Check for dead minions toRet = BoardStateFactoryBase.handleDeadMinions(toRet, singleRealizationOnly); } } return toRet; } /** * Places a minion on the board by using the card in hand * * @param side * @param targetMinion The target minion (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position. * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned * @throws HSException */ @Override protected HearthTreeNode use_core(PlayerSide side, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { if (hasBeenUsed || side == PlayerSide.WAITING_PLAYER || boardState.data_.modelForSide(side).isBoardFull()) { return null; } HearthTreeNode toRet = boardState; toRet = super.use_core(side, targetMinion, toRet, singleRealizationOnly); return toRet; } @Override public CardEffectCharacter getTargetableEffect() { return new CardEffectCharacterSummon(this); } @Override public CharacterFilter getTargetableFilter() { return CharacterFilterSummon.ALL_FRIENDLIES; } /** * Places a minion on the board via a summon effect * <p> * This function is meant to be used when summoning minions through means other than a direct card usage. * * @param targetSide * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned */ public HearthTreeNode summonMinion(PlayerSide targetSide, int targetMinionIndex, HearthTreeNode boardState, boolean wasPlayed, boolean singleRealizationOnly) { if (boardState.data_.modelForSide(targetSide).isBoardFull()) return null; HearthTreeNode toRet = boardState; toRet = this.summonMinion_core(targetSide, targetMinionIndex, toRet); if (this instanceof MinionUntargetableBattlecry) { toRet = this.useUntargetableBattlecry(targetMinionIndex, toRet, singleRealizationOnly); } if (this instanceof MinionTargetableBattlecry) { MinionTargetableBattlecry battlecryOrigin = ((MinionTargetableBattlecry) this); HearthTreeNode child; Minion origin; int originCharacterIndex = toRet.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getIndexForCharacter(this); for (BoardModel.CharacterLocation characterLocation : toRet.data_) { if (battlecryOrigin.canTargetWithBattlecry(targetSide, this, characterLocation.getPlayerSide(), characterLocation.getIndex(), toRet.data_)) { child = new HearthTreeNode(toRet.data_.deepCopy()); origin = child.data_.getCharacter(PlayerSide.CURRENT_PLAYER, originCharacterIndex); child = origin.useTargetableBattlecry(characterLocation.getPlayerSide(), characterLocation.getIndex(), child, singleRealizationOnly); if (child != null) { toRet.addChild(child); } } } } if (wasPlayed) { toRet = toRet.notifyMinionPlayed(targetSide, this); } toRet = toRet.notifyMinionSummon(targetSide, this); return toRet; } public HearthTreeNode summonMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, boolean wasPlayed, boolean singleRealizationOnly) { return this.summonMinion(targetSide, boardState.data_.getCurrentPlayer().getIndexForCharacter(targetMinion), boardState, wasPlayed, singleRealizationOnly); } public HearthTreeNode summonMinionAtEnd(PlayerSide targetSide, HearthTreeNode boardState, boolean wasPlayed, boolean singleRealizationOnly) { PlayerModel player = boardState.data_.modelForSide(targetSide); return this.summonMinion(targetSide, player.getNumMinions(), boardState, wasPlayed, singleRealizationOnly); } /** * * Places a minion on the board via a summon effect * * This function is meant to be used when summoning minions through means other than a direct card usage. * * @param targetSide * @param targetIndex The target character (can be a Hero). The new minion is always placed to the right of (higher index) the target minion. If the target minion is a hero, then it is placed at the left-most position. * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned * @throws HSException */ protected HearthTreeNode summonMinion_core(PlayerSide targetSide, int targetIndex, HearthTreeNode boardState) { boardState.data_.placeMinion(targetSide, this, targetIndex); if (!charge_) { hasAttacked_ = true; } hasBeenUsed = true; return boardState; } /** * * Attack with the minion * * * * @param targetMinionPlayerSide * @param targetMinion The target minion * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned */ public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { // can't attack a stealthed target if (targetMinion.getStealthed()) return null; if (!this.canAttack()) { return null; } if (targetMinionPlayerSide == PlayerSide.CURRENT_PLAYER) { return null; } PlayerModel currentPlayer = boardState.data_.getCurrentPlayer(); PlayerModel targetPlayer = boardState.data_.modelForSide(targetMinionPlayerSide); // Notify all that an attack is beginning HearthTreeNode toRet; int attackerIndex = this instanceof Hero ? 0 : currentPlayer.getMinions() .indexOf(this) + 1; int targetIndex = targetMinion instanceof Hero ? 0 : targetPlayer.getMinions() .indexOf(targetMinion) + 1; // Do the actual attack toRet = this.attack_core(targetMinionPlayerSide, targetMinion, boardState, singleRealizationOnly); // check for and remove dead minions if (toRet != null) { toRet.setAction(new HearthAction(Verb.ATTACK, PlayerSide.CURRENT_PLAYER, attackerIndex, targetMinionPlayerSide, targetIndex)); toRet = BoardStateFactoryBase.handleDeadMinions(toRet, singleRealizationOnly); } // Attacking means you lose stealth if (toRet != null) this.stealthed_ = false; return toRet; } public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, int targetCharacterIndex, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { Minion targetCharacter = boardState.data_.modelForSide(targetMinionPlayerSide).getCharacter(targetCharacterIndex); return this.attack(targetMinionPlayerSide, targetCharacter, boardState, singleRealizationOnly); } /** * * Attack with the minion * * * * @param targetMinionPlayerSide * @param targetMinion The target minion * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned */ protected HearthTreeNode attack_core(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { HearthTreeNode toRet = boardState; byte origAttack = targetMinion.getTotalAttack(); toRet = targetMinion.takeDamageAndNotify(this.getTotalAttack(), PlayerSide.CURRENT_PLAYER, targetMinionPlayerSide, toRet, false, false); toRet = this.takeDamageAndNotify(origAttack, targetMinionPlayerSide, PlayerSide.CURRENT_PLAYER, toRet, false, false); if (windFury_ && !hasWindFuryAttacked_) hasWindFuryAttacked_ = true; else hasAttacked_ = true; return toRet; } @Override public JSONObject toJSON() { JSONObject json = super.toJSON(); json.put("attack", attack_); json.put("baseAttack", this.getBaseAttack()); if (health_ != maxHealth_) json.put("health", health_); json.put("baseHealth", this.getBaseHealth()); json.put("maxHealth", maxHealth_); if (taunt_) json.put("taunt", taunt_); if (divineShield_) json.put("divineShield", divineShield_); if (windFury_) json.put("windFury", windFury_); if (charge_) json.put("charge", charge_); if (frozen_) json.put("frozen", frozen_); if (silenced_) json.put("silenced", silenced_); if (hasAttacked_) json.put("hasAttacked", hasAttacked_); if (spellDamage_ != 0) json.put("spellDamage", spellDamage_); return json; } /** * Deep copy of the object * * Note: the event actions are not actually deep copied. */ @Override public Card deepCopy() { Minion minion = null; try { minion = getClass().newInstance(); } catch(InstantiationException e) { Minion.log.error("instantiation error", e); } catch(IllegalAccessException e) { Minion.log.error("illegal access error", e); } if (minion == null) { throw new RuntimeException("unable to instantiate minion."); } minion.baseManaCost = baseManaCost; minion.attack_ = attack_; minion.health_ = health_; minion.extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd_; minion.auraAttack_ = auraAttack_; minion.maxHealth_ = maxHealth_; minion.auraHealth_ = auraHealth_; minion.spellDamage_ = spellDamage_; minion.taunt_ = taunt_; minion.divineShield_ = divineShield_; minion.windFury_ = windFury_; minion.charge_ = charge_; minion.hasAttacked_ = hasAttacked_; minion.hasWindFuryAttacked_ = hasWindFuryAttacked_; minion.frozen_ = frozen_; minion.silenced_ = silenced_; minion.stealthed_ = stealthed_; minion.heroTargetable_ = heroTargetable_; minion.destroyOnTurnStart_ = destroyOnTurnStart_; minion.destroyOnTurnEnd_ = destroyOnTurnEnd_; minion.deathrattleAction_ = deathrattleAction_; minion.isInHand_ = isInHand_; minion.hasBeenUsed = hasBeenUsed; // TODO: continue here. return minion; } @Override public boolean equals(Object other) { if (!super.equals(other)) { return false; } Minion otherMinion = (Minion)other; if (health_ != otherMinion.health_) return false; if (maxHealth_ != otherMinion.maxHealth_) return false; if (this.getBaseHealth() != otherMinion.getBaseHealth()) return false; if (auraHealth_ != otherMinion.auraHealth_) return false; if (attack_ != otherMinion.attack_) return false; if (this.getBaseAttack() != otherMinion.getBaseAttack()) return false; if (extraAttackUntilTurnEnd_ != otherMinion.extraAttackUntilTurnEnd_) return false; if (auraAttack_ != otherMinion.auraAttack_) return false; if (taunt_ != otherMinion.taunt_) return false; if (divineShield_ != otherMinion.divineShield_) return false; if (windFury_ != otherMinion.windFury_) return false; if (charge_ != otherMinion.charge_) return false; if (stealthed_ != otherMinion.stealthed_) return false; if (hasAttacked_ != otherMinion.hasAttacked_) return false; if (heroTargetable_ != otherMinion.heroTargetable_) return false; if (hasWindFuryAttacked_ != otherMinion.hasWindFuryAttacked_) return false; if (frozen_ != otherMinion.frozen_) return false; if (silenced_ != otherMinion.silenced_) return false; if (destroyOnTurnStart_ != otherMinion.destroyOnTurnStart_) return false; if (destroyOnTurnEnd_ != otherMinion.destroyOnTurnEnd_) return false; if (spellDamage_ != otherMinion.spellDamage_) return false; // This is checked for reference equality if (deathrattleAction_ == null && ((Minion)other).deathrattleAction_ != null) return false; if (deathrattleAction_ != null && !deathrattleAction_.equals(((Minion)other).deathrattleAction_)) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (taunt_ ? 1 : 0); result = 31 * result + (divineShield_ ? 1 : 0); result = 31 * result + (windFury_ ? 1 : 0); result = 31 * result + (charge_ ? 1 : 0); result = 31 * result + (hasAttacked_ ? 1 : 0); result = 31 * result + (hasWindFuryAttacked_ ? 1 : 0); result = 31 * result + (frozen_ ? 1 : 0); result = 31 * result + (silenced_ ? 1 : 0); result = 31 * result + (stealthed_ ? 1 : 0); result = 31 * result + (heroTargetable_ ? 1 : 0); result = 31 * result + health_; result = 31 * result + maxHealth_; result = 31 * result + this.getBaseHealth(); result = 31 * result + auraHealth_; result = 31 * result + attack_; result = 31 * result + this.getBaseAttack(); result = 31 * result + extraAttackUntilTurnEnd_; result = 31 * result + auraAttack_; result = 31 * result + (destroyOnTurnStart_ ? 1 : 0); result = 31 * result + (destroyOnTurnEnd_ ? 1 : 0); result = 31 * result + spellDamage_; result = 31 * result + (deathrattleAction_ != null ? deathrattleAction_.hashCode() : 0); result = 31 * result + (this.getPlacementImportant() ? 1 : 0); return result; } @Deprecated public Minion(String name, byte mana, byte attack, byte health, byte baseAttack, byte extraAttackUntilTurnEnd, byte auraAttack, byte baseHealth, byte maxHealth, byte auraHealth, byte spellDamage, boolean taunt, boolean divineShield, boolean windFury, boolean charge, boolean hasAttacked, boolean hasWindFuryAttacked, boolean frozen, boolean silenced, boolean stealthed, boolean heroTargetable, boolean summoned, boolean transformed, boolean destroyOnTurnStart, boolean destroyOnTurnEnd, AttackAction attackAction, boolean isInHand, boolean hasBeenUsed) { super(name, mana, hasBeenUsed, isInHand, (byte) 0); attack_ = attack; health_ = health; taunt_ = taunt; divineShield_ = divineShield; windFury_ = windFury; charge_ = charge; hasAttacked_ = hasAttacked; extraAttackUntilTurnEnd_ = extraAttackUntilTurnEnd; hasWindFuryAttacked_ = hasWindFuryAttacked; frozen_ = frozen; silenced_ = silenced; maxHealth_ = maxHealth; destroyOnTurnStart_ = destroyOnTurnStart; destroyOnTurnEnd_ = destroyOnTurnEnd; auraAttack_ = auraAttack; auraHealth_ = auraHealth; spellDamage_ = spellDamage; stealthed_ = stealthed; heroTargetable_ = heroTargetable; } @Deprecated public boolean hasAttacked() { return hasAttacked_; } @Deprecated public void silenced(PlayerSide thisPlayerSide, HearthTreeNode boardState) throws HSInvalidPlayerIndexException { this.silenced(thisPlayerSide, boardState.data_); } @Deprecated public HearthTreeNode takeDamage(byte damage, PlayerSide attackPlayerSide, PlayerSide thisPlayerSide, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean isSpellDamage, boolean handleMinionDeath) throws HSException { return this.takeDamageAndNotify(damage, attackPlayerSide, thisPlayerSide, boardState, isSpellDamage, handleMinionDeath); } @Deprecated public HearthTreeNode destroyed(PlayerSide thisPlayerSide, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.destroyAndNotify(thisPlayerSide, boardState, singleRealizationOnly); } @Deprecated public HearthTreeNode takeHeal(byte healAmount, PlayerSide thisPlayerSide, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.takeHealAndNotify(healAmount, thisPlayerSide, boardState); } @Deprecated public HearthTreeNode useUntargetableBattlecry(Minion minionPlacementTarget, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { return this.useUntargetableBattlecry(boardState.data_.getCurrentPlayer().getIndexForCharacter(minionPlacementTarget), boardState, singleRealizationOnly); } @Deprecated public HearthTreeNode useUntargetableBattlecry(Minion minionPlacementTarget, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.useUntargetableBattlecry(minionPlacementTarget, boardState, singleRealizationOnly); } @Deprecated public HearthTreeNode summonMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean wasPlayed, boolean singleRealizationOnly) throws HSException { return this.summonMinion(targetSide, targetMinion, boardState, wasPlayed, singleRealizationOnly); } @Deprecated public HearthTreeNode summonMinion(PlayerSide targetSide, int targetIndex, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean wasPlayed, boolean singleRealizationOnly) throws HSException { PlayerModel player = boardState.data_.modelForSide(targetSide); Minion targetLocation = player.getCharacter(targetIndex); return this.summonMinion(targetSide, targetLocation, boardState, wasPlayed, singleRealizationOnly); } @Deprecated public HearthTreeNode summonMinionAtEnd(PlayerSide targetSide, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean wasPlayed, boolean singleRealizationOnly) throws HSException { PlayerModel player = boardState.data_.modelForSide(targetSide); return this.summonMinion(targetSide, player.getNumMinions(), boardState, wasPlayed, singleRealizationOnly); } @Deprecated protected HearthTreeNode summonMinion_core(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { int targetIndex = 0; if (!targetMinion.isHero()) { PlayerModel targetPlayer = boardState.data_.modelForSide(targetSide); targetIndex = targetPlayer.getMinions().indexOf(targetMinion) + 1; } return this.summonMinion_core(targetSide, targetIndex, boardState); } @Deprecated protected HearthTreeNode summonMinion_core(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.summonMinion_core(targetSide, targetMinion, boardState, singleRealizationOnly); } /** * Place a minion on the board * * Use this function if you need to place a minion on the board without triggering any of the "On Summon" effects * * @param targetSide * @param targetMinion * @param boardState * @param singleRealizationOnly * @return * @throws HSException */ @Deprecated public HearthTreeNode placeMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { if (isHero(targetMinion)) { boardState.data_.placeMinion(targetSide, this, 0); } else { PlayerModel targetPlayer = boardState.data_.modelForSide(targetSide); boardState.data_.placeMinion(targetSide, this, targetPlayer.getMinions().indexOf(targetMinion) + 1); } return this.notifyMinionPlacement(boardState, targetSide); } @Deprecated public HearthTreeNode placeMinion(PlayerSide targetSide, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.placeMinion(targetSide, targetMinion, boardState, singleRealizationOnly); } @Deprecated public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.attack(targetMinionPlayerSide, targetMinion, boardState, singleRealizationOnly); } @Deprecated public HearthTreeNode attack(PlayerSide targetMinionPlayerSide, int targetCharacterIndex, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.attack(targetMinionPlayerSide, targetCharacterIndex, boardState, singleRealizationOnly); } @Deprecated protected HearthTreeNode attack_core(PlayerSide targetMinionPlayerSide, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1, boolean singleRealizationOnly) throws HSException { return this.attack_core(targetMinionPlayerSide, targetMinion, boardState, singleRealizationOnly); } // Various notifications @Deprecated protected HearthTreeNode notifyMinionSummon(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionSummon(boardState, targetSide); } @Deprecated protected HearthTreeNode notifyMinionSummon(HearthTreeNode boardState, PlayerSide targetSide) throws HSException { return boardState.notifyMinionSummon(targetSide, this); } @Deprecated protected HearthTreeNode notifyMinionPlacement(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionPlacement(boardState, targetSide); } @Deprecated protected HearthTreeNode notifyMinionPlacement(HearthTreeNode boardState, PlayerSide targetSide) throws HSException { return boardState.notifyMinionPlacement(targetSide, this); } @Deprecated protected HearthTreeNode notifyMinionPlayed(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionPlayed(boardState, targetSide); } @Deprecated protected HearthTreeNode notifyMinionPlayed(HearthTreeNode boardState, PlayerSide targetSide) throws HSException { return boardState.notifyMinionPlayed(targetSide, this); } @Deprecated protected HearthTreeNode notifyMinionDamaged(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionDamaged(boardState, targetSide); } @Deprecated protected HearthTreeNode notifyMinionDamaged(HearthTreeNode boardState, PlayerSide targetSide) throws HSException { return boardState.notifyMinionDamaged(targetSide, this); } @Deprecated protected HearthTreeNode notifyMinionDead(PlayerSide deadMinionPlayerSide, Minion deadMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionDead(deadMinionPlayerSide, deadMinion, boardState); } @Deprecated protected HearthTreeNode notifyMinionDead(PlayerSide deadMinionPlayerSide, Minion deadMinion, HearthTreeNode boardState) throws HSException { return boardState.notifyMinionDead(deadMinionPlayerSide, deadMinion); } @Deprecated protected HearthTreeNode notifyMinionHealed(HearthTreeNode boardState, PlayerSide targetSide, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.notifyMinionHealed(boardState, targetSide); } @Deprecated protected HearthTreeNode notifyMinionHealed(HearthTreeNode boardState, PlayerSide targetSide) throws HSException { return boardState.notifyMinionHealed(targetSide, this); } @Deprecated public boolean currentPlayerBoardFull(HearthTreeNode boardState) { return boardState.data_.getCurrentPlayer().isBoardFull(); } }
package jp.kshoji.blemidi.util; import java.util.Timer; import java.util.TimerTask; import jp.kshoji.blemidi.device.MidiInputDevice; import jp.kshoji.blemidi.listener.OnMidiInputEventListener; /** * MIDI Parser<br /> * The protocol compatible with Apple's `MIDI over Bluetooth LE` specification. * * @author K.Shoji */ public final class BleMidiParser { // MIDI event message private int midiEventKind; private int midiEventNote; private int midiEventVelocity; // for RPN/NRPN messages private static final int PARAMETER_MODE_NONE = 0; private static final int PARAMETER_MODE_RPN = 1; private static final int PARAMETER_MODE_NRPN = 2; private int parameterMode = PARAMETER_MODE_NONE; private int parameterNumber = 0x3fff; private int parameterValue = 0x3fff; // for SysEx messages private final ReusableByteArrayOutputStream systemExclusiveStream = new ReusableByteArrayOutputStream(); // states private static final int MIDI_STATE_TIMESTAMP = 0; private static final int MIDI_STATE_WAIT = 1; private static final int MIDI_STATE_SIGNAL_2BYTES_2 = 21; private static final int MIDI_STATE_SIGNAL_3BYTES_2 = 31; private static final int MIDI_STATE_SIGNAL_3BYTES_3 = 32; private static final int MIDI_STATE_SIGNAL_SYSEX = 41; private int midiState; // for Timestamp private static final int MAX_TIMESTAMP = 8192; private static final int BUFFER_LENGTH_MILLIS = 10; private boolean useTimestamp = true; private int timestamp = 0; private int lastTimestamp; private long lastTimestampRecorded = 0; private int zeroTimestampCount = 0; final Timer timer; OnMidiInputEventListener midiInputEventListener; final MidiInputDevice sender; /** * Constructor * @param sender the sender */ public BleMidiParser(MidiInputDevice sender) { this.sender = sender; timer = new Timer(); midiState = MIDI_STATE_TIMESTAMP; midiEventKind = 0; midiEventNote = 0; midiEventVelocity = 0; } /** * Sets {@link jp.kshoji.blemidi.listener.OnMidiInputEventListener} * @param midiInputEventListener the listener for MIDI events */ public void setMidiInputEventListener(OnMidiInputEventListener midiInputEventListener) { this.midiInputEventListener = midiInputEventListener; } /** * Calculate `time to wait` for the event's timestamp * * @param timestamp the event's timestamp * @return time to wait */ private int calculateTimeToWait(int timestamp) { long currentTimeMillis = System.currentTimeMillis(); if (lastTimestampRecorded == 0) { // first time lastTimestamp = timestamp; lastTimestampRecorded = currentTimeMillis; return 0; } if (currentTimeMillis - lastTimestampRecorded > MAX_TIMESTAMP) { // the event comes after long pause lastTimestamp = timestamp; lastTimestampRecorded = currentTimeMillis; zeroTimestampCount = 0; return 0; } if (timestamp == 0) { zeroTimestampCount++; if (zeroTimestampCount >= 3) { // decides timestamp is always zero: event fires immediately useTimestamp = false; return 0; } } else { zeroTimestampCount = 0; } int originalTimestamp = timestamp; if (timestamp < lastTimestamp) { timestamp += MAX_TIMESTAMP; } int result = BUFFER_LENGTH_MILLIS + timestamp - lastTimestamp - (int)(currentTimeMillis - lastTimestampRecorded); // Log.i(Constants.TAG, "timestamp: " + timestamp + ", lastTimestamp: " + lastTimestamp + ", currentTimeMillis: " + currentTimeMillis + ", lastTimestampRecorded:" + lastTimestampRecorded + ", wait: " + result); lastTimestamp = originalTimestamp; lastTimestampRecorded = currentTimeMillis; return result; } /** * {@link java.util.TimerTask} with MIDI event data */ private abstract class MidiTimerTask extends TimerTask { private static final int INVALID = -1; final int arg1; final int arg2; final int arg3; final byte[] array; private MidiTimerTask(int arg1, int arg2, int arg3, byte[] array) { this.arg1 = arg1; this.arg2 = arg2; this.arg3 = arg3; this.array = array; } /** * Constructor with no arguments */ MidiTimerTask() { this(INVALID, INVALID, INVALID, null); } /** * Constructor with 1 argument * @param arg1 argument 1 */ MidiTimerTask(int arg1) { this(arg1, INVALID, INVALID, null); } /** * Constructor with 2 arguments * @param arg1 argument 1 * @param arg2 argument 2 */ MidiTimerTask(int arg1, int arg2) { this(arg1, arg2, INVALID, null); } /** * Constructor with 3 arguments * @param arg1 argument 1 * @param arg2 argument 2 * @param arg3 argument 3 */ MidiTimerTask(int arg1, int arg2, int arg3) { this (arg1, arg2, arg3, null); } /** * Constructor with array * @param array data */ MidiTimerTask(byte[] array) { this(INVALID, INVALID, INVALID, array); } } /** * Parses MIDI events * * @param header the header bits * @param event the event byte */ private void parseMidiEvent(int header, byte event) { int midiEvent = event & 0xff; int timeToWait; if (midiState == MIDI_STATE_TIMESTAMP) { if ((midiEvent & 0x80) == 0) { // running status midiState = MIDI_STATE_WAIT; } } if (midiState == MIDI_STATE_TIMESTAMP) { timestamp = ((header & 0x3f) << 7) | (event & 0x7f); midiState = MIDI_STATE_WAIT; } else if (midiState == MIDI_STATE_WAIT) { switch (midiEvent & 0xf0) { case 0xf0: { switch (midiEvent) { case 0xf0: synchronized (systemExclusiveStream) { systemExclusiveStream.reset(); systemExclusiveStream.write(midiEvent); midiState = MIDI_STATE_SIGNAL_SYSEX; } break; case 0xf1: case 0xf3: // 0xf1 MIDI Time Code Quarter Frame. : 2bytes // 0xf3 Song Select. : 2bytes midiEventKind = midiEvent; midiState = MIDI_STATE_SIGNAL_2BYTES_2; break; case 0xf2: // 0xf2 Song Position Pointer. : 3bytes midiEventKind = midiEvent; midiState = MIDI_STATE_SIGNAL_3BYTES_2; break; case 0xf6: // 0xf6 Tune Request : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiTuneRequest(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiTuneRequest(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xf8: // 0xf8 Timing Clock : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiTimingClock(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiTimingClock(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xfa: // 0xfa Start : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiStart(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiStart(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xfb: // 0xfb Continue : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiContinue(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiContinue(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xfc: // 0xfc Stop : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiStop(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiStop(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xfe: // 0xfe Active Sensing : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiActiveSensing(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiActiveSensing(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xff: // 0xff Reset : 1byte timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask() { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiReset(sender); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiReset(sender); } } midiState = MIDI_STATE_TIMESTAMP; break; default: break; } } break; case 0x80: case 0x90: case 0xa0: case 0xb0: case 0xe0: // 3bytes pattern midiEventKind = midiEvent; midiState = MIDI_STATE_SIGNAL_3BYTES_2; break; case 0xc0: // program change case 0xd0: // channel after-touch // 2bytes pattern midiEventKind = midiEvent; midiState = MIDI_STATE_SIGNAL_2BYTES_2; break; default: // 0x00 - 0x70: running status if ((midiEventKind & 0xf0) != 0xf0) { // previous event kind is multi-bytes pattern midiEventNote = midiEvent; midiState = MIDI_STATE_SIGNAL_3BYTES_3; } break; } } else if (midiState == MIDI_STATE_SIGNAL_2BYTES_2) { switch (midiEventKind & 0xf0) { // 2bytes pattern case 0xc0: // program change midiEventNote = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiProgramChange(sender, arg1 & 0xf, arg2); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiProgramChange(sender, midiEventKind & 0xf, midiEventNote); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xd0: // channel after-touch midiEventNote = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiChannelAftertouch(sender, arg1 & 0xf, arg2); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiChannelAftertouch(sender, midiEventKind & 0xf, midiEventNote); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xf0: { switch (midiEventKind) { case 0xf1: // 0xf1 MIDI Time Code Quarter Frame. : 2bytes midiEventNote = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventNote) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiTimeCodeQuarterFrame(sender, arg1); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiTimeCodeQuarterFrame(sender, midiEventNote); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xf3: // 0xf3 Song Select. : 2bytes midiEventNote = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventNote) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiSongSelect(sender, arg1); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiSongSelect(sender, midiEventNote); } } midiState = MIDI_STATE_TIMESTAMP; break; default: midiState = MIDI_STATE_TIMESTAMP; break; } } break; default: midiState = MIDI_STATE_TIMESTAMP; break; } } else if (midiState == MIDI_STATE_SIGNAL_3BYTES_2) { switch (midiEventKind & 0xf0) { case 0x80: case 0x90: case 0xa0: case 0xb0: case 0xe0: case 0xf0: // 3bytes pattern midiEventNote = midiEvent; midiState = MIDI_STATE_SIGNAL_3BYTES_3; break; default: midiState = MIDI_STATE_TIMESTAMP; break; } } else if (midiState == MIDI_STATE_SIGNAL_3BYTES_3) { switch (midiEventKind & 0xf0) { // 3bytes pattern case 0x80: // note off midiEventVelocity = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiNoteOff(sender, arg1 & 0xf, arg2, arg3); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiNoteOff(sender, midiEventKind & 0xf, midiEventNote, midiEventVelocity); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0x90: // note on midiEventVelocity = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { if (midiEventVelocity == 0) { midiInputEventListener.onMidiNoteOff(sender, arg1 & 0xf, arg2, arg3); } else { midiInputEventListener.onMidiNoteOn(sender, arg1 & 0xf, arg2, arg3); } } } }, timeToWait); } else { if (midiInputEventListener != null) { if (midiEventVelocity == 0) { midiInputEventListener.onMidiNoteOff(sender, midiEventKind & 0xf, midiEventNote, midiEventVelocity); } else { midiInputEventListener.onMidiNoteOn(sender, midiEventKind & 0xf, midiEventNote, midiEventVelocity); } } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xa0: // control polyphonic key pressure midiEventVelocity = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiPolyphonicAftertouch(sender, arg1 & 0xf, arg2, arg3); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiPolyphonicAftertouch(sender, midiEventKind & 0xf, midiEventNote, midiEventVelocity); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xb0: // control change midiEventVelocity = midiEvent; switch (midiEventNote & 0x7f) { case 98: // NRPN LSB parameterNumber &= 0x3f80; parameterNumber |= midiEventVelocity & 0x7f; parameterMode = PARAMETER_MODE_NRPN; break; case 99: // NRPN MSB parameterNumber &= 0x007f; parameterNumber |= (midiEventVelocity & 0x7f) << 7; parameterMode = PARAMETER_MODE_NRPN; break; case 100: // RPN LSB parameterNumber &= 0x3f80; parameterNumber |= midiEventVelocity & 0x7f; parameterMode = PARAMETER_MODE_RPN; break; case 101: // RPN MSB parameterNumber &= 0x007f; parameterNumber |= (midiEventVelocity & 0x7f) << 7; parameterMode = PARAMETER_MODE_RPN; break; case 38: // data LSB parameterValue &= 0x3f80; parameterValue |= midiEventVelocity & 0x7f; if (parameterNumber != 0x3fff) { if (parameterMode == PARAMETER_MODE_RPN) { timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, parameterNumber, parameterValue) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onRPNMessage(sender, arg1 & 0xf, arg2 & 0x3fff, arg3 & 0x3fff); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onRPNMessage(sender, midiEventKind & 0xf, parameterNumber & 0x3fff, parameterValue & 0x3fff); } } } else if (parameterMode == PARAMETER_MODE_NRPN) { timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, parameterNumber, parameterValue) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onNRPNMessage(sender, arg1 & 0xf, arg2 & 0x3fff, arg3 & 0x3fff); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onNRPNMessage(sender, midiEventKind & 0xf, parameterNumber & 0x3fff, parameterValue & 0x3fff); } } } } break; case 6: // data MSB parameterValue &= 0x007f; parameterValue |= (midiEventVelocity & 0x7f) << 7; if (parameterNumber != 0x3fff) { if (parameterMode == PARAMETER_MODE_RPN) { timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, parameterNumber, parameterValue) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onRPNMessage(sender, arg1 & 0xf, arg2 & 0x3fff, arg3 & 0x3fff); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onRPNMessage(sender, midiEventKind & 0xf, parameterNumber & 0x3fff, parameterValue & 0x3fff); } } } else if (parameterMode == PARAMETER_MODE_NRPN) { timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, parameterNumber, parameterValue) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onNRPNMessage(sender, arg1 & 0xf, arg2 & 0x3fff, arg3 & 0x3fff); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onNRPNMessage(sender, midiEventKind & 0xf, parameterNumber & 0x3fff, parameterValue & 0x3fff); } } } } break; default: // do nothing break; } timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiControlChange(sender, arg1 & 0xf, arg2, arg3); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiControlChange(sender, midiEventKind & 0xf, midiEventNote, midiEventVelocity); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xe0: // pitch bend midiEventVelocity = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventKind, midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiPitchWheel(sender, arg1 & 0xf, (arg2 & 0x7f) | ((arg3 & 0x7f) << 7)); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiPitchWheel(sender, midiEventKind & 0xf, (midiEventNote & 0x7f) | ((midiEventVelocity & 0x7f) << 7)); } } midiState = MIDI_STATE_TIMESTAMP; break; case 0xf0: // Song Position Pointer. midiEventVelocity = midiEvent; timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(midiEventNote, midiEventVelocity) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiSongPositionPointer(sender, (arg1 & 0x7f) | ((arg2 & 0x7f) << 7)); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiSongPositionPointer(sender, (midiEventNote & 0x7f) | ((midiEventVelocity & 0x7f) << 7)); } } midiState = MIDI_STATE_TIMESTAMP; break; default: midiState = MIDI_STATE_TIMESTAMP; break; } } else if (midiState == MIDI_STATE_SIGNAL_SYSEX) { if (midiEvent == 0xf7) { // the end of message synchronized (systemExclusiveStream) { systemExclusiveStream.write(midiEvent); timeToWait = calculateTimeToWait(timestamp); if (useTimestamp && timeToWait > 0) { timer.schedule(new MidiTimerTask(systemExclusiveStream.toByteArray()) { @Override public void run() { if (midiInputEventListener != null) { midiInputEventListener.onMidiSystemExclusive(sender, array); } } }, timeToWait); } else { if (midiInputEventListener != null) { midiInputEventListener.onMidiSystemExclusive(sender, systemExclusiveStream.toByteArray()); } } } midiState = MIDI_STATE_TIMESTAMP; } else { synchronized (systemExclusiveStream) { systemExclusiveStream.write(midiEvent); } } } } /** * Updates incoming data * @param data incoming data */ public void parse(byte[] data) { if (data.length > 1) { int header = data[0] & 0xff; for (int i = 1; i < data.length; i++) { parseMidiEvent(header, data[i]); } } } }
package com.j256.ormlite.field; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.SQLException; import java.util.Collection; import java.util.Map; import com.j256.ormlite.dao.BaseDaoImpl; import com.j256.ormlite.dao.BaseForeignCollection; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.dao.EagerForeignCollection; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.dao.LazyForeignCollection; import com.j256.ormlite.dao.ObjectCache; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.field.types.VoidType; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.stmt.mapped.MappedQueryForId; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.DatabaseResults; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.TableInfo; /** * Per field information configured from the {@link DatabaseField} annotation and the associated {@link Field} in the * class. Use the {@link #createFieldType} static method to instantiate the class. * * @author graywatson */ public class FieldType { /** default suffix added to fields that are id fields of foreign objects */ public static final String FOREIGN_ID_FIELD_SUFFIX = "_id"; /* * Default values. * * NOTE: These don't get any values so the compiler assigns them to the default values for the type. Ahhhh. Smart. */ private static boolean DEFAULT_VALUE_BOOLEAN; private static byte DEFAULT_VALUE_BYTE; private static char DEFAULT_VALUE_CHAR; private static short DEFAULT_VALUE_SHORT; private static int DEFAULT_VALUE_INT; private static long DEFAULT_VALUE_LONG; private static float DEFAULT_VALUE_FLOAT; private static double DEFAULT_VALUE_DOUBLE; private final ConnectionSource connectionSource; private final String tableName; private final Field field; private final String columnName; private final DatabaseFieldConfig fieldConfig; private final boolean isId; private final boolean isGeneratedId; private final String generatedIdSequence; private final Method fieldGetMethod; private final Method fieldSetMethod; private DataPersister dataPersister; private Object defaultValue; private Object dataTypeConfigObj; private FieldConverter fieldConverter; private FieldType foreignIdField; private Constructor<?> foreignConstructor; private FieldType foreignFieldType; private Dao<?, ?> foreignDao; private MappedQueryForId<Object, Object> mappedQueryForId; private static final ThreadLocal<LevelCounters> threadLevelCounters = new ThreadLocal<LevelCounters>() { @Override protected LevelCounters initialValue() { return new LevelCounters(); } }; /** * You should use {@link FieldType#createFieldType} to instantiate one of these field if you have a {@link Field}. */ public FieldType(ConnectionSource connectionSource, String tableName, Field field, DatabaseFieldConfig fieldConfig, Class<?> parentClass) throws SQLException { this.connectionSource = connectionSource; this.tableName = tableName; DatabaseType databaseType = connectionSource.getDatabaseType(); this.field = field; Class<?> clazz = field.getType(); DataPersister dataPersister; if (fieldConfig.getDataPersister() == null) { Class<? extends DataPersister> persisterClass = fieldConfig.getPersisterClass(); if (persisterClass == null || persisterClass == VoidType.class) { dataPersister = DataPersisterManager.lookupForField(field); } else { Method method; try { method = persisterClass.getDeclaredMethod("getSingleton"); } catch (Exception e) { throw SqlExceptionUtil.create("Could not find getSingleton static method on class " + persisterClass, e); } Object result; try { result = method.invoke(null); } catch (InvocationTargetException e) { throw SqlExceptionUtil.create("Could not run getSingleton method on class " + persisterClass, e.getTargetException()); } catch (Exception e) { throw SqlExceptionUtil.create("Could not run getSingleton method on class " + persisterClass, e); } if (result == null) { throw new SQLException("Static getSingleton method should not return null on class " + persisterClass); } try { dataPersister = (DataPersister) result; } catch (Exception e) { throw SqlExceptionUtil.create( "Could not cast result of static getSingleton method to DataPersister from class " + persisterClass, e); } } } else { dataPersister = fieldConfig.getDataPersister(); if (!dataPersister.isValidForField(field)) { throw new IllegalArgumentException("Field class " + clazz + " for field " + this + " is not valid for data persister " + dataPersister); } } String foreignColumnName = fieldConfig.getForeignColumnName(); String defaultFieldName = field.getName(); if (fieldConfig.isForeign() || fieldConfig.isForeignAutoRefresh() || foreignColumnName != null) { if (dataPersister != null && dataPersister.isPrimitive()) { throw new IllegalArgumentException("Field " + this + " is a primitive class " + clazz + " but marked as foreign"); } if (foreignColumnName == null) { defaultFieldName = defaultFieldName + FOREIGN_ID_FIELD_SUFFIX; } else { defaultFieldName = defaultFieldName + "_" + foreignColumnName; } if (ForeignCollection.class.isAssignableFrom(clazz)) { throw new SQLException("Field '" + field.getName() + "' in class " + clazz + "' should use the @" + ForeignCollectionField.class.getSimpleName() + " annotation not foreign=true"); } } else if (fieldConfig.isForeignCollection()) { if (clazz != Collection.class && !ForeignCollection.class.isAssignableFrom(clazz)) { throw new SQLException("Field class for '" + field.getName() + "' must be of class " + ForeignCollection.class.getSimpleName() + " or Collection."); } Type type = field.getGenericType(); if (!(type instanceof ParameterizedType)) { throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection."); } Type[] genericArguments = ((ParameterizedType) type).getActualTypeArguments(); if (genericArguments.length == 0) { // i doubt this will ever be reached throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection with at least 1 type."); } } else if (dataPersister == null && (!fieldConfig.isForeignCollection())) { if (byte[].class.isAssignableFrom(clazz)) { throw new SQLException("ORMLite can't store unknown class " + clazz + " for field '" + field.getName() + "'. byte[] fields must specify dataType=DataType.BYTE_ARRAY or SERIALIZABLE"); } else if (Serializable.class.isAssignableFrom(clazz)) { throw new SQLException("ORMLite can't store unknown class " + clazz + " for field '" + field.getName() + "'. Serializable fields must specify dataType=DataType.SERIALIZABLE"); } else { throw new IllegalArgumentException("ORMLite does not know how to store field class " + clazz + " for field " + this); } } if (fieldConfig.getColumnName() == null) { this.columnName = defaultFieldName; } else { this.columnName = fieldConfig.getColumnName(); } this.fieldConfig = fieldConfig; if (fieldConfig.isId()) { if (fieldConfig.isGeneratedId() || fieldConfig.getGeneratedIdSequence() != null) { throw new IllegalArgumentException("Must specify one of id, generatedId, and generatedIdSequence with " + field.getName()); } this.isId = true; this.isGeneratedId = false; this.generatedIdSequence = null; } else if (fieldConfig.isGeneratedId()) { if (fieldConfig.getGeneratedIdSequence() != null) { throw new IllegalArgumentException("Must specify one of id, generatedId, and generatedIdSequence with " + field.getName()); } this.isId = true; this.isGeneratedId = true; if (databaseType.isIdSequenceNeeded()) { this.generatedIdSequence = databaseType.generateIdSequenceName(tableName, this); } else { this.generatedIdSequence = null; } } else if (fieldConfig.getGeneratedIdSequence() != null) { this.isId = true; this.isGeneratedId = true; String seqName = fieldConfig.getGeneratedIdSequence(); if (databaseType.isEntityNamesMustBeUpCase()) { seqName = seqName.toUpperCase(); } this.generatedIdSequence = seqName; } else { this.isId = false; this.isGeneratedId = false; this.generatedIdSequence = null; } if (this.isId && (fieldConfig.isForeign() || fieldConfig.isForeignAutoRefresh())) { throw new IllegalArgumentException("Id field " + field.getName() + " cannot also be a foreign object"); } if (fieldConfig.isUseGetSet()) { this.fieldGetMethod = DatabaseFieldConfig.findGetMethod(field, true); this.fieldSetMethod = DatabaseFieldConfig.findSetMethod(field, true); } else { if (!field.isAccessible()) { try { this.field.setAccessible(true); } catch (SecurityException e) { throw new IllegalArgumentException("Could not open access to field " + field.getName() + ". You may have to set useGetSet=true to fix."); } } this.fieldGetMethod = null; this.fieldSetMethod = null; } if (fieldConfig.isAllowGeneratedIdInsert() && !fieldConfig.isGeneratedId()) { throw new IllegalArgumentException("Field " + field.getName() + " must be a generated-id if allowGeneratedIdInsert = true"); } if (fieldConfig.isForeignAutoRefresh() && !fieldConfig.isForeign()) { throw new IllegalArgumentException("Field " + field.getName() + " must have foreign = true if foreignAutoRefresh = true"); } if (fieldConfig.isForeignAutoCreate() && !fieldConfig.isForeign()) { throw new IllegalArgumentException("Field " + field.getName() + " must have foreign = true if foreignAutoCreate = true"); } if (fieldConfig.getForeignColumnName() != null && !fieldConfig.isForeign()) { throw new IllegalArgumentException("Field " + field.getName() + " must have foreign = true if foreignColumnName is set"); } if (fieldConfig.isVersion() && (dataPersister == null || !dataPersister.isValidForVersion())) { throw new IllegalArgumentException("Field " + field.getName() + " is not a valid type to be a version field"); } assignDataType(databaseType, dataPersister); } /** * Because we go recursive in a lot of situations if we construct DAOs inside of the FieldType constructor, we have * to do this 2nd pass initialization so we can better use the DAO caches. * * @see BaseDaoImpl#initialize() */ public void configDaoInformation(ConnectionSource connectionSource, Class<?> parentClass) throws SQLException { Class<?> fieldClass = field.getType(); DatabaseType databaseType = connectionSource.getDatabaseType(); TableInfo<?, ?> foreignTableInfo; final FieldType foreignIdField; final Constructor<?> foreignConstructor; final FieldType foreignFieldType; final Dao<?, ?> foreignDao; final MappedQueryForId<Object, Object> mappedQueryForId; String foreignColumnName = fieldConfig.getForeignColumnName(); if (fieldConfig.isForeignAutoRefresh() || foreignColumnName != null) { DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); if (tableConfig == null) { // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, fieldClass); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); } else { tableConfig.extractFieldTypes(connectionSource); // NOTE: the cast is necessary for maven foreignDao = (BaseDaoImpl<?, ?>) DaoManager.createDao(connectionSource, tableConfig); foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); } if (foreignColumnName == null) { foreignIdField = foreignTableInfo.getIdField(); if (foreignIdField == null) { throw new IllegalArgumentException("Foreign field " + fieldClass + " does not have id field"); } } else { foreignIdField = foreignTableInfo.getFieldTypeByColumnName(foreignColumnName); if (foreignIdField == null) { throw new IllegalArgumentException("Foreign field " + fieldClass + " does not have field named '" + foreignColumnName + "'"); } } @SuppressWarnings("unchecked") MappedQueryForId<Object, Object> castMappedQueryForId = (MappedQueryForId<Object, Object>) MappedQueryForId.build(databaseType, foreignTableInfo, foreignIdField); mappedQueryForId = castMappedQueryForId; foreignConstructor = foreignTableInfo.getConstructor(); foreignFieldType = null; } else if (fieldConfig.isForeign()) { if (this.dataPersister != null && this.dataPersister.isPrimitive()) { throw new IllegalArgumentException("Field " + this + " is a primitive class " + fieldClass + " but marked as foreign"); } DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); if (tableConfig != null) { tableConfig.extractFieldTypes(connectionSource); // NOTE: the cast is necessary for maven foreignDao = (Dao<?, ?>) DaoManager.createDao(connectionSource, tableConfig); } else { /* * Initially we were only doing this just for BaseDaoEnabled.class and isForeignAutoCreate(). But we * need it also for foreign fields because the alternative was to use reflection. Chances are if it is * foreign we're going to need the DAO in the future anyway so we might as well create it. This also * allows us to make use of any table configs. */ // NOTE: the cast is necessary for maven foreignDao = (Dao<?, ?>) DaoManager.createDao(connectionSource, fieldClass); } foreignTableInfo = ((BaseDaoImpl<?, ?>) foreignDao).getTableInfo(); foreignIdField = foreignTableInfo.getIdField(); foreignConstructor = foreignTableInfo.getConstructor(); if (foreignIdField == null) { throw new IllegalArgumentException("Foreign field " + fieldClass + " does not have id field"); } if (isForeignAutoCreate() && !foreignIdField.isGeneratedId()) { throw new IllegalArgumentException("Field " + field.getName() + ", if foreignAutoCreate = true then class " + fieldClass.getSimpleName() + " must have id field with generatedId = true"); } foreignFieldType = null; mappedQueryForId = null; } else if (fieldConfig.isForeignCollection()) { if (fieldClass != Collection.class && !ForeignCollection.class.isAssignableFrom(fieldClass)) { throw new SQLException("Field class for '" + field.getName() + "' must be of class " + ForeignCollection.class.getSimpleName() + " or Collection."); } Type type = field.getGenericType(); if (!(type instanceof ParameterizedType)) { throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection."); } Type[] genericArguments = ((ParameterizedType) type).getActualTypeArguments(); if (genericArguments.length == 0) { // i doubt this will ever be reached throw new SQLException("Field class for '" + field.getName() + "' must be a parameterized Collection with at least 1 type."); } Class<?> collectionClazz = (Class<?>) genericArguments[0]; DatabaseTableConfig<?> tableConfig = fieldConfig.getForeignTableConfig(); Dao<Object, Object> foundDao; if (tableConfig == null) { @SuppressWarnings("unchecked") Dao<Object, Object> castDao = (Dao<Object, Object>) DaoManager.createDao(connectionSource, collectionClazz); foundDao = castDao; } else { @SuppressWarnings("unchecked") Dao<Object, Object> castDao = (Dao<Object, Object>) DaoManager.createDao(connectionSource, tableConfig); foundDao = castDao; } foreignDao = foundDao; foreignFieldType = findForeignFieldType(collectionClazz, parentClass, (BaseDaoImpl<?, ?>) foundDao); foreignIdField = null; foreignConstructor = null; mappedQueryForId = null; } else { foreignConstructor = null; foreignIdField = null; foreignFieldType = null; foreignDao = null; mappedQueryForId = null; } this.mappedQueryForId = mappedQueryForId; this.foreignConstructor = foreignConstructor; this.foreignFieldType = foreignFieldType; this.foreignDao = foreignDao; this.foreignIdField = foreignIdField; // we have to do this because if we habe a foreign field then our id type might have gone to an _id primitive if (this.foreignIdField != null) { assignDataType(databaseType, this.foreignIdField.getDataPersister()); } } public Field getField() { return field; } public String getTableName() { return tableName; } public String getFieldName() { return field.getName(); } /** * Return the class of the field associated with this field type. */ public Class<?> getType() { return field.getType(); } public String getColumnName() { return columnName; } public DataPersister getDataPersister() { return dataPersister; } public Object getDataTypeConfigObj() { return dataTypeConfigObj; } public SqlType getSqlType() { return fieldConverter.getSqlType(); } /** * Return the default value as parsed from the {@link DatabaseFieldConfig#getDefaultValue()}. */ public Object getDefaultValue() { return defaultValue; } public int getWidth() { return fieldConfig.getWidth(); } public boolean isCanBeNull() { return fieldConfig.isCanBeNull(); } /** * Return whether the field is an id field. It is an id if {@link DatabaseField#id}, * {@link DatabaseField#generatedId}, OR {@link DatabaseField#generatedIdSequence} are enabled. */ public boolean isId() { return isId; } /** * Return whether the field is a generated-id field. This is true if {@link DatabaseField#generatedId} OR * {@link DatabaseField#generatedIdSequence} are enabled. */ public boolean isGeneratedId() { return isGeneratedId; } /** * Return whether the field is a generated-id-sequence field. This is true if * {@link DatabaseField#generatedIdSequence} is specified OR if {@link DatabaseField#generatedId} is enabled and the * {@link DatabaseType#isIdSequenceNeeded} is enabled. If the latter is true then the sequence name will be * auto-generated. */ public boolean isGeneratedIdSequence() { return generatedIdSequence != null; } /** * Return the generated-id-sequence associated with the field or null if {@link #isGeneratedIdSequence} is false. */ public String getGeneratedIdSequence() { return generatedIdSequence; } public boolean isForeign() { return fieldConfig.isForeign(); } /** * Assign to the data object the val corresponding to the fieldType. */ public void assignField(Object data, Object val, boolean parentObject, ObjectCache objectCache) throws SQLException { // if this is a foreign object then val is the foreign object's id val if (foreignIdField != null && val != null) { // get the current field value which is the foreign-id Object foreignId = extractJavaFieldValue(data); /* * See if we don't need to create a new foreign object. If we are refreshing and the id field has not * changed then there is no need to create a new foreign object and maybe lose previously refreshed field * information. */ if (foreignId != null && foreignId.equals(val)) { return; } if (!parentObject) { Object foreignObject; /* * If we don't have a mappedQueryForId or if we have recursed the proper number of times, just return a * shell with the id set. */ LevelCounters levelCounters = threadLevelCounters.get(); if (mappedQueryForId == null || levelCounters.autoRefreshlevel >= fieldConfig.getMaxForeignAutoRefreshLevel()) { // create a shell and assign its id field foreignObject = TableInfo.createObject(foreignConstructor, foreignDao); foreignIdField.assignField(foreignObject, val, false, objectCache); } else { levelCounters.autoRefreshlevel++; try { DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(); try { foreignObject = mappedQueryForId.execute(databaseConnection, val, objectCache); } finally { connectionSource.releaseConnection(databaseConnection); } } finally { levelCounters.autoRefreshlevel } } // the value we are to assign to our field is now the foreign object itself val = foreignObject; } } if (fieldSetMethod == null) { try { field.set(data, val); } catch (IllegalArgumentException e) { throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e); } catch (IllegalAccessException e) { throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e); } } else { try { fieldSetMethod.invoke(data, val); } catch (Exception e) { throw SqlExceptionUtil.create("Could not call " + fieldSetMethod + " on object with '" + val + "' for " + this, e); } } } /** * Assign an ID value to this field. */ public Object assignIdValue(Object data, Number val, ObjectCache objectCache) throws SQLException { Object idVal = dataPersister.convertIdNumber(val); if (idVal == null) { throw new SQLException("Invalid class " + dataPersister + " for sequence-id " + this); } else { assignField(data, idVal, false, objectCache); return idVal; } } /** * Return the value from the field in the object that is defined by this FieldType. */ public <FV> FV extractRawJavaFieldValue(Object object) throws SQLException { Object val; if (fieldGetMethod == null) { try { // field object may not be a T yet val = field.get(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not get field value for " + this, e); } } else { try { val = fieldGetMethod.invoke(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not call " + fieldGetMethod + " for " + this, e); } } @SuppressWarnings("unchecked") FV converted = (FV) val; return converted; } /** * Return the value from the field in the object that is defined by this FieldType. If the field is a foreign object * then the ID of the field is returned instead. */ public Object extractJavaFieldValue(Object object) throws SQLException { Object val = extractRawJavaFieldValue(object); // if this is a foreign object then we want its id field if (foreignIdField != null && val != null) { val = foreignIdField.extractRawJavaFieldValue(val); } return val; } /** * Extract a field from an object and convert to something suitable to be passed to SQL as an argument. */ public Object extractJavaFieldToSqlArgValue(Object object) throws SQLException { return convertJavaFieldToSqlArgValue(extractJavaFieldValue(object)); } /** * Convert a field value to something suitable to be stored in the database. */ public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException { if (fieldVal == null) { return null; } else { return fieldConverter.javaToSqlArg(this, fieldVal); } } /** * Move the SQL value to the next one for version processing. */ public Object moveToNextValue(Object val) { if (dataPersister == null) { return null; } else { return dataPersister.moveToNextValue(val); } } /** * Return the id field associated with the foreign object or null if none. */ public FieldType getForeignIdField() { return foreignIdField; } /** * Call through to {@link DataPersister#isEscapedValue()} */ public boolean isEscapedValue() { return dataPersister.isEscapedValue(); } public Enum<?> getUnknownEnumVal() { return fieldConfig.getUnknownEnumValue(); } /** * Return the format of the field. */ public String getFormat() { return fieldConfig.getFormat(); } public boolean isUnique() { return fieldConfig.isUnique(); } public boolean isUniqueCombo() { return fieldConfig.isUniqueCombo(); } public String getIndexName() { return fieldConfig.getIndexName(tableName); } public String getUniqueIndexName() { return fieldConfig.getUniqueIndexName(tableName); } /** * Call through to {@link DataPersister#isEscapedDefaultValue()} */ public boolean isEscapedDefaultValue() { return dataPersister.isEscapedDefaultValue(); } /** * Call through to {@link DataPersister#isComparable()} */ public boolean isComparable() throws SQLException { if (fieldConfig.isForeignCollection()) { return false; } /* * We've seen dataPersister being null here in some strange cases. Why? It may because someone is searching on * an improper field. Or maybe a table-config does not match the Java object? */ if (dataPersister == null) { throw new SQLException("Internal error. Data persister has not been configured for field. " + "Please post the _full_ exception with associated objects to mailing list: " + this); } else { return dataPersister.isComparable(); } } /** * Call through to {@link DataPersister#isArgumentHolderRequired()} */ public boolean isArgumentHolderRequired() { return dataPersister.isArgumentHolderRequired(); } /** * Call through to {@link DatabaseFieldConfig#isForeignCollection()} */ public boolean isForeignCollection() { return fieldConfig.isForeignCollection(); } /** * Build and return a foreign collection based on the field settings that matches the id argument. This can return * null in certain circumstances. * * @param parent * The parent object that we will set on each item in the collection. * @param id * The id of the foreign object we will look for. This can be null if we are creating an empty * collection. * @param forceEager * Set to true to force this to be an eager collection. */ public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(FT parent, FID id, boolean forceEager) throws SQLException { // this can happen if we have a foreign-auto-refresh scenario if (foreignFieldType == null) { return null; } @SuppressWarnings("unchecked") Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao; if (!fieldConfig.isForeignCollectionEager() && !forceEager) { // we know this won't go recursive so no need for the counters return new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType.columnName, fieldConfig.getForeignCollectionOrderColumn()); } LevelCounters levelCounters = threadLevelCounters.get(); // are we over our level limit? if (levelCounters.foreignCollectionLevel >= fieldConfig.getMaxEagerForeignCollectionLevel()) { // then return a lazy collection instead return new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType.columnName, fieldConfig.getForeignCollectionOrderColumn()); } levelCounters.foreignCollectionLevel++; try { return new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType.columnName, fieldConfig.getForeignCollectionOrderColumn()); } finally { levelCounters.foreignCollectionLevel } } /** * Get the result object from the results. A call through to {@link FieldConverter#resultToJava}. */ public <T> T resultToJava(DatabaseResults results, Map<String, Integer> columnPositions) throws SQLException { Integer dbColumnPos = columnPositions.get(columnName); if (dbColumnPos == null) { dbColumnPos = results.findColumn(columnName); columnPositions.put(columnName, dbColumnPos); } @SuppressWarnings("unchecked") T converted = (T) fieldConverter.resultToJava(this, results, dbColumnPos); if (fieldConfig.isForeign()) { /* * Subtle problem here. If your foreign field is a primitive and the value was null then this would return 0 * from getInt(). We have to specifically test to see if we have a foreign field so if it is null we return * a null value to not create the sub-object. */ if (results.wasNull(dbColumnPos)) { return null; } } else if (dataPersister.isPrimitive()) { if (fieldConfig.isThrowIfNull() && results.wasNull(dbColumnPos)) { throw new SQLException("Results value for primitive field '" + field.getName() + "' was an invalid null value"); } } else if (!fieldConverter.isStreamType() && results.wasNull(dbColumnPos)) { // we can't check if we have a null if this is a stream type return null; } return converted; } /** * Call through to {@link DataPersister#isSelfGeneratedId()} */ public boolean isSelfGeneratedId() { return dataPersister.isSelfGeneratedId(); } /** * Call through to {@link DatabaseFieldConfig#isAllowGeneratedIdInsert()} */ public boolean isAllowGeneratedIdInsert() { return fieldConfig.isAllowGeneratedIdInsert(); } /** * Call through to {@link DatabaseFieldConfig#getColumnDefinition()} */ public String getColumnDefinition() { return fieldConfig.getColumnDefinition(); } /** * Call through to {@link DatabaseFieldConfig#isForeignAutoCreate()} */ public boolean isForeignAutoCreate() { return fieldConfig.isForeignAutoCreate(); } /** * Call through to {@link DatabaseFieldConfig#isVersion()} */ public boolean isVersion() { return fieldConfig.isVersion(); } /** * Call through to {@link DataPersister#generateId()} */ public Object generateId() { return dataPersister.generateId(); } /** * Return the value of field in the data argument if it is not the default value for the class. If it is the default * then null is returned. */ public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException { @SuppressWarnings("unchecked") FV fieldValue = (FV) extractJavaFieldValue(object); if (isFieldValueDefault(fieldValue)) { return null; } else { return fieldValue; } } /** * Return whether or not the data object has a default value passed for this field of this type. */ public boolean isObjectsFieldValueDefault(Object object) throws SQLException { Object fieldValue = extractJavaFieldValue(object); return isFieldValueDefault(fieldValue); } /** * Return whether or not the field value passed in is the default value for the type of the field. Null will return * true. */ public Object getJavaDefaultValueDefault() { if (field.getType() == boolean.class) { return DEFAULT_VALUE_BOOLEAN; } else if (field.getType() == byte.class || field.getType() == Byte.class) { return DEFAULT_VALUE_BYTE; } else if (field.getType() == char.class || field.getType() == Character.class) { return DEFAULT_VALUE_CHAR; } else if (field.getType() == short.class || field.getType() == Short.class) { return DEFAULT_VALUE_SHORT; } else if (field.getType() == int.class || field.getType() == Integer.class) { return DEFAULT_VALUE_INT; } else if (field.getType() == long.class || field.getType() == Long.class) { return DEFAULT_VALUE_LONG; } else if (field.getType() == float.class || field.getType() == Float.class) { return DEFAULT_VALUE_FLOAT; } else if (field.getType() == double.class || field.getType() == Double.class) { return DEFAULT_VALUE_DOUBLE; } else { return null; } } /** * Pass the foreign data argument to the foreign {@link Dao#create(Object)} method. */ public <T> int createWithForeignDao(T foreignData) throws SQLException { @SuppressWarnings("unchecked") Dao<T, ?> castDao = (Dao<T, ?>) foreignDao; return castDao.create(foreignData); } /** * Return An instantiated {@link FieldType} or null if the field does not have a {@link DatabaseField} annotation. */ public static FieldType createFieldType(ConnectionSource connectionSource, String tableName, Field field, Class<?> parentClass) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); DatabaseFieldConfig fieldConfig = DatabaseFieldConfig.fromField(databaseType, tableName, field); if (fieldConfig == null) { return null; } else { return new FieldType(connectionSource, tableName, field, fieldConfig, parentClass); } } @Override public boolean equals(Object arg) { if (arg == null || arg.getClass() != this.getClass()) { return false; } FieldType other = (FieldType) arg; return field.equals(other.field); } @Override public int hashCode() { return field.hashCode(); } @Override public String toString() { return getClass().getSimpleName() + ":name=" + field.getName() + ",class=" + field.getDeclaringClass().getSimpleName(); } /** * Return whether or not the field value passed in is the default value for the type of the field. Null will return * true. */ private boolean isFieldValueDefault(Object fieldValue) { if (fieldValue == null) { return true; } else { return fieldValue.equals(getJavaDefaultValueDefault()); } } /** * If we have a class Foo with a collection of Bar's then we go through Bar's DAO looking for a Foo field. We need * this field to build the query that is able to find all Bar's that have foo_id that matches our id. */ private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, BaseDaoImpl<?, ?> foreignDao) throws SQLException { String foreignColumnName = fieldConfig.getForeignCollectionColumnName(); for (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) { if (fieldType.getType() == foreignClass && (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) { if (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) { // this may never be reached throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' contains a field of class " + foreignClass + " but it's not foreign"); } return fieldType; } } // build our complex error message StringBuilder sb = new StringBuilder(); sb.append("Foreign collection class ").append(clazz.getName()); sb.append(" for field '").append(field.getName()).append("' column-name does not contain a foreign field"); if (foreignColumnName != null) { sb.append(" named '").append(foreignColumnName).append('\''); } sb.append(" of class ").append(foreignClass.getName()); throw new SQLException(sb.toString()); } /** * Configure our data persister and any dependent fields. We have to do this here because both the constructor and * {@link #configDaoInformation} method can set the data-type. */ private void assignDataType(DatabaseType databaseType, DataPersister dataPersister) throws SQLException { this.dataPersister = dataPersister; if (dataPersister == null) { if (!fieldConfig.isForeign() && !fieldConfig.isForeignCollection()) { // may never happen but let's be careful out there throw new SQLException("Data persister for field " + this + " is null but the field is not a foreign or foreignCollection"); } return; } this.fieldConverter = databaseType.getFieldConverter(dataPersister); if (this.isGeneratedId && !dataPersister.isValidGeneratedType()) { StringBuilder sb = new StringBuilder(); sb.append("Generated-id field '").append(field.getName()); sb.append("' in ").append(field.getDeclaringClass().getSimpleName()); sb.append(" can't be type ").append(this.dataPersister.getSqlType()); sb.append(". Must be one of: "); for (DataType dataType : DataType.values()) { DataPersister persister = dataType.getDataPersister(); if (persister != null && persister.isValidGeneratedType()) { sb.append(dataType).append(' '); } } throw new IllegalArgumentException(sb.toString()); } if (fieldConfig.isThrowIfNull() && !dataPersister.isPrimitive()) { throw new SQLException("Field " + field.getName() + " must be a primitive if set with throwIfNull"); } if (this.isId && !dataPersister.isAppropriateId()) { throw new SQLException("Field '" + field.getName() + "' is of data type " + dataPersister + " which cannot be the ID field"); } this.dataTypeConfigObj = dataPersister.makeConfigObject(this); String defaultStr = fieldConfig.getDefaultValue(); if (defaultStr == null || defaultStr.equals("")) { this.defaultValue = null; } else if (this.isGeneratedId) { throw new SQLException("Field '" + field.getName() + "' cannot be a generatedId and have a default value '" + defaultStr + "'"); } else { this.defaultValue = this.fieldConverter.parseDefaultString(this, defaultStr); } } private static class LevelCounters { int autoRefreshlevel; int foreignCollectionLevel; } }
package pl.magosa.microbe; import java.util.ArrayList; import java.util.function.Consumer; public class FeedForwardNetwork extends Network { protected ArrayList<FeedForwardLayer> layers; public FeedForwardNetwork() { layers = new ArrayList<>(); } public FeedForwardLayer createLayer(Consumer<FeedForwardLayer> initFunction) { FeedForwardLayer layer = new FeedForwardLayer(); if (!layers.isEmpty()) { layer.setPreviousLayer(getLastLayer()); } initFunction.accept(layer); // It must be below initFunction, because while creating layer, last layer is needed. layers.add(layer); return layer; } /** * Helper method for easy creation of input layer. * @param inputNeurons */ public void createInputLayer(final int inputNeurons) { createLayer((FeedForwardLayer layer) -> { layer.createNeurons(inputNeurons, (Neuron neuron) -> { neuron.setTransferFunction(new LinearTransferFunction()); neuron.setThreshold(0); neuron.createInput((Input input) -> { input.setWeight(1); }); }); }); } /** * Sets input values of network * @param values */ public void setValues(final double[] values) { if (values.length != layers.get(0).getNeurons().size()) { throw new RuntimeException("Incorrect number of input values."); } ArrayList<Neuron> neurons = layers.get(0).getNeurons(); for (int index = 0; index < values.length; index++) { neurons.get(index).getInputs().get(0).setValue(values[index]); } } /** * Activate neurons on each layer */ public void run() { for (FeedForwardLayer layer : layers) { layer.run(); if (layer.hasNextLayer()) { layer.forward(); } } } /** * Returns array of outputs from last layer * @return */ public double[] getOutput() { FeedForwardLayer layer = getLastLayer(); ArrayList<Neuron> neurons = layer.getNeurons(); double[] output = new double[neurons.size()]; for (int i = 0; i < neurons.size(); i++) { output[i] = neurons.get(i).getOutput(); } return output; } public FeedForwardLayer getLastLayer() { return layers.get(layers.size() - 1); } public ArrayList<FeedForwardLayer> getLayers() { return layers; } }
package com.jcabi.github.mock; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.github.Commit; import com.jcabi.github.Status; import com.jcabi.github.Statuses; import java.io.IOException; import javax.json.JsonObject; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; /** * Mock of GitHub commit statuses. * @author Chris Rebert (github@rebertia.com) * @version $Id$ * @since 0.24 * @todo #1129:30min Finish implementing this class (MkStatuses), a mock of * GitHub's commits statuses (the "Statuses" interface). */ @Immutable @Loggable(Loggable.DEBUG) @EqualsAndHashCode(of = { "cmmt" }) final class MkStatuses implements Statuses { /** * Commit whose statuses this represents. */ private final transient Commit cmmt; /** * Ctor. * @param cmt Commit whose statuses this represents */ MkStatuses( @NotNull(message = "commit can't be NULL") final Commit cmt ) { this.cmmt = cmt; } @Override @NotNull(message = "commit is never NULL") public Commit commit() { return this.cmmt; } @Override public Status create( @NotNull(message = "status creation data can't be NULL") final StatusCreate status ) throws IOException { throw new UnsupportedOperationException("Not yet implemented"); } @Override @NotNull(message = "iterable of statuses is never NULL") public Iterable<Status> list( @NotNull(message = "ref can't be NULL") final String ref ) { throw new UnsupportedOperationException("Not implemented yet"); } @Override @NotNull(message = "JSON is never NULL") public JsonObject json() { throw new UnsupportedOperationException("Yet to be implemented"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-06-24"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package com.timgroup.statsd; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * A simple StatsD client implementation facilitating metrics recording. * * <p>Upon instantiation, this client will establish a socket connection to a StatsD instance * running on the specified host and port. Metrics are then sent over this connection as they are * received by the client. * </p> * * <p>Three key methods are provided for the submission of data-points for the application under * scrutiny: * <ul> * <li>{@link #incrementCounter} - adds one to the value of the specified named counter</li> * <li>{@link #recordGaugeValue} - records the latest fixed value for the specified named gauge</li> * <li>{@link #recordExecutionTime} - records an execution time in milliseconds for the specified named operation</li> * </ul> * From the perspective of the application, these methods are non-blocking, with the resulting * IO operations being carried out in a separate thread. Furthermore, these methods are guaranteed * not to throw an exception which may disrupt application execution. * </p> * * <p>As part of a clean system shutdown, the {@link #stop()} method should be invoked * on any StatsD clients.</p> * * @author Tom Denley * */ public final class StatsDClient { private final String prefix; private final DatagramSocket clientSocket; private final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() { final ThreadFactory delegate = Executors.defaultThreadFactory(); @Override public Thread newThread(Runnable r) { Thread result = delegate.newThread(r); result.setName("StatsD-" + result.getName()); return result; } }); /** * Create a new StatsD client communicating with a StatsD instance on the * specified host and port. All messages send via this client will have * their keys prefixed with the specified string. The new client will * attempt to open a connection to the StatsD server immediately upon * instantiation, and may throw an exception if that a connection cannot * be established. * * @param prefix * the prefix to apply to keys sent via this client * @param hostname * the host name of the targeted StatsD server * @param port * the port of the targeted StatsD server */ public StatsDClient(String prefix, String hostname, int port) { this.prefix = prefix; try { this.clientSocket = new DatagramSocket(); this.clientSocket.connect(new InetSocketAddress(hostname, port)); } catch (SocketException e) { throw new IllegalStateException(e); } } /** * Cleanly shut down this StatsD client. This method may throw an exception if * the socket cannot be closed. */ public void stop() { try { executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); } catch (Exception e) { throw new IllegalStateException(e); } finally { if (clientSocket != null) { clientSocket.close(); } } } /** * Increments the specified counter by one. * * <p>This method is non-blocking and is guaranteed not to throw an exception.</p> * * @param aspect * the name of the counter to increment */ public void incrementCounter(String aspect) { send(String.format("%s.%s:%d|c", prefix, aspect, 1)); } /** * Records the latest fixed value for the specified named gauge. * * <p>This method is non-blocking and is guaranteed not to throw an exception.</p> * * @param aspect * the name of the gauge * @param value * the new reading of the gauge */ public void recordGaugeValue(String aspect, int value) { send(String.format("%s.%s:%d|g", prefix, aspect, value)); } /** * Records an execution time in milliseconds for the specified named operation. * * <p>This method is non-blocking and is guaranteed not to throw an exception.</p> * * @param aspect * the name of the timed operation * @param timeInMs * the time in milliseconds */ public void recordExecutionTime(String aspect, int timeInMs) { send(String.format("%s.%s:%d|ms", prefix, aspect, timeInMs)); } private void send(final String message) { try { executor.execute(new Runnable() { @Override public void run() { blockingSend(message); } }); } catch (Exception e) { // we cannot allow exceptions to interfere with our caller's execution } } private void blockingSend(String message) { try { final byte[] sendData = message.getBytes(); final DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length); clientSocket.send(sendPacket); } catch (Exception e) { } } }
package com.vzome.core.editor; import java.util.Iterator; import org.w3c.dom.Element; import com.vzome.core.commands.XmlSaveFormat; import com.vzome.core.commands.Command.Failure; import com.vzome.core.construction.Point; import com.vzome.core.construction.Segment; import com.vzome.core.construction.SegmentJoiningPoints; import com.vzome.core.model.Connector; import com.vzome.core.model.Manifestation; import com.vzome.core.model.RealizedModel; public class JoinPoints extends ChangeConstructions { public JoinPoints( Selection selection, RealizedModel realized, boolean groupInSelection, boolean closedLoop ) { super( selection, realized, groupInSelection ); this .closedLoop = closedLoop; } protected void getXmlAttributes( Element element ) { if ( ! closedLoop ) element .setAttribute( "closedLoop", "false" ); } protected void setXmlAttributes( Element xml, XmlSaveFormat format ) throws Failure { String attr = xml .getAttribute( "closedLoop" ); if ( attr != null && ! attr.isEmpty() ) closedLoop = Boolean .valueOf( attr ) .booleanValue(); } public void perform() throws Failure { Point firstPoint = null, lastPoint = null; for ( Iterator mans = mSelection .iterator(); mans .hasNext(); ) { Manifestation man = (Manifestation) mans .next(); unselect( man ); if ( man instanceof Connector ) { Point nextPoint = (Point) ((Connector) man) .getConstructions() .next(); if ( lastPoint != null ) { Segment segment = new SegmentJoiningPoints( lastPoint, nextPoint ); addConstruction( segment ); select( manifestConstruction( segment ) ); } else firstPoint = nextPoint; lastPoint = nextPoint; } } if ( closedLoop && lastPoint != null && firstPoint != null && lastPoint != firstPoint ) { Segment segment = new SegmentJoiningPoints( lastPoint, firstPoint ); addConstruction( segment ); select( manifestConstruction( segment ) ); } redo(); } private boolean closedLoop = true; protected String getXmlElementName() { return "JoinPoints"; } }
package com.yahoo.sketches.fdt; import static com.yahoo.sketches.Util.MAX_LG_NOM_LONGS; import java.util.List; import com.yahoo.memory.Memory; import com.yahoo.sketches.BinomialBoundsN; import com.yahoo.sketches.SketchesArgumentException; import com.yahoo.sketches.tuple.strings.ArrayOfStringsSketch; public class FdtSketch extends ArrayOfStringsSketch { /** * Create new instance of Frequent Distinct Tuples sketch with the given * Log-base2 of required nominal entries. * @param lgK Log-base2 of required nominal entries. */ public FdtSketch(final int lgK) { super(lgK); } /** * Used by deserialization. * @param mem the image of a FdtSketch */ FdtSketch(final Memory mem) { super(mem); } /** * Create a new instance of Frequent Distinct Tuples sketch with a size determined by the given * threshold and rse. * @param threshold : the fraction, between zero and 1.0, of the total distinct stream length * that defines a "Frequent" (or heavy) item. * @param rse the maximum Relative Standard Error for the estimate of the distinct population of a * reported tuple (selected with a primary key) at the threshold. */ public FdtSketch(final double threshold, final double rse) { super(computeLgK(threshold, rse)); } /** * Update the sketch with the given string array tuple. * @param tuple the given string array tuple. */ public void update(final String[] tuple) { super.update(tuple, tuple); } /** * Returns an ordered List of Groups of the most frequent distinct population of subset tuples * represented by the count of entries of each group. * @param priKeyIndices these indices define the dimensions used for the Primary Keys. * @param limit the maximum number of groups to return. If this value is &le; 0, all * groups will be returned. * @param numStdDev the number of standard deviations for the upper and lower error bounds, * this value is an integer and must be one of 1, 2, or 3. * <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a> * @param sep the separator character * @return an ordered List of Groups of the most frequent distinct population of subset tuples * represented by the count of entries of each group. */ public List<Group> getResult(final int[] priKeyIndices, final int limit, final int numStdDev, final char sep) { final PostProcessor proc = new PostProcessor(this, new Group(), sep); return proc.getGroupList(priKeyIndices, numStdDev, limit); } /** * Returns the PostProcessor that enables multiple queries against the sketch results. * This assumes the default Group and the default separator character '|'. * @return the PostProcessor */ public PostProcessor getPostProcessor() { return getPostProcessor(new Group(), '|'); } /** * Returns the PostProcessor that enables multiple queries against the sketch results. * @param group the Group class to use during post processing. * @param sep the separator character. * @return the PostProcessor */ public PostProcessor getPostProcessor(final Group group, final char sep) { return new PostProcessor(this, group, sep); } /** * Gets the estimate of the true distinct population of subset tuples represented by the count * of entries in a group. This is primarily used internally. * @param numSubsetEntries number of entries for a chosen subset of the sketch. * @return the estimate of the true distinct population of subset tuples represented by the count * of entries in a group. */ public double getEstimate(final int numSubsetEntries) { if (!isEstimationMode()) { return numSubsetEntries; } return numSubsetEntries / getTheta(); } /** * Gets the estimate of the lower bound of the true distinct population represented by the count * of entries in a group. * @param numStdDev * <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a> * @param numSubsetEntries number of entries for a chosen subset of the sketch. * @return the estimate of the lower bound of the true distinct population represented by the count * of entries in a group. */ public double getLowerBound(final int numStdDev, final int numSubsetEntries) { if (!isEstimationMode()) { return numSubsetEntries; } return BinomialBoundsN.getLowerBound(numSubsetEntries, getTheta(), numStdDev, isEmpty()); } /** * Gets the estimate of the upper bound of the true distinct population represented by the count * of entries in a group. * @param numStdDev * <a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a> * @param numSubsetEntries number of entries for a chosen subset of the sketch. * @return the estimate of the upper bound of the true distinct population represented by the count * of entries in a group. */ public double getUpperBound(final int numStdDev, final int numSubsetEntries) { if (!isEstimationMode()) { return numSubsetEntries; } return BinomialBoundsN.getUpperBound(numSubsetEntries, getTheta(), numStdDev, isEmpty()); } // Restricted /** * Computes LgK given the threshold and RSE. * @param threshold the fraction, between zero and 1.0, of the total stream length that defines * a "Frequent" (or heavy) tuple. * @param rse the maximum Relative Standard Error for the estimate of the distinct population of a * reported tuple (selected with a primary key) at the threshold. * @return LgK */ static int computeLgK(final double threshold, final double rse) { final double v = Math.ceil(1.0 / (threshold * rse * rse)); final int lgK = (int) Math.ceil(Math.log(v) / Math.log(2)); if (lgK > MAX_LG_NOM_LONGS) { throw new SketchesArgumentException("Requested Sketch (LgK = " + lgK + " &gt; 2^26), " + "either increase the threshold, the rse or both."); } return lgK; } }
package com.yahoo.sketches.fun; import static com.yahoo.sketches.Util.MAX_LG_NOM_LONGS; import static com.yahoo.sketches.Util.ceilingPowerOf2; import static com.yahoo.sketches.Util.simpleIntLog2; import com.yahoo.sketches.SketchesArgumentException; import com.yahoo.sketches.tuple.SketchIterator; import com.yahoo.sketches.tuple.UpdatableSketch; import com.yahoo.sketches.tuple.UpdatableSketchBuilder; import com.yahoo.sketches.tuple.strings.ArrayOfStringsSummary; import com.yahoo.sketches.tuple.strings.ArrayOfStringsSummaryFactory; /** * A Frequent Unique Nodes sketch. * @author Lee Rhodes */ public class FunSketch { private final int lgK; private final UpdatableSketchBuilder<String[], ArrayOfStringsSummary> bldr = new UpdatableSketchBuilder<>(new ArrayOfStringsSummaryFactory()); private final UpdatableSketch<String[], ArrayOfStringsSummary> sketch; /** * Create new instance of Frequent Unique Nodes Sketch with the given * Log-base2 of required nominal entries. * @param lgK Log-base2 of required nominal entries. */ public FunSketch(final int lgK) { this.lgK = lgK; bldr.reset(); bldr.setNominalEntries(1 << this.lgK); sketch = bldr.build(); } /** * Create a new instance of Frequent Unique Nodes Sketch with the given * threshold and rse. * @param threshold the fraction, between zero and 1.0, of the total stream length that defines * a "Frequent" (or heavy) item. * @param rse the desired Relative Standard Error for the sketch. */ public FunSketch(final double threshold, final double rse) { lgK = computeLgK(threshold, rse); bldr.reset(); bldr.setNominalEntries(1 << lgK); sketch = bldr.build(); } /** * Update the sketch with the given nodes array. * @param nodesArr the given array of node names. */ public void update(final String[] nodesArr) { final int[] key = computeKey(nodesArr); sketch.update(key, nodesArr); } /** * Returns the sketch iterator. * @return the iterator over the sketch contents */ public SketchIterator<ArrayOfStringsSummary> getIterator() { return sketch.iterator(); } /** * Computes LgK given the threshold and RSE. * @param threshold the fraction, between zero and 1.0, of the total stream length that defines * a "Frequent" (or heavy) item. * @param rse the desired Relative Standard Error for a computed estimate at the threshold. * @return LgK */ static int computeLgK(final double threshold, final double rse) { final int k = ceilingPowerOf2((int) Math.ceil(1.0 / (threshold * rse * rse))); if (k > (1 << MAX_LG_NOM_LONGS)) { throw new SketchesArgumentException("Requested Sketch is too large, " + "either increase the threshold or the rse or both."); } return simpleIntLog2(k); } /** * @param nodesArr array of node Strings * @return int array of node hashCodes. */ static int[] computeKey(final String[] nodesArr) { final int len = nodesArr.length; final int[] arr = new int[len]; for (int i = 0; i < len; i++) { arr[i] = nodesArr.hashCode(); } return arr; } }
package de.chrgroth.jsonstore; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.chrgroth.jsonstore.json.AbstractFlexjsonTypeHandler; import de.chrgroth.jsonstore.json.FlexjsonHelper; import de.chrgroth.jsonstore.json.FlexjsonHelper.FlexjsonHelperBuilder; import de.chrgroth.jsonstore.store.JsonSingletonStore; import de.chrgroth.jsonstore.store.JsonStore; import de.chrgroth.jsonstore.store.VersionMigrationHandler; import de.chrgroth.jsonstore.store.exception.JsonStoreException; /** * Central API class to create JSON stores. Stores are maintained per class using {@link #resolve(Class)}, * {@link #ensure(Class, Integer, VersionMigrationHandler...)} and {@link #drop(Class)} and similar methods for singleton stores. Each JSON store will create a * separate file. The {@link #save()} method acts as shortcut to save all stores. If an instance is created with auto save mode enabled (see {@link #builder()}) * then {@link #ensure(Class, Integer, VersionMigrationHandler...)} and {@link #ensureSingleton(Class, Integer, VersionMigrationHandler...)} will automatically * load possibly existing data from configured storage path. * * @author Christian Groth */ public class JsonStores { private static final Logger LOG = LoggerFactory.getLogger(JsonStores.class); private final FlexjsonHelper flexjsonHelper; private final Map<Class<?>, JsonStore<?>> stores; private final Map<Class<?>, JsonSingletonStore<?>> singletonStores; private final File storage; private final Charset charset; private final boolean prettyPrint; private final boolean autoSave; /** * Builder class to control creation of {@link JsonStores}. * * @author Christian Groth */ public static class JsonStoresBuilder { private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private File storage; private Charset charset; private boolean prettyPrint; private boolean autoSave; private FlexjsonHelperBuilder flexjsonHelperBuilder; public JsonStoresBuilder() { flexjsonHelperBuilder = FlexjsonHelper.builder(); } /** * {@link FlexjsonHelperBuilder#dateTimePattern(String)} * * @param dateTimePattern * date time pattern to be used. * @return builder */ public JsonStoresBuilder dateTimePattern(String dateTimePattern) { flexjsonHelperBuilder.dateTimePattern(dateTimePattern); return this; } /** * {@link FlexjsonHelperBuilder#handler(Class, AbstractFlexjsonTypeHandler)} * * @param type * type the handler applies on * @param handler * handler to be applied * @return builder */ public JsonStoresBuilder factory(Class<?> type, AbstractFlexjsonTypeHandler handler) { flexjsonHelperBuilder.handler(type, handler); return this; } /** * {@link FlexjsonHelperBuilder#handler(String, AbstractFlexjsonTypeHandler)} * * @param path * path the handler applies on * @param handler * handler to be applied * @return builder */ public JsonStoresBuilder factory(String path, AbstractFlexjsonTypeHandler handler) { flexjsonHelperBuilder.handler(path, handler); return this; } /** * Configures persistent JSON storage with given base directory, default UTF-8 charset, pretty-print mode disabled and auto-save mode enabled. * * @param storage * base storage directory * @return builder */ public JsonStoresBuilder storage(File storage) { this.storage = storage; charset = DEFAULT_CHARSET; prettyPrint = false; autoSave = true; return this; } /** * Configures persistent JSON storage with given base directory, charset, pretty-print mode and auto-save mode. * * @param storage * base storage directory * @param charset * storage charset * @param prettyPrint * pretty-print mode * @param autoSave * auto-save mode * @return builder */ public JsonStoresBuilder storage(File storage, Charset charset, boolean prettyPrint, boolean autoSave) { this.storage = storage; this.charset = charset; this.prettyPrint = prettyPrint; this.autoSave = autoSave; return this; } /** * Creates the {@link JsonStores} instance. * * @return stores instance */ public JsonStores build() { return new JsonStores(flexjsonHelperBuilder.build(), storage, charset, prettyPrint, autoSave); } } /** * Creates a new builder instance. * * @return stores builder */ public static JsonStoresBuilder builder() { return new JsonStoresBuilder(); } private JsonStores(FlexjsonHelper flexjsonHelper, File storage, Charset charset, boolean prettyPrint, boolean autoSave) { // init state this.flexjsonHelper = flexjsonHelper; stores = new HashMap<>(); singletonStores = new HashMap<>(); this.storage = storage == null ? null : storage.getAbsoluteFile(); this.charset = charset; this.prettyPrint = prettyPrint; this.autoSave = autoSave; // prepare storage if (isPersistent()) { // check if exists if (!Files.exists(storage.toPath())) { try { LOG.info("creating storage path " + storage.getAbsolutePath()); Files.createDirectories(storage.toPath()); } catch (IOException e) { LOG.error("Unable to initialize storage path: " + storage.getAbsolutePath() + "!!", e); } } } } /** * Ensures existence of JSON store for given class. If auto save mode is enabled store will automatically load possibly existing data from configured * storage path. If any error occurs during load of eisting data a {@link JsonStoreException} will be thrown cause otherwise data loss may occur on next * successful save. * * @param payloadClass * class for JSON store * @param payloadClassVersion * version of payload class, next version is always supposed to be increased by one * @param versionMigrationHandlers * all migration handlers * @return existing or created JSON store * @param <T> * concrete type of data * @see VersionMigrationHandler */ public <T> JsonStore<T> ensure(Class<T> payloadClass, Integer payloadClassVersion, VersionMigrationHandler... versionMigrationHandlers) { // ensure store if (!stores.containsKey(payloadClass)) { create(payloadClass, payloadClassVersion, versionMigrationHandlers); } // load data JsonStore<T> store = resolve(payloadClass); if (isPersistent() && autoSave) { try { store.load(); } catch (Exception e) { throw new JsonStoreException("Unable to delegate data load for " + payloadClass + ": " + store.getFile().getAbsolutePath() + "!!", e); } } // done return store; } private void create(Class<?> payloadClass, Integer payloadClassVersion, VersionMigrationHandler... versionMigrationHandlers) { stores.put(payloadClass, new JsonStore<>(payloadClass, payloadClassVersion, flexjsonHelper, storage, charset, prettyPrint, autoSave, versionMigrationHandlers)); } /** * Resolves JSON store for given class. * * @param dataClass * class for JSON store * @return existing JSON store, may be null * @param <T> * concrete type of data */ @SuppressWarnings("unchecked") public <T> JsonStore<T> resolve(Class<T> dataClass) { return (JsonStore<T>) stores.get(dataClass); } /** * Ensures existence of JSON singleton store for given class. If auto save mode is enabled store will automatically load possibly existing data from * configured storage path. If any error occurs during load of eisting data a {@link JsonStoreException} will be thrown cause otherwise data loss may occur * on next successful save. * * @param payloadClass * class for JSON store * @param payloadClassVersion * version of payload class, next version is always supposed to be increased by one * @param versionMigrationHandlers * all migration handlers * @return existing or created JSON singleton store * @param <T> * concrete type of data * @see VersionMigrationHandler */ public <T> JsonSingletonStore<T> ensureSingleton(Class<T> payloadClass, Integer payloadClassVersion, VersionMigrationHandler... versionMigrationHandlers) { // ensure store if (!singletonStores.containsKey(payloadClass)) { createSingleton(payloadClass, payloadClassVersion, versionMigrationHandlers); } // load data JsonSingletonStore<T> store = resolveSingleton(payloadClass); if (isPersistent() && autoSave) { try { store.load(); } catch (Exception e) { throw new JsonStoreException("Unable to delegate data load for " + payloadClass + ": " + store.getFile().getAbsolutePath() + "!!", e); } } // done return store; } private void createSingleton(Class<?> payloadClass, Integer payloadClassVersion, VersionMigrationHandler... versionMigrationHandlers) { singletonStores.put(payloadClass, new JsonSingletonStore<>(payloadClass, payloadClassVersion, flexjsonHelper, storage, charset, prettyPrint, autoSave, versionMigrationHandlers)); } /** * Resolves JSON singleton store for given class. * * @param dataClass * class for JSON store * @return existing JSON singleton store, may be null * @param <T> * concrete type of data */ @SuppressWarnings("unchecked") public <T> JsonSingletonStore<T> resolveSingleton(Class<T> dataClass) { return (JsonSingletonStore<T>) singletonStores.get(dataClass); } /** * Drops JSON store for given class, is existent. Results in calling {@link JsonStore#drop()} if using auto-save mode and store exists. * * @param dataClass * class for JSON store * @return dropped JSON store * @param <T> * concrete type of data */ @SuppressWarnings("unchecked") public <T> JsonStore<T> drop(Class<T> dataClass) { // drop in memory JsonStore<T> store = (JsonStore<T>) stores.remove(dataClass); if (store != null && isPersistent()) { // remove file store.drop(); } // done return store; } /** * Drops JSON singleton store for given class, is existent. Results in calling {@link JsonSingletonStore#drop()} if using auto-save mode and store exists. * * @param dataClass * class for JSON store * @return dropped JSON singleton store * @param <T> * concrete type of data */ @SuppressWarnings("unchecked") public <T> JsonSingletonStore<T> dropSingleton(Class<T> dataClass) { // drop in memory JsonSingletonStore<T> store = (JsonSingletonStore<T>) singletonStores.remove(dataClass); if (store != null && isPersistent()) { // remove file store.drop(); } // done return store; } /** * If stores are persistent {@link JsonStore#save()} will be invoked using parallel stream on all existing stores. */ public void save() { // abort on transient stores if (!isPersistent()) { return; } // delegate to all stores stores.values().parallelStream().forEach(store -> store.save()); singletonStores.values().parallelStream().forEach(store -> store.save()); } public boolean isPersistent() { return storage != null; } }
package de.cosmicsand.webtools.path; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.regex.Pattern.compile; import static org.apache.commons.lang.StringUtils.isEmpty; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class Path implements Comparable<Path> { // needs to be defined before the very first constructor invocation protected static final Pattern SYNTAX_PATTERN = compile("(/[^/]*)*"); public static final Path ROOT = new Path(); private static final String ERR_MESS_SYNTAX_PATTERN = "If not empty the given path is required to follow the pattern '/your/path'. Current value: '%s'"; public final String rawPath; private List<PathAtom> atoms; public Path(String rawPath) { this.rawPath = isEmpty(rawPath) ? "/" : rawPath; if (!SYNTAX_PATTERN.matcher(this.rawPath).matches()) throw new URLPathException(format(ERR_MESS_SYNTAX_PATTERN, rawPath)); } public Path() { this(""); } public Path(PathAtom... pathAtoms) { rawPath = buildRawPath(pathAtoms); atoms = asList(pathAtoms); } private String buildRawPath(PathAtom... pathAtoms) { StringBuilder pathBuilder = new StringBuilder(); for (PathAtom atom : pathAtoms) pathBuilder.append(atom.getOuterName()); return pathBuilder.toString(); } public Path(Path path) { if (path == null) rawPath = ROOT.rawPath; else rawPath = path.rawPath; } @Override public String toString() { return rawPath; } @Override public boolean equals(Object obj) { if (obj instanceof Path) return rawPath.equals(((Path) obj).rawPath); return false; } @Override public int hashCode() { return rawPath.hashCode(); } @Override public int compareTo(Path other) { return rawPath.compareTo(other.rawPath); } public List<PathAtom> getAtoms() { if (ROOT.equals(this)) atoms = emptyList(); if (atoms == null) extractAtoms(); return atoms; } private void extractAtoms() { atoms = new ArrayList<PathAtom>(); String[] split = rawPath.substring(1).split("/"); for (String rawAtom : split) atoms.add(atoms.size(), new PathAtom(rawAtom)); } public Path add(Path path) { StringBuilder resultPath = new StringBuilder(this.rawPath); resultPath.append(new Path(path).rawPath); cleanupObsoleteSlashes(resultPath); return new Path(resultPath.toString()); } private void cleanupObsoleteSlashes(StringBuilder dirtyPath) { if (dirtyPath.length() > 1 && dirtyPath.charAt(1) == '/') dirtyPath.replace(0, 1, ""); } public Path merge(Path path) { if (!this.equals(path)) this.add(path); return this; } }
package de.prob2.ui.groovy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.control.ContextMenu; import javafx.scene.control.TextArea; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; public class GroovyConsole extends TextArea { private int charCounterInLine = 0; private int currentPosInLine = 0; private final KeyCode[] rest = {KeyCode.ESCAPE,KeyCode.SCROLL_LOCK,KeyCode.PAUSE,KeyCode.NUM_LOCK,KeyCode.INSERT,KeyCode.CONTEXT_MENU,KeyCode.CAPS}; private List<Instruction> instructions; private int posInList = -1; private GroovyInterpreter interpreter; public GroovyConsole() { super(); this.setContextMenu(new ContextMenu()); this.instructions = new ArrayList<>(); this.appendText("Prob 2.0 Groovy Console \n >"); setListeners(); } public void setInterpreter(GroovyInterpreter interpreter) { this.interpreter = interpreter; } @Override public void paste() { if(this.getLength() - 1 - this.getCaretPosition() >= charCounterInLine) { goToLastPos(); } String oldText = this.getText(); int posOfEnter = oldText.lastIndexOf("\n"); super.paste(); int diff = this.getLength() - oldText.length(); String currentLine = this.getText().substring(posOfEnter + 3, this.getText().length()); if(currentLine.contains("\n")) { this.setText(oldText); goToLastPos(); return; } charCounterInLine += diff; currentPosInLine += diff; } @Override public void copy() { super.copy(); goToLastPos(); } @Override public void cut() { super.cut(); } @Override public void forward() { if(currentPosInLine < charCounterInLine && this.getLength() - 1 - this.getCaretPosition() <= charCounterInLine) { currentPosInLine++; super.forward(); this.setScrollTop(Double.MIN_VALUE); } } @Override public void backward() { //handleLeft if(currentPosInLine > 0 && this.getLength() - 1 - this.getCaretPosition() <= charCounterInLine) { currentPosInLine = Math.max(currentPosInLine - 1, 0); super.backward(); this.setScrollTop(Double.MIN_VALUE); } } @Override public void selectForward() { //do nothing, but stay at correct position if(currentPosInLine != charCounterInLine) { currentPosInLine } } @Override public void selectBackward() { //do nothing, but stay at correct position if(currentPosInLine != 0) { currentPosInLine++; } } private void setListeners() { this.addEventFilter(KeyEvent.ANY, e-> { if(e.getCode() == KeyCode.Z && (e.isShortcutDown() || e.isAltDown())) { e.consume(); } }); this.addEventFilter(MouseEvent.ANY, e-> { if(e.getButton() == MouseButton.PRIMARY) { if(this.getLength() - 1 - this.getCaretPosition() < charCounterInLine) { currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); } } }); this.setOnKeyPressed(e -> { if (e.getCode().equals(KeyCode.UP) || e.getCode().equals(KeyCode.DOWN)) { handleArrowKeys(e); this.setScrollTop(Double.MAX_VALUE); } else if (e.getCode().isArrowKey()) { } else if (e.getCode().isNavigationKey()) { e.consume(); } else if (e.getCode().equals(KeyCode.BACK_SPACE) || e.getCode().equals(KeyCode.DELETE)) { handleDeletion(e); } else if (e.getCode().equals(KeyCode.ENTER)) { handleEnter(e); } else if (!e.getCode().isFunctionKey() && !e.getCode().isMediaKey() && !e.getCode().isModifierKey()) { handleInsertChar(e); } else if (handleRest(e)) { } }); } private void goToLastPos() { this.positionCaret(this.getLength()); currentPosInLine = charCounterInLine; } private void handleInsertChar(KeyEvent e) { if(e.getText().equals("") || (!(e.isShortcutDown() || e.isAltDown()) && (this.getLength() - this.getCaretPosition()) > charCounterInLine)) { if(!(e.getCode().equals(KeyCode.UNDEFINED) || e.getCode().equals(KeyCode.ALT_GRAPH))) { goToLastPos(); } if(e.getText().equals("")) { e.consume(); return; } } if (e.isShortcutDown() || e.isAltDown()) { return; } charCounterInLine++; currentPosInLine++; posInList = instructions.size() - 1; } private void handleEnter(KeyEvent e) { charCounterInLine = 0; currentPosInLine = 0; e.consume(); if(getCurrentLine().equals("")) { this.appendText("\n" + "null"); } else { if(instructions.isEmpty() || !instructions.get(instructions.size() - 1).getInstruction().equals("")) { instructions.add(new Instruction(getCurrentLine(), InstructionOption.ENTER)); } else { instructions.set(instructions.size() - 1, new Instruction(getCurrentLine(), InstructionOption.UP)); } posInList = instructions.size() - 1; this.appendText("\n" + interpreter.exec(instructions.get(posInList))); } this.appendText("\n >"); } private void handleArrowKeys(KeyEvent e) { boolean needReturn; if(e.getCode().equals(KeyCode.UP)) { needReturn = handleUp(e); } else { needReturn = handleDown(e); } if(needReturn) { return; } setTextAfterArrowKey(); } private boolean handleUp(KeyEvent e) { e.consume(); if(posInList == -1) { return true; } if(posInList == instructions.size() - 1) { String lastinstruction = instructions.get(instructions.size()-1).getInstruction(); if(!lastinstruction.equals(getCurrentLine())) { if(posInList == instructions.size() - 1) { if(instructions.get(posInList).getOption() == InstructionOption.UP) { instructions.set(instructions.size() - 1, new Instruction(getCurrentLine(), InstructionOption.UP)); } else { instructions.add(new Instruction(getCurrentLine(), InstructionOption.UP)); setTextAfterArrowKey(); return true; } } } } posInList = Math.max(posInList - 1, 0); return false; } private boolean handleDown(KeyEvent e) { e.consume(); if(posInList == instructions.size() - 1) { return true; } posInList = Math.min(posInList+1, instructions.size() - 1); return false; } private void setTextAfterArrowKey() { int posOfEnter = this.getText().lastIndexOf("\n"); this.setText(this.getText().substring(0, posOfEnter + 3)); String currentLine = instructions.get(posInList).getInstruction(); charCounterInLine = currentLine.length(); currentPosInLine = charCounterInLine; this.appendText(currentLine); } private boolean handleRest(KeyEvent e) { if(Arrays.asList(rest).contains(e.getCode())) { e.consume(); return true; } return false; } private void handleDeletion(KeyEvent e) { boolean needReturn = false; if(!this.getSelectedText().equals("") || this.getLength() - this.getCaretPosition() > charCounterInLine || e.isShortcutDown() || e.isAltDown()) { e.consume(); return; } if(e.getCode().equals(KeyCode.BACK_SPACE)) { needReturn = handleBackspace(e); if(needReturn) { return; } } else { needReturn = handleDelete(e); if(needReturn) { return; } } } private boolean handleBackspace(KeyEvent e) { if(currentPosInLine > 0) { currentPosInLine = Math.max(currentPosInLine - 1, 0); charCounterInLine = Math.max(charCounterInLine - 1, 0); } else { e.consume(); return true; } return false; } private boolean handleDelete(KeyEvent e) { if(currentPosInLine < charCounterInLine) { charCounterInLine = Math.max(charCounterInLine - 1, 0); } else if(currentPosInLine == charCounterInLine) { return true; } return false; } private String getCurrentLine() { int posOfEnter = this.getText().lastIndexOf("\n"); return this.getText().substring(posOfEnter + 3, this.getText().length()); } public void closeObjectStage() { interpreter.closeObjectStage(); } }
package de.retest.recheck; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TestCaseFinder { /* * TODO We need a special implementation for data-driven testing with annotations such as JUnit's @Theory, because * then a single method is invoked multiple times. */ private static final Set<String> testCaseAnnotations = new HashSet<String>( Arrays.asList( // JUnit Vintage (v4) "org.junit.Test", "org.junit.Before", "org.junit.After", "org.junit.BeforeClass", "org.junit.AfterClass", // JUnit Jupiter (v5) "org.junit.jupiter.api.Test", "org.junit.jupiter.api.BeforeEach", "org.junit.jupiter.api.AfterEach", "org.junit.jupiter.api.BeforeAll", "org.junit.jupiter.api.AfterAll", "org.junit.jupiter.params.ParameterizedTest", // TestNG "org.testng.annotations.Test", "org.testng.annotations.BeforeMethod", "org.testng.annotations.AfterMethod", "org.testng.annotations.BeforeClass", "org.testng.annotations.AfterClass" ) ); public static StackTraceElement findTestCaseMethodInStack() { for ( final StackTraceElement[] stack : Thread.getAllStackTraces().values() ) { final StackTraceElement testCaseStackElement = findTestCaseMethodInStack( stack ); if ( testCaseStackElement != null ) { return testCaseStackElement; } } return null; } private static StackTraceElement findTestCaseMethodInStack( final StackTraceElement[] trace ) { boolean inTestCase = false; for ( int i = 0; i < trace.length; i++ ) { if ( isTestCase( trace[i] ) ) { inTestCase = true; } else if ( inTestCase ) { return trace[i - 1]; } } return null; } private static boolean isTestCase( final StackTraceElement element ) { final Method method = tryToFindMethodForStackTraceElement( element ); if ( method == null ) { return false; } final Annotation[] annotations = method.getAnnotations(); for ( final Annotation annotation : annotations ) { final String annotationName = annotation.annotationType().getName(); if ( testCaseAnnotations.contains( annotationName ) ) { return true; } } return false; } private static Method tryToFindMethodForStackTraceElement( final StackTraceElement element ) { final Class<?> clazz; Method method = null; try { clazz = Class.forName( element.getClassName() ); } catch ( final ClassNotFoundException e ) { return null; } for ( final Method methodCandidate : clazz.getDeclaredMethods() ) { if ( methodCandidate.getName().equals( element.getMethodName() ) ) { if ( method == null ) { method = methodCandidate; } else { // two methods with same name found, can't determine correct one! return null; } } } return method; } }
package dk.itu.kelvin.component; // General utilities import java.util.ArrayList; import java.util.List; // JavaFX scene utilities import javafx.scene.Group; import javafx.scene.Scene; // JavaFX geometry import javafx.geometry.Bounds; import javafx.geometry.BoundingBox; // JavaFX transformations import javafx.scene.transform.Affine; /** * Tile grid class. * * @version 1.0.0 */ public final class TileGrid extends Group { /** * The affine transformation associated with the tile grid. * * Whenever this transformation changes, the tile grid will adjust its tiles * accordingly. */ private Affine affine; /** * List of tiles contained within the tile grid. */ private List<Tile> tiles = new ArrayList<>(); /** * Initialize a tile grid. * * @param affine The affine transformation associated with the tile grid. */ public TileGrid(final Affine affine) { this.affine = affine; this.layoutTiles(); this.affine.txProperty().addListener((ob, ov, nv) -> { this.layoutTiles(); }); this.affine.tyProperty().addListener((ob, ov, nv) -> { this.layoutTiles(); }); } /** * Add a tile to the tile grid. * * @param tile The tile to add. */ public void tile(final Tile tile) { if (tile == null) { return; } this.tiles.add(tile); } /** * Get a list of tiles contained within the tile grid. * * @return A list of tiles contained within the tile grid. */ public List<Tile> tiles() { return this.tiles; } /** * Add a tile to the tile grid scene graph. * * @param tile The tile to add. */ private void add(final Tile tile) { if (!this.getChildren().contains(tile)) { this.getChildren().add(tile); } } /** * Remove a tile from the tile grid scene graph. * * @param tile The tile to remove. */ private void remove(final Tile tile) { if (this.getChildren().contains(tile)) { this.getChildren().remove(tile); } } /** * Check if a given tile is within the visible bounds of the tile grid. * * @param tile The tile to check the visibility of. * @return A boolean indicating whether or not the specified tile is * within the visible bounds of the tile grid. */ private boolean withinBounds(final Tile tile) { Scene scene = this.getScene(); if (scene == null) { return false; } // Create a bounding box corresponding to the bounds of the scene. Bounds sceneBounds = new BoundingBox( 0, 0, scene.getWidth(), scene.getHeight() ); // Get the bounds of the tile relatively to the bounds of the scene. Bounds tileBounds = this.localToScene( tile.getBoundsInParent() ); // If the bounds of the scene and tile intersect, the tile will be within // the bounds of the scene. return sceneBounds.intersects(tileBounds); } /** * Add the visible tiles to the tile grid. */ private void layoutTiles() { for (Tile tile: this.tiles) { if (this.withinBounds(tile)) { this.add(tile); } else { this.remove(tile); } } } }
package eu.spitfire.ssp; import com.google.common.util.concurrent.ThreadFactoryBuilder; import eu.spitfire.ssp.backends.coap.CoapBackendComponentFactory; import eu.spitfire.ssp.backends.files.FilesBackendComponentFactory; import eu.spitfire.ssp.backends.generic.BackendComponentFactory; import eu.spitfire.ssp.backends.uberdust.UberdustBackendComponentFactory; import eu.spitfire.ssp.server.channels.LocalPipelineFactory; import eu.spitfire.ssp.server.channels.SmartServiceProxyPipelineFactory; import eu.spitfire.ssp.server.channels.handler.HttpRequestDispatcher; import eu.spitfire.ssp.server.channels.handler.MqttResourceHandler; import eu.spitfire.ssp.server.channels.handler.cache.DummySemanticCache; import eu.spitfire.ssp.server.channels.handler.cache.JenaTdbSemanticCache; import eu.spitfire.ssp.server.channels.handler.cache.SemanticCache; import org.apache.commons.configuration.Configuration; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class ComponentFactory { private Logger log = LoggerFactory.getLogger(this.getClass().getName()); private String sspHostName; private int sspHttpPort; private ScheduledExecutorService scheduledExecutorService; private OrderedMemoryAwareThreadPoolExecutor ioExecutorService; private ServerBootstrap serverBootstrap; private LocalPipelineFactory localPipelineFactory; private ExecutionHandler executionHandler; private HttpRequestDispatcher httpRequestDispatcher; private MqttResourceHandler mqttResourceHandler; private SemanticCache semanticCache; private Collection<BackendComponentFactory> backendComponentFactories; public ComponentFactory(Configuration config) throws Exception { this.sspHostName = config.getString("SSP_HOST_NAME"); this.sspHttpPort = config.getInt("SSP_HTTP_SERVER_PORT", 8080); //Create Executor Services createScheduledExecutorService(); createIoExecutorService(config); //Create Pipeline Components createExecutionHandler(); createSemanticCache(config); createMqttResourceHandler(config); createHttpRequestDispatcher(); createServerBootstrap(config); createLocalPipelineFactory(); //Create backend component factories createBackendComponentFactories(config); } public ServerBootstrap getServerBootstrap() { return this.serverBootstrap; } public Collection<BackendComponentFactory> getBackendComponentFactories() { return this.backendComponentFactories; } private void createBackendComponentFactories(Configuration config) throws Exception { String[] enabledBackends = config.getStringArray("ENABLE_BACKEND"); this.backendComponentFactories = new ArrayList<>(enabledBackends.length); for (String proxyServiceManagerName : enabledBackends) { //Local files if (proxyServiceManagerName.equals("files")) { String directory = config.getString("files.directory"); if (directory == null) { throw new Exception("Property 'files.directory' not set."); } boolean copyExamples = config.getBoolean("files.copyExamples"); //int numberOfRandomFiles = config.getInt("files.numberOfRandomFiles", 0); BackendComponentFactory backendComponentFactory = new FilesBackendComponentFactory("files", localPipelineFactory, scheduledExecutorService, sspHostName, sspHttpPort, Paths.get(directory), copyExamples); this.backendComponentFactories.add(backendComponentFactory); continue; } else if (proxyServiceManagerName.equals("coap")) { log.info("Create CoAP Backend"); InetAddress registrationServerAddress = InetAddress.getByName(config.getString("coap.registration.server.ip")); BackendComponentFactory backendComponentFactory = new CoapBackendComponentFactory("coap", localPipelineFactory, scheduledExecutorService, sspHostName, sspHttpPort, registrationServerAddress); this.backendComponentFactories.add(backendComponentFactory); continue; } else if (proxyServiceManagerName.equals("uberdust")) { log.info("Create Uberdust Backend"); final int insertThreadCount = config.getInt("UBERDUST_INSERT_THREAD_COUNT",1); this.backendComponentFactories.add(new UberdustBackendComponentFactory("uberdust", localPipelineFactory, scheduledExecutorService, sspHostName, sspHttpPort,insertThreadCount)); } //Unknown AbstractGatewayFactory type else { log.error("Config file error: Gateway for '" + proxyServiceManagerName + "' not found!"); continue; } } } private void createLocalPipelineFactory() { LinkedHashSet<ChannelHandler> handler = new LinkedHashSet<>(); if (!(mqttResourceHandler == null)) handler.add(mqttResourceHandler); handler.add(semanticCache); handler.add(httpRequestDispatcher); this.localPipelineFactory = new LocalPipelineFactory(handler); log.debug("Local Pipeline Factory created."); } private void createServerBootstrap(Configuration config) throws Exception { //read parameters from config boolean tcpNoDelay = config.getBoolean("SSP_TCP_NODELAY"); int ioThreads = config.getInt("SSP_I/O_THREADS"); //create the bootstrap this.serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(16) )); this.serverBootstrap.setOption("reuseAddress", true); this.serverBootstrap.setOption("tcpNoDelay", false); LinkedHashSet<ChannelHandler> handler = new LinkedHashSet<>(); handler.add(executionHandler); if (!(mqttResourceHandler == null)) handler.add(mqttResourceHandler); handler.add(semanticCache); handler.add(httpRequestDispatcher); this.serverBootstrap.setPipelineFactory(new SmartServiceProxyPipelineFactory(handler)); log.debug("Server Bootstrap created."); } private void createIoExecutorService(Configuration config) { int executionThreads = config.getInt("SSP_REQUEST_EXECUTION_THREADS"); int messageQueueSize = config.getInt("SSP_MESSAGE_QUEUE_SIZE"); ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("SSP-REQUEST-EXECUTION-Thread .build(); this.ioExecutorService = new OrderedMemoryAwareThreadPoolExecutor(executionThreads, 0, messageQueueSize, 60, TimeUnit.SECONDS, threadFactory); log.debug("Request-Executor-Service created."); } private void createExecutionHandler() { this.executionHandler = new ExecutionHandler(this.ioExecutorService); log.debug("Execution Handler created."); } private void createHttpRequestDispatcher() throws Exception { this.httpRequestDispatcher = new HttpRequestDispatcher(ioExecutorService, semanticCache.supportsSPARQL(), semanticCache, sspHostName, sspHttpPort); log.debug("HTTP Request Dispatcher created."); } private void createMqttResourceHandler(Configuration config) throws Exception { if (config.getBoolean("ENABLE_MQTT", false)) { String mqttBrokerUri = config.getString("MQTT_BROKER_URI"); int mqttBrokerHttpPort = config.getInt("MQTT_BROKER_HTTP_PORT"); this.mqttResourceHandler = new MqttResourceHandler(mqttBrokerUri, mqttBrokerHttpPort); log.debug("MQTT Handler created."); } else { this.mqttResourceHandler = null; log.debug("MQTT was disabled."); } } private void createSemanticCache(Configuration config) { String cacheType = config.getString("cache"); if ("dummy".equals(cacheType)) { this.semanticCache = new DummySemanticCache(scheduledExecutorService); log.info("Semantic Cache is of type {}", this.semanticCache.getClass().getSimpleName()); return; } if ("jenaTDB".equals(cacheType)) { String dbDirectory = config.getString("cache.jenaTDB.dbDirectory"); if (dbDirectory == null) throw new RuntimeException("'cache.jenaSDB.jdbc.url' missing in ssp.properties"); this.semanticCache = new JenaTdbSemanticCache(scheduledExecutorService, Paths.get(dbDirectory)); return; } throw new RuntimeException("No cache type defined in ssp.properties"); } private void createScheduledExecutorService() { //Scheduled executorservice for management tasks ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Proxy-Service-Mgmt.-Thread .build(); int numberOfMgmtThreads = Math.max(Runtime.getRuntime().availableProcessors() * 2, 4); this.scheduledExecutorService = Executors.newScheduledThreadPool(numberOfMgmtThreads, threadFactory); log.debug("Scheduled Executor created."); } }
package com.airbnb.lottie; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.provider.Settings; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.AppCompatImageView; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import org.json.JSONObject; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; public class LottieAnimationView extends AppCompatImageView { private static final String TAG = LottieAnimationView.class.getSimpleName(); /** * Caching strategy for compositions that will be reused frequently. * Weak or Strong indicates the GC reference strength of the composition in the cache. */ @SuppressWarnings("WeakerAccess") public enum CacheStrategy { None, Weak, Strong } private static final Map<String, LottieComposition> strongRefCache = new HashMap<>(); private static final Map<String, WeakReference<LottieComposition>> weakRefCache = new HashMap<>(); private final OnCompositionLoadedListener loadedListener = new OnCompositionLoadedListener() { @Override public void onCompositionLoaded(LottieComposition composition) { setComposition(composition); compositionLoader = null; } }; private final LottieDrawable lottieDrawable = new LottieDrawable(); private CacheStrategy defaultCacheStrategy; private String animationName; @Nullable private Cancellable compositionLoader; /** * Can be null because it is created async */ @Nullable private LottieComposition composition; public LottieAnimationView(Context context) { super(context); init(null); } public LottieAnimationView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(@Nullable AttributeSet attrs) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.LottieAnimationView); String fileName = ta.getString(R.styleable.LottieAnimationView_lottie_fileName); if (!isInEditMode() && fileName != null) { setAnimation(fileName); } if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_autoPlay, false)) { lottieDrawable.playAnimation(); } lottieDrawable.loop(ta.getBoolean(R.styleable.LottieAnimationView_lottie_loop, false)); setImageAssetsFolder(ta.getString(R.styleable.LottieAnimationView_lottie_imageAssetsFolder)); setProgress(ta.getFloat(R.styleable.LottieAnimationView_lottie_progress, 0)); int cacheStrategy = ta.getInt( R.styleable.LottieAnimationView_lottie_cacheStrategy, CacheStrategy.None.ordinal()); defaultCacheStrategy = CacheStrategy.values()[cacheStrategy]; ta.recycle(); setLayerType(LAYER_TYPE_SOFTWARE, null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { float systemAnimationScale = Settings.Global.getFloat(getContext().getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1.0f); if (systemAnimationScale == 0f) { lottieDrawable.systemAnimationsAreDisabled(); } } } @Override public void setImageResource(int resId) { super.setImageResource(resId); recycleBitmaps(); } @Override public void setImageDrawable(Drawable drawable) { if (drawable != lottieDrawable) { recycleBitmaps(); } super.setImageDrawable(drawable); } @Override public void invalidateDrawable(@NonNull Drawable dr) { if (getDrawable() == lottieDrawable) { // We always want to invalidate the root drawable to it redraws the whole drawable. // Eventually it would be great to be able to invalidate just the changed region. super.invalidateDrawable(lottieDrawable); } else { // Otherwise work as regular ImageView super.invalidateDrawable(dr); } } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.animationName = animationName; ss.progress = lottieDrawable.getProgress(); ss.isAnimating = lottieDrawable.isAnimating(); ss.isLooping = lottieDrawable.isLooping(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); this.animationName = ss.animationName; if (!TextUtils.isEmpty(animationName)) { setAnimation(animationName); } setProgress(ss.progress); loop(ss.isLooping); if (ss.isAnimating) { playAnimation(); } } @Override protected void onDetachedFromWindow() { recycleBitmaps(); super.onDetachedFromWindow(); } @VisibleForTesting void recycleBitmaps() { lottieDrawable.recycleBitmaps(); } /** * Sets the animation from a file in the assets directory. * This will load and deserialize the file asynchronously. * <p> * Will not cache the composition once loaded. */ @SuppressWarnings("WeakerAccess") public void setAnimation(String animationName) { setAnimation(animationName, defaultCacheStrategy); } /** * Sets the animation from a file in the assets directory. * This will load and deserialize the file asynchronously. * <p> * You may also specify a cache strategy. Specifying {@link CacheStrategy#Strong} will hold a * strong reference to the composition once it is loaded * and deserialized. {@link CacheStrategy#Weak} will hold a weak reference to said composition. */ @SuppressWarnings("WeakerAccess") public void setAnimation(final String animationName, final CacheStrategy cacheStrategy) { this.animationName = animationName; if (weakRefCache.containsKey(animationName)) { WeakReference<LottieComposition> compRef = weakRefCache.get(animationName); if (compRef.get() != null) { setComposition(compRef.get()); return; } } else if (strongRefCache.containsKey(animationName)) { setComposition(strongRefCache.get(animationName)); return; } this.animationName = animationName; lottieDrawable.cancelAnimation(); cancelLoaderTask(); compositionLoader = LottieComposition.Factory.fromAssetFileName(getContext(), animationName, new OnCompositionLoadedListener() { @Override public void onCompositionLoaded(LottieComposition composition) { if (cacheStrategy == CacheStrategy.Strong) { strongRefCache.put(animationName, composition); } else if (cacheStrategy == CacheStrategy.Weak) { weakRefCache.put(animationName, new WeakReference<>(composition)); } setComposition(composition); } }); } /** * Sets the animation from a JSONObject. * This will load and deserialize the file asynchronously. * <p> * This is particularly useful for animations loaded from the network. You can fetch the * bodymovin json from the network and pass it directly here. */ public void setAnimation(final JSONObject json) { cancelLoaderTask(); compositionLoader = LottieComposition.Factory.fromJson(getResources(), json, loadedListener); } private void cancelLoaderTask() { if (compositionLoader != null) { compositionLoader.cancel(); compositionLoader = null; } } /** * Sets a composition. * You can set a default cache strategy if this view was inflated with xml by * using {@link R.attr#lottie_cacheStrategy}. */ public void setComposition(@NonNull LottieComposition composition) { if (L.DBG) { Log.v(TAG, "Set Composition \n" + composition); } lottieDrawable.setCallback(this); boolean isNewComposition = lottieDrawable.setComposition(composition); if (!isNewComposition) { // We can avoid re-setting the drawable, and invalidating the view, since the composition // hasn't changed. return; } int screenWidth = Utils.getScreenWidth(getContext()); int screenHeight = Utils.getScreenHeight(getContext()); int compWidth = composition.getBounds().width(); int compHeight = composition.getBounds().height(); if (compWidth > screenWidth || compHeight > screenHeight) { float xScale = screenWidth / (float) compWidth; float yScale = screenHeight / (float) compHeight; setScale(Math.min(xScale, yScale)); Log.w(L.TAG, String.format( "Composition larger than the screen %dx%d vs %dx%d. Scaling down.", compWidth, compHeight, screenWidth, screenHeight)); } // If you set a different composition on the view, the bounds will not update unless // the drawable is different than the original. setImageDrawable(null); setImageDrawable(lottieDrawable); this.composition = composition; requestLayout(); } /** * Returns whether or not any layers in this composition has masks. */ @SuppressWarnings("unused") public boolean hasMasks() { return lottieDrawable.hasMasks(); } /** * Returns whether or not any layers in this composition has a matte layer. */ @SuppressWarnings("unused") public boolean hasMatte() { return lottieDrawable.hasMatte(); } /** * If you use image assets, you must explicitly specify the folder in assets/ in which they are * located because bodymovin uses the name filenames across all compositions (img_#). * Do NOT rename the images themselves. * * If your images are located in src/main/assets/airbnb_loader/ then call * `setImageAssetsFolder("airbnb_loader/");`. */ @SuppressWarnings("WeakerAccess") public void setImageAssetsFolder(String imageAssetsFolder) { lottieDrawable.setImagesAssetsFolder(imageAssetsFolder); } public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.addAnimatorUpdateListener(updateListener); } @SuppressWarnings("unused") public void removeUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.removeAnimatorUpdateListener(updateListener); } public void addAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.addAnimatorListener(listener); } @SuppressWarnings("unused") public void removeAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.removeAnimatorListener(listener); } public void loop(boolean loop) { lottieDrawable.loop(loop); } public boolean isAnimating() { return lottieDrawable.isAnimating(); } public void playAnimation() { lottieDrawable.playAnimation(); } public void resumeAnimation() { lottieDrawable.resumeAnimation(); } @SuppressWarnings("unused") public void reverseAnimation() { lottieDrawable.reverseAnimation(); } @SuppressWarnings("unused") public void resumeReverseAnimation() { lottieDrawable.resumeReverseAnimation(); } @SuppressWarnings("unused") public void setSpeed(float speed) { lottieDrawable.setSpeed(speed); } /** * Use this if you can't bundle images with your app. This may be useful if you download the * animations from the network or have the images saved to an SD Card. In that case, Lottie * will defer the loading of the bitmap to this delegate. */ @SuppressWarnings("unused") public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) { lottieDrawable.setImageAssetDelegate(assetDelegate); } void setScale(float scale) { lottieDrawable.setScale(scale); setImageDrawable(null); setImageDrawable(lottieDrawable); } public void cancelAnimation() { lottieDrawable.cancelAnimation(); } public void pauseAnimation() { float progress = getProgress(); lottieDrawable.cancelAnimation(); setProgress(progress); } public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) { lottieDrawable.setProgress(progress); } @FloatRange(from = 0.0f, to = 1.0f) public float getProgress() { return lottieDrawable.getProgress(); } @SuppressWarnings("unused") public long getDuration() { return composition != null ? composition.getDuration() : 0; } private static class SavedState extends BaseSavedState { String animationName; float progress; boolean isAnimating; boolean isLooping; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); animationName = in.readString(); progress = in.readFloat(); isAnimating = in.readInt() == 1; isLooping = in.readInt() == 1; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(animationName); out.writeFloat(progress); out.writeInt(isAnimating ? 1 : 0); out.writeInt(isLooping ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package hudson.remoting.jnlp; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import hudson.remoting.EngineListener; import java.io.StringWriter; import java.io.PrintWriter; import java.util.logging.Logger; import static java.util.logging.Level.INFO; import static java.util.logging.Level.SEVERE; /** * {@link EngineListener} implementation that shows GUI. */ public final class GuiListener implements EngineListener { public final MainDialog frame; public GuiListener() { GUI.setUILookAndFeel(); frame = new MainDialog(); frame.setVisible(true); } public void status(final String msg) { status(msg,null); } public void status(final String msg, final Throwable t) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame.status(msg); if(t!=null) LOGGER.log(INFO, msg, t); } }); } @SuppressFBWarnings(value = "DM_EXIT", justification = "This is an error handler for GUI, exit is valid") public void error(final Throwable t) { SwingUtilities.invokeLater(new Runnable() { public void run() { LOGGER.log(SEVERE, t.getMessage(), t); StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); JOptionPane.showMessageDialog( frame,sw.toString(),"Error", JOptionPane.ERROR_MESSAGE); System.exit(-1); } }); } public void onDisconnect() { SwingUtilities.invokeLater(new Runnable() { public void run() { // discard all the menu items that might have been added by the master. frame.resetMenuBar(); } }); } public void onReconnect() { } private static final Logger LOGGER = Logger.getLogger(GuiListener.class.getName()); }
package innovimax.mixthem.arguments; import java.util.EnumSet; /** * <p>This is a detailed enumeration of rules used to mix files.</p> * <p>Some rules may not be implemented yet.<.p> * <p>(Also used to print usage.)</p> * @author Innovimax * @version 1.0 */ public enum Rule { FILE_1("1", "1", "will output file1", true, EnumSet.noneOf(RuleParam.class)), FILE_2("2", "2", "will output file2", true, EnumSet.noneOf(RuleParam.class)), ADD("+", "add", "will output file1+file2", true, EnumSet.noneOf(RuleParam.class)), ALT_LINE("alt-line", "altline", "will output one line of each starting with first line of file1", true, EnumSet.noneOf(RuleParam.class)), ALT_CHAR("alt-char", "altchar", "will output one char of each starting with first char of file1", true, EnumSet.noneOf(RuleParam.class)), RANDOM_ALT_LINE("random-alt-line", "random-altline", "will output one line of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED)), JOIN("join", "join", "will output merging of lines that have common occurrence", true, EnumSet.of(RuleParam.JOIN_COL1, RuleParam.JOIN_COL2)), ZIP_LINE("zip-line", "zipline", "will output zip of line from file1 and file2", true, EnumSet.of(RuleParam.ZIP_SEP)), ZIP_CHAR("zip-char", "zipchar", "will output zip of char from file1 and file2", true, EnumSet.of(RuleParam.ZIP_SEP)), ZIP_CELL("zip-cell", "zipcell", "will output zip of cell from file1 and file2", true, EnumSet.of(RuleParam.ZIP_SEP)); private final String name, extension, description; private final boolean implemented; private final EnumSet<RuleParam> params; private Rule(final String name, final String extension, final String description, final boolean implemented, final EnumSet<RuleParam> params) { this.name = name; this.extension = extension; this.description = description; this.implemented = implemented; this.params = params; } /** * Returns true if the rule is currently implemented. * @return True if the rule is currently implemented */ public boolean isImplemented() { return this.implemented; } /** * Returns the name of this rule on command line. * @return The name of the rule on command line */ public String getName() { return this.name; } /** * Returns the file extension used for outputting. * @return The file extension for the rule */ public String getExtension() { return this.extension; } /** * Returns the description of this rule. * @return The description of the rule */ public String getDescription() { return this.description; } /** * Returns an iterator over the additional parameters in this rule. * @return An iterator over the additional parameters in this rule */ public Iterable<RuleParam> getParams() { return this.params; } /** * Finds the Rule object correponding to a name * @param name The name of the rule in command line * @return The {@link Rule} object */ public static Rule findByName(final String name) { for(Rule rule : values()){ if (rule.getName().equals(name)) { return rule; } } return null; } }
package io.coinswap.swap; import net.minidev.json.JSONObject; import org.bitcoinj.core.Coin; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public class AtomicSwapTrade { public static final Coin FEE = Coin.ZERO; // exchange fee, in satoshis per 10 microcoins public final Coin fee; public final String[] coins; public final Coin[] quantities; // buy = trading currency 0 for 1 // sell = trading 1 for 0 public final boolean buy; // if true, only fill already open orders // if false, open a new order if neccessary // TODO: move this field into an 'OrderOptions' object public boolean immediate = false; // coins: 0 = chain A (A->B), 1 = chain B (B->A) // quantities: 0 = amount traded from A->B (quantity), 1 = B->A (total) public AtomicSwapTrade(boolean buy, String[] coins, Coin[] quantities, Coin fee) { this.buy = buy; this.coins = checkNotNull(coins); checkNotNull(coins[0]); checkNotNull(coins[1]); this.quantities = checkNotNull(quantities); checkNotNull(quantities[0]); checkNotNull(quantities[1]); this.fee = checkNotNull(fee); } public Coin getFeeAmount(boolean a) { Coin[] divided = quantities[a ? 0 : 1].divideAndRemainder(1000); long tensOfMicrocoins = divided[0].longValue(); // ceil the number of 10*microcoins if(divided[1].longValue() > 0) tensOfMicrocoins++; return fee.multiply(tensOfMicrocoins); } public Map toJson() { Map data = new JSONObject(); data.put("buy", buy); data.put("fee", fee.longValue()); data.put("coins", coins); data.put("quantities", new long[]{ quantities[0].longValue(), quantities[1].longValue() }); data.put("immediate", immediate); return data; } public static AtomicSwapTrade fromJson(Map data) { checkNotNull(data); List<Integer> longQuantities = (ArrayList<Integer>) checkNotNull(data.get("quantities")); checkState(longQuantities.size() == 2); checkNotNull(longQuantities.get(0)); checkNotNull(longQuantities.get(1)); Coin[] quantities = new Coin[]{ Coin.valueOf(longQuantities.get(0)), Coin.valueOf(longQuantities.get(1)) }; List<String> coins = (ArrayList<String>) checkNotNull(data.get("coins")); checkState(coins.size() == 2); checkNotNull(coins.get(0)); checkNotNull(coins.get(1)); AtomicSwapTrade output = new AtomicSwapTrade( (boolean) checkNotNull(data.get("buy")), new String[]{ coins.get(0), coins.get(1) }, quantities, Coin.valueOf((int) checkNotNull(data.get("fee")))); output.immediate = (boolean) checkNotNull(data.get("immediate")); return output; } }
package istc.bigdawg.signature; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import convenience.RTED; import istc.bigdawg.packages.QueryContainerForCommonDatabase; import istc.bigdawg.plan.operators.Operator; import istc.bigdawg.signature.builder.ArraySignatureBuilder; import istc.bigdawg.signature.builder.RelationalSignatureBuilder; import istc.bigdawg.utils.IslandsAndCast.Scope; import istc.bigdawg.utils.sqlutil.SQLExpressionUtils; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Parenthesis; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.schema.Column; public class Signature { private static String fieldSeparator = "|||||"; private static String fieldSeparatorRest = "[|][|][|][|][|]"; private static String elementSeparator = "&&&&&"; private static String elementSeparatorRest = "[&][&][&][&][&]"; private Scope island; private String sig1; private List<String> sig2; private List<String> sig3; private String query; private List<String> sig4k; private List<Map<String, Set<String>>> objectExpressionMapping = null; // private String identifier; // private static Pattern possibleObjectsPattern = Pattern.compile("[_@a-zA-Z0-9]+"); // private static Pattern tagPattern = Pattern.compile("BIGDAWGTAG_[0-9_]+"); /** * Construct a signature of three parts: sig1 tells about the structure, sig2 are all object references, sig3 are all constants * @param cc * @param query * @param island * @throws Exception */ public Signature(String query, Scope island, Operator root, Map<String, QueryContainerForCommonDatabase> container) throws Exception { if (island.equals(Scope.RELATIONAL)){ setSig2(RelationalSignatureBuilder.sig2(query)); setSig3(RelationalSignatureBuilder.sig3(query)); } else if (island.equals(Scope.ARRAY)) { setSig2(ArraySignatureBuilder.sig2(query)); setSig3(ArraySignatureBuilder.sig3(query)); } else { throw new Exception("Invalid Signature island input: "+island); } objectExpressionMapping = new ArrayList<>(); if (container.isEmpty() ) { Map<String, Set<String>> mapping = root.getObjectToExpressionMappingForSignature(); root.removeCTEEntriesFromObjectToExpressionMapping(mapping); objectExpressionMapping.add(mapping); } List<String> cs = new ArrayList<>(); for (String s : container.keySet()) { cs.add(container.get(s).generateTreeExpression()); objectExpressionMapping.add(container.get(s).generateObjectToExpressionMapping()); } setSig4k(cs); setSig1(root.getTreeRepresentation(true)); this.setQuery(query); this.setIsland(island); } public Signature(String s) throws Exception{ List<String> parsed = Arrays.asList(s.split(fieldSeparatorRest)); if (parsed.size() != 5 && parsed.size() != 6) { throw new Exception("Ill-formed input string; cannot recover signature; String: "+s); } try { this.island = Scope.valueOf(parsed.get(0)); this.sig1 = new String(parsed.get(1)); this.sig2 = Arrays.asList(parsed.get(2).split(elementSeparatorRest)); this.sig3 = Arrays.asList(parsed.get(3).split(elementSeparatorRest)); this.query = new String(parsed.get(4)); if (parsed.size() == 5) this.sig4k = new ArrayList<>(); else this.sig4k = Arrays.asList(parsed.get(5).split(elementSeparatorRest)); } catch (Exception e) { e.printStackTrace(); throw new Exception("Ill-formed input string; cannot recover signature; String: "+s); } } public static double getTreeEditDistance(String s1, String s2) { return RTED.computeDistance(s1, s2); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Signature:\n"); sb.append("Island : ").append(island.toString()).append('\n'); sb.append("Signature 1 : ").append(sig1.toString()).append('\n'); sb.append("Signature 2 : ").append(sig2.toString()).append('\n'); sb.append("Signature 3 : ").append(sig3.toString()).append('\n'); sb.append("Query : ").append(query).append('\n'); sb.append("Signature 4-k: ").append(sig4k.toString()).append('\n'); return sb.toString(); } public void print() { System.out.println(this.toString()); } public String getSig1() { return sig1; } public void setSig1(String sig1) { this.sig1 = sig1; } public List<String> getSig2() { return sig2; } public void setSig2(List<String> sig2) { this.sig2 = sig2; } public List<String> getSig3() { return sig3; } public void setSig3(List<String> sig3) { this.sig3 = sig3; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public Scope getIsland() { return island; } private void setIsland(Scope island) { this.island = island; } public List<String> getSig4k() { return sig4k; } public void setSig4k(List<String> sig4k) { this.sig4k = sig4k; } public List<Map<String, Set<String>>> getObjectToExpressionMapping() { return objectExpressionMapping; } public List<Map<String, Set<String>>> getTreesOfObjectToExpressionMapping() throws JSQLParserException { List<Map<String, Set<String>>> ret = new ArrayList<>(); for (Map<String, Set<String>> mapping : objectExpressionMapping) { Map<String, Set<String>> addition = new HashMap<>(); for (String obj : mapping.keySet()) { Set<String> expr = new HashSet<>(); for (String exp : mapping.get(obj)) { expr.add(SQLExpressionUtils.parseCondForTree(CCJSqlParserUtil.parseCondExpression(exp))); } addition.put(obj, expr); } ret.add(addition); } return ret; } public List<Map<String, Set<String>>> getTreesOfStrippedDownObjectToExpressionMapping() throws JSQLParserException { List<Map<String, Set<String>>> ret = new ArrayList<>(); for (Map<String, Set<String>> mapping : objectExpressionMapping) { Map<String, Set<String>> addition = new HashMap<>(); for (String obj : mapping.keySet()) { Set<String> expr = new HashSet<>(); for (String exp : mapping.get(obj)) { Expression e = SQLExpressionUtils.stripDownExpressionForSignature(CCJSqlParserUtil.parseCondExpression(exp)); while (e instanceof Parenthesis) e = ((Parenthesis)e).getExpression(); if (e instanceof Column) continue; expr.add(SQLExpressionUtils.parseCondForTree(e)); } addition.put(obj, expr); } ret.add(addition); } return ret; } public static void printO2EMapping(Operator o) throws Exception { Map<String, Set<String>> m = o.getObjectToExpressionMappingForSignature(); o.removeCTEEntriesFromObjectToExpressionMapping(m); System.out.println("Mapping: "); for (String s : m.keySet()) { System.out.printf("-- %s:\n",s); for (String s2 : m.get(s)) { String e; try { e = SQLExpressionUtils.parseCondForTree(CCJSqlParserUtil.parseCondExpression(s2)); } catch (JSQLParserException ex) { e = SQLExpressionUtils.parseCondForTree(CCJSqlParserUtil.parseExpression(s2)); } System.out.printf(" - %s\n",e); } } } public static void printStrippedO2EMapping(Operator o) throws Exception { Map<String, Set<String>> m = o.getObjectToExpressionMappingForSignature(); o.removeCTEEntriesFromObjectToExpressionMapping(m); System.out.println("Stripped down function: "); for (String s : m.keySet()) { System.out.printf("-- %s:\n",s); for (String s2 : m.get(s)) { Expression e; try { e = SQLExpressionUtils.stripDownExpressionForSignature(CCJSqlParserUtil.parseCondExpression(s2)); } catch (JSQLParserException ex) { e = SQLExpressionUtils.stripDownExpressionForSignature(CCJSqlParserUtil.parseExpression(s2)); } while (e instanceof Parenthesis) e = ((Parenthesis)e).getExpression(); if (e instanceof Column) continue; System.out.printf(" - %s\n",SQLExpressionUtils.parseCondForTree(e)); } } } public String toRecoverableString() { StringBuilder sb = new StringBuilder(); sb.append(island.toString()); sb.append(fieldSeparator).append(sig1); sb.append(fieldSeparator).append(String.join(elementSeparator, sig2)); sb.append(fieldSeparator).append(String.join(elementSeparator, sig3)); sb.append(fieldSeparator).append(query); if (sig4k.size() > 0) sb.append(fieldSeparator).append(String.join(elementSeparator, sig4k)); return sb.toString(); } public double compare(Signature sig) { double dist = 0; List<String> l2; List<String> l4k2 = new ArrayList<>(sig.sig4k); int size; // sig1 dist = getTreeEditDistance(sig1, sig.sig1); // sig2 if (sig2.size() > sig.sig2.size()) { l2 = new ArrayList<>(sig2); l2.retainAll(sig.sig2); size = sig2.size(); } else { l2 = new ArrayList<>(sig.sig2); l2.retainAll(sig2); size = sig.sig2.size(); } dist *= ((double)l2.size()) / size; // sig3 dist += (sig3.size() > sig.sig3.size()) ? sig3.size() - sig.sig3.size() : sig.sig3.size() - sig3.size(); // sig4k dist += sig4k.size() < sig.sig4k.size() ? sig.sig4k.size() - sig4k.size() : sig4k.size() - sig.sig4k.size(); for (int i = 0 ; i < sig4k.size() ; i++ ) { double result = Double.MAX_VALUE; int j = 0; int holder = -1; while (!l4k2.isEmpty() && j < l4k2.size()) { double temp = getTreeEditDistance(sig4k.get(i), l4k2.get(j)); if (temp < result) { result = temp; holder = j; } j++; } if (holder > 0) { l4k2.remove(holder); dist += result; } else break; } return dist; } }
package kalang.compiler; import kalang.util.MathType; import kalang.util.AstUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Stack; import kalang.ast.AssignExpr; import kalang.ast.AstNode; import kalang.ast.AstVisitor; import kalang.ast.BinaryExpr; import kalang.ast.CastExpr; import kalang.ast.CatchBlock; import kalang.ast.ClassNode; import kalang.ast.ElementExpr; import kalang.ast.ExprNode; import kalang.ast.IfStmt; import kalang.ast.InvocationExpr; import kalang.ast.LoopStmt; import kalang.ast.MethodNode; import kalang.ast.ReturnStmt; import kalang.ast.Statement; import kalang.ast.TryStmt; import kalang.ast.UnaryExpr; import kalang.ast.VarExpr; import kalang.ast.VarObject; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import kalang.ast.AnnotationNode; import kalang.ast.Annotationable; import kalang.ast.AssignableExpr; import kalang.ast.ClassReference; import kalang.ast.ErrorousExpr; import kalang.ast.LocalVarNode; import kalang.ast.ThrowStmt; import kalang.ast.UnknownFieldExpr; import kalang.ast.UnknownInvocationExpr; import kalang.core.ArrayType; import kalang.core.ObjectType; import kalang.core.ExecutableDescriptor; import kalang.core.MethodDescriptor; import kalang.core.PrimitiveType; import kalang.core.Type; import kalang.core.Types; import kalang.core.VarTable; import kalang.util.BoxUtil; import kalang.util.CollectionsUtil; import kalang.util.MethodUtil; /** * The semantic analyzer class infers and checks the componentType of expressions. It may transform the abstract syntax tree. * * @author Kason Yang <i@kasonyang.com> */ public class SemanticAnalyzer extends AstVisitor<Type> { private HashMap<String, VarObject> fields; private AstLoader astLoader; private ClassNode clazz; private MethodNode method; //private List<String> methodDeclared; private boolean returned; private SemanticErrorReporter err; private CompileErrorHandler errHandler; private Stack<Map<Type,AstNode>> exceptionStack = new Stack(); private CompilationUnit source; private VarTable<LocalVarNode,Void> assignedVars = new VarTable<>(); public SemanticAnalyzer(CompilationUnit source,AstLoader astLoader) { this.astLoader = astLoader; this.source = source; errHandler = (error) -> { System.err.println(error.toString()); }; } private Type getDefaultType(){ return Types.getRootType(); } public void setAstSemanticErrorHandler(CompileErrorHandler handler) { errHandler = handler; } /** * checks whether an expression as assignable to another expression , and transform the expression if needed. * * @param expr * @param from * @param to * @param node * @return the assignable expression when assignable ,or null */ @Nullable private ExprNode checkAssign(ExprNode expr, Type from, Type to, AstNode node) { expr = BoxUtil.assign(expr, from, to); if (expr == null) { err.failedToCast(node, from.getName(), to.getName()); return null; } return expr; } @Nullable public ClassNode loadAst(String name, AstNode node) { ClassNode ast = this.astLoader.getAst(name); if (ast == null) { err.classNotFound(node, name); return null; } return ast; } public void check(ClassNode clz) { err = new SemanticErrorReporter(clz,source ,new SemanticErrorReporter.AstSemanticReporterCallback() { @Override public void handleAstSemanticError(SemanticError error) { errHandler.handleCompileError(error); } }); this.fields = new HashMap(); //this.methodDeclared = new LinkedList(); for (VarObject f : clz.fields) { this.fields.put(f.name, f); } this.clazz = clz; visit(clazz); if (clazz.interfaces.size() > 0) { for (ObjectType itfNode : clazz.interfaces) { if (itfNode == null) { continue; } List<MethodDescriptor> unImps = AstUtil.getUnimplementedMethod(clazz, itfNode); if (unImps.size() > 0) { err.notImplementedMethods(clazz, itfNode, unImps); } } } } @Override public Type visit(AstNode node) { if(node==null) return null; if (node instanceof Statement && returned) { err.fail("unable to reach statement", SemanticError.LACKS_OF_STATEMENT, node); return null; } if(node instanceof Annotationable){ validateAnnotation(((Annotationable)node).getAnnotations()); } if(node instanceof VarExpr){ if(!assignedVars.exist(((VarExpr)node).getVar(), true)){ err.fail(node.toString() + " is uninitialized!", 0, node); } } Object ret = super.visit(node); if (ret instanceof Type) { return (Type) ret; }else if(node instanceof ExprNode){ return ((ExprNode)node).getType(); } return null; } @Override public Type visitCastExpr(CastExpr node) { Type et = visit(node.getExpr()); // if(!node.getToType().isSubTypeOf(et) // && !node.getToType().equals(et) // err.failedToCast(node, et.getName(), node.getToType().getName()); return null; } @Override public Type visitAssignExpr(AssignExpr node) { AssignableExpr to = node.getTo(); ExprNode from = node.getFrom(); visit(from); if(to instanceof VarExpr){ assignedVars.put(((VarExpr)to).getVar(), null); } Type ft = from.getType(); Type tt = to.getType(); if(!requireNoneVoid(ft, node)) return getDefaultType(); if(!requireNoneVoid(tt, node)) return getDefaultType(); if(!ft.equals(tt)){ from = checkAssign(from, ft, tt, node); if(from==null) return getDefaultType(); node.setFrom(from); } return tt; } @Nullable public static PrimitiveType getPrimitiveType(Type t){ if(t instanceof PrimitiveType){ return (PrimitiveType) t; }else if(t instanceof ObjectType){ return Types.getPrimitiveType((ObjectType)t); }else{ return null; } } public static PrimitiveType getMathType(Type t1, Type t2, String op) { PrimitiveType pt1= getPrimitiveType(t1); PrimitiveType pt2 = getPrimitiveType(t2); if(pt1==null){ throw new IllegalArgumentException(t1.getName()); } if(pt2==null) throw new IllegalArgumentException(t2.getName()); String ret = MathType.getType(pt1.getName(), pt2.getName(), op); return Types.getPrimitiveType(ret); } @Override public Type visitBinaryExpr(BinaryExpr node) { Type t1 = visit(node.getExpr1()); Type t2 = visit(node.getExpr2()); String op = node.getOperation(); Type t; switch (op) { case "==": case "!=": if (Types.isNumber(t1)) { if (!Types.isNumber(t2)) { err.failedToCast(node, t2.getName(), Types.getIntClassType().getName()); return getDefaultType(); } } else { //TODO pass anything.may be Object needed? } t = Types.BOOLEAN_TYPE; break; case "+": if(isNumber(t1) && isNumber(t2)){ t = getMathType(t1, t2, op); }else{ node.setExpr1(checkAssign(node.getExpr1(), t1, Types.getStringClassType(), node)); node.setExpr2(checkAssign(node.getExpr2(), t2, Types.getStringClassType(), node)); t =Types.getStringClassType(); } break; case "-": case "*": case "/": case "%": if(!requireNumber(node, t1)) return getDefaultType(); if(!requireNumber(node, t2)) return getDefaultType(); t = (getMathType(t1, t2, op)); break; case ">=": case "<=": case ">": case "<": if(!requireNumber(node, t1)) return getDefaultType(); if(!requireNumber(node, t2)) return getDefaultType(); t = Types.BOOLEAN_TYPE; break; case "&&": case "||": if(!requireBoolean(node, t1)) return getDefaultType(); if(!requireBoolean(node, t2)) return getDefaultType(); t = Types.BOOLEAN_TYPE; break; case "&": case "|": case "^": case BinaryExpr.OP_SHIFT_LEFT: case BinaryExpr.OP_SHIFT_RIGHT: if(!requireNumber(node, t1)) return getDefaultType(); if(!requireNumber(node, t2)) return getDefaultType(); t = getPrimitiveType(Types.getHigherType(t1, t2)); break; default: err.fail("unsupport operation:" + op, SemanticError.UNSUPPORTED, node); return getDefaultType(); } return t; } @Override public Type visitElementExpr(ElementExpr node) { super.visitElementExpr(node); requireArray(node, node.getArrayExpr().getType()); return null; } // @Override // public Type visitFieldExpr(FieldExpr node) { // super.visitFieldExpr(node); // if (isStatic(method.modifier)) { // FieldNode field = node.getField(); // requireStatic(field.modifier, node); // return null; @Override public Type visitInvocationExpr(InvocationExpr node) { super.visitInvocationExpr(node); ExecutableDescriptor invokeMethod = node.getMethod(); // boolean inStaticMethod = Modifier.isStatic(node.getMethod().modifier) && Modifier.isStatic(this.method.modifier); // if (inStaticMethod) { // if(!requireStatic(invokeMethod.modifier, node)) return getDefaultType(); for(Type et:invokeMethod.getExceptionTypes()){ this.exceptionStack.peek().put(et,node); } return node.getType(); } @Override public Type visitUnaryExpr(UnaryExpr node) { super.visitUnaryExpr(node); String op = node.getOperation(); Type et = node.getExpr().getType(); switch(op){ case UnaryExpr.OPERATION_LOGIC_NOT: requireBoolean(node, et); break; case UnaryExpr.OPERATION_NEG: case UnaryExpr.OPERATION_POS: case UnaryExpr.OPERATION_NOT: requireNumber(node, et); } return et; } private void caughException(Type type) { Map<Type, AstNode> exceptions = this.exceptionStack.peek(); Type[] exTypes = exceptions.keySet().toArray(new Type[0]); for (Type e : exTypes) { if ( e.equals(type) || ((ObjectType)e).isSubTypeOf(type) ) { exceptions.remove(e); } } } @Override public Type visitTryStmt(TryStmt node) { this.exceptionStack.add(new HashMap<>()); List<VarTable<LocalVarNode,Void>> assignedList = new ArrayList(node.getCatchStmts().size()+1); enterNewFrame(); assignedList.add(assignedVars); visit(node.getExecStmt()); exitFrame(); boolean tryReturned = this.returned; for(CatchBlock cs:node.getCatchStmts()){ this.returned = false; enterNewFrame(); assignedList.add(assignedVars); visit(cs); exitFrame(); tryReturned = tryReturned && this.returned; } addIntersectedAssignedVar(assignedList.toArray(new VarTable[assignedList.size()])); Map<Type, AstNode> uncaught = this.exceptionStack.pop(); if (uncaught.size() > 0) { this.exceptionStack.peek().putAll(uncaught); } returned = false; Statement finallyStmt = node.getFinallyStmt(); if(finallyStmt!=null){ visit(finallyStmt); } this.returned = tryReturned || returned; return null; } @Override public Type visitCatchBlock(CatchBlock node) { this.caughException(node.catchVar.type); return super.visitCatchBlock(node); } @Override public Type visitIfStmt(IfStmt node) { requireBoolean(node.getConditionExpr()); VarTable<LocalVarNode, Void> trueAssignedVars=null,falseAssignedVars =null; if (node.getTrueBody() != null) { enterNewFrame(); trueAssignedVars = assignedVars; visit(node.getTrueBody()); exitFrame(); } boolean returnedOld = returned; returned = false; if (node.getFalseBody() != null) { enterNewFrame(); falseAssignedVars = assignedVars; visit(node.getFalseBody()); exitFrame(); } else { returned = false; } returned = returnedOld && returned; if(trueAssignedVars!=null && falseAssignedVars!=null){ addIntersectedAssignedVar(trueAssignedVars,falseAssignedVars); } return null; } @Override public Type visitLoopStmt(LoopStmt node) { if (node.preConditionExpr != null) { requireBoolean(node.preConditionExpr); } if (node.loopBody != null) { enterNewFrame(); visit(node.loopBody); exitFrame(); } if (node.postConditionExpr != null) { requireBoolean(node.postConditionExpr); } return null; } @Override public Type visitMethodNode(MethodNode node) { method = node; returned = false; this.exceptionStack.push(new HashMap<>()); super.visitMethodNode(node); if (method.exceptionTypes != null) { for (Type e : method.exceptionTypes) { this.caughException(e); } } Map<Type, AstNode> uncaught = this.exceptionStack.pop(); for(Type k:uncaught.keySet()){ err.uncaughtException(uncaught.get(k),k.getName()); } boolean needReturn = ( node.type != null && !node.type.equals(Types.VOID_TYPE) ); if (node.body != null && needReturn && !returned) { err.fail("Missing return statement in method:" + MethodUtil.toString(node), SemanticError.LACKS_OF_STATEMENT, node); } return null; } @Override public Type visitReturnStmt(ReturnStmt node) { Type retType = method.type; if (node.expr == null) { if(!retType.equals(Types.VOID_TYPE)){ err.fail("expression expected", 0, node); } }else{ Type exType = visit(node.expr); node.expr = this.checkAssign(node.expr, exType, retType, node); } returned = true; return null; } boolean requireNumber(AstNode node, Type t) { if (!isNumber(t)) { err.failedToCast(node, t.getName(),Types.getIntClassType().getName() ); return false; } return true; } boolean requireBoolean(ExprNode node) { visit(node); return requireBoolean(node, node.getType()); } boolean requireBoolean(AstNode node, Type t) { if (!Types.isBoolean(t)) { err.failedToCast(node, t.getName(), Types.getBooleanClassType().getName()); return false; } return true; } boolean isArray(Type t) { return t instanceof ArrayType; } boolean requireArray(AstNode node, Type t) { if (!isArray(t)) { err.failedToCast(node, t.getName(), "array"); return false; } return true; } public boolean isStatic(int modifier) { return AstUtil.isStatic(modifier); } boolean requireStatic(Integer modifier, AstNode node) { boolean isStatic = isStatic(modifier); if (!isStatic) { err.fail("couldn't refer non-static member in static context", SemanticError.UNSUPPORTED, node); return false; } return true; } boolean requireNoneVoid(Type type, AstNode node) { if (type == null || type == Types.VOID_TYPE || type == Types.getVoidClassType() ){ err.unsupported("use void type as value", node); return false; } return true; } private boolean isNumber(Type t1) { return Types.isNumber(t1); } public AstLoader getAstLoader() { return astLoader; } @Override public Type visitThrowStmt(ThrowStmt node) { Type ret = super.visitThrowStmt(node); returned = true; return ret; } @Override public Type visitUnknownInvocationExpr(UnknownInvocationExpr node) { String type = ""; AstNode target = node.getTarget(); if(target instanceof ExprNode){ type =((ExprNode) target).getType().getName(); }else if(target instanceof ClassReference){ type = ((ClassReference)target).getReferencedClassNode().name; } err.methodNotFound(node,type,node.getMethodName(),AstUtil.getExprTypes(node.getArguments())); return getDefaultType(); } @Override public Type visitUnknownFieldExpr(UnknownFieldExpr node) { err.fieldNotFound(node, node.getFieldName()); return getDefaultType(); } @Override public Type visitErrorousExpr(ErrorousExpr node) { err.fail("not an expression",0, node); return null; } protected void validateAnnotation(AnnotationNode[] annotation){ for(AnnotationNode an:annotation) validateAnnotation(an); } protected void validateAnnotation(AnnotationNode annotation){ MethodNode[] mds = annotation.getAnnotationType().getDeclaredMethodNodes(); Set<String> attrKeys = annotation.values.keySet(); List<String> missingValues = new LinkedList<>(); for(MethodNode m:mds){ String name = m.name; if(!attrKeys.contains(name)){ missingValues.add(name); } } if(missingValues.size()>0){ err.fail("Missing attribute for annotation:" + missingValues.toString(), -1, clazz); } } protected void enterNewFrame(){ assignedVars = new VarTable<>(assignedVars); } protected void exitFrame(){ assignedVars = assignedVars.getParent(); } protected void addIntersectedAssignedVar(VarTable<LocalVarNode,Void>... assignedVarsList){ Set<LocalVarNode>[] assigned = new Set[assignedVarsList.length]; for(int i=0;i<assigned.length;i++){ assigned[i] = assignedVarsList[i].keySet(); } Set<LocalVarNode> sets = CollectionsUtil.getIntersection(assigned); for(LocalVarNode s:sets){ assignedVars.put(s, null); } } }
package pacman.graphique.model; import java.awt.event.KeyEvent; import pacman.graphique.engine.Cmd; import pacman.graphique.engine.GameController; /** * @author Horatiu Cirstea, Vincent Thomas * * controleur de type KeyListener * */ public class PacmanController implements GameController { /** * commande en cours */ private Cmd commandeEnCours; /** * construction du controleur par defaut le controleur n'a pas de commande */ public PacmanController() { this.commandeEnCours = Cmd.IDLE; } /** * quand on demande les commandes, le controleur retourne la commande en * cours * * @return commande faite par le joueur */ public Cmd getCommand() { return this.commandeEnCours; } @Override /** * met a jour les commandes en fonctions des touches appuyees */ public void keyPressed(KeyEvent e) { switch (e.getKeyChar()) { case 'q': this.commandeEnCours = Cmd.LEFT; break; case 'd': this.commandeEnCours = Cmd.RIGHT; break; case 's': this.commandeEnCours = Cmd.DOWN; break; case 'z': this.commandeEnCours = Cmd.UP; default: this.commandeEnCours = Cmd.IDLE; } } @Override /** * met a jour les commandes quand le joueur relache une touche */ public void keyReleased(KeyEvent e) { this.commandeEnCours = Cmd.IDLE; } @Override /** * ne fait rien */ public void keyTyped(KeyEvent e) { } }
package mcjty.immcraft.proxy; import mcjty.immcraft.ImmersiveCraft; import mcjty.immcraft.blocks.ModBlocks; import mcjty.immcraft.config.ConfigSetup; import mcjty.immcraft.events.ForgeEventHandlers; import mcjty.immcraft.items.ModItems; import mcjty.immcraft.network.ImmCraftPacketHandler; import mcjty.immcraft.worldgen.WorldGen; import mcjty.lib.network.PacketHandler; import mcjty.lib.proxy.AbstractCommonProxy; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; public class CommonProxy extends AbstractCommonProxy { @Override public void preInit(FMLPreInitializationEvent e) { super.preInit(e); MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers()); SimpleNetworkWrapper network = PacketHandler.registerMessages(ImmersiveCraft.MODID, "immcraft"); ImmCraftPacketHandler.registerMessages(network); ConfigSetup.preInit(e); ModBlocks.init(); ModItems.init(); WorldGen.init(); } @Override public void init(FMLInitializationEvent e) { super.init(e); NetworkRegistry.INSTANCE.registerGuiHandler(ImmersiveCraft.instance, new GuiProxy()); } @Override public void postInit(FMLPostInitializationEvent e) { super.postInit(e); ConfigSetup.postInit(); } }
package net.alpenblock.bungeeperms; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Mysql { public static void closeResultSet(AutoCloseable res) { if (res == null) { return; } try { res.close(); } catch (Exception e) { } } private final Config config; private final Debug debug; private final String configsection; private Connection connection; public Mysql(Config c, Debug d, String configsection) { config = c; debug = d; this.configsection = configsection; } public void connect() { try { //URL zusammenbasteln String url = "jdbc:mysql://" + config.getString(configsection + ".general.mysqlhost", "localhost") + ":" + config.getString(configsection + ".general.mysqlport", "3306") + "/" + config.getString(configsection + ".general.mysqldb", configsection) + "?autoReconnect=true&dontTrackOpenResources=true"; this.connection = DriverManager.getConnection(url, config.getString(configsection + ".general.mysqluser", configsection), config.getString(configsection + ".general.mysqlpw", "password")); } catch (Exception e) { debug.log(e); } } public void close() { if (this.connection != null) { try { if (isConnected()) { this.connection.close(); } } catch (Exception e) { debug.log(e); } } } public boolean isConnected() { boolean connected = false; ResultSet rs = null; try { rs = this.returnQuery("SELECT 1;", false); if (rs == null) { connected = false; } else if (rs.next()) { connected = true; } } catch (Exception e) { connected = false; } finally { closeResultSet(rs); } return connected; } public ResultSet returnQuery(String query) { return returnQuery(query, true); } public boolean runQuery(String query) { return runQuery(query, true); } public long runQueryGetId(String query) { return runQueryGetId(query, true); } public boolean tableExists(String table) { boolean tableexists = false; ResultSet res = null; try { res = this.returnQuery("SHOW TABLES"); while (res.next()) { if (res.getString(1).equalsIgnoreCase(table)) { tableexists = true; break; } } } catch (Exception e) { debug.log(e); } finally { Mysql.closeResultSet(res); } return tableexists; } public boolean addColumn(String table, String column, String type, String after, String value) { boolean success = false; ResultSet res = null; try { String getc = "SHOW COLUMNS FROM " + table; res = returnQuery(getc); boolean found = false; while (res.next()) { if (res.getString("Field").equalsIgnoreCase(column)) { found = true; break; } } if (!found) { String c = "ALTER TABLE `" + table + "` ADD COLUMN `" + column + "` " + type + " AFTER `" + after + "`"; runQuery(c); c = "UPDATE " + table + " SET " + column + "=" + value; runQuery(c); } success = true; } catch (Exception e) { debug.log(e); success = false; } finally { Mysql.closeResultSet(res); } return success; } public int columnExists(String table, String column) { //0: error //1: coulumn found //2: cloumn not found int fsuccess = 2; ResultSet res = null; try { String getc = "SHOW COLUMNS FROM " + table; res = returnQuery(getc); while (res.next()) { if (res.getString("Field").equalsIgnoreCase(column)) { fsuccess = 1; } } } catch (Exception e) { debug.log(e); fsuccess = 0; } finally { closeResultSet(res); } return fsuccess; } private ResultSet returnQuery(String query, boolean checkconnection) { Statement stmt = null; ResultSet rs = null; try { if (checkconnection) { checkConnection(); } stmt = this.connection.createStatement(); rs = stmt.executeQuery(query); } catch (SQLException e) { closeResultSet(rs); closeResultSet(stmt); throw new RuntimeException(e); } finally { try { //stmt.closeOnCompletion(); } catch (Exception e) { } } return rs; } private boolean runQuery(String query, boolean checkconnection) { try { if (checkconnection) { checkConnection(); } boolean success; try (Statement stmt = this.connection.createStatement()) { success = stmt.execute(query); } return success; } catch (Exception e) { throw new RuntimeException(e); } } private long runQueryGetId(String query, boolean checkconnection) { long id = 0; Statement stmt = null; ResultSet rs = null; try { if (checkconnection) { checkConnection(); } stmt = this.connection.createStatement(); stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); if (rs.last()) { id = rs.getLong(1); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeResultSet(rs); closeResultSet(stmt); } return id; } private void checkConnection() { if (!isConnected()) { reconnect(); } } private void reconnect() { close(); connect(); } public static String escape(String s) { if (s == null) { return null; } String ret = s; ret = ret.replaceAll("\\\\", "\\\\\\\\"); ret = ret.replaceAll("\\n", "\\\\n"); ret = ret.replaceAll("\\r", "\\\\r"); ret = ret.replaceAll("\\t", "\\\\t"); ret = ret.replaceAll("\\00", "\\\\0"); ret = ret.replaceAll("'", "\\\\'"); ret = ret.replaceAll("\\\"", "\\\\\""); return ret; } public static String unescape(String s) { if (s == null) { return null; } String ret = s; ret = ret.replaceAll("\\\\n", "\\n"); ret = ret.replaceAll("\\\\r", "\\r"); ret = ret.replaceAll("\\\\t", "\\t"); ret = ret.replaceAll("\\\\0", "\\00"); ret = ret.replaceAll("\\\\'", "'"); ret = ret.replaceAll("\\\\\"", "\\\""); ret = ret.replaceAll("\\\\\\\\", "\\\\"); return ret; } }
package net.imagej.legacy; import org.scijava.command.Interactive; import org.scijava.menu.MenuConstants; import org.scijava.options.OptionsPlugin; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.welcome.WelcomeService; import org.scijava.widget.Button; /** * Allows the setting and persisting of options relevant to ImageJ2, in ImageJ1. * Not displayed in the IJ2 UI. * * @author Mark Hiner */ @Plugin(type = OptionsPlugin.class, visible = false, label = "ImageJ2 Options", menu = { @Menu(label = MenuConstants.EDIT_LABEL, weight = MenuConstants.EDIT_WEIGHT, mnemonic = MenuConstants.EDIT_MNEMONIC), @Menu(label = "Options"), @Menu(label = "ImageJ2") }) public class ImageJ2Options extends OptionsPlugin implements Interactive { // Constants for field lookup public static final String USE_SCIFIO = "useSCIFIO"; // Fields /** * If true, SCIFIO will be used during {@code File > Open} IJ1 calls. */ @Parameter(label = "Use SCIFIO when opening files", callback = "run") private Boolean useSCIFIO = true; @Parameter(label = "What is ImageJ2?", persist = false, callback = "help") private Button help; @Parameter private DefaultLegacyService legacyService; @Parameter(required = false) private WelcomeService welcomeService; // -- Option accessors -- public Boolean isUseSCIFIO() { return useSCIFIO; } @SuppressWarnings("unused") private void help() { if (welcomeService != null) { welcomeService.displayWelcome(); } } }
package net.imglib2.meta; /** * A Euclidean space whose dimensions have units and calibrations. * * @author Curtis Rueden * @see CalibratedAxis */ public interface CalibratedSpace<A extends CalibratedAxis> extends TypedSpace<A> { /** * @deprecated Use {@code axis(d).unit()} instead. * @see CalibratedAxis#unit() */ @Deprecated String unit(int d); /** * @deprecated Use {@code axis(d).setUnit(unit)} instead. * @see CalibratedAxis#setUnit(String) */ @Deprecated void setUnit(String unit, int d); }
package net.intelie.disq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PersistentQueue<T> implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PersistentQueue.class); private static final long MAX_WAIT = 10_000_000_000L; private final ObjectPool<Slot> pool; private final ArrayRawQueue fallback; private final RawQueue queue; private final SerializerFactory<T> serializerFactory; private final int initialBufferCapacity; private final int maxBufferCapacity; private final Lock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); private boolean popPaused, pushPaused; public PersistentQueue(RawQueue queue, SerializerFactory<T> serializer, int initialBufferCapacity, int maxBufferCapacity) { this(queue, serializer, initialBufferCapacity, maxBufferCapacity, 0); } public PersistentQueue(RawQueue queue, SerializerFactory<T> serializer, int initialBufferCapacity, int maxBufferCapacity, int fallbackBufferCapacity) { this.fallback = new ArrayRawQueue(fallbackBufferCapacity, true); this.queue = queue; this.serializerFactory = serializer; this.initialBufferCapacity = initialBufferCapacity; this.maxBufferCapacity = maxBufferCapacity; this.pool = new ObjectPool<>(Slot::new); } public RawQueue rawQueue() { return queue; } public ArrayRawQueue fallbackQueue() { return fallback; } public void setPopPaused(boolean popPaused) { lock.lock(); try { this.popPaused = popPaused; this.notFull.signalAll(); this.notEmpty.signalAll(); } finally { lock.unlock(); } } public void setPushPaused(boolean pushPaused) { lock.lock(); try { this.pushPaused = pushPaused; this.notFull.signalAll(); this.notEmpty.signalAll(); } finally { lock.unlock(); } } public void reopen() throws IOException { queue.reopen(); fallback.reopen(); } public long bytes() { return queue.bytes() + fallback.bytes(); } public long count() { return queue.count() + fallback.count(); } public long remainingBytes() { return queue.remainingBytes(); } public long remainingCount() { return queue.remainingCount(); } public void clear() throws IOException { queue.clear(); fallback.clear(); } public void flush() throws IOException { queue.flush(); fallback.flush(); } public T blockingPop(long amount, TimeUnit unit) throws InterruptedException, IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); lock.lockInterruptibly(); try { long target = System.nanoTime() + unit.toNanos(amount); while (!notifyingPop(slot.buffer)) { long wait = Math.min(MAX_WAIT, target - System.nanoTime()); if (wait <= 0) return null; notEmpty.awaitNanos(wait); } } finally { lock.unlock(); } return safeDeserialize(slot.buffer, slot.serializer); } } public T blockingPop() throws InterruptedException, IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); lock.lockInterruptibly(); try { while (!notifyingPop(slot.buffer)) notEmpty.awaitNanos(MAX_WAIT); } finally { lock.unlock(); } return safeDeserialize(slot.buffer, slot.serializer); } } public boolean blockingPush(T obj, long amount, TimeUnit unit) throws InterruptedException, IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); serialize(obj, slot.buffer, slot.serializer); lock.lockInterruptibly(); try { long target = System.nanoTime() + unit.toNanos(amount); while (!notifyingPush(slot.buffer)) { long wait = Math.min(MAX_WAIT, target - System.nanoTime()); if (wait <= 0) return false; notFull.awaitNanos(wait); } } finally { lock.unlock(); } return true; } } public boolean blockingPush(T obj) throws InterruptedException, IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); serialize(obj, slot.buffer, slot.serializer); lock.lockInterruptibly(); try { while (!notifyingPush(slot.buffer)) notFull.awaitNanos(MAX_WAIT); } finally { lock.unlock(); } return true; } } public T pop() throws IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); lock.lock(); try { if (!notifyingPop(slot.buffer)) return null; } finally { lock.unlock(); } return safeDeserialize(slot.buffer, slot.serializer); } } private T safeDeserialize(Buffer buffer, Serializer<T> serializer) throws IOException { try { return serializer.deserialize(buffer); } catch (Throwable e) { queue.notifyFailedRead(); throw e; } } public boolean push(T obj) throws IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); serialize(obj, slot.buffer, slot.serializer); lock.lock(); try { if (!notifyingPush(slot.buffer)) return false; } finally { lock.unlock(); } return true; } } private boolean notifyingPop(Buffer buffer) { if (popPaused) return false; if (!innerPop(buffer)) return false; else { notFull.signalAll(); return true; } } private boolean notifyingPush(Buffer buffer) { if (pushPaused) return false; if (!innerPush(buffer)) return false; else { notEmpty.signal(); return true; } } private void serialize(T obj, Buffer buffer, Serializer<T> serializer) throws IOException { if (obj == null) throw new NullPointerException("Null elements not allowed in persistent queue."); buffer.setCount(0, false); serializer.serialize(buffer, obj); } public T peek() throws IOException { try (ObjectPool<Slot>.Ref ref = pool.acquire()) { Slot slot = ref.obj(); if (!innerPeek(slot.buffer)) return null; return safeDeserialize(slot.buffer, slot.serializer); } } private boolean innerPeek(Buffer buffer) { if (popPaused) return false; if (fallback.peek(buffer)) return true; try { return queue.peek(buffer); } catch (IOException e) { LOGGER.info("Error peeking", e); return false; } } private boolean innerPop(Buffer buffer) { if (fallback.pop(buffer)) return true; try { return queue.pop(buffer); } catch (IOException e) { LOGGER.info("Error popping", e); return false; } } private boolean innerPush(Buffer buffer) { try { return queue.push(buffer); } catch (IOException e) { LOGGER.info("Error pushing", e); return fallback.push(buffer); } } public void close() { queue.close(); } private class Slot { private final Buffer buffer = new Buffer(initialBufferCapacity, maxBufferCapacity); private final Serializer<T> serializer = serializerFactory.create(); } }
package net.sf.jabref.gui; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import net.sf.jabref.*; import net.sf.jabref.groups.*; import net.sf.jabref.groups.structure.AbstractGroup; import net.sf.jabref.groups.structure.AllEntriesGroup; import net.sf.jabref.gui.actions.Actions; import net.sf.jabref.gui.worker.MarkEntriesAction; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.model.entry.BibtexEntry; import net.sf.jabref.model.entry.BibtexEntryType; import net.sf.jabref.specialfields.Printed; import net.sf.jabref.specialfields.Priority; import net.sf.jabref.specialfields.Quality; import net.sf.jabref.specialfields.Rank; import net.sf.jabref.specialfields.ReadStatus; import net.sf.jabref.specialfields.Relevance; import net.sf.jabref.specialfields.SpecialField; import net.sf.jabref.specialfields.SpecialFieldValue; import net.sf.jabref.specialfields.SpecialFieldsUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class RightClickMenu extends JPopupMenu implements PopupMenuListener { private static final Log LOGGER = LogFactory.getLog(RightClickMenu.class); private final BasePanel panel; private final MetaData metaData; private final JMenu groupAddMenu = new JMenu(Localization.lang("Add to group")); private final JMenu groupRemoveMenu = new JMenu(Localization.lang("Remove from group")); private final JMenu groupMoveMenu = new JMenu(Localization.lang("Assign exclusively to group")); // JZTODO lyrics private final JMenu typeMenu = new JMenu(Localization.lang("Change entry type")); private final JMenuItem groupAdd; private final JMenuItem groupRemove; private final JCheckBoxMenuItem floatMarked = new JCheckBoxMenuItem(Localization.lang("Float marked entries"), Globals.prefs.getBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES)); public RightClickMenu(BasePanel panel_, MetaData metaData_) { panel = panel_; metaData = metaData_; // Are multiple entries selected? boolean multiple = panel.mainTable.getSelectedRowCount() > 1; // If only one entry is selected, get a reference to it for adapting the menu. BibtexEntry be = null; if (panel.mainTable.getSelectedRowCount() == 1) { be = panel.mainTable.getSelected().get(0); } addPopupMenuListener(this); add(new AbstractAction(Localization.lang("Copy"), GUIGlobals.getImage("copy")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY); } catch (Throwable ex) { LOGGER.warn("Could not execute copy", ex); } } }); add(new AbstractAction(Localization.lang("Paste"), GUIGlobals.getImage("paste")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.PASTE); } catch (Throwable ex) { LOGGER.warn("Could not execute paste", ex); } } }); add(new AbstractAction(Localization.lang("Cut"), GUIGlobals.getImage("cut")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.CUT); } catch (Throwable ex) { LOGGER.warn("Could not execute cut", ex); } } }); add(new AbstractAction(Localization.lang("Delete"), GUIGlobals.getImage("delete")) { @Override public void actionPerformed(ActionEvent e) { /*SwingUtilities.invokeLater(new Runnable () { public void run() {*/ try { panel.runCommand(Actions.DELETE); } catch (Throwable ex) { LOGGER.warn("Could not execute delete", ex); } } }); addSeparator(); add(new AbstractAction(Localization.lang("Export to clipboard")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.EXPORT_TO_CLIPBOARD); } catch (Throwable ex) { LOGGER.warn("Could not execute exportToClipboard", ex); } } }); add(new AbstractAction(Localization.lang("Send as email")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.SEND_AS_EMAIL); } catch (Throwable ex) { LOGGER.warn("Could not execute sendAsEmail", ex); } } }); addSeparator(); JMenu markSpecific = JabRefFrame.subMenu("Mark specific color"); JabRefFrame frame = panel.frame; for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) { markSpecific.add(new MarkEntriesAction(frame, i).getMenuItem()); } if (multiple) { add(new AbstractAction(Localization.lang("Mark entries"), GUIGlobals.getImage("markEntries")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute markEntries", ex); } } }); add(markSpecific); add(new AbstractAction(Localization.lang("Unmark entries"), GUIGlobals.getImage("unmarkEntries")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.UNMARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute unmarkEntries", ex); } } }); addSeparator(); } else if (be != null) { String marked = be.getField(BibtexFields.MARKED); // We have to check for "" too as the marked field may be empty if (marked == null || marked.isEmpty()) { add(new AbstractAction(Localization.lang("Mark entry"), GUIGlobals.getImage("markEntries")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute markEntries", ex); } } }); add(markSpecific); } else { add(markSpecific); add(new AbstractAction(Localization.lang("Unmark entry"), GUIGlobals.getImage("unmarkEntries")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.UNMARK_ENTRIES); } catch (Throwable ex) { LOGGER.warn("Could not execute unmarkEntries", ex); } } }); } addSeparator(); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) { if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) { JMenu rankingMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(rankingMenu, Rank.getInstance(), panel.frame); add(rankingMenu); } // TODO: multiple handling for relevance and quality-assurance // if multiple values are selected ("if (multiple)"), two options (set / clear) should be offered // if one value is selected either set or clear should be offered if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) { add(Relevance.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) { add(Quality.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) { add(Printed.getInstance().getValues().get(0).getMenuAction(panel.frame)); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) { JMenu priorityMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(priorityMenu, Priority.getInstance(), panel.frame); add(priorityMenu); } if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) { JMenu readStatusMenu = new JMenu(); RightClickMenu.populateSpecialFieldMenu(readStatusMenu, ReadStatus.getInstance(), panel.frame); add(readStatusMenu); } addSeparator(); } add(new AbstractAction(Localization.lang("Open folder"), GUIGlobals.getImage("openFolder")) { { if (!isFieldSetForSelectedEntry("file")) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_FOLDER); } catch (Throwable ex) { LOGGER.warn("Could not open folder", ex); } } }); add(new AbstractAction(Localization.lang("Open file"), GUIGlobals.getImage("openExternalFile")) { { if(!isFieldSetForSelectedEntry("file")) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_EXTERNAL_FILE); } catch (Throwable ex) { LOGGER.warn("Could not open external file", ex); } } }); add(new AbstractAction(Localization.lang("Attach file"), GUIGlobals.getImage("open")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.ADD_FILE_LINK); } catch (Throwable ex) { LOGGER.warn("Could not attach file", ex); } } }); /*add(new AbstractAction(Globals.lang("Open PDF or PS"), GUIGlobals.getImage("openFile")) { public void actionPerformed(ActionEvent e) { try { panel.runCommand("openFile"); } catch (Throwable ex) {} } });*/ add(new AbstractAction(Localization.lang("Open URL or DOI"), GUIGlobals.getImage("www")) { { if(!(isFieldSetForSelectedEntry("url") || isFieldSetForSelectedEntry("doi"))) { this.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.OPEN_URL); } catch (Throwable ex) { LOGGER.warn("Could not execute open URL", ex); } } }); add(new AbstractAction(Localization.lang("Copy BibTeX key")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY_KEY); } catch (Throwable ex) { LOGGER.warn("Could not copy BibTex key", ex); } } }); add(new AbstractAction(Localization.lang("Copy") + " \\cite{" + Localization.lang("BibTeX key") + '}') { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.COPY_CITE_KEY); } catch (Throwable ex) { LOGGER.warn("Could not copy cite key", ex); } } }); addSeparator(); populateTypeMenu(); add(typeMenu); add(new AbstractAction(Localization.lang("Plain text import")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.PLAIN_TEXT_IMPORT); } catch (Throwable ex) { LOGGER.debug("Could not import plain text", ex); } } }); add(JabRef.jrf.massSetField); add(JabRef.jrf.manageKeywords); addSeparator(); // for "add/move/remove to/from group" entries (appended here) groupAdd = new JMenuItem(new AbstractAction(Localization.lang("Add to group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.ADD_TO_GROUP); //BibtexEntry[] bes = panel.getSelectedEntries(); //JMenu groupMenu = buildGroupMenu(bes, true, false); } catch (Throwable ex) { LOGGER.debug("Could not add to group", ex); } } }); add(groupAdd); groupRemove = new JMenuItem(new AbstractAction(Localization.lang("Remove from group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.REMOVE_FROM_GROUP); } catch (Throwable ex) { LOGGER.debug("Could not remove from group", ex); } } }); add(groupRemove); JMenuItem groupMoveTo = add(new AbstractAction(Localization.lang("Move to group")) { @Override public void actionPerformed(ActionEvent e) { try { panel.runCommand(Actions.MOVE_TO_GROUP); } catch (Throwable ex) { LOGGER.debug("Could not execute move to group", ex); } } }); add(groupMoveTo); floatMarked.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Globals.prefs.putBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES, floatMarked.isSelected()); panel.mainTable.refreshSorting(); // Bad remote access } }); } /** * Remove all types from the menu. Then cycle through all available * types, and add them. */ private void populateTypeMenu() { typeMenu.removeAll(); for (String key : BibtexEntryType.getAllTypes()) { typeMenu.add(new ChangeTypeAction(BibtexEntryType.getType(key), panel)); } } /** * Remove all types from the menu. * Then cycle through all available values, and add them. */ public static void populateSpecialFieldMenu(JMenu menu, SpecialField field, JabRefFrame frame) { //menu.removeAll(); menu.setText(field.getMenuString()); menu.setIcon(field.getRepresentingIcon()); for (SpecialFieldValue val : field.getValues()) { menu.add(val.getMenuAction(frame)); } } /** * Set the dynamic contents of "Add to group ..." submenu. */ @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { BibtexEntry[] bes = panel.getSelectedEntries(); panel.storeCurrentEdit(); GroupTreeNode groups = panel.metaData().getGroups(); if (groups == null) { groupAdd.setEnabled(false); groupRemove.setEnabled(false); } else { groupAdd.setEnabled(true); groupRemove.setEnabled(true); } addSeparator(); floatMarked.setSelected(Globals.prefs.getBoolean(JabRefPreferences.FLOAT_MARKED_ENTRIES)); add(floatMarked); } private JMenu buildGroupMenu(BibtexEntry[] bes, boolean add, boolean move) { if (bes == null) { return null; } JMenu groupMenu = new JMenu(); GroupTreeNode groups = metaData.getGroups(); if (groups == null) { groupAddMenu.setEnabled(false); groupMoveMenu.setEnabled(false); groupRemoveMenu.setEnabled(false); return null; } /*groupAddMenu.setEnabled(true); groupMoveMenu.setEnabled(true); groupRemoveMenu.setEnabled(true); groupAddMenu.removeAll(); groupMoveMenu.removeAll(); groupRemoveMenu.removeAll(); add(groupAddMenu); add(groupMoveMenu); add(groupRemoveMenu); groupAddMenu.setEnabled(false); groupMoveMenu.setEnabled(false); groupRemoveMenu.setEnabled(false);*/ /*insertNodes(groupAddMenu,metaData.getGroups(),bes,true,false); insertNodes(groupMoveMenu,metaData.getGroups(),bes,true,true); insertNodes(groupRemoveMenu,metaData.getGroups(),bes,false,false);*/ insertNodes(groupMenu, metaData.getGroups(), bes, add, move); return groupMenu; } /** * @param move For add: if true, remove from previous groups */ private void insertNodes(JMenu menu, GroupTreeNode node, BibtexEntry[] selection, boolean add, boolean move) { final AbstractAction action = getAction(node, selection, add, move); if (node.getChildCount() == 0) { JMenuItem menuItem = new JMenuItem(action); setGroupFontAndIcon(menuItem, node.getGroup()); menu.add(menuItem); if (action.isEnabled()) { menu.setEnabled(true); } return; } JMenu submenu; if (node.getGroup() instanceof AllEntriesGroup) { for (int i = 0; i < node.getChildCount(); ++i) { insertNodes(menu, (GroupTreeNode) node.getChildAt(i), selection, add, move); } } else { submenu = new JMenu('[' + node.getGroup().getName() + ']'); setGroupFontAndIcon(submenu, node.getGroup()); // setEnabled(true) is done above/below if at least one menu // entry (item or submenu) is enabled submenu.setEnabled(action.isEnabled()); JMenuItem menuItem = new JMenuItem(action); setGroupFontAndIcon(menuItem, node.getGroup()); submenu.add(menuItem); submenu.add(new Separator()); for (int i = 0; i < node.getChildCount(); ++i) { insertNodes(submenu, (GroupTreeNode) node.getChildAt(i), selection, add, move); } menu.add(submenu); if (submenu.isEnabled()) { menu.setEnabled(true); } } } /** Sets the font and icon to be used, depending on the group */ private void setGroupFontAndIcon(JMenuItem menuItem, AbstractGroup group) { if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC)) { menuItem.setFont(menuItem.getFont().deriveFont(group.isDynamic() ? Font.ITALIC : Font.PLAIN)); } if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_ICONS)) { switch (group.getHierarchicalContext()) { case INCLUDING: menuItem.setIcon(GUIGlobals.getImage("groupIncluding")); break; case REFINING: menuItem.setIcon(GUIGlobals.getImage("groupRefining")); break; default: menuItem.setIcon(GUIGlobals.getImage("groupRegular")); break; } } } /** * @param move For add: if true, remove from all previous groups */ private AbstractAction getAction(GroupTreeNode node, BibtexEntry[] selection, boolean add, boolean move) { AbstractAction action = add ? new AddToGroupAction(node, move, panel) : new RemoveFromGroupAction(node, panel); AbstractGroup group = node.getGroup(); if (!move) { action.setEnabled(add ? group.supportsAdd() && !group.containsAll(selection) : group.supportsRemove() && group.containsAny(selection)); } else { action.setEnabled(group.supportsAdd()); } return action; } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { remove(groupAddMenu); remove(groupMoveMenu); remove(groupRemoveMenu); } @Override public void popupMenuCanceled(PopupMenuEvent e) { // nothing to do } private boolean isFieldSetForSelectedEntry(String fieldname) { if (panel.mainTable.getSelectedRowCount() == 1) { BibtexEntry entry = panel.mainTable.getSelected().get(0); if (entry.getAllFields().contains(fieldname)) { return true; } else { return false; } } else { return false; } } static class ChangeTypeAction extends AbstractAction { final BibtexEntryType type; final BasePanel panel; public ChangeTypeAction(BibtexEntryType type, BasePanel bp) { super(type.getName()); this.type = type; panel = bp; } @Override public void actionPerformed(ActionEvent evt) { panel.changeType(type); } } }
package net.xprova.xprova; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import net.xprova.dot.GraphDotPrinter; import net.xprova.graph.Graph; import net.xprova.netlist.GateLibrary; import net.xprova.netlist.Netlist; import net.xprova.netlistgraph.Generator; import net.xprova.netlistgraph.NetlistGraph; import net.xprova.netlistgraph.NetlistGraphDotFormatter; import net.xprova.netlistgraph.Vertex; import net.xprova.piccolo.Command; import net.xprova.piccolo.Console; import net.xprova.propertylanguage.Property; import net.xprova.propertylanguage.PropertyBuilder; import net.xprova.simulations.CodeGenerator; import net.xprova.simulations.Waveform; import net.xprova.verilogparser.VerilogParser; public class ConsoleHandler { private GateLibrary lib = null; private NetlistGraph current = null; private PrintStream out = null; private HashMap<String, FlipFlop> defsFF = null; private ArrayList<Property> assumptions = null; private ArrayList<Property> assertions = null; private TreeMap<String, NetlistGraph> designs = null; public ConsoleHandler(PrintStream ps) { out = ps; defsFF = new HashMap<String, FlipFlop>(); assumptions = new ArrayList<Property>(); assertions = new ArrayList<Property>(); designs = new TreeMap<String, NetlistGraph>(); } // Commands: //@formatter:off @Command( description = "add and manage cell libraries", help = { "Usage:", " library load <verilog_file>", " library list" } ) //@formatter:on public void library(String[] args) throws Exception { if (args.length > 0) { String cmd = args[0]; if ("load".equals(cmd) && args.length > 1) { String libFile = args[1]; ArrayList<Netlist> libMods = VerilogParser.parseFile(libFile, new GateLibrary()); lib = new GateLibrary(libMods); out.printf("Loaded %d modules from library %s\n", libMods.size(), libFile); return; } else if ("list".equals(cmd)) { if (lib == null) out.println("No library is currently loaded"); else lib.printModules(); return; } } throw new Exception("error parsing arguments of library"); } //@formatter:off @Command( aliases = { "read" }, description = "read verilog file (gate-level netlist)", help = { "Usage:", " read [-m <module>] [-b] <verilog_file>", "", "Options:", " -m <module> specify top module (first in file be default)", " -b --behavioral read behavioral design (synthesize in background using yosys)" } ) //@formatter:on public void read(String args[]) throws Exception { // parse command input Option optModule = Option.builder("m").hasArg().build(); Option optBehav = Option.builder("b").longOpt("behavioral").build(); Options options = new Options(); options.addOption(optModule); options.addOption(optBehav); CommandLineParser parser = new DefaultParser(); CommandLine line; line = parser.parse(options, args); if (line.getArgList().isEmpty()) throw new Exception("no file specified"); // use first non-empty argument as file name String verilogFile = ""; for (String str : line.getArgList()) if (!str.isEmpty()) verilogFile = str.trim(); // read verilog file if (lib == null) { throw new Exception("No library is currently loaded"); } else { if (line.hasOption("b")) { String synthFile = getTempFile("synth.v"); out.printf("Synthesizing behavioral design to %s ...\n", synthFile); (new SynthesisEngine()).synthesis(verilogFile, synthFile, out); verilogFile = synthFile; } ArrayList<Netlist> nls = VerilogParser.parseFile(verilogFile, lib); HashMap<String, Netlist> newNLs = new HashMap<String, Netlist>(); for (Netlist nl : nls) newNLs.put(nl.name, nl); String moduleName = line.getOptionValue("m", nls.get(0).name); if (!newNLs.containsKey(moduleName)) throw new Exception(String.format("Cannot find module <%s> in file <%s>", moduleName, verilogFile)); ArrayList<NetlistGraph> newDesigns = new ArrayList<NetlistGraph>(); out.printf("Reading file <%s> ...\n", verilogFile); for (Netlist nl : nls) { newDesigns.add(new NetlistGraph(nl)); out.printf("Parsed design <%s>\n", nl.name, verilogFile); } int countBefore = designs.size(); for (NetlistGraph ng : newDesigns) designs.put(ng.getName(), ng); int countAfter = designs.size(); int countNew = countAfter - countBefore; int countOverwritten = newDesigns.size() - countNew; out.printf("Successfully parsed and loaded %d new design(s) \n", newDesigns.size()); if (countOverwritten > 0) { out.printf("%d existing modules were re-read.\n", countOverwritten); } out.printf("Current design is <%s>\n", moduleName); current = designs.get(moduleName); } } //@formatter:off @Command( description = "export current design as a verilog netlist", help = { "Usage:", " write <verilog_file>", } ) //@formatter:on public void write(String args[]) throws Exception { if (args.length != 1) throw new Exception("requires one argument: filename"); String outputVerilogFile = args[0]; Generator.generateFile(current, outputVerilogFile); } //@formatter:off @Command( description = "export a graph representation of the loaded design in DOT format", help = { "Usage:", " dot [--ignore-edges e1,e2,...] [--ignore-vertices v1,v2,...]", " [--type fng] [--to flipflop] [--combine v1,v2,...]", " [--pdf] [--module-types] <output_file>", "", "Options:", " -e --ignore-edges e1,e2,... exclude edges from graph", " -v --ignore-vertices v1,v2,... exclude vertices from graph", " -o --to <flipflop> export sub-graph of flipflop and its combinational logic", " -t --type fng include (f)lip-flops, (n)ets and/or (g)ates", " -c --combine v1,v2,... combine group of vertices into a single vertex", " -p --pdf output a PDF file directly (requires DOT)", " -m --module-types label modules with types instead of instance names" } ) //@formatter:on public void dot(String[] args) throws Exception { // parse command input Option[] opts = { Option.builder("e").hasArg().longOpt("ignore-edges").build(), Option.builder("v").hasArg().longOpt("ignore-vertices").build(), Option.builder("t").longOpt("type").hasArg().build(), Option.builder("o").longOpt("to").hasArg().build(), Option.builder("c").longOpt("combine").hasArg().build(), Option.builder("p").longOpt("pdf").build(), Option.builder("m").longOpt("module-types").build(), }; Options options = new Options(); for (Option opt : opts) options.addOption(opt); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.getArgList().isEmpty()) throw new Exception("no file specified"); // use first non-empty argument as file name String outFile = ""; for (String str : line.getArgList()) if (!str.isEmpty()) outFile = str.trim(); // produce graph assertDesignLoaded(); NetlistGraph effectiveNetlist; if (line.hasOption("to")) { String vName = line.getOptionValue("to"); Vertex flop = current.getVertex(vName); if (flop == null) { throw new Exception( String.format("netlist <%s> does not contain flip-flop <%s>", current.getName(), vName)); } HashSet<Vertex> flipflops = current.getModulesByTypes(defsFF.keySet()); HashSet<Vertex> flopInputVertices = current.bfs(flop, flipflops, true); Graph<Vertex> flopGraph = current.reduce(flipflops); flopInputVertices.add(flop); flopInputVertices.addAll(flopGraph.getSources(flop)); effectiveNetlist = current.getSubGraph(flopInputVertices); } else { effectiveNetlist = current; } HashSet<Vertex> selectedVertices; if (!line.hasOption('t')) { // no type specified, include all vertex types (net, gate, // flip-flop) selectedVertices = effectiveNetlist.getVertices(); } else { // vertex types were specified String vTypes = line.getOptionValue('t'); selectedVertices = new HashSet<Vertex>(); HashSet<Vertex> flipflops = current.getModulesByTypes(defsFF.keySet()); // are flipflops are flipflops2 the same? HashSet<Vertex> gates = effectiveNetlist.getModules(); gates.removeAll(flipflops); if (vTypes.contains("n")) selectedVertices.addAll(effectiveNetlist.getNets()); if (vTypes.contains("f")) selectedVertices.addAll(flipflops); if (vTypes.contains("g")) selectedVertices.addAll(gates); } Graph<Vertex> sg = effectiveNetlist.reduce(selectedVertices); if (line.hasOption("combine")) { for (String s : line.getOptionValue("combine").split(",")) combineVertices(s, selectedVertices, effectiveNetlist, sg); } boolean useModuleTypeLabels = line.hasOption("m"); NetlistGraphDotFormatter formatter = new NetlistGraphDotFormatter(current, useModuleTypeLabels); if (line.hasOption("ignore-edges")) { formatter.setIgnoredEdges(line.getOptionValue("ignore-edges").split(",")); } if (line.hasOption("ignore-vertices")) { formatter.setIgnoredVertices(line.getOptionValue("ignore-vertices").split(",")); } if (line.hasOption("--pdf")) { String tempDotFile = getTempFile("netlist.dot"); // write temp dot file GraphDotPrinter.printGraph(tempDotFile, sg, formatter, selectedVertices); // invoke DOT String cmdDot = "dot -Tpdf " + tempDotFile + " -o " + outFile; int dotExitCode = executeProgram(cmdDot, true, true); if (dotExitCode != 0) throw new Exception("Error while attempting to convert dot file to pdf using DOT"); } else { GraphDotPrinter.printGraph(outFile, sg, formatter, selectedVertices); } } //@formatter:off @Command( aliases = { "augment"}, description = "add metastable flip-flop models and associated connections", help = { "Usage:", " augment", } ) //@formatter:on public void augment() throws Exception { if (current == null) { out.println("No design is currently loaded"); } else { Transformer t1 = new Transformer(current, defsFF); t1.transformCDC(true); } } //@formatter:off @Command( description = "manage flip-flop definitions", help = { "Usage:", " flop clear", " flop list", " flop define <module> <clk> <rst> <d>", } ) //@formatter:on public void flop(String[] args) throws Exception { String cmd = args[0]; if ("clear".equals(cmd)) { out.println("Cleared flip-flop definitions"); defsFF.clear(); return; } else if ("list".equals(cmd)) { if (defsFF.isEmpty()) { out.println("No flip-flop definitions"); } else { String strFormat = "%20s %14s %14s %14s\n"; out.print(String.format(strFormat, "Flip-flop Module", "Clock Port", "Reset Port", "Data Port")); out.print(String.format(strFormat, " for (FlipFlop f : defsFF.values()) out.print(String.format(strFormat, f.moduleName, f.clkPort, f.rstPort, f.dPort)); } return; } else if ("define".equals(cmd)) { String modName = args[1]; String clkPort = args[2]; String rstPort = args[3]; String dPort = args[4]; if (defsFF.containsKey(modName)) { throw new Exception(String.format("definition already exists for flip-flop <%s> ", modName)); } else { FlipFlop ff = new FlipFlop(modName, clkPort, rstPort, dPort); defsFF.put(modName, ff); out.printf("defined flip-flop <%s>\n", modName); return; } } throw new Exception("Unable to parse def_ff arguments"); } //@formatter:off @Command( description = "generate design reports", help = { "Usage:", " report domains", " report xpaths", } ) //@formatter:on public void report(String arg) throws Exception { if ("domains".equals(arg)) { reportClockDomains(); } else if ("xpaths".equals(arg)) { reportCrossoverPaths(); } else { out.println("Unrecognized option"); } } //@formatter:off @Command( description = "manage loaded designs", help = { "Usage:", " design list", " design current <name>", " design remove (*|<name>)" } ) //@formatter:on public void design(String args[]) throws Exception { if (args.length > 0) { String cmd = args[0]; if (cmd.equals("list")) { if (designs.size() > 0) { out.println("Loaded designs:"); for (Entry<String, NetlistGraph> e : designs.entrySet()) { String curStr = (e.getValue() == current) ? " (current)" : ""; out.printf(" * %s%s\n", e.getKey(), curStr); } return; } else { out.println("no designs are currently loaded"); return; } } else if (cmd.equals("current") && args.length > 1) { String designName = args[1]; NetlistGraph d = designs.get(designName); if (d == null) { String strE = String.format("Design <%s> not found", designName); throw new Exception(strE); } else { current = d; out.printf("Current design is <%s>\n", designName); return; } } else if (cmd.equals("remove") && args.length > 1) { String designName = args[1]; if (designName.equals("*")) { designs.clear(); current = null; out.println("Removed all designs"); return; } NetlistGraph d = designs.get(designName); if (d == null) { String strE = String.format("Design <%s> not found", designName); throw new Exception(strE); } else { designs.remove(designName); out.printf("Removed design <%s>\n", designName); if (current == d) { current = null; if (designs.size() > 0) { Entry<String, NetlistGraph> entry = designs.entrySet().iterator().next(); current = entry.getValue(); out.printf("Current design is <%s>\n", entry.getKey()); } } return; } } } throw new Exception("error parsing arguments of design"); } //@formatter:off @Command( description = "rename nets or modules", help = { "Usage:", " rename [--ignore net1,net2 ...] [--format net%d] nets", " rename [--ignore mod1,mod2 ...] [--format mod%s%d] modules", " rename [--format _%s_%d_] splitarr", "", "Options:", " -i --ignore item1,item2 ... exclude nets/modules from renaming", " -f --format %s%d ... specify renaming format (%s = module type or array name, %d = index)" } ) //@formatter:on public void rename(String args[]) throws Exception { // parse input Option optIgnore = Option.builder("i").hasArg().required(false).longOpt("ignore").build(); Option optFormat = Option.builder("f").hasArg().required(false).longOpt("format").build(); Options options = new Options(); options.addOption(optIgnore); options.addOption(optFormat); options.addOption(optIgnore); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String ignoreStr = line.getOptionValue("ignore", ""); HashSet<String> ignored = new HashSet<String>(Arrays.asList(ignoreStr.split(","))); if (args.length > 0) { // use first non-empty argument as file name String cmd = ""; for (String str : line.getArgList()) if (!str.isEmpty()) cmd = str.trim(); if ("modules".equals(cmd)) { String strFormat = line.getOptionValue("format", "%s%d"); renameModules(ignored, strFormat); return; } else if ("nets".equals(cmd)) { String strFormat = line.getOptionValue("format", "n%d"); renameNets(ignored, strFormat); return; } else if ("splitarr".equals(cmd)) { String strFormat = line.getOptionValue("format", "%s_%d_"); splitArr(strFormat); return; } } throw new Exception("error parsing arguments of rename"); } //@formatter:off @Command( description = "generate state space graph", help = { "Usage:", " space" } ) //@formatter:on public void space() throws Exception { // code: assertDesignLoaded(); final String codeGenTemplateFile = "template3.j"; final String codeGenClassName = "CodeSimulator"; NetlistGraph currentCopy = current; String javaFile = getTempFile(codeGenClassName + ".java"); String compileCmd = "javac " + javaFile; String runCodeGenCmd = String.format("java -classpath %s %s", getTempFile(""), codeGenClassName); // generate code String templateCode = loadResourceString(codeGenTemplateFile); ArrayList<Property> emptyList = new ArrayList<Property>(); ArrayList<String> lines = CodeGenerator.generate(currentCopy, emptyList, emptyList, templateCode); out.println("Saving code to " + javaFile + " ..."); PrintStream fout = new PrintStream(javaFile); for (String l : lines) fout.println(l); fout.close(); // compile using javac out.println("Compiling ..."); int compileExitCode = executeProgram(compileCmd, true, true); if (compileExitCode != 0) throw new Exception("Compilation failed"); // run code out.println("Executing compiled code ..."); // TODO: check exit code and report if failed: executeProgram(runCodeGenCmd, true, true); } //@formatter:off @Command( description = "run formal verification", help = { "Usage:", " prove [--print] [--vcd <file>] [--txt <file>] [--gtkwave]", " [--wavejson] [--signals sig1,sig2...] [--keep]", " [--onlycode] [--dfs]", "", "Options:", " -p --print print counter-example to console", " -v --vcd <file> export counter-example to vcd file", " -t --txt <file> export counter-example to plain-text file", " -g --gtkwave open counter-example using gtkwave", " -w --wavejson print counter-example in WaveJSON format", " -s --signals list of signals to include in counter-example", " -k --keep keep assertion logic in current design (debugging)", " -c --onlycode generate code but do not compile or run Java model (debugging)", " -d --dfs use DFS (required for verifying liveness properties)", } ) //@formatter:on public void prove(String args[]) throws Exception { // parse command input Option[] opts = { Option.builder("v").longOpt("vcd").hasArg().build(), Option.builder("t").longOpt("txt").hasArg().build(), Option.builder("s").longOpt("signals").hasArg().build(), Option.builder("p").longOpt("print").build(), Option.builder("w").longOpt("wavejson").build(), Option.builder("g").longOpt("gtkwave").build(), Option.builder("k").longOpt("keep").build(), Option.builder("c").longOpt("onlycode").build(), Option.builder("d").longOpt("depth").build(), }; Options options = new Options(); for (Option o : opts) options.addOption(o); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); // code: assertDesignLoaded(); boolean keepAssertionLogic = line.hasOption("k"); boolean useDepthTemplate = line.hasOption("d"); final String codeGenTemplateFile = useDepthTemplate ? "template2.j" : "template1.j"; final String codeGenClassName = "CodeSimulator"; NetlistGraph currentCopy = keepAssertionLogic ? current : new NetlistGraph(current); (new Transformer(currentCopy, defsFF)).expandDFFx(); String defaultTextFile = getTempFile("counter-example.txt"); String txtFile = line.getOptionValue("txt", defaultTextFile); String txtArg = "--txt " + txtFile; String javaFile = getTempFile(codeGenClassName + ".java"); String compileCmd = "javac " + javaFile; String runCodeGenCmd = String.format("java -Xmx6g -classpath %s %s %s", getTempFile(""), codeGenClassName, txtArg); // generate code String templateCode = loadResourceString(codeGenTemplateFile); ArrayList<String> lines = CodeGenerator.generate(currentCopy, assumptions, assertions, templateCode); out.println("Saving code to " + javaFile + " ..."); PrintStream fout = new PrintStream(javaFile); for (String l : lines) fout.println(l); fout.close(); if (line.hasOption("c")) return; // compile using javac out.println("Compiling ..."); int compileExitCode = executeProgram(compileCmd, true, true); if (compileExitCode != 0) throw new Exception("Compilation failed"); // run code out.println("Executing compiled code ..."); int genExitCode = executeProgram(runCodeGenCmd, true, true); if (genExitCode == 100) { // 100 is a special exit code for terminating successfully after // finding a counter-example boolean runGtkwave = line.hasOption("g"); boolean printToConsole = line.hasOption("p"); boolean writeVCD = line.hasOption("v"); boolean printWaveJSON = line.hasOption('w'); String defVCD = getTempFile("counter-example.vcd"); String vcdFile = line.getOptionValue("v", defVCD); boolean loadCounter = runGtkwave || printToConsole || writeVCD || printWaveJSON; if (loadCounter) { Waveform counter = new Waveform(txtFile); if (line.hasOption('s')) counter.selectSignals(line.getOptionValue('s').split(",")); if (printToConsole) counter.print(System.out); if (runGtkwave || writeVCD) counter.writeVCDFile(vcdFile, runGtkwave); if (printWaveJSON) counter.printWaveJSON(System.out); } } else if (genExitCode != 0) { throw new Exception("state space exploration failed"); } } //@formatter:off @Command( aliases = {"synth"}, description = "synthesize behavioral verilog design using yosys", help = { "Usage:", " synth <input> <output>" } ) //@formatter:on public void synth(String args[]) throws Exception { // TODO: implement the following switches // -v : verbose mode, show output of yosys // --lib myfile.lib: specify custom library for yosys String behavioralDesign = args[0]; String synthDesign = args[1]; (new SynthesisEngine()).synthesis(behavioralDesign, synthDesign, out); } //@formatter:off @Command( description = "add an assumption for formal verification", help = { "Usage:", " assume <property>", } ) //@formatter:on public void assume(String args[]) throws Exception { String pStr = String.join(" ", args); Property p = PropertyBuilder.build(pStr, getIdentifiers()); System.out.println("Assumption : " + pStr); p.print(); assumptions.add(p); } //@formatter:off @Command( aliases = {"assert"}, description = "add an assertion for formal verification", help = { "Usage:", " assert <property>", } ) //@formatter:on public void assertp(String args[]) throws Exception { String pStr = String.join(" ", args); Property p = PropertyBuilder.build(pStr, getIdentifiers()); System.out.println("Assertion : " + pStr); p.print(); assertions.add(p); } //@formatter:off @Command( description = "manage design properties", help = { "Usage:", " props list", " props clear (*|<num>)" } ) //@formatter:on public void props(String args[]) throws Exception { String cmd = args.length > 0 ? args[0] : ""; if ("list".equals(cmd)) { if (assumptions.size() + assertions.size() > 0) { out.println("Properties:"); int i = 1; for (Property p : assumptions) out.printf(" [%d] Assumption : %s\n", i++, p); for (Property p : assertions) out.printf(" [%d] Assertion : %s\n", i++, p); } else { out.println("no properties defined"); } return; } else if ("clear".equals(cmd) && args.length > 1) { if ("*".equals(args[1])) { assumptions.clear(); assertions.clear(); } else { int n = Integer.valueOf(args[1]); if (n < 1 || n > (assumptions.size() + assertions.size())) { throw new Exception("invalid property index"); } if (n > assumptions.size()) { assertions.remove(n - assumptions.size() - 1); } else { assumptions.remove(n - 1); } } return; } } //@formatter:off @Command( description = "substitute cells with designs", help = { "Usage:", " report -r", " report <cell_type>", } ) //@formatter:on public void expand(String args[]) throws Exception { String cmd = args.length > 0 ? args[0] : ""; if ("DFFx".equals(cmd)) { (new Transformer(current, defsFF)).expandDFFx(); return; } // TODO: implement -r } @Command public void depen(String file) throws Exception { HashMap<String, HashSet<String>> dependencies = VerilogParser.getDependencies(file); ArrayList<TreeSet<String>> hierarchy = DependencyTree.depen(dependencies); System.out.println("Design dependencies (bottom to top):"); for (int i = 0; i < hierarchy.size(); i++) { System.out.printf("Level %d:\n", i); for (String s : hierarchy.get(i)) System.out.println(" - " + s); } } // Internal Methods: private int executeProgram(String cmd, boolean showOutput, boolean waitFor) throws Exception { final Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String sErr = "", sOut = ""; ArrayList<String> errLines = new ArrayList<String>(); // stderr of the process must be read to prevent the process from // blocking. The read err lines are current stored in a list so that the // can be printed after stdout messages (the latter printed as they are // read) if (waitFor) while (sErr != null || sOut != null) { sErr = stdError.readLine(); sOut = stdInput.readLine(); if (sErr != null) errLines.add(sErr); if (sOut != null) System.out.println(sOut); } stdInput.close(); stdError.close(); for (String s : errLines) System.out.println(s); if (waitFor) { proc.waitFor(); return proc.exitValue(); } else { return 0; } } private void assertDesignLoaded() throws Exception { if (current == null) throw new Exception("no design is loaded"); } private void reportClockDomains() throws Exception { Transformer t1 = new Transformer(current, defsFF); HashSet<Vertex> clks = t1.getClocks(); String strFormat = "%20s %14s\n"; out.printf("Found %d clock domain(s):\n\n", clks.size()); out.print(String.format(strFormat, "Clock Domain Net", " FFs")); out.print(String.format(strFormat, " for (Vertex clk : clks) { int count = t1.getDomainFlops(clk).size(); out.print(String.format(strFormat, clk, count)); } } private void reportCrossoverPaths() { String strFormat = "%20s -> %20s"; ArrayList<String> paths = new ArrayList<String>(); HashSet<Vertex> flops = current.getModulesByTypes(defsFF.keySet()); Graph<Vertex> ffGraph = current.reduce(flops); for (Vertex src : flops) { for (Vertex dst : ffGraph.getDestinations(src)) { Vertex clk1 = current.getNet(src, defsFF.get(src.subtype).clkPort); Vertex clk2 = current.getNet(dst, defsFF.get(dst.subtype).clkPort); if (clk1 != clk2) paths.add(String.format(strFormat, src, dst)); } } Collections.sort(paths); // output out.printf("Found %d crossover paths:\n\n", paths.size()); for (String p : paths) { out.println(p); } } private void renameModules(HashSet<String> ignored, String strFormat) { // rename modules List<Vertex> sortedMods = new ArrayList<Vertex>(current.getModules()); Collections.sort(sortedMods, new Comparator<Vertex>() { @Override public int compare(Vertex arg0, Vertex arg1) { return arg0.name.compareTo(arg1.name); } }); HashMap<String, Integer> modCounts = new HashMap<String, Integer>(); for (Vertex v : sortedMods) { if (!ignored.contains(v.name)) { String lowerMod = v.subtype.toLowerCase(); Integer c = modCounts.get(lowerMod); c = (c == null) ? 1 : c + 1; v.name = String.format(strFormat, lowerMod, c); modCounts.put(lowerMod, c); } } } private void renameNets(HashSet<String> ignored, String strFormat) { // renames internal (i.e. non-port) nets // rename nets int netCount = 0; HashSet<Vertex> nonIO = current.getNets(); nonIO.removeAll(current.getIONets()); List<Vertex> nonIOList = new ArrayList<Vertex>(nonIO); Collections.sort(nonIOList, new Comparator<Vertex>() { @Override public int compare(Vertex arg0, Vertex arg1) { return arg0.name.compareTo(arg1.name); } }); for (Vertex n : nonIOList) { if (!ignored.contains(n.name)) { String jNetName = n.name; // to obtain a Java-friendly variable name, // replace all non-word chars with underscores jNetName = jNetName.replaceAll("[\\W]+", "_"); netCount += 1; String nn = strFormat; nn = nn.replace("%d", "" + netCount); nn = nn.replace("%s", "" + jNetName); n.name = nn; } } } private static String loadResourceString(String file) { Scanner s = null; String bannerFileContent; try { final InputStream stream; stream = Console.class.getClassLoader().getResourceAsStream(file); s = new Scanner(stream); bannerFileContent = s.useDelimiter("\\Z").next(); } catch (Exception e) { bannerFileContent = "<could not load internal file>\n"; } finally { if (s != null) s.close(); } return bannerFileContent; } private void splitArr(String netNameFormat) { for (Vertex v : current.getNets()) { int k1 = v.name.indexOf("["); int k2 = v.name.indexOf("]"); String name = v.name; int bit = 0; if (k1 != -1 && k2 != -1) { name = v.name.substring(0, k1); bit = Integer.valueOf(v.name.substring(k1 + 1, k2)); v.name = String.format(netNameFormat, name, bit); } } } private void combineVertices(String prefix, HashSet<Vertex> selectedVertices, NetlistGraph effectiveNetlist, Graph<Vertex> sg) throws Exception { HashSet<Vertex> grp1 = new HashSet<Vertex>(); HashSet<String> grp1_types = new HashSet<String>(); Vertex comb = null; int n = prefix.length(); for (Vertex v : selectedVertices) { String upToNCharacters = v.name.substring(0, Math.min(v.name.length(), n)); if (upToNCharacters.equals(prefix)) { grp1.add(v); grp1_types.add(v.subtype); comb = v; } } if (!grp1.isEmpty()) { grp1.remove(comb); selectedVertices.removeAll(grp1); comb.name = prefix; if (grp1_types.size() > 1) { comb.subtype = "BLOCK"; } sg.combineVertices(comb, grp1); } } private String getTempFile(String filename) { // returns absolute path of file with name `filename` in a temp // directory File tempDir = new File(System.getProperty("java.io.tmpdir")); File temp = new File(tempDir, filename); return temp.getAbsolutePath(); } private Map<String, Integer> getIdentifiers() throws Exception { assertDesignLoaded(); HashMap<String, Integer> result = new HashMap<String, Integer>(); for (Vertex n : current.getNets()) { String arrName = n.arraySize > 0 ? n.arrayName : n.name; result.put(arrName, n.arraySize); } return result; } }
package nl.han.ica.ap.nlp.export; import java.util.ArrayList; import java.util.TreeMap; import nl.han.ica.ap.nlp.model.Class; public interface IExport { /** * Exports NLP model to other format. * @param classes List of classes. * @return path of exported file or empty string if error. */ String export(ArrayList<Class> classes); }
package no.geonorge.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.time.LocalDate; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriInfo; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.query.SelectQuery; import org.apache.commons.io.FilenameUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.rometools.rome.feed.synd.SyndCategory; import com.rometools.rome.feed.synd.SyndCategoryImpl; import com.rometools.rome.feed.synd.SyndContent; import com.rometools.rome.feed.synd.SyndContentImpl; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.feed.synd.SyndFeedImpl; import com.rometools.rome.feed.synd.SyndLink; import com.rometools.rome.feed.synd.SyndLinkImpl; import com.rometools.rome.io.FeedException; import com.rometools.rome.io.SyndFeedOutput; import com.vividsolutions.jts.geom.Geometry; import no.geonorge.nedlasting.config.Config; import no.geonorge.nedlasting.data.Dataset; import no.geonorge.nedlasting.data.DatasetFile; import no.geonorge.nedlasting.data.DownloadItem; import no.geonorge.nedlasting.data.DownloadOrder; import no.geonorge.nedlasting.data.client.Area; import no.geonorge.nedlasting.data.client.CanDownloadRequest; import no.geonorge.nedlasting.data.client.CanDownloadResponse; import no.geonorge.nedlasting.data.client.Capabilities; import no.geonorge.nedlasting.data.client.DownloadErrorResponse; import no.geonorge.nedlasting.data.client.File; import no.geonorge.nedlasting.data.client.Format; import no.geonorge.nedlasting.data.client.Order; import no.geonorge.nedlasting.data.client.OrderArea; import no.geonorge.nedlasting.data.client.OrderLine; import no.geonorge.nedlasting.data.client.Projection; import no.geonorge.nedlasting.external.CodelistRegistry; import no.geonorge.nedlasting.external.External; import no.geonorge.nedlasting.external.data.RegisterItem; import no.geonorge.nedlasting.security.FileProxyURLGenerator; import no.geonorge.nedlasting.utils.GeometryUtils; import no.geonorge.nedlasting.utils.GsonCreator; import no.geonorge.nedlasting.utils.IOUtils; @Path("api") public class DownloadService { @Context UriInfo uri; private static final Logger log = Logger.getLogger(DownloadService.class.getName()); private String getUrlPrefix() { if (uri == null) { return ""; } return uri.getBaseUri().toString() + "api/"; } private boolean isPretty() { if (uri == null) { return false; } if (!uri.getQueryParameters().containsKey("pretty")) { return false; } return !uri.getQueryParameters().getFirst("pretty").equalsIgnoreCase(Boolean.FALSE.toString()); } private Gson gson() { GsonBuilder b = GsonCreator.builder(); if (isPretty()) { b = b.setPrettyPrinting(); } return b.create(); } @GET @Path("status") @Produces(MediaType.TEXT_PLAIN) public Response returnStatus() throws IOException { try { ObjectContext ctxt = Config.getObjectContext(); SelectQuery query = new SelectQuery(Dataset.class); query.setFetchLimit(1); ctxt.performQuery(query); } catch (RuntimeException e) { return Response.serverError().build(); } return Response.ok("ok", MediaType.TEXT_PLAIN).build(); } @GET @Path("capabilities/{metadataUuid}") @Produces(MediaType.APPLICATION_JSON) public Response returnCapabilities(@PathParam("metadataUuid") String metadataUuid) throws IOException { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } Capabilities ct = dataset.getCapabilities(getUrlPrefix()); String json = gson().toJson(ct); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } /** * * @param metadataUuid * @return json of valid file formats of a given metadataUuid * @throws Exception */ @GET @Path("v2/codelists/format/{metadataUuid}") @Produces(MediaType.APPLICATION_JSON) public Response returnFormats(@PathParam("metadataUuid") String metadataUuid) throws IOException { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } Collection<Format> formats = dataset.getFormats(); String json = gson().toJson(formats); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } /** * * @param metadataUuid * @return json of valid areas of a given metadataUuid * @throws Exception */ @GET @Path("v2/codelists/area/{metadataUuid}") @Produces(MediaType.APPLICATION_JSON) public Response returnAreas(@PathParam("metadataUuid") String metadataUuid) throws IOException { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } List<Area> areas = dataset.getAreas(); String json = gson().toJson(areas); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } /** * * @param metadataUuid * @return json of valid projections of a given metadataUuid * @throws Exception */ @GET @Path("v2/codelists/projection/{metadataUuid}") @Produces(MediaType.APPLICATION_JSON) public Response returnProjections(@PathParam("metadataUuid") String metadataUuid) throws IOException { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } Collection<Projection> projections = dataset.getProjections(); String json = gson().toJson(projections); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } @POST @Path("v2/can-download") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String canDownload(String jsonRequest) throws IOException { log.info("can-download request: " + jsonRequest); CanDownloadRequest req = gson().fromJson(jsonRequest, CanDownloadRequest.class); ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, req.getMetadataUuid()); CanDownloadResponse canDownload = new CanDownloadResponse(); if (dataset == null) { log.info("could not find dataset"); canDownload.setCanDownload(false); canDownload.setMessage("could not find dataset"); return gson().toJson(canDownload); } // check if can select polygon if (req.hasCoordinates() && !dataset.isSupportsPolygonSelection()) { log.info("trying to select polygon, but dataset does not support it"); canDownload.setCanDownload(false); canDownload.setMessage("trying to select polygon, but dataset does not support it"); return gson().toJson(canDownload); } // check coordinates if (req.hasCoordinates() && dataset.isSupportsPolygonSelection()) { Geometry geom = null; try { geom = req.getGeometry(); if (geom == null || geom.isEmpty() || !geom.isValid()) { canDownload.setCanDownload(false); canDownload.setMessage("coordinates is not valid polygon"); return gson().toJson(canDownload); } } catch (RuntimeException e) { canDownload.setCanDownload(false); canDownload.setMessage("not able to parse coordinates. " + e.getMessage()); return gson().toJson(canDownload); } // check if selected polygon is too large if (dataset.getMaxArea() != null) { try { double selectedSquareKvm = GeometryUtils.calculateAreaSquareKilometer(geom, req.getSrid()); if (selectedSquareKvm > dataset.getMaxArea().doubleValue()) { canDownload.setCanDownload(false); canDownload.setMessage("too large area"); return gson().toJson(canDownload); } } catch (RuntimeException e) { canDownload.setCanDownload(false); canDownload.setMessage("not able to calculate area. " + e.getMessage()); return gson().toJson(canDownload); } } } canDownload.setCanDownload(true); return gson().toJson(canDownload); } /** * * @param referenceNumber * @return json of valid projections of a given metadataUuid * @throws Exception */ @GET @Path("v2/order/{referenceNumber}") @Produces(MediaType.APPLICATION_JSON) public Response getOrderInfo(@PathParam("referenceNumber") String referenceNumber) throws IOException { ObjectContext ctxt = Config.getObjectContext(); DownloadOrder order = DownloadOrder.get(ctxt, referenceNumber); if (order == null) { return Response.status(Response.Status.NOT_FOUND).build(); } String json = gson().toJson(order.getOrderReceipt(getUrlPrefix())); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } /** * * * @return String json with reference to order * @throws Exception */ @POST @Path("v2/order") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response orderDownload(String jsonRequest) throws IOException { log.info("order request: " + jsonRequest); Order order = gson().fromJson(jsonRequest, Order.class); ObjectContext ctxt = Config.getObjectContext(); DownloadOrder downloadOrder = ctxt.newObject(DownloadOrder.class); downloadOrder.setEmail(order.getEmail()); downloadOrder.setStartTime(new Date()); downloadOrder.setReferenceNumber(UUID.randomUUID().toString()); for (OrderLine orderLine : order.getOrderLines()) { List<OrderArea> areaRest = new ArrayList<>(orderLine.getAreas()); List<Format> formatRest = new ArrayList<>(orderLine.getFormats()); List<Projection> projectionRest = new ArrayList<>(orderLine.getProjections()); Dataset dataset = Dataset.forMetadataUUID(ctxt, orderLine.getMetadataUuid()); /* An order can be a combination of preproduced files and polygon from map */ for (DatasetFile datasetFile : DatasetFile.findForOrderLine(ctxt, orderLine)) { DownloadItem downloadItem = ctxt.newObject(DownloadItem.class); downloadItem.setProjection(datasetFile.getProjection()); downloadItem.setUrl(datasetFile.getUrl()); downloadItem.setFileId(datasetFile.getFileId()); downloadItem.setFileName(datasetFile.getFileName()); downloadItem.setMetadataUuid(datasetFile.getDataset().getMetadataUuid()); downloadOrder.addToItems(downloadItem); areaRest.remove(datasetFile.getOrderArea()); formatRest.remove(datasetFile.getFormat()); projectionRest.remove(datasetFile.getProjection().forClient()); } /* Remove the combinations that are already preproduced files */ if (!areaRest.isEmpty() && !formatRest.isEmpty() && !projectionRest.isEmpty() && dataset.isExternal()) { for (Format format : orderLine.getFormats()) { for (Projection projection : orderLine.getProjections()) { for (OrderArea area : orderLine.getAreas()) { if (area.isTypePolygonSelection() && orderLine.hasCoordinates()) { areaRest.remove(area); area = null; } External external = dataset.getExternal(); // TODO: Support cells (municipalities,counties,map sheets etc) enabling use of // administrative area codes in the external-API String jobId = external.submitJob(format, projection, order.getEmail(), orderLine.getCoordinates()); DownloadItem downloadItem = ctxt.newObject(DownloadItem.class); downloadItem.setSrid(projection.getSrid()); downloadItem.setFileId(UUID.randomUUID().toString()); downloadItem.setMetadataUuid(dataset.getMetadataUuid()); downloadItem.setExternalJobId(jobId); downloadItem.setCoordinates(orderLine.getCoordinates()); downloadOrder.addToItems(downloadItem); areaRest.remove(area); formatRest.remove(format); projectionRest.remove(projection); } } } } DownloadErrorResponse r = new DownloadErrorResponse(orderLine); r.setAreaRest(areaRest); r.setFormatRest(formatRest); r.setProjectionRest(projectionRest); if (r.hasRest()) { return Response.status(Response.Status.BAD_REQUEST).entity(gson().toJson(r)) .type(MediaType.APPLICATION_JSON).build(); } } ctxt.commitChanges(); String json = gson().toJson(downloadOrder.getOrderReceipt(getUrlPrefix())); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } @GET @Path("v2/download/order/{orderUuid}/{fileId}") public Response getFileForOrder(@PathParam("orderUuid") String orderUuid,@PathParam("fileId") String fileId) { ObjectContext ctxt = Config.getObjectContext(); DownloadOrder order = DownloadOrder.get(ctxt, orderUuid); if (order == null) { return Response.status(Response.Status.NOT_FOUND).build(); } try { Date orderDate = order.getOrderReceipt(getUrlPrefix()).getOrderDate(); LocalDate then = orderDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate now = LocalDate.now(); long days = ChronoUnit.DAYS.between(then, now); if (days > Config.getOrderDaysValid()) { // Fetch your file within a working week please Response.status(Response.Status.GONE).build(); } } catch (IOException ignored) { Response.status(Response.Status.NOT_FOUND).build(); } DownloadItem item = order.getItemForFileId(fileId); if (item == null) { return Response.status(Response.Status.NOT_FOUND).build(); } try { return createResponseFromRemoteFile(item.getUrl()); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } @GET @Path("fileproxy/{metadataUuid}/{fileId}") public Response getFileForDownload(@PathParam("metadataUuid") String metadataUuid,@PathParam("fileId") String fileId){ ObjectContext ctxt = Config.getObjectContext(); /* Store downloads for statistical use */ DownloadOrder downloadOrder = ctxt.newObject(DownloadOrder.class); downloadOrder.setStartTime(new Date()); downloadOrder.setReferenceNumber(UUID.randomUUID().toString()); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } DatasetFile datasetFile = dataset.getFile(fileId); if (datasetFile == null) { return Response.status(Response.Status.NOT_FOUND).build(); } try { DownloadItem downloadItem = ctxt.newObject(DownloadItem.class); downloadItem.setProjection(datasetFile.getProjection()); downloadItem.setFileId(datasetFile.getFileId()); downloadItem.setFileName(datasetFile.getFileName()); downloadItem.setMetadataUuid(dataset.getMetadataUuid()); downloadOrder.addToItems(downloadItem); ctxt.commitChanges(); return createResponseFromRemoteFile(datasetFile.getUrl()); } catch (IOException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } private Response createResponseFromRemoteFile(String urlString) throws IOException { String extension = FilenameUtils.getExtension(urlString); String baseName = FilenameUtils.getBaseName(urlString); String fileName = baseName.concat(".").concat(extension); URL url = new URL(urlString); // Check if fileType and remote host is allowed if (!Config.getAllowedFiletypes().isEmpty() && !Config.getAllowedFiletypes().contains(extension.toLowerCase())) { return Response.status(Response.Status.FORBIDDEN).build(); } if (!Config.getAllowedHosts().isEmpty() && !Config.getAllowedHosts().contains(url.getHost().toLowerCase())) { return Response.status(Response.Status.FORBIDDEN).build(); } // Return file proxied by this API HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (uc.getResponseCode() != 200) { return Response.status(Response.Status.NOT_FOUND).build(); } Client client = ClientBuilder.newClient(); final InputStream responseStream = client.target(urlString).request().get(InputStream.class); StreamingOutput output = new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { try { IOUtils.copy(responseStream, out); responseStream.close(); } catch (Exception e) { e.printStackTrace(); throw new WebApplicationException ("File not found"); } } }; return Response.ok(output,MediaType.APPLICATION_OCTET_STREAM).header( "Content-Disposition","attachment; filename=\"" + fileName + "\"").build(); } @GET @Path("internal/dataset") @Produces(MediaType.APPLICATION_JSON) public Response getDatasets() { ObjectContext ctxt = Config.getObjectContext(); List<no.geonorge.nedlasting.data.client.Dataset> datasetViews = new ArrayList<>(); for (Dataset dataset : Dataset.getAll(ctxt)) { datasetViews.add(dataset.forClientWithoutFiles()); } String json = gson().toJson(datasetViews); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } @GET @Path("internal/dataset/{metadataUuid}") @Produces(MediaType.APPLICATION_JSON) public Response getDataset(@PathParam("metadataUuid") String metadataUuid) { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } String json = gson().toJson(dataset.forClient(getUrlPrefix())); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } @PUT @Path("internal/dataset/{metadataUuid}") @Consumes(MediaType.APPLICATION_JSON) public Response putDataset(@PathParam("metadataUuid") String metadataUuid, String jsonRequest) throws IOException { no.geonorge.nedlasting.data.client.Dataset requestDataset = gson().fromJson(jsonRequest, no.geonorge.nedlasting.data.client.Dataset.class); if (requestDataset.isExternal()) { // test external configuration try { External e = External.create(requestDataset.getExternalParameters()); if (e == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (RuntimeException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } } ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { dataset = ctxt.newObject(Dataset.class); dataset.setMetadataUuid(metadataUuid); } dataset.setTitle(requestDataset.getTitle()); dataset.setMaxArea(requestDataset.getMaxArea()); if (!requestDataset.ignoreFiles()) { Set<String> restFileIds = new HashSet<>(dataset.getFileIds()); for (File file : requestDataset.getFiles()) { restFileIds.remove(file.getFileId()); DatasetFile datasetFile = dataset.getFile(file.getFileId()); if (datasetFile == null) { datasetFile = ctxt.newObject(DatasetFile.class); datasetFile.setFileId(file.getFileId()); dataset.addToFiles(datasetFile); } datasetFile.setUrl(file.getDownloadUrl()); datasetFile.setAreaCode(file.getArea()); datasetFile.setAreaName(file.getAreaName()); datasetFile.setAreaType(file.getAreaType()); datasetFile.setProjection(no.geonorge.nedlasting.data.Projection.getForSrid(ctxt, Integer.parseInt(file.getProjection()))); datasetFile.setFormatName(file.getFormat()); datasetFile.setFileName(file.getName()); datasetFile.setFileDate(file.getFileDate() == null ? new Date() : file.getFileDate()); } for (String fileId : restFileIds) { DatasetFile file = dataset.getFile(fileId); if (file != null) { ctxt.deleteObject(file); } } } if (requestDataset.isExternal()) { dataset.setExternal(requestDataset.getExternalParameters()); } else { dataset.setExternal(Collections.emptyMap()); } dataset.setSupportsAreaSelection(!dataset.getAreas().isEmpty()); dataset.setSupportsFormatSelection(!dataset.getFormats().isEmpty()); dataset.setSupportsProjectionSelection(!dataset.getProjections().isEmpty()); dataset.setSupportsPolygonSelection(dataset.isExternal()); ctxt.commitChanges(); return Response.status(Response.Status.OK).build(); } @POST @Path("internal/dataset/{metadataUuid}") @Consumes(MediaType.APPLICATION_JSON) public Response postDataset(@PathParam("metadataUuid") String metadataUuid, String jsonRequest) throws IOException { return putDataset(metadataUuid, jsonRequest); } @DELETE @Path("internal/dataset/{metadataUuid}") public Response deleteDataset(@PathParam("metadataUuid") String metadataUuid) { ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } ctxt.deleteObject(dataset); ctxt.commitChanges(); return Response.status(Response.Status.NO_CONTENT).build(); } @GET @Path("atomfeeds") public Response getAtomFeeds() { ObjectContext ctxt = Config.getObjectContext(); SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("atom_1.0"); feed.setTitle("GEONORGE DATASET ATOM FEEDS "); feed.setDescription("ATOM Feeds for Datasets"); feed.setLink(getUrlPrefix().concat("atomfeeds")); Date lastDate = null; List<SyndEntry> entries = new ArrayList<>(); for (Dataset dataset : Dataset.getAll(ctxt)) { // Do not add entry when dataset has no files if (dataset.getFiles().isEmpty()) { continue; } SyndEntry entry = new SyndEntryImpl(); entry.setTitle(dataset.getTitle()); Date lastFileDate = dataset.getLastFileDate(); if (lastFileDate != null) { entry.setPublishedDate(lastFileDate); entry.setUpdatedDate(lastFileDate); if (lastDate == null || lastDate.before(lastFileDate)) { lastDate = lastFileDate; } } SyndContent description = new SyndContentImpl(); description.setType(MediaType.TEXT_PLAIN); description.setValue("Dataset ATOM Feed"); entry.setDescription(description); List<SyndLink> links = new ArrayList<>(2); SyndLinkImpl alternateLink = new SyndLinkImpl(); alternateLink.setHref(getUrlPrefix().concat("atom/".concat(dataset.getMetadataUuid()))); alternateLink.setRel("alternate"); links.add(alternateLink); if (dataset.getMetadataUuid() != null) { SyndLinkImpl describedbyLink = new SyndLinkImpl(); describedbyLink.setHref("https: .concat(dataset.getMetadataUuid())); describedbyLink.setRel("describedby"); describedbyLink.setTitle("Dataset Metadata"); describedbyLink.setType("application/xml"); links.add(describedbyLink); } entry.setLinks(links); entries.add(entry); } feed.setEntries(entries); if (lastDate != null) { feed.setPublishedDate(lastDate); } try { String atom = new SyndFeedOutput().outputString(feed); return Response.ok(atom,MediaType.APPLICATION_ATOM_XML).build(); } catch (FeedException e) { e.printStackTrace(); return Response.serverError().build(); } } @GET @Path("atom/{metadataUuid}") public Response getAtomFeed(@PathParam("metadataUuid") String metadataUuid) { CodelistRegistry clReg = new CodelistRegistry(); List<RegisterItem> vectorFormats = clReg.getVectorFormats(); List<RegisterItem> areaCategories = clReg.getAreaCategories(); List<RegisterItem> crsCodes = clReg.getCrsCodes(); ObjectContext ctxt = Config.getObjectContext(); Dataset dataset = Dataset.forMetadataUUID(ctxt, metadataUuid); if (dataset == null) { return Response.status(Response.Status.NOT_FOUND).build(); } SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("atom_1.0"); feed.setTitle(dataset.getTitle()); feed.setDescription(dataset.getTitle() + " ATOM Feed"); feed.setLink(getUrlPrefix()+"atom/"+metadataUuid); Date lastFileDate = dataset.getLastFileDate(); if (lastFileDate != null) { feed.setPublishedDate(lastFileDate); } List<SyndEntry> entries = new ArrayList<>(); List<DatasetFile> datasetFiles = dataset.getFiles(); for (DatasetFile datasetFile:datasetFiles) { SyndEntry entry = new SyndEntryImpl(); StringBuilder sb = new StringBuilder(); sb.append(dataset.getTitle()); sb.append("-").append(datasetFile.getAreaType()); sb.append("-").append(datasetFile.getAreaName()); sb.append("-").append(datasetFile.getProjection().getName()); sb.append("-").append(datasetFile.getFormat().getName()); entry.setTitle(sb.toString()); if (datasetFile.getFileDate() != null) { entry.setPublishedDate(datasetFile.getFileDate()); entry.setUpdatedDate(datasetFile.getFileDate()); } entry.setLink(FileProxyURLGenerator.createUrl(getUrlPrefix(), datasetFile)); List<SyndCategory> categories = new ArrayList<>(); SyndCategory formatCategory = new SyndCategoryImpl(); formatCategory.setName("Format:" + datasetFile.getFormatName()); formatCategory.setTaxonomyUri("https://register.geonorge.no/api/metadata-kodelister/vektorformater.xml"); categories.add(formatCategory); SyndCategory areaCategory = new SyndCategoryImpl(); areaCategory.setName(getLabelForCode(areaCategories,datasetFile.getAreaType())); areaCategory.setLabel(datasetFile.getAreaName()); // <category term="Fylke" label="Akershus"/> areaCategory.setTaxonomyUri("https://register.geonorge.no/api/metadata-kodelister/geografisk-distribusjonsinndeling.xml"); categories.add(areaCategory); SyndCategory crsCategory = new SyndCategoryImpl(); crsCategory.setName(datasetFile.getProjection().getAuthorityAndCode()); crsCategory.setTaxonomyUri(datasetFile.getProjection().getScheme()); crsCategory.setLabel(getLabelForCode(crsCodes,datasetFile.getProjection().getSrid().toString())); categories.add(crsCategory); entry.setCategories(categories); /* <summary />*/ SyndContent description = new SyndContentImpl(); description.setType(MediaType.TEXT_PLAIN); description.setValue(dataset.getTitle().concat("-").concat(datasetFile.getFileName())); entry.setDescription(description); entries.add(entry); } feed.setEntries(entries); try { String atom = new SyndFeedOutput().outputString(feed); return Response.ok(atom,MediaType.APPLICATION_ATOM_XML).build(); } catch (FeedException e) { e.printStackTrace(); return Response.serverError().build(); } } private String getLabelForCode(List<RegisterItem> items,String code) { // areaType is not syncronized with this codelist if (code.equalsIgnoreCase("fylke")) { code = "fylkesvis"; } if (code.equalsIgnoreCase("landsdekkende")) { code = "landsfiler"; } if (code.equalsIgnoreCase("kommune")) { code = "kommunevis"; } if (code.equalsIgnoreCase("region")) { code = "regional inndeling"; } for (RegisterItem item:items) { if (item.getCodevalue() != null) { // First match on codeValues if (item.getCodevalue().equalsIgnoreCase(code)) { return item.getLabel(); } // Then try to match on partial code value if (item.getCodevalue().length() > code.length()) { if (item.getCodevalue().substring(0, code.length() - 1).equalsIgnoreCase(code)) { return item.getLabel(); } } else { if (item.getCodevalue().equalsIgnoreCase(code.substring(0,item.getCodevalue().length()-1))) { return item.getLabel(); } } } } return null; } }
package org.fiteagle.north.sfa.sa; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.math.BigInteger; import java.security.*; import java.security.cert.*; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import info.openmultinet.ontology.vocabulary.Omn; import info.openmultinet.ontology.vocabulary.Omn_lifecycle; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.*; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.cert.CertIOException; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.fiteagle.api.core.*; import org.fiteagle.north.sfa.aaa.CertificateAuthority; import org.fiteagle.north.sfa.aaa.CredentialFactory; import org.fiteagle.north.sfa.aaa.KeyStoreManagement; import org.fiteagle.north.sfa.aaa.X509Util; import org.fiteagle.north.sfa.aaa.jaxbClasses.Credential; import org.fiteagle.north.sfa.aaa.jaxbClasses.SignedCredential; import org.fiteagle.north.sfa.am.ISFA_AM; import org.fiteagle.north.sfa.am.dm.SFA_AM_MDBSender; import org.fiteagle.north.sfa.util.URN; import redstone.xmlrpc.XmlRpcArray; import redstone.xmlrpc.XmlRpcStruct; import javax.security.auth.x500.X500Principal; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; public class SFA_SA implements ISFA_SA { protected static Logger LOGGER = Logger.getLogger(SFA_SA.class.getName()); ISFA_SA_Delegate delegate; public SFA_SA() { } @Override public Object handle(final String methodName, final List<?> parameter, final String path, final X509Certificate cert) { Object result; this.delegate = null; SFA_SA.LOGGER.log(Level.INFO, "Working on method: " + methodName); try { switch (methodName.toUpperCase()) { case ISFA_AM.METHOD_GET_VERSION: result = this.getVersion(parameter); break; case ISFA_SA.METHOD_GET_CREDENTIAL: LOGGER.log(Level.SEVERE,"=======================Starting GET_CREDENTIAL"); result = this.getCredential(cert, parameter); // TODO DEBUG LINE - WILL BE DELETED if(result == null){ LOGGER.log(Level.SEVERE,"==========GET_CREDENTIAL RESULT NULL");}; break; case ISFA_SA.METHOD_REGISTER: result = this.register(parameter); break; case ISFA_SA.METHOD_RENEW_SLICE: result = this.renewSlice(parameter); break; case ISFA_SA.METHOD_RESOLVE: result = this.resolve(parameter); break; case ISFA_SA.METHOD_GET_KEYS: result = this.getKeys(parameter); break; default: result = "Unimplemented method '" + methodName + "'"; break; } }catch(CertificateParsingException e){ HashMap<String, Object> exceptionBody = new HashMap<>(); //handleException(exceptionBody, e, GENI_CodeEnum.BADARGS); LOGGER.log(Level.WARNING,e.getMessage(),e); result = exceptionBody; } catch (Exception e){ HashMap<String, Object> exceptionBody = new HashMap<>(); //handleException(exceptionBody, e, GENI_CodeEnum.BADARGS); LOGGER.log(Level.WARNING,e.getMessage(),e); result = exceptionBody; } return result; } @Override public Object getVersion(final List<?> parameter) { final Map<String, Object> result = new HashMap<>(); return result; } @Override public Object getCredential(X509Certificate userCertificate, List<?> parameter) throws Exception { HashMap<String,Object> result = new HashMap<>(); //TODO get urn from properties Config config = new Config(); URN sliceAuthorityURN = new URN("urn:publicid:IDN+"+config.getProperty(IConfig.KEY_HOSTNAME)+"+authority+SA"); KeyStoreManagement keyStoreManagement = KeyStoreManagement.getInstance(); X509Certificate sliceAuthorityCert = keyStoreManagement.getSliceAuthorityCert(); URN ownerURN = X509Util.getURN(userCertificate); Credential credential = null; if(!parameter.isEmpty()){ LOGGER.log(Level.SEVERE, "found parameter list"); String urnString = ""; Map<String, String> inputMap = (Map<String, String>) parameter.get(0); URN target = new URN(inputMap.get("urn")); LOGGER.log(Level.SEVERE, target.toString()); PrivateKey caPrivateKey = keyStoreManagement.getSAPrivateKey(); X509Certificate sliceCert = createSliceCert(sliceAuthorityCert,caPrivateKey,target); credential = CredentialFactory.newCredential(userCertificate,ownerURN ,sliceCert,target); }else { credential = CredentialFactory.newCredential(userCertificate, ownerURN, sliceAuthorityCert, sliceAuthorityURN); } String signedCredential = CredentialFactory.signCredential(credential); String output = ""; int code = 0; result.put("value",signedCredential); result.put("code",code); result.put("output",output); LOGGER.log(Level.SEVERE, signedCredential); return result; } private X509Certificate createSliceCert(X509Certificate caCert,PrivateKey caPrivateKey, URN target) throws CertificateException, OperatorCreationException, IOException { X500Name issuer = new JcaX509CertificateHolder(caCert).getSubject(); ContentSigner contentsigner = new JcaContentSignerBuilder( "SHA1WithRSAEncryption").build(caPrivateKey); X500Name subject = createX500Name(target.getSubject()); PublicKey aPublic = createSlicePublicKey(); SubjectPublicKeyInfo subjectsPublicKeyInfo = getSubjectPublicKey(aPublic); X509v3CertificateBuilder ca_gen = new X509v3CertificateBuilder(issuer, new BigInteger(new SecureRandom().generateSeed(256)), new Date(), new Date(System.currentTimeMillis() + 31500000000L), subject, subjectsPublicKeyInfo); BasicConstraints ca_constraint = new BasicConstraints(false); ca_gen.addExtension(X509Extension.basicConstraints, true, ca_constraint); GeneralNames subjectAltName = new GeneralNames(new GeneralName( GeneralName.uniformResourceIdentifier, target.toString())); X509Extension extension = new X509Extension(false, new DEROctetString( subjectAltName)); ca_gen.addExtension(X509Extension.subjectAlternativeName, false, extension.getParsedValue()); X509CertificateHolder holder = (X509CertificateHolder) ca_gen .build(contentsigner); CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(holder .getEncoded())); } private SubjectPublicKeyInfo getSubjectPublicKey(PublicKey aPublic) throws IOException { SubjectPublicKeyInfo subPubInfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Sequence.fromByteArray(aPublic.getEncoded())); return subPubInfo; } private PublicKey createSlicePublicKey() { KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair().getPublic(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } } private X500Name createX500Name(String username) { X500Principal prince = new X500Principal("CN=" + username); X500Name x500Name = new X500Name(prince.getName()); return x500Name; } @Override public Object register(List<?> parameter) throws Exception { if(parameter.size()> 1 || parameter.size() < 1){ throw new RuntimeException(); } Map<String, Object> inputMap = (Map<String, Object>) parameter.get(0); RegisterDelegate registerDelegate = new RegisterDelegate(inputMap).invoke(); X509Certificate ownerCert = registerDelegate.getOwnerCert(); URN ownerURN = registerDelegate.getOwnerURN(); X509Certificate sliceCert = registerDelegate.getSliceCert(); URN sliceURN = registerDelegate.getSliceURN(); Credential sliceCredential = CredentialFactory.newCredential(ownerCert,ownerURN, sliceCert,sliceURN); String sliceCertString = CredentialFactory.signCredential(sliceCredential); Model groupModel = createGroupModel(sliceURN, sliceCert); Model resultModel = sendGroup(groupModel); HashMap<String,Object> result = new HashMap<>(); if(resultModel != null) { String output = ""; int code = 0; result.put("output", output); result.put("code", code); result.put("value", sliceCertString); } return result; } @Override public Object renewSlice(List<?> parameter) throws JAXBException, DatatypeConfigurationException { HashMap<String,Object> result = new HashMap<>(); Map<String, String> inputMap = (Map<String, String>) parameter.get(0); String credentialString = inputMap.get("credential"); SignedCredential signedCredential = CredentialFactory.buildCredential(credentialString); URN sliceURN = new URN(signedCredential.getCredential().getTargetURN()); Credential newCredential = signedCredential.getCredential(); String expirationValue = inputMap.get("expiration"); ParsePosition parsePos = new ParsePosition(0); Date newDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse(expirationValue,parsePos); GregorianCalendar gregorianCalendar = (GregorianCalendar)GregorianCalendar.getInstance(); gregorianCalendar.setTime(newDate); XMLGregorianCalendar xmlval = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); newCredential.setExpires(xmlval); String newCredentialString = CredentialFactory.signCredential(newCredential); if(newCredentialString != null) { String output = ""; int code = 0; result.put("output", output); result.put("code", code); result.put("value", newCredentialString); } return result; } @Override public Object resolve(List<?> parameter) { LOGGER.log(Level.INFO, "Logging Resolve "); HashMap<String,Object> result = new HashMap<>(); HashMap<String,Object> value = new HashMap<>(); HashMap<String,Object> subAuth = new HashMap<>(); URN ownerURN = null; for(Object o: parameter){ LOGGER.log(Level.INFO,parameter.toString()); Object o2 = ((XmlRpcStruct)o).get("credential"); if(o2.getClass().equals(String.class)){ String credentialString = (String) o2; JAXBContext context; try { context = JAXBContext.newInstance("org.fiteagle.north.sfa.aaa.jaxbClasses"); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(credentialString); SignedCredential sc = (SignedCredential) unmarshaller.unmarshal(reader); ownerURN = new URN(sc.getCredential().getOwnerURN()); value.put("gid", sc.getCredential().getOwnerGid()); value.put("name", ownerURN.getSubject()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } String output = ""; int code = 0; result.put("output", output); result.put("code", code); subAuth.put("urn:publicid:IDN+172.20.30.13+authority+root", "https://172.20.30.13:5443/sfa/api/sa/v1"); value.put("subauthorities",subAuth ); value.put("uid","testsubject" ); value.put("hrn","testbed.test" ); value.put("urn","urn:publicid:IDN+172.20.30.13+user+alex" ); value.put("uuid","ba21afe5-97d9-11e3-883a-001517becd24" ); value.put("email","testsubject@testmail.com" ); // value.put("gid","MIIEJzCCAw+gAwIBAgKCAQBeKHoUlCUKO616nUrVrfxjM9u9+f1B5f/A85hjz/AUxo6zlKuw0E7AEgEBbgYhyMuns9qgfXS668L4QS+tMmkAdi0QcY+0kmW4XQd9bBQJmLt1iMbA64XgGooNdSkpnbgGizufbmqLSSxDwG/Bus2+vSdSoxc2SRKNEEmxOWd33YlGciy1S7Jbq/0j3Y23BdFVrYkSCV31UqudseVgfvAZ/z48CVxrhkVs1U0XdeCpPPfoSCDnXqh+C7oEzNaMKR0GCaGudKnsB6aWjZzuZ3vmtMHa653ba/1oMALKmVFcycQ08mdc2YyjpTPpXTCI/pbskKSPU/Tgz237xIBWxwx3MA0GCSqGSIb3DQEBBQUAMFsxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIDAZCZXJsaW4xDzANBgNVBAcMBkJlcmxpbjEMMAoGA1UECgwDVFVCMQswCQYDVQQLDAJBVjEPMA0GA1UEAwwGdGVzdENBMB4XDTE2MDkwNTEzNDQyNFoXDTE3MDkwNTAzNDQyNFowDzENMAsGA1UEAwwEYWxleDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK7+Ne3raihBc7faFVC3jlsiG99wnhnPSyLuzxV2zYeyaO1UOvu8SYqoh2ZWBnrdoNtmmc8DNFNpJ5tv0ktDBwDMf8MVj38FMfMPTgvZoqbk2Ifb8ef1GwZj6mgJ6KZGSWd0AKRs9fegQV7zfclu28nUlHtyievwyfNwkF38HppbZ9iyxlJJ6DWAYOz0sVKJG+pCvoOP0YMG9NRZsBkcnkdJDpQrHaQxPBgbBe/yzTrPg6DE7Vw/vbuyqDhtcyJGtQSqAbl2oIy+JwZTNpqIsMvZQNk3aW713gv9Ibsf+cZ2ZvQB5fhwTzdvMLe+WRImzYEybQ5odyHcMok8rTiqcu8CAwEAAaNBMD8wDAYDVR0TAQH/BAIwADAvBgNVHREEKDAmhiR1cm46cHVibGljaWQ6SUROK2xvY2FsaG9zdCt1c2VyK2FsZXgwDQYJKoZIhvcNAQEFBQADggEBAG4zn0Jrgg0Bk8px1F2JhmROVlj3v5MK/fxwMQRcV68ELD7Citbhc0qOh+zCh1QO9rHA4a7rEXMylPvFAu04UiPdXylSlGa/3U0wSLiBV5AXech5tM10oY/Ix9vlebNgfX/UIy1Ffl0uQG+kf0i2ySbFKGpeJiJHV0nlSO/rbg/vqwXcdVfvk0BJCR5w9GX0hiZwTve0LLCGLHvQDuuj7+YckzZj5J+jl+jDx/Tr3a3w1vP2xpxmTBQIJ4VUHZgPYeA81wJDsJEOwfvzrmvA1bHJonUr1I6n0zJ5DcKur6+wthOYMc7hcpW3SNvJGW5lLRBL6CZzFjYfZfwT92gNEbo=" ); // value.put("name","alex" ); value.put("slices",new ArrayList<>() ); result.put("value",value); return result; } @Override public Object getKeys(List<?> parameter) { LOGGER.log(Level.INFO, "Logging getKeys "); for(Object o: parameter){ LOGGER.log(Level.INFO,parameter.toString()); } HashMap<String,Object> result = new HashMap<>(); String output = ""; int code = 0; result.put("output", output); result.put("code", code); result.put("value", ""); return result; } private Model createGroupModel(URN sliceURN, X509Certificate sliceCert) throws Exception { Model groupModel = ModelFactory.createDefaultModel(); //TODO change this to URN.toURI() Resource resource = groupModel.createResource("http://"+ sliceURN.getDomain() + "/topology/"+sliceURN.getSubject()); resource.addProperty(RDF.type, Omn.Topology ); resource.addProperty(RDFS.label, resource.getURI()); Property authInfo = groupModel.createProperty(Omn_lifecycle.hasAuthenticationInformation.getNameSpace(),Omn_lifecycle.hasAuthenticationInformation.getLocalName()); authInfo.addProperty(RDF.type, OWL.FunctionalProperty); resource.addProperty(authInfo, X509Util.getCertificateBodyEncoded(sliceCert)); return groupModel; } private Model sendGroup(Model groupModel) { String serializedModel = MessageUtil.serializeModel(groupModel,IMessageBus.SERIALIZATION_TURTLE); Model resultModel = SFA_AM_MDBSender.getInstance().sendRDFRequest(serializedModel, IMessageBus.TYPE_CREATE, IMessageBus.TARGET_RESERVATION); return resultModel; } private class RegisterDelegate { private Map<String, Object> inputMap; private URN sliceURN; private URN ownerURN; private X509Certificate ownerCert; private X509Certificate sliceCert; public RegisterDelegate(Map<String, Object> inputMap) { this.inputMap = inputMap; } public URN getSliceURN() { return sliceURN; } public URN getOwnerURN() { return ownerURN; } public X509Certificate getOwnerCert() { return ownerCert; } public X509Certificate getSliceCert() { return sliceCert; } public RegisterDelegate invoke() throws Exception { sliceURN = new URN((String)inputMap.get("urn")); String type =(String) inputMap.get((String)"type"); String credentialString = (String)inputMap.get("credential"); JAXBContext context = JAXBContext.newInstance("org.fiteagle.north.sfa.aaa.jaxbClasses"); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(credentialString); SignedCredential sc = (SignedCredential) unmarshaller.unmarshal(reader); ownerURN = new URN(sc.getCredential().getOwnerURN()); ownerCert = X509Util.buildX509Certificate(sc.getCredential().getOwnerGid()); CertificateAuthority ca = CertificateAuthority.getInstance(); sliceCert = ca.createSliceCertificate(sliceURN); return this; } /* public RegisterDelegate invoke() throws Exception { sliceURN = new URN(()inputMap.get("urn")); String type = inputMap.get("type"); XmlRpcArray credentialArray = inputMap.get("credentials"); String credentialString = credentialArray.getString(0); JAXBContext context = JAXBContext.newInstance("org.fiteagle.north.sfa.aaa.jaxbClasses"); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(credentialString); SignedCredential sc = (SignedCredential) unmarshaller.unmarshal(reader); ownerURN = new URN(sc.getCredential().getOwnerURN()); ownerCert = X509Util.buildX509Certificate(sc.getCredential().getOwnerGid()); CertificateAuthority ca = CertificateAuthority.getInstance(); sliceCert = ca.createSliceCertificate(sliceURN); return this; } */ } }
package net.finmath.montecarlo; import java.io.Serializable; import java.util.Arrays; import net.finmath.stochastic.RandomVariableInterface; import net.finmath.time.TimeDiscretizationInterface; import cern.jet.random.engine.MersenneTwister64; /** * Implementation of a time-discrete n-dimensional Brownian motion * <i>W = (W<sub>1</sub>,...,W<sub>n</sub>)</i> where <i>W<sub>i</sub></i> is * a Brownian motion and <i>W<sub>i</sub></i>, <i>W<sub>j</sub></i> are * independent for <i>i</i> not equal <i>j</i>. * * For a correlated Brownian motion with see * {@link net.finmath.montecarlo.CorrelatedBrownianMotion}. * * Here the dimension <i>n</i> is called factors since this Brownian motion is used to * generate multi-dimensional multi-factor Ito processes and there one might * use a different number of factors to generate Ito processes of different * dimension. * * The class is immutable and thread safe. It uses lazy initialization. * * @author Christian Fries * @version 1.6 */ public class BrownianMotion implements BrownianMotionInterface, Serializable { private static final long serialVersionUID = -5430067621669213475L; private final TimeDiscretizationInterface timeDiscretization; private final int numberOfFactors; private final int numberOfPaths; private final int seed; private transient RandomVariableInterface[][] brownianIncrements; /** * Construct a Brownian motion. * * @param timeDiscretization The time discretization used for the Brownian increments. * @param numberOfFactors Number of factors. * @param numberOfPaths Number of paths to simulate. * @param seed The seed of the random number generator. */ public BrownianMotion( TimeDiscretizationInterface timeDiscretization, int numberOfFactors, int numberOfPaths, int seed) { super(); this.timeDiscretization = timeDiscretization; this.numberOfFactors = numberOfFactors; this.numberOfPaths = numberOfPaths; this.seed = seed; this.brownianIncrements = null; // Lazy initialization } @Override public BrownianMotionInterface getCloneWithModifiedSeed(int seed) { return new BrownianMotion(getTimeDiscretization(), getNumberOfFactors(), getNumberOfPaths(), seed); } /* (non-Javadoc) * @see net.finmath.montecarlo.BrownianMotionInterface#getBrownianIncrement(int, int) */ @Override public RandomVariableInterface getBrownianIncrement(int timeIndex, int factor) { // Thread safe lazy initialization synchronized(this) { if(brownianIncrements == null) doGenerateBrownianMotion(); } /* * For performance reasons we return directly the stored data (no defensive copy). * We return an immutable object to ensure that the receiver does not alter the data. */ return brownianIncrements[timeIndex][factor]; } /** * Lazy initialization of brownianIncrement. Synchronized to ensure thread safety of lazy init. */ private void doGenerateBrownianMotion() { if(brownianIncrements != null) return; // Nothing to do // Create random number sequence generator (we use MersenneTwister64 from colt) MersenneTwister64 mersenneTwister = new MersenneTwister64(seed); // Allocate memory double[][][] brownianIncrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors][numberOfPaths]; // Pre-calculate square roots of deltaT double[] sqrtOfTimeStep = new double[timeDiscretization.getNumberOfTimeSteps()]; for(int timeIndex=0; timeIndex<sqrtOfTimeStep.length; timeIndex++) { sqrtOfTimeStep[timeIndex] = Math.sqrt(timeDiscretization.getTimeStep(timeIndex)); } /* * Generate normal distributed independent increments. * * The inner loop goes over time and factors. * MersenneTwister is known to generate "independent" increments in 623 dimensions. * Since we want to generate independent streams (paths), the loop over path is the outer loop. */ for(int path=0; path<numberOfPaths; path++) { for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) { double sqrtDeltaT = sqrtOfTimeStep[timeIndex]; // Generate uncorrelated Brownian increment for(int factor=0; factor<numberOfFactors; factor++) { double uniformIncement = mersenneTwister.nextDouble(); brownianIncrementsArray[timeIndex][factor][path] = net.finmath.functions.NormalDistribution.inverseCumulativeDistribution(uniformIncement) * sqrtDeltaT; } } } // Allocate memory for RandomVariable wrapper objects. brownianIncrements = new RandomVariable[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors]; // Wrap the values in RandomVariable objects for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) { for(int factor=0; factor<numberOfFactors; factor++) { brownianIncrements[timeIndex][factor] = new RandomVariable(timeDiscretization.getTime(timeIndex+1), brownianIncrementsArray[timeIndex][factor]); } } } /* (non-Javadoc) * @see net.finmath.montecarlo.BrownianMotionInterface#getTimeDiscretization() */ @Override public TimeDiscretizationInterface getTimeDiscretization() { return timeDiscretization; } /* (non-Javadoc) * @see net.finmath.montecarlo.BrownianMotionInterface#getNumberOfFactors() */ @Override public int getNumberOfFactors() { return numberOfFactors; } /* (non-Javadoc) * @see net.finmath.montecarlo.BrownianMotionInterface#getNumberOfPaths() */ @Override public int getNumberOfPaths() { return numberOfPaths; } /** * @return Returns the seed. */ public int getSeed() { return seed; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return super.toString() + "\n" + "timeDiscretization: " + timeDiscretization.toString() + "\n" + "numberOfPaths: " + numberOfPaths + "\n" + "numberOfFactors: " + numberOfFactors + "\n" + "seed: " + seed; } }
package org.jpmml.converter; import com.google.common.base.Objects.ToStringHelper; import org.dmg.pmml.Apply; import org.dmg.pmml.DataType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.FieldRef; import org.dmg.pmml.OpType; import org.dmg.pmml.TypeDefinitionField; public class PowerFeature extends Feature implements HasDerivedName { private int power = 1; public PowerFeature(PMMLEncoder encoder, TypeDefinitionField field, int power){ this(encoder, field.getName(), field.getDataType(), power); } public PowerFeature(PMMLEncoder encoder, FieldName name, DataType dataType, int power){ super(encoder, name, dataType); setPower(power); } @Override public FieldName getDerivedName(){ return FieldName.create((getName()).getValue() + "^" + getPower()); } @Override public ContinuousFeature toContinuousFeature(){ PMMLEncoder encoder = ensureEncoder(); FieldName derivedName = getDerivedName(); DerivedField derivedField = encoder.getDerivedField(derivedName); if(derivedField == null){ Apply apply = PMMLUtil.createApply("pow", new FieldRef(getName()), PMMLUtil.createConstant(getPower())); derivedField = encoder.createDerivedField(derivedName, OpType.CONTINUOUS, DataType.DOUBLE, apply); } return new ContinuousFeature(encoder, derivedField); } @Override protected ToStringHelper toStringHelper(){ return super.toStringHelper() .add("power", getPower()); } public int getPower(){ return this.power; } private void setPower(int power){ this.power = power; } }
package net.furfurylic.chionographis; import java.util.List; import java.util.stream.Collectors; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.w3c.dom.Node; /** * A helper class to extract information from XML documents by XPath expressions. */ final class XMLUtils { /** A private default constructor which inhibits instantiation; that is, a misuse. */ private XMLUtils() { } /** * Extracts string values from XPath expressions. * * <p>This method synchronizes on each elemnts of {@code referents}.</p> * * @param node * a node to apply the XPath expressions. * @param referents * the XPath expressions. * * @return * the extracted string values arranged in a list in the same order as {@code referents}. */ public static List<String> extract(Node node, List<XPathExpression> referents) { return referents.stream().map(r -> extractOne(node, r)) .collect(Collectors.toList()); } private static String extractOne(Node node, XPathExpression expr) { try { synchronized (expr) { return (String) expr.evaluate(node, XPathConstants.STRING); } } catch (XPathExpressionException e) { return null; } } /** * Parses a qualified name string which has a form of {@code local-part}, {@code * namespace-prefix:local-part} or <code>{namespace-uri}local-part</code>. * * @param name * the qualified name string to be parsed. * @param namespaceContext * an object which can resolve {@code namespace-prefix} to {@code namespace-uri}. * @param location * the location where this parsing is required. * * @return * the resulted {@link QName} object, whose {@link QName#getPrefix() prefix} shall be * {@code namespace-prefix} if <var>name</var> has a form of * {@code namespace-prefix:local-part}, or be {@link XMLConstants#DEFAULT_NS_PREFIX} otherwise. * * @throws BuildException * when the {@code namespace-prefix} has no mappings in <var>namespaceContext</var>. */ public static QName parseQualifiedName( String name, NamespaceContext namespaceContext, Location location) { if (name.startsWith("{")) { return QName.valueOf(name); } int indexOfColon = name.indexOf(':'); if (indexOfColon == -1) { return new QName(name); } String prefix = name.substring(0, indexOfColon); String namespaceURI = namespaceContext.getNamespaceURI(prefix); if (namespaceURI.equals(XMLConstants.NULL_NS_URI)) { throw new BuildException( "Unbound namespace prefix: " + prefix, location); } String localName = name.substring(indexOfColon + 1); return new QName(namespaceURI, localName, prefix); } /** * Makes a {@code local-part} or {@code namespace-prefix:local-part} form string * representation from a {@link QName} object. * * @param qName * the {@link QName} to make the string representation. * * @return * the resulted string representation. */ public static String createQualifiedName(QName qName) { if (qName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) { return qName.getLocalPart(); } else { return qName.getPrefix() + ':' + qName.getLocalPart(); } } }
package org.jtrfp.trcl.mem; import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.Callable; import org.jtrfp.trcl.core.TRFuture; import org.jtrfp.trcl.gpu.GLProgram; import org.jtrfp.trcl.gpu.GLUniform; import org.jtrfp.trcl.gpu.GPU; import org.jtrfp.trcl.gpu.MemoryUsageHint; import org.jtrfp.trcl.gpu.ReallocatableGLTextureBuffer; import org.jtrfp.trcl.pool.IndexPool; import org.jtrfp.trcl.pool.IndexPool.GrowthBehavior; public final class MemoryManager { private final IndexPool pageIndexPool = new IndexPool(); private final ByteBuffer [] physicalMemory = new ByteBuffer[1]; private final ReallocatableGLTextureBuffer glPhysicalMemory; private final GPU gpu; private final ArrayList<WeakReference<PagedByteBuffer>> pagedByteBuffers = new ArrayList<WeakReference<PagedByteBuffer>>(1024); public MemoryManager(GPU gpu){ this.gpu=gpu; try{ glPhysicalMemory = gpu.getTr().getThreadManager().submitToGL(new Callable<ReallocatableGLTextureBuffer>(){ @Override public ReallocatableGLTextureBuffer call() throws Exception { ReallocatableGLTextureBuffer tb; tb=new ReallocatableGLTextureBuffer(MemoryManager.this.gpu); tb.reallocate(PagedByteBuffer.PAGE_SIZE_BYTES); physicalMemory[0] = tb.map(); tb.setUsageHint(MemoryUsageHint.StreamDraw); return tb; }}).get(); }catch(Exception e){throw new RuntimeException(e);} pageIndexPool.setGrowthBehavior(new GrowthBehavior(){ @Override public int grow(final int previousMaxCapacity) { final TRFuture<Integer> ft = MemoryManager.this.gpu.getTr().getThreadManager().submitToGL(new Callable<Integer>(){ @Override public Integer call(){ glPhysicalMemory.reallocate(previousMaxCapacity*PagedByteBuffer.PAGE_SIZE_BYTES*2); physicalMemory[0] = glPhysicalMemory.map(); return previousMaxCapacity*2; }//end call() }); try{return ft.get();}catch(Exception e){e.printStackTrace();} return previousMaxCapacity;//Fail by maintaining original size }//end grow(...) }); }//end constructor public int getMaxCapacityInBytes(){ return PagedByteBuffer.PAGE_SIZE_BYTES*pageIndexPool.getMaxCapacity(); } public void map(){ if((physicalMemory[0] = glPhysicalMemory.map())==null)throw new NullPointerException("Failed to map GPU memory. (returned null)"); } public void flushRange(int startPositionInBytes, int lengthInBytes){ glPhysicalMemory.flushRange(startPositionInBytes, lengthInBytes); } public void unmap(){ physicalMemory[0]=null;//Make sure we don't start reading/writing somewhere bad. glPhysicalMemory.unmap(); } public PagedByteBuffer createPagedByteBuffer(int initialSizeInBytes, String debugName){ return new PagedByteBuffer(gpu, physicalMemory, pageIndexPool, initialSizeInBytes, debugName); } void registerPagedByteBuffer(WeakReference<PagedByteBuffer> b){ synchronized(pagedByteBuffers){ pagedByteBuffers.add(b);} } void deRegisterPagedByteBuffer(WeakReference<PagedByteBuffer> b){ synchronized(pagedByteBuffers){ pagedByteBuffers.remove(b);} } public void flushStalePages(){ if(!glPhysicalMemory.isMapped()) return; synchronized(pagedByteBuffers){ final Iterator<WeakReference<PagedByteBuffer>> it = pagedByteBuffers.iterator(); while(it.hasNext()){ final WeakReference<PagedByteBuffer> r = it.next(); if(r.get()==null) it.remove(); else{ r.get().flushStalePages(); }//end else{} }//end while(hasNext) }//end sync() }//end flushStalePages() public void bindToUniform(int textureUnit, GLProgram shaderProgram, GLUniform uniform) { glPhysicalMemory.bindToUniform(textureUnit, shaderProgram, uniform); } public void dumpAllGPUMemTo(ByteBuffer dest) throws IOException{ map(); physicalMemory[0].clear(); dest.clear(); physicalMemory[0].limit(dest.limit());//Avoid overflow dest.put(physicalMemory[0]); physicalMemory[0].clear(); dest.clear(); } }//end MemmoryManager
package org.lightmare.utils.fs; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Set; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; /** * Utility for removing {@link File}s recursively from file system * * @author Levan Tsinadze * @since 0.0.20-SNAPSHOT */ public class FileUtils { // First bytes for ZIP file private static byte[] MAGIC = { 'P', 'K', 0x3, 0x4 }; // Read privilege for random access file private static final String READ = "r"; /** * Lists java archive class files in passed file * * @param file * @return {@link File}[] */ private static File[] listJavaFiles(File file) { File[] subFiles = file.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String name) { return name.endsWith(ArchiveUtils.JAR_FILE_EXT) || name.endsWith(ArchiveUtils.CLASS_FILE_EXT) || file.isDirectory(); } }); return subFiles; } /** * Adds passed {@link File}'s {@link URL} to passed {@link Collection} of * {@link URL} objects * * @param urls * @param file * @throws IOException */ private static void addURL(Collection<URL> urls, File file) throws IOException { try { urls.add(file.toURI().toURL()); } catch (MalformedURLException ex) { throw new IOException(ex); } } /** * Adds sub files of passed {@link File} array to passed {@link List} of * {@link URL} objects * * @param files * @param urls * @throws IOException */ private static void addSubDirectory(File[] files, Set<URL> urls) throws IOException { for (File subFile : files) { if (subFile.isDirectory()) { getSubfiles(subFile, urls); } else { addURL(urls, subFile); } } } /** * Gets all jar or class subfiles from specified {@link File} recursively * * @param file * @param urls * @throws IOException */ public static void getSubfiles(File file, Set<URL> urls) throws IOException { if (file.isDirectory()) { File[] subFiles = listJavaFiles(file); if (CollectionUtils.valid(subFiles)) { addSubDirectory(subFiles, urls); } } else { addURL(urls, file); } } /** * Check whether passed {@link URL} is from extracted ear directory * * @param url * @return boolean * @throws IOException */ public static boolean checkOnEarDir(URL url) throws IOException { boolean isEarDir; File file; try { file = new File(url.toURI()); isEarDir = checkOnEarDir(file); } catch (URISyntaxException ex) { throw new IOException(ex); } return isEarDir; } /** * Check whether passed path is extracted ear directory path * * @param file * @return boolean */ public static boolean checkOnEarDir(String path) { boolean isEarDir; File file = new File(path); isEarDir = checkOnEarDir(file); return isEarDir; } /** * Check whether passed file is extracted ear directory * * @param file * @return boolean */ public static boolean checkOnEarDir(File file) { boolean isEarDir = file.isDirectory(); if (isEarDir) { File[] files = file.listFiles(); isEarDir = CollectionUtils.valid(files); if (isEarDir) { String path = file.getPath(); String delim; if (path.endsWith(ArchiveUtils.FILE_SEPARATOR)) { delim = StringUtils.EMPTY_STRING; } else { delim = ArchiveUtils.FILE_SEPARATOR; } String appxmlPath = StringUtils.concat(path, delim, ArchiveUtils.APPLICATION_XML_PATH); File appXmlFile = new File(appxmlPath); isEarDir = appXmlFile.exists(); } } return isEarDir; } /** * Removes passed {@link File}s from file system and if * {@link File#isDirectory()} removes all it's content recursively * * @param file * @return boolean */ public static boolean deleteFile(File file) { if (file.isDirectory()) { File[] subFiles = file.listFiles(); if (CollectionUtils.valid(subFiles)) { for (File subFile : subFiles) { deleteFile(subFile); } } } return file.delete(); } /** * Iterates over passed {@link File}s and removes each of them from file * system and if {@link File#isDirectory()} removes all it's content * recursively * * @param files */ public static void deleteFiles(Iterable<File> files) { for (File fileToDelete : files) { deleteFile(fileToDelete); } } /** * Converts passed file to {@link URL} instance * * @param file * @return {@link URL} * @throws IOException */ public static URL toURL(File file) throws IOException { return file.toURI().toURL(); } /** * Creates {@link URL} from passed path * * @param path * @return {@link URL} * @throws IOException */ public static URL toURL(String path) throws IOException { File file = new File(path); return toURL(file); } /** * Checks passed path and if its empty path for current class directory * * @param path * @return {@link String} */ public static List<URL> toURLWithClasspath(String path) throws IOException { List<URL> urls = new ArrayList<URL>(); URL url; if (StringUtils.valid(path)) { url = toURL(path); urls.add(url); } else if (ObjectUtils.notNull(path) && path.isEmpty()) { Enumeration<URL> urlEnum = LibraryLoader.getContextClassLoader() .getResources(path); while (urlEnum.hasMoreElements()) { url = urlEnum.nextElement(); urls.add(url); } } return urls; } }
package org.myrobotlab.framework; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArrayList; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.framework.interfaces.Broadcaster; import org.myrobotlab.framework.interfaces.Invoker; import org.myrobotlab.framework.interfaces.NameProvider; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.framework.repo.ServiceData; import org.myrobotlab.image.Util; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.service.Runtime; import org.myrobotlab.service.config.ServiceConfig; import org.myrobotlab.service.data.Locale; import org.myrobotlab.service.interfaces.AuthorizationProvider; import org.myrobotlab.service.interfaces.QueueReporter; import org.myrobotlab.service.meta.abstracts.MetaData; import org.slf4j.Logger; /** * * Service is the base of the MyRobotLab Service Oriented Architecture. All * meaningful Services derive from the Service class. There is a * _TemplateService.java in the org.myrobotlab.service package. This can be used * as a very fast template for creating new Services. Each Service begins with * two threads One is for the "OutBox" this delivers messages out of the * Service. The other is the "InBox" thread which processes all incoming * messages. * */ public abstract class Service implements Runnable, Serializable, ServiceInterface, Invoker, Broadcaster, QueueReporter { // FIXME upgrade to ScheduledExecutorService /** * contains all the meta data about the service - pulled from the static * method getMetaData() each instance will call the method and populate the * data for an instance * */ protected MetaData serviceType; private static final long serialVersionUID = 1L; transient public final static Logger log = LoggerFactory.getLogger(Service.class); /** * key into Runtime's hosts of ServiceEnvironments mrlscheme://[gateway * name]/scheme://key for gateway mrl://gateway/xmpp://incubator incubator if * host == null the service is local */ private URI instanceId = null; /** * unique name of the service (eqv. hostname) */ private String name; /** * unique id - (eqv. domain suffix) */ protected String id; /** * simpleName used in serialization */ protected String simpleName; /** * full class name used in serialization */ protected String serviceClass; private boolean isRunning = false; transient protected Thread thisThread = null; transient protected Inbox inbox = null; transient protected Outbox outbox = null; protected String serviceVersion = null; /** * default en.properties - if there is one */ protected Properties defaultLocalization = null; /** * map of keys to localizations - * * <pre> * Match Service with current Locale of the Runtime service * Match Service with Default (English) Locale * Match Runtime with current Locale of the Runtime service. * Match Runtime with Default (English) Locale * </pre> * * service specific - then runtime */ protected transient Properties localization = null; /** * for promoting portability and good pathing */ transient protected static String fs = File.separator; /** * for promoting portability and good pathing */ transient protected String ps = File.pathSeparator; /** * a more capable task handler */ transient Map<String, Timer> tasks = new HashMap<String, Timer>(); /** * used as a static cache for quick method name testing FIXME - if you make * this static it borks things - not sure why this should be static info and * should not be a member variable ! */ transient protected Set<String> methodSet; /** * This is the map of interfaces - its really "static" information, since its * a definition. However, since gson will not process statics - we are making * it a member variable */ protected Map<String, String> interfaceSet; /** * order which this service was created */ int creationOrder = 0; // FIXME SecurityProvider protected AuthorizationProvider authProvider = null; protected Status lastError = null; protected Long lastErrorTs = null; protected Status lastStatus = null; protected Long lastStatusTs = null; protected long statusBroadcastLimitMs = 1000; /** * variable for services to virtualize some of their dependencies - defaults * to be the same as Runtime's unless explicitly set */ protected boolean isVirtual = false; /** * overload this if your service needs other environmental or dependencies to * be ready */ protected boolean ready = true; /** * Locale for the service - defaults to be the same as Runtime's unless * explicitly set */ protected Locale locale; /** * starting all peers on start of service */ protected boolean autoStartPeers = true; public boolean isAutoStartPeers() { return autoStartPeers; } public void setAutoStartPeers(boolean autoStartPeers) { this.autoStartPeers = autoStartPeers; } /** * copyShallowFrom is used to help maintain state information with * * @param target * t * @param source * s * @return o */ public static Object copyShallowFrom(Object target, Object source) { if (target == source) { // data is myself - operating on local copy return target; } Set<Class<?>> ancestry = new HashSet<Class<?>>(); Class<?> targetClass = source.getClass(); ancestry.add(targetClass); // if we are a org.myrobotlab object climb up the ancestry to // copy all super-type fields ... // GroG says: I wasn't comfortable copying of "Service" - because its never // been tested before - so we copy all definitions from // other superclasses e.g. - org.myrobotlab.service.abstracts // it might be safe in the future to copy all the way up without stopping... while (targetClass.getCanonicalName().startsWith("org.myrobotlab") && !targetClass.getCanonicalName().startsWith("org.myrobotlab.framework")) { ancestry.add(targetClass); targetClass = targetClass.getSuperclass(); } for (Class<?> sourceClass : ancestry) { Field fields[] = sourceClass.getDeclaredFields(); for (int j = 0, m = fields.length; j < m; j++) { try { Field f = fields[j]; int modifiers = f.getModifiers(); // if (Modifier.isPublic(mod) // !(Modifier.isPublic(f.getModifiers()) // Hmmm JSON mappers do hacks to get by // GROG - recent change from this // if ((!Modifier.isPublic(modifiers) // to this String fname = f.getName(); /* * if (fname.equals("desktops") || fname.equals("useLocalResources") * ){ log.info("here"); } */ if (Modifier.isPrivate(modifiers) || fname.equals("log") || Modifier.isTransient(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { log.debug("skipping {}", f.getName()); continue; } else { log.debug("copying {}", f.getName()); } Type t = f.getType(); // log.info(String.format("setting %s", f.getName())); /* * if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { * continue; } */ // GroG - this is new 1/26/2017 - needed to get webgui data to // load f.setAccessible(true); Field targetField = sourceClass.getDeclaredField(f.getName()); targetField.setAccessible(true); if (t.equals(java.lang.Boolean.TYPE)) { targetField.setBoolean(target, f.getBoolean(source)); } else if (t.equals(java.lang.Character.TYPE)) { targetField.setChar(target, f.getChar(source)); } else if (t.equals(java.lang.Byte.TYPE)) { targetField.setByte(target, f.getByte(source)); } else if (t.equals(java.lang.Short.TYPE)) { targetField.setShort(target, f.getShort(source)); } else if (t.equals(java.lang.Integer.TYPE)) { targetField.setInt(target, f.getInt(source)); } else if (t.equals(java.lang.Long.TYPE)) { targetField.setLong(target, f.getLong(source)); } else if (t.equals(java.lang.Float.TYPE)) { targetField.setFloat(target, f.getFloat(source)); } else if (t.equals(java.lang.Double.TYPE)) { targetField.setDouble(target, f.getDouble(source)); } else { // log.debug(String.format("setting reference to remote // object %s", f.getName())); targetField.set(target, f.get(source)); } } catch (Exception e) { log.error("copy failed source {} to a {}", source, target, e); } } // for each field in class } // for each in ancestry return target; } public static String getHostName(final String inHost) { if (inHost != null) return inHost; try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.error("could not find host, host is null or empty !"); } return "localhost"; // no network - still can't be null // chumby } static public void logTimeEnable(Boolean b) { Logging.logTimeEnable(b); } public boolean setSecurityProvider(AuthorizationProvider provider) { if (authProvider != null) { log.error("security provider is already set - it can not be unset .. THAT IS THE LAW !!!"); return false; } authProvider = provider; return true; } /** * sleep without the throw * * @param millis * the time in milliseconds * */ public static void sleep(int millis) { sleep((long) millis); } public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } public final static String stackToString(final Throwable e) { StringWriter sw; try { sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); } catch (Exception e2) { return "bad stackToString"; } return " } public String getRootDataDir() { return Runtime.DATA_DIR; } public String getHomeDir() { return System.getProperty("user.home"); } static public String getDataDir(String typeName) { String dataDir = Runtime.DATA_DIR + fs + typeName; File f = new File(dataDir); if (!f.exists()) { f.mkdirs(); } return Runtime.DATA_DIR + fs + typeName; } public String getDataDir() { return getDataDir(getClass().getSimpleName()); } public String getDataInstanceDir() { String dataDir = Runtime.DATA_DIR + fs + getClass().getSimpleName() + fs + getName(); File f = new File(dataDir); if (!f.exists()) { f.mkdirs(); } return Runtime.DATA_DIR + fs + getClass().getSimpleName() + fs + getName(); } /** * Non-static getResourceDir() will return /resource/{service type name} e.g. * /resource/Arduino * * @return the resource directory * */ public String getResourceDir() { return getResourceDir(getClass()); } /** * Static getResourceDir(Class clazz) will return the appropriate resource * directory, typically it will be /resource/{MetaData} but depending if run * in the presence of other developing directories. * * @param clazz * the class name * @return the resource dir * */ static public String getResourceDir(Class<?> clazz) { return getResourceDir(clazz.getSimpleName(), null); } static public String getResourceDir(Class<?> clazz, String additionalPath) { return getResourceDir(clazz.getSimpleName(), additionalPath); } /** * getResourceDir gets the appropriate resource path for any resource supplied * in additionalPath. This is a private method, if you need a resource, use * getResource or getResourceAsString * * <pre> * Order of increasing precedence is: * 1. resource * 2. src/resource/{MetaData} or * 3. ../{MetaData}/resource/{MetaData} * </pre> * * @param serviceType * the type of service * @param additionalPath * to glue together * @return the full resolved path * */ static public String getResourceDir(String serviceType, String additionalPath) { // setting resource directory String resourceDir = "resource" + fs + serviceType; // overriden by src String override = "src" + fs + "main" + fs + "resources" + fs + "resource" + fs + serviceType; File test = new File(override); if (test.exists()) { log.info("found override resource dir {}", override); resourceDir = override; } override = ".." + fs + serviceType + fs + "resource" + fs + serviceType; test = new File(override); if (test.exists()) { log.info("found override repo dir {}", override); resourceDir = override; } if (additionalPath != null) { resourceDir = FileIO.gluePaths(resourceDir, additionalPath); } return resourceDir; } /** * non static get resource path return the path to a resource - since the root * can change depending if in debug or runtime - it gets the appropriate root * and adds the additionalPath.. * * @param additionalPath * additional paths to add to the resource path * @return the combined file path * */ public String getResourcePath(String additionalPath) { return FileIO.gluePaths(getResourceDir(), additionalPath); } /** * All resource access should be using this method. Util.getResource... should * be deprecated. This should be the one source which determines the location * and resolves the priority of setting this configuration * * @return the root folder for the resource dir * */ static public String getResourceRoot() { // setting resource root details String resourceRootDir = "resource"; // allow default to be overriden by src if it exists File src = new File("src"); if (src.exists()) { resourceRootDir = "src" + fs + "main" + fs + "resources" + fs + "resource"; } return resourceRootDir; } /** * * @return list of resources for this service top level * */ public File[] getResourceDirList() { return getResourceDirList(null); } /** * Get a resource, first parameter is serviceType * * @param serviceType * - the type of service * @param resourceName * - the path of the resource * @return the bytes of the resource */ static public byte[] getResource(String serviceType, String resourceName) { String filename = getResourceDir(serviceType, resourceName); File f = new File(filename); if (!f.exists()) { log.error("resource {} does not exist", f); return null; } byte[] content = null; try { content = Files.readAllBytes(Paths.get(filename)); } catch (IOException e) { log.error("getResource threw", e); } return content; } public byte[] getResource(String resourceName) { return getResource(getClass(), resourceName); } /** * static getResource(Class, resourceName) to access a different services * resources * * @param clazz * the class * @param resourceName * the resource name * @return bytes of the resource * */ static public byte[] getResource(Class<?> clazz, String resourceName) { return getResource(clazz.getSimpleName(), resourceName); } /** * Get a resource as a string. This will follow the conventions of finding the * appropriate resource dir * * @param resourceName * the name of the resource * @return the string of the bytes , assuming utf-8 * */ public String getResourceAsString(String resourceName) { byte[] data = getResource(resourceName); if (data != null) { try { return new String(data, "UTF-8"); } catch (Exception e) { log.error("getResourceAsString threw", e); } } return null; } static public String getResourceAsString(Class<?> clazz, String resourceName) { return getResourceAsString(clazz.getSimpleName(), resourceName); } static public String getResourceAsString(String serviceType, String resourceName) { byte[] data = getResource(serviceType, resourceName); if (data != null) { try { return new String(data, "UTF-8"); } catch (Exception e) { log.error("getResourceAsString threw", e); } } return null; } /** * Constructor of service, reservedkey typically is a services name and inId * will be its process id * * @param reservedKey * the service name * @param inId * process id * */ public Service(String reservedKey, String inId) { name = reservedKey; // necessary for serialized transport\ if (inId == null) { id = Platform.getLocalInstance().getId(); log.debug("creating local service for id {}", id); } else { id = inId; log.debug("creating remote proxy service for id {}", id); } serviceClass = this.getClass().getCanonicalName(); simpleName = this.getClass().getSimpleName(); MethodCache cache = MethodCache.getInstance(); cache.cacheMethodEntries(this.getClass()); // soft set (not forced) of meta data and overrides in planStore ServiceData.setMetaData(name, getClass().getSimpleName()); // pull back the overrides serviceType = ServiceData.getMetaData(name, getClass().getSimpleName()); // FIXME - this is 'sort-of' static :P if (methodSet == null) { methodSet = getMessageSet(); } interfaceSet = getInterfaceSet(); if (locale == null) { if (!Runtime.isRuntime(this)) { locale = Runtime.getInstance().getLocale(); } else { // is runtime locale = Locale.getDefault(); } } // load appropriate localization properties based on current local language loadLocalizations(); this.inbox = new Inbox(getFullName()); this.outbox = new Outbox(this); File versionFile = new File(getResourceDir() + fs + "version.txt"); if (versionFile.exists()) { try { String version = FileIO.toString(versionFile); if (version != null) { version = version.trim(); serviceVersion = version; } } catch (Exception e) { /* don't care */} } // register this service if local - if we are a foreign service, we probably // are being created in a // registration already if (id.equals(Platform.getLocalInstance().getId())) { Registration registration = new Registration(this); Runtime.register(registration); } } /** * * @param additionalPath * get a list of resource files in a resource path * @return list of files * */ public File[] getResourceDirList(String additionalPath) { String resDir = getResourceDir(getClass(), additionalPath); File f = new File(resDir); return f.listFiles(); } /** * new overload - mqtt uses this for json encoded MrlListener to process * subscriptions * * @param data * - listener callback info */ public void addListener(Map data) { // {topicMethod=pulse, callbackName=mqtt01, callbackMethod=onPulse} if (!data.containsKey("topicMethod")) { error("addListener topicMethod missing"); } if (!data.containsKey("callbackName")) { error("addListener callbackName missing"); } if (!data.containsKey("callbackMethod")) { error("addListener callbackMethod missing"); } addListener(data.get("topicMethod").toString(), data.get("callbackName").toString(), data.get("callbackMethod").toString()); } public void addListener(MRLListener listener) { addListener(listener.topicMethod, listener.callbackName, listener.callbackMethod); } public void addListener(String topicMethod, String callbackName) { addListener(topicMethod, callbackName, CodecUtils.getCallbackTopicName(topicMethod)); } /** * adds a MRL message listener to this service this is the result of a * "subscribe" from a different service FIXME !! - implement with HashMap or * HashSet .. WHY ArrayList ??? * * @param topicMethod * - method when called, it's return will be sent to the * callbackName/calbackMethod * @param callbackName * - name of the service to send return message to * @param callbackMethod * - name of the method to send return data to */ public void addListener(String topicMethod, String callbackName, String callbackMethod) { MRLListener listener = new MRLListener(topicMethod, callbackName, callbackMethod); if (outbox.notifyList.containsKey(listener.topicMethod)) { // iterate through all looking for duplicate boolean found = false; List<MRLListener> nes = outbox.notifyList.get(listener.topicMethod); for (int i = 0; i < nes.size(); ++i) { MRLListener entry = nes.get(i); if (entry.equals(listener)) { log.debug("attempting to add duplicate MRLListener {}", listener); found = true; break; } } if (!found) { log.debug("adding addListener from {}.{} to {}.{}", this.getName(), listener.topicMethod, listener.callbackName, listener.callbackMethod); nes.add(listener); } } else { List<MRLListener> notifyList = new CopyOnWriteArrayList<MRLListener>(); notifyList.add(listener); log.debug("adding addListener from {}.{} to {}.{}", this.getName(), listener.topicMethod, listener.callbackName, listener.callbackMethod); outbox.notifyList.put(listener.topicMethod, notifyList); } } public boolean hasSubscribed(String listener, String topicMethod) { List<MRLListener> nes = outbox.notifyList.get(topicMethod); for (MRLListener ne : nes) { if (ne.callbackName.contentEquals(listener)) { return true; } } return false; } @Override public void addTask(long intervalMs, String method) { addTask(intervalMs, method, new Object[] {}); } @Override public void addTask(long intervalMs, String method, Object... params) { addTask(method, intervalMs, 0, method, params); } @Override public void addTaskOneShot(long delayMs, String method, Object... params) { addTask(method, 0, delayMs, method, params); } /** * a stronger bigger better task handler ! * * @param taskName * task name * @param intervalMs * how frequent in milliseconds * @param delayMs * the delay * @param method * the method * @param params * the params to pass */ @Override synchronized public void addTask(String taskName, long intervalMs, long delayMs, String method, Object... params) { if (tasks.containsKey(taskName)) { log.info("already have active task \"{}\"", taskName); return; } Timer timer = new Timer(String.format("%s.timer", String.format("%s.%s", getName(), taskName))); Message msg = Message.createMessage(getName(), getName(), method, params); Task task = new Task(this, taskName, intervalMs, msg); timer.schedule(task, delayMs); tasks.put(taskName, timer); } @Override public Map<String, Timer> getTasks() { return tasks; } @Override public boolean containsTask(String taskName) { return tasks.containsKey(taskName); } @Override final public void invokeFuture(String method, long delayMs) { invokeFuture(method, delayMs, (Object[])null); } @Override final public void invokeFuture(String method, long delayMs, Object... params) { addTaskOneShot(delayMs, method, params); } @Override synchronized public void purgeTask(String taskName) { if (tasks.containsKey(taskName)) { log.debug("remove task {}", taskName); Timer timer = tasks.get(taskName); if (timer != null) { try { timer.cancel(); timer.purge(); timer = null; } catch (Exception e) { log.info(e.getMessage()); } } } else { log.debug("purgeTask - task {} does not exist", taskName); } tasks.remove(taskName); } @Override public void purgeTasks() { for (String taskName : tasks.keySet()) { Timer timer = tasks.get(taskName); if (timer != null) { try { timer.purge(); timer.cancel(); timer = null; } catch (Exception e) { log.info(e.getMessage()); } } } tasks.clear(); } @Override public void broadcastState() { invoke("publishState"); } @Override public void broadcastStatus(Status status) { long now = System.currentTimeMillis(); /* * if (status.equals(lastStatus) && now - lastStatusTs < * statusBroadcastLimitMs) { return; } */ if (status.name == null) { status.name = getName(); } if (status.level.equals(StatusLevel.ERROR)) { lastError = status; lastErrorTs = now; log.error(status.toString()); invoke("publishError", status); } else { log.info(status.toString()); } invoke("publishStatus", status); lastStatusTs = now; lastStatus = status; } @Override public String clearLastError() { String le = lastError.toString(); lastError = null; return le; } public void close(Writer w) { if (w == null) { return; } try { w.flush(); } catch (Exception e) { Logging.logError(e); } finally { try { w.close(); } catch (Exception e) { // don't really care } } } /** * method for getting actual name from a service of its peer based on a 'key' * - the return value would change depending on if the service is local or * not. * * FIXME - if not local - it needs to be prefixed by the gateway e.g. * {remote}.arduino.serial * * @param peerKey * r * @return service interface */ public synchronized ServiceInterface createPeer(String peerKey) { try { ServiceReservation sr = serviceType.getPeer(peerKey); if (sr == null) { error("can not create peer from reservedkey %s - no type definition !", peerKey); return null; } if (Runtime.getService(sr.actualName) != null) { // peer already created return Runtime.getService(sr.actualName); } ServiceInterface si = null; Runtime runtime = Runtime.getInstance(); // String filename = runtime.getConfigDir() + fs + runtime.getConfigName() // + fs + name + ".yml"; String filename = runtime.getConfigDir() + fs + runtime.getConfigName() + fs + sr.actualName + ".yml"; File check = new File(filename); if (check.exists()) { si = Runtime.create(sr.actualName); } else { si = Runtime.create(sr.actualName, sr.type); } sr.state = "created"; return si; } catch (Exception e) { error(e); } return null; } @Override public String[] getDeclaredMethodNames() { Method[] methods = getDeclaredMethods(); String[] ret = new String[methods.length]; log.info("getDeclaredMethodNames loading {} non-sub-routable methods", methods.length); for (int i = 0; i < methods.length; ++i) { ret[i] = methods[i].getName(); } Arrays.sort(ret); return ret; } @Override public Method[] getDeclaredMethods() { return this.getClass().getDeclaredMethods(); } public Inbox getInbox() { return inbox; } @Override public URI getInstanceId() { return instanceId; } public String getIntanceName() { return name; } @Override public Status getLastError() { return lastError; } // FIXME - use the method cache public Set<String> getMessageSet() { Set<String> ret = new TreeSet<String>(); Method[] methods = getMethods(); log.debug("getMessageSet loading {} non-sub-routable methods", methods.length); for (int i = 0; i < methods.length; ++i) { ret.add(methods[i].getName()); } return ret; } // FIXME - should be a "Set" not an array ! @Override public String[] getMethodNames() { Method[] methods = getMethods(); /* * Set<String> m = new TreeSet<String>(); m.addAll(methods); */ String[] ret = new String[methods.length]; log.info("getMethodNames loading {} non-sub-routable methods", methods.length); for (int i = 0; i < methods.length; ++i) { ret[i] = methods[i].getName(); } Arrays.sort(ret); return ret; } @Override public Method[] getMethods() { return this.getClass().getMethods(); } public Map<String, String> getInterfaceSet() { Map<String, String> ret = new TreeMap<String, String>(); Class<?> c = getClass(); while (c != Object.class) { Class<?>[] interfaces = c.getInterfaces(); for (int i = 0; i < interfaces.length; ++i) { Class<?> interfaze = interfaces[i]; // ya silly :P - but gson's default conversion of a HashSet is an // array ret.put(interfaze.getName(), interfaze.getName()); } c = c.getSuperclass(); } return ret; } public Message getMsg() throws InterruptedException { return inbox.getMsg(); } @Override public List<MRLListener> getNotifyList(String key) { if (getOutbox() == null) { // this is remote system - it has a null outbox, because its // been serialized with a transient outbox // and your in a skeleton // use the runtime to send a message // FIXME - parameters ! ArrayList<MRLListener> remote = null; try { remote = (ArrayList<MRLListener>) Runtime.getInstance().sendBlocking(getName(), "getNotifyList", new Object[] { key }); } catch (Exception e) { log.error("remote getNotifyList threw", e); } return remote; } else { return getOutbox().notifyList.get(key); } } @Override public ArrayList<String> getNotifyListKeySet() { ArrayList<String> ret = new ArrayList<String>(); if (getOutbox() == null) { // this is remote system - it has a null outbox, because its // been serialized with a transient outbox // and your in a skeleton // use the runtime to send a message ArrayList<String> remote = null; try { remote = (ArrayList<String>) Runtime.getInstance().sendBlocking(getName(), "getNotifyListKeySet"); } catch (Exception e) { log.error("remote getNotifyList threw", e); } return remote; } else { ret.addAll(getOutbox().notifyList.keySet()); } return ret; } public Outbox getOutbox() { return outbox; } @Override public String getSimpleName() { return simpleName; } public Thread getThisThread() { return thisThread; } @Override public String getType() { return getClass().getCanonicalName(); } @Override public boolean hasError() { return lastError != null; } @Override public boolean hasPeers() { try { Class<?> theClass = Class.forName(serviceClass); Method method = theClass.getMethod("getPeers", String.class); } catch (Exception e) { log.debug("{} does not have a getPeers", serviceClass); return false; } return true; } public String help(String format, String level) { StringBuffer sb = new StringBuffer(); Method[] methods = this.getClass().getDeclaredMethods(); TreeMap<String, Method> sorted = new TreeMap<String, Method>(); for (int i = 0; i < methods.length; ++i) { Method m = methods[i]; sorted.put(m.getName(), m); } for (String key : sorted.keySet()) { Method m = sorted.get(key); sb.append("/").append(getName()).append("/").append(m.getName()); Class<?>[] types = m.getParameterTypes(); if (types != null) { for (int j = 0; j < types.length; ++j) { Class<?> c = types[j]; sb.append("/").append(c.getSimpleName()); } } sb.append("\n"); } sb.append("\n"); return sb.toString(); } @Override public void in(Message msg) { inbox.add(msg); } /** * This is where all messages are routed to and processed */ @Override final public Object invoke(Message msg) { Object retobj = null; if (log.isDebugEnabled()) { log.debug("--invoking {}.{}({}) {} --", name, msg.method, CodecUtils.getParameterSignature(msg.data), msg.msgId); } // recently added - to support "nameless" messages - concept you may get // a message at this point // which does not belong to you - but is for a service in the same // Process // this is to support nameless Runtime messages but theoretically it // could // happen in other situations... if (Runtime.getInstance().isLocal(msg) && !name.equals(msg.getName())) { // wrong Service - get the correct one return Runtime.getService(msg.getName()).invoke(msg); } retobj = invokeOn(false, this, msg.method, msg.data); return retobj; } @Override final public Object invoke(String method) { return invokeOn(false, this, method, (Object[]) null); } @Override final public Object invoke(String method, Object... params) { return invokeOn(false, this, method, params); } /** * Broadcast publishes messages synchronously without queuing ! Messages will * be processed on the same thread which calls broadcast. This is unlike * invoke, which will queue/buffer the message and wait for inbox thread to * pick it up. */ @Override final public Object broadcast(String method) { return invokeOn(true, this, method, (Object[]) null); } /** * Broadcast publishes messages synchronously without queuing ! Messages will * be processed on the same thread which calls broadcast. This is unlike * invoke, which will queue/buffer the message and wait for inbox thread to * pick it up. */ @Override final public Object broadcast(String method, Object... params) { return invokeOn(true, this, method, params); } /** * thread blocking invoke call on different service in the same process * * @param serviceName * the service to invoke on * @param methodName * the method to invoke * @param params * var args of the params to pass * @return the returned value from invoking * */ final public Object invokeOn(String serviceName, String methodName, Object... params) { return invokeOn(false, Runtime.getService(serviceName), methodName, params); } /** * the core working invoke method * * @param obj * - the object * @param methodName * - the method to invoke on that object * @param params * - the list of args to pass to the method * @return return object */ @Override final public Object invokeOn(boolean blockLocally, Object obj, String methodName, Object... params) { Object retobj = null; try { MethodCache cache = MethodCache.getInstance(); if (obj == null) { log.error("cannot invoke on a null object ! {}({})", methodName, MethodCache.formatParams(params)); return null; } Method method = cache.getMethod(obj.getClass(), methodName, params); if (method == null) { error("could not find method %s.%s(%s)", obj.getClass().getSimpleName(), methodName, MethodCache.formatParams(params)); return null; // should this be allowed to throw to a higher level ? } retobj = method.invoke(obj, params); if (blockLocally) { List<MRLListener> subList = outbox.notifyList.get(methodName); // correct? get local (default?) gateway Runtime runtime = Runtime.getInstance(); if (subList != null) { for (MRLListener listener : subList) { Message msg = Message.createMessage(getFullName(), listener.callbackName, listener.callbackMethod, retobj); if (msg == null) { log.error("Unable to create message.. null message created"); } msg.sendingMethod = methodName; if (runtime.isLocal(msg)) { ServiceInterface si = Runtime.getService(listener.callbackName); if (si == null) { log.info("{} cannot callback to listener {} does not exist for {} ", getName(), listener.callbackName, listener.callbackMethod); } else { Method m = cache.getMethod(si.getClass(), listener.callbackMethod, retobj); if (m == null) { log.warn("Null Method as a result of cache lookup. {} {} {}", si.getClass(), listener.callbackMethod, retobj); } try { m.invoke(si, retobj); } catch (Throwable e) { // we attempted to invoke this , it blew up. Catch it here, // continue // through the rest of the listeners instead of bombing out. log.error("Invoke blew up! on: {} calling method {} ", si.getName(), m.toString(), e); } } } else { send(msg); } } } } else { out(methodName, retobj); } } catch (Exception e) { error("could not invoke %s.%s (%s) - check logs for details", getName(), methodName, params); log.error("could not invoke {}.{} ({})", getName(), methodName, params, e); } return retobj; } @Override public boolean isLocal() { return instanceId == null; } @Override public boolean isRuntime() { return Runtime.class == this.getClass(); } @Override public boolean isReady() { return ready; } protected void setReady(Boolean ready) { if (!ready.equals(this.ready)) { this.ready = ready; broadcastState(); } } @Override public boolean isRunning() { return isRunning; } /** * Default load config method, subclasses should override this to support * service specific configuration in the service yaml files. * */ public ServiceConfig load(ServiceConfig config) { log.info("Default service config loading for service: {} type: {}", getName(), getType()); // setVirtual(config.isVirtual); "overconfigured" - user Runtimes virtual // setLocale(config.locale); // FIXME - TODO - // assigne a ServiceConfig config member variable the incoming config return config; } /** * Default getConfig returns name and type with null service specific config * */ public ServiceConfig getConfig() { // FIXME !!! - this should be null for services that do not have it ! log.info("{} of type {} does not currently define its own config", getName(), getSimpleName()); // return new ServiceConfig(); return null; } public ServiceConfig load() throws IOException { ServiceConfig config = Runtime.load(getName()); return config; } public void out(Message msg) { outbox.add(msg); } /** * Creating a message function call - without specifying the recipients - * static routes will be applied this is good for Motor drivers - you can swap * motor drivers by creating a different static route The motor is not "Aware" * of the driver - only that it wants to method="write" data to the driver */ public void out(String method, Object o) { Message m = Message.createMessage(getFullName(), null, method, o); if (m.sender.length() == 0) { m.sender = this.getFullName(); } if (m.sendingMethod.length() == 0) { m.sendingMethod = method; } if (outbox == null) { log.info("******************OUTBOX IS NULL*************************"); return; } outbox.add(m); } // override for extended functionality public boolean preProcessHook(Message m) { return true; } // override for extended functionality public boolean preRoutingHook(Message m) { return true; } /** * framework diagnostic publishing method for examining load, capacity, and * throughput of Inbox &amp; Outbox queues * * @param stats * s * @return the stats */ public QueueStats publishQueueStats(QueueStats stats) { return stats; } /** * publishing point for the whole service the entire Service is published * * @return the service */ public Service publishState() { return this; } /** * FIXME - implement This SHOULD NOT be called by the framework - since - the * framework does not know about dna mutation - or customizations which have * been applied such that Arduinos are shared between services or peers of * services * * It SHOULD shutdown all the peers of a service - but it SHOULD NOT be * automatically called by the framework. If the 'user' wants to release all * peers - it should fufill the request */ @Override public void releasePeers() { releasePeers(null); } // FIXME - startPeers sets fields - this method should "unset" fields !!! synchronized private void releasePeers(String peerKey) { log.info("{}.releasePeers ({})", getName(), peerKey); try { // get sub peers climbing tree Map<String, ServiceReservation> peers = serviceType.getPeers(); for (String s : peers.keySet()) { ServiceInterface si = getPeer(s); if (si == null) { // peer does not exist continue; } if (peerKey == null) { Runtime.release(si.getName()); } else if (peerKey != null && peerKey.equals(s)) Runtime.release(si.getName()); } } catch (Exception e) { log.debug("{} does not have a getPeers", serviceClass); } } public void releasePeer(String peerName) { releasePeers(peerName); ServiceReservation sr2 = serviceType.getPeer(peerName); sr2.state = "inactive"; broadcastState(); } /** * Releases resources, and unregisters service from the runtime */ @Override synchronized public void releaseService() { purgeTasks(); // recently added - preference over detach(Runtime.getService(getName())); // since this service is releasing - it should be detached from all existing // services detach(); // note - if stopService is overwritten with extra // threads - releaseService will need to be overwritten too stopService(); // TODO ? detach all other services currently attached // detach(); // @grog is it ok for now ? // GroG says, I don't think so - this is releasing itself from itself // detach(Runtime.getService(getName())); releasePeers(); // Runtime.release(getName()); infinite loop with peers ! :( Runtime.unregister(getName()); } public void removeAllListeners() { outbox.notifyList.clear(); } public void removeListener(String topicMethod, String callbackName) { removeListener(topicMethod, callbackName, CodecUtils.getCallbackTopicName(topicMethod)); } @Override public void removeListener(String outMethod, String serviceName, String inMethod) { if (outbox.notifyList.containsKey(outMethod)) { List<MRLListener> nel = outbox.notifyList.get(outMethod); for (int i = 0; i < nel.size(); ++i) { MRLListener target = nel.get(i); if (target.callbackName.compareTo(serviceName) == 0) { nel.remove(i); log.info("removeListener requested {}.{} to be removed", serviceName, outMethod); } } } else { log.info("removeListener requested {}.{} to be removed - but does not exist", serviceName, outMethod); } } @Override public boolean requiresSecurity() { return authProvider != null; } @Override final public void run() { isRunning = true; try { while (isRunning) { // TODO should this declaration be outside the while loop? if // so, make sure to release prior to continue Message m = getMsg(); if (!preRoutingHook(m)) { continue; } // nameless Runtime messages if (m.getName() == null) { // don't know if this is "correct" // but we are substituting the Runtime name as soon as we // see that its a null // name message m.setName(Runtime.getInstance().getFullName()); } // route if necessary if (!m.getName().equals(this.getName())) // && RELAY { outbox.add(m); // RELAYING continue; // sweet - that was a long time coming fix ! } if (!preProcessHook(m)) { // if preProcessHook returns false // the message does not need to continue // processing continue; } Object ret = invoke(m); } } catch (InterruptedException edown) { info("shutting down"); } catch (Exception e) { error(e); } } /** * method of serializing default will be simple xml to name file */ @Override public boolean save() { return save(null, null, null); } public boolean save(String filename) { return save(filename, null, null); } public boolean save(String filename, Boolean allowNullFields, Boolean saveNonConfigServices) { try { if (allowNullFields == null) { allowNullFields = true; } if (saveNonConfigServices == null) { saveNonConfigServices = false; } if (filename == null) { filename = Runtime.getInstance().getConfigDir() + fs + Runtime.getInstance().getConfigName() + fs + getName() + ".yml"; } String format = filename.substring(filename.lastIndexOf(".") + 1); ServiceConfig config = getConfig(); if (config == null) { log.info("{} has null config - not saving", getName()); return false; } // bad idea of an optimizaton /** * <pre> * if (config.getClass().equals(ServiceConfig.class) && !saveNonConfigServices && config.listeners == null) { * log.info("service {} without config - will not save file", getName()); * return true; * } * </pre> */ String data = null; if ("json".equals(format.toLowerCase())) { data = CodecUtils.toJson(config); } else { data = CodecUtils.toYaml(config); } FileIO.toFile(filename, data.getBytes()); info("saved %s config to %s", getName(), filename); return true; } catch (Exception e) { error(e); } return false; } public ServiceInterface getPeer(String peerKey) { String peerName = serviceType.getPeerActualName(peerKey); return Runtime.getService(peerName); } public void send(String name, String method) { send(name, method, (Object[]) null); } public void sendToPeer(String peerName, String method) { send(String.format("%s.%s", name, peerName), method, (Object[]) null); } public Object invokePeer(String peerName, String method) { return invokeOn(false, getPeer(peerName), method, (Object[]) null); } public Object invokePeer(String peerName, String method, Object... data) { return invokeOn(false, getPeer(peerName), method, data); } public void sendToPeer(String peerName, String method, Object... data) { send(String.format("%s.%s", name, peerName), method, data); } public void send(String name, String method, Object... data) { Message msg = Message.createMessage(getName(), name, method, data); msg.sender = this.getFullName(); // All methods which are invoked will // get the correct sendingMethod // here its hardcoded msg.sendingMethod = "send"; // log.info(CodecUtils.toJson(msg)); send(msg); } public void send(Message msg) { outbox.add(msg); } public Object sendBlocking(String name, Integer timeout, String method, Object... data) throws InterruptedException, TimeoutException { Message msg = Message.createMessage(getName(), name, method, data); msg.sender = this.getFullName(); msg.msgId = Runtime.getUniqueID(); return sendBlocking(msg, timeout); } /** * In theory the only reason this should need to use synchronized wait/notify * is when the msg destination is in another remote process. sendBlocking * should either invoke directly or use a gateway's sendBlockingRemote. To use * a gateways sendBlockingRemote - the msg must have a remote src * * <pre> * after attach: * stdin (remote) --&gt; gateway sendBlockingRemote --&gt; invoke * &lt;-- &lt;-- * </pre> * */ public Object sendBlocking(Message msg, Integer timeout) throws InterruptedException, TimeoutException { if (Runtime.getInstance().isLocal(msg)) { return invoke(msg); } else { return waitOn(msg.getFullName(), msg.getMethod(), timeout, msg); } } /** * This method waits on a remote topic by sending a subscription and waiting * for a message to come back. It is used both by sendBlocking and waitFor to * normalize the code - they are equivalent. The only difference between * sendBlocking and waitFor is sendBlocking sends an activating msg to the * remote topic. If timeout occurs before a return message, a TimeoutException * is thrown. This is important to distinguish between a timeout and a valid * null return. * * @param fullName * - service name * @param method * - method name * @param timeout * - max time to wait in ms * @param sendMsg * - optional message to send to the remote topic * @return the returned object * @throws InterruptedException * boom * @throws TimeoutException * boom */ protected Object waitOn(String fullName, String method, Integer timeout, Message sendMsg) throws InterruptedException, TimeoutException { String subscriber = null; if (sendMsg != null) { // InProcCli proxies - so the subscription needs to be from the sender NOT // from runtime ! subscriber = sendMsg.getSrcFullName(); } else { subscriber = getFullName(); } // put in-process lock in map String callbackMethod = CodecUtils.getCallbackTopicName(method); String blockingKey = String.format("%s.%s", subscriber, callbackMethod); Object[] blockingLockContainer = null; if (!inbox.blockingList.containsKey(blockingKey)) { blockingLockContainer = new Object[1]; inbox.blockingList.put(blockingKey, blockingLockContainer); } else { // if it already exists - other threads are already waiting for the // same callback ... blockingLockContainer = inbox.blockingList.get(blockingKey); } // send subscription subscribe(fullName, method, subscriber, CodecUtils.getCallbackTopicName(method)); if (sendMsg != null) { // possible race condition - counting on the delay of // starting a thread for the program counter to reach the // wait before the msg is sent new Thread("blocking-msg") { public void run() { Runtime.getInstance().send(sendMsg); } }.start(); } synchronized (blockingLockContainer) { if (timeout == null) { blockingLockContainer.wait(); } else { long startTs = System.currentTimeMillis(); blockingLockContainer.wait(timeout); if (System.currentTimeMillis() - startTs >= timeout) { throw new TimeoutException("timeout of %d for %s.%s exceeded", timeout, fullName, method); } } } // cleanup unsubscribe(fullName, method, subscriber, CodecUtils.getCallbackTopicName(method)); return blockingLockContainer[0]; } // equivalent to sendBlocking without the sending a message public Object waitFor(String fullName, String method, Integer timeout) throws InterruptedException, TimeoutException { return waitOn(fullName, method, timeout, null); } public Object sendBlocking(String name, String method) throws InterruptedException, TimeoutException { return sendBlocking(name, method, (Object[]) null); } public Object sendBlocking(String name, String method, Object... data) throws InterruptedException, TimeoutException { // default 1 second timeout - FIXME CONFIGURABLE return sendBlocking(name, 1000, method, data); } @Override public void setInstanceId(URI uri) { instanceId = uri; } /** * rarely should this be used. Gateways use it to provide x-route natting * services by re-writing names with prefixes */ @Override public String getName() { return name; } public Service setState(Service s) { return (Service) copyShallowFrom(this, s); } public void setThisThread(Thread thisThread) { this.thisThread = thisThread; } /** * loadPeer attempts to create then load a peer with current configuration. If * no configuration is found it is not an error, since it was a peer there is * enough information to correctly create a peer service from this services * meta data. * * @param reservedKey * @return */ public ServiceInterface loadPeer(String reservedKey) { try { ServiceInterface si = null; ServiceReservation sr = serviceType.getPeer(reservedKey); if (sr == null) { error("can not create peer from reservedkey %s - no type definition !", reservedKey); return null; } si = createPeer(reservedKey); Runtime runtime = Runtime.getInstance(); String filename = runtime.getConfigDir() + fs + runtime.getConfigName() + fs + sr.actualName + ".yml"; File check = new File(filename); if (!check.exists()) { log.info("no config for {} {} {}", getName(), sr.actualName, filename); return si; } Runtime.load(sr.actualName); return si; } catch (Exception e) { error(e); } return null; } public ServiceInterface startPeer(String reservedKey) { ServiceInterface si = null; try { si = createPeer(reservedKey); if (si == null) { error("could not create service from key %s", reservedKey); return null; } loadPeer(reservedKey); ServiceReservation sr2 = serviceType.getPeer(reservedKey); si.startService(); if (sr2 != null) { sr2.state = "started"; } } catch (Exception e) { error(e.getMessage()); log.error("startPeer threw", e); } broadcastState(); return si; } @Override public void loadAndStart() { try { load(); startService(); } catch (Exception e) { log.error("Load and Start failed.", e); } } @Override synchronized public void startService() { // register locally /* * had to register here for synchronization issues before ... Registration * registration = new Registration(this); Runtime.register(registration); */ // startPeers(); FIXME - TOO BIG A CHANGE .. what should happen is services // should be created // currently they are started by the UI vs created - and there is no desire // or current capability of starting it // afterwards if (!isRunning()) { outbox.start(); if (thisThread == null) { thisThread = new Thread(this, name); } thisThread.start(); isRunning = true; Runtime runtime = Runtime.getInstance(); if (runtime != null) { runtime.broadcast("started", getFullName()); } } else { log.debug("startService request: service {} is already running", name); } if (autoStartPeers) { startPeers(); } } public void startPeers() { log.info("starting peers"); Map<String, ServiceReservation> peers = serviceType.getPeers(); if (peers != null) { for (ServiceReservation sr : peers.values()) { startPeer(sr.key); } } Set<Class<?>> ancestry = new HashSet<Class<?>>(); Class<?> targetClass = this.getClass(); // if we are a org.myrobotlab object climb up the ancestry to // copy all super-type fields ... // GroG says: I wasn't comfortable copying of "Service" - because its never // been tested before - so we copy all definitions from // other superclasses e.g. - org.myrobotlab.service.abstracts // it might be safe in the future to copy all the way up without stopping... while (targetClass.getCanonicalName().startsWith("org.myrobotlab") && !targetClass.getCanonicalName().startsWith("org.myrobotlab.framework")) { ancestry.add(targetClass); targetClass = targetClass.getSuperclass(); } // AUTO ASSIGNMENT - a good idea ? or not ? for (Class<?> sourceClass : ancestry) { Field fields[] = sourceClass.getDeclaredFields(); for (int j = 0, m = fields.length; j < m; j++) { try { Field f = fields[j]; /** * <pre> * int modifiers = f.getModifiers(); * String fname = f.getName(); * if (Modifier.isPrivate(modifiers) || fname.equals("log") || Modifier.isTransient(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { * log.debug("skipping {}", f.getName()); * continue; * } else { * log.debug("copying {}", f.getName()); * } * * Type t = f.getType(); * </pre> */ f.setAccessible(true); Field targetField = sourceClass.getDeclaredField(f.getName()); targetField.setAccessible(true); if (peers.containsKey(f.getName())) { ServiceReservation sr = peers.get(f.getName()); if (sr.autoStart == null || sr.autoStart == false) { log.info("peer defined - but configured to not autoStart"); continue; } if (f.get(this) != null) { log.info("peer {} already assigned", f.getName()); continue; } log.info("assinging {}.{} = startPeer({})", sourceClass.getSimpleName(), f.getName(), f.getName()); Object o = startPeer(f.getName()); targetField.set(this, o); } } catch (Exception e) { log.error("copy failed", e); } } // for each field in class } } /** * Stops the service. Stops threads. */ @Override synchronized public void stopService() { isRunning = false; outbox.stop(); if (thisThread != null) { thisThread.interrupt(); } thisThread = null; Runtime runtime = Runtime.getInstance(); runtime.broadcast("stopped", getFullName()); } public void subscribe(NameProvider topicName, String topicMethod) { String callbackMethod = CodecUtils.getCallbackTopicName(topicMethod); subscribe(topicName.getName(), topicMethod, getName(), callbackMethod); } public void subscribe(String topicName, String topicMethod) { String callbackMethod = CodecUtils.getCallbackTopicName(topicMethod); subscribe(topicName, topicMethod, getName(), callbackMethod); } public void subscribeTo(String service, String method) { subscribe(service, method, getName(), CodecUtils.getCallbackTopicName(method)); } public void subscribeToRuntime(String method) { subscribe(Runtime.getInstance().getName(), method, getName(), CodecUtils.getCallbackTopicName(method)); } public void unsubscribeTo(String service, String method) { unsubscribe(service, method, getName(), CodecUtils.getCallbackTopicName(method)); } public void unsubscribeToRuntime(String method) { unsubscribe(Runtime.getInstance().getName(), method, getName(), CodecUtils.getCallbackTopicName(method)); } public void subscribe(String topicName, String topicMethod, String callbackName, String callbackMethod) { log.info("subscribe [{}/{} ---> {}/{}]", topicName, topicMethod, callbackName, callbackMethod); // TODO - do regex matching if (topicName.contains("*")) { // FIXME "any regex expression List<String> tnames = Runtime.getServiceNames(topicName); for (String serviceName : tnames) { MRLListener listener = new MRLListener(topicMethod, callbackName, callbackMethod); send(Message.createMessage(getName(), serviceName, "addListener", listener)); } } else { if (topicMethod.contains("*")) { // FIXME "any regex expression Set<String> tnames = Runtime.getMethodMap(topicName).keySet(); for (String method : tnames) { MRLListener listener = new MRLListener(method, callbackName, callbackMethod); send(Message.createMessage(getName(), topicName, "addListener", listener)); } } else { MRLListener listener = new MRLListener(topicMethod, callbackName, callbackMethod); send(Message.createMessage(getName(), topicName, "addListener", listener)); } } } public void unsubscribe(NameProvider topicName, String topicMethod) { String callbackMethod = CodecUtils.getCallbackTopicName(topicMethod); unsubscribe(topicName.getName(), topicMethod, getName(), callbackMethod); } public void unsubscribe(String topicName, String topicMethod) { String callbackMethod = CodecUtils.getCallbackTopicName(topicMethod); unsubscribe(topicName, topicMethod, getName(), callbackMethod); } public void unsubscribe(String topicName, String topicMethod, String callbackName, String callbackMethod) { log.info("unsubscribe [{}/{} ---> {}/{}]", topicName, topicMethod, callbackName, callbackMethod); send(Message.createMessage(getName(), topicName, "removeListener", new Object[] { topicMethod, callbackName, callbackMethod })); } public Status error(Exception e) { log.error("status:", e); Status ret = Status.error(e); ret.name = getName(); log.error(ret.toString()); invoke("publishStatus", ret); return ret; } @Override public Status error(String format, Object... args) { Status ret = null; if (format != null) { ret = Status.error(String.format(format, args)); } else { ret = Status.error(String.format("", args)); } ret.name = getName(); log.error(ret.toString()); invoke("publishStatus", ret); return ret; } public Status error(String msg) { return error(msg, (Object[]) null); } public Status warn(String msg) { return warn(msg, (Object[]) null); } @Override public Status warn(String format, Object... args) { Status status = Status.warn(format, args); status.name = getName(); log.warn(status.toString()); invoke("publishStatus", status); return status; } /** * set status broadcasts an info string to any subscribers * * @param msg * m * @return string */ public Status info(String msg) { return info(msg, (Object[]) null); } /** * set status broadcasts an formatted info string to any subscribers */ @Override public Status info(String format, Object... args) { Status status = Status.info(format, args); status.name = getName(); log.info(status.toString()); invoke("publishStatus", status); return status; } /** * error only channel publishing point versus publishStatus which handles * info, warn &amp; error * * @param status * status * @return the status */ public Status publishError(Status status) { return status; } public Status publishStatus(Status status) { return status; } @Override public String toString() { return getName(); } // interesting this is not just in memory public Map<String, MethodEntry> getMethodMap() { return Runtime.getMethodMap(getName()); } @Override public void updateStats(QueueStats stats) { invoke("publishStats", stats); } @Override public QueueStats publishStats(QueueStats stats) { // %d ms %d Kbps", // stats.total, stats.interval, stats.ts - stats.lastTS, 8 * // stats.interval/ (stats.delta))); return stats; } public String getDescription() { return serviceType.getDescription(); } /** * Attachable.detach(serviceName) - routes to reference parameter * Attachable.detach(Attachable) * * FIXME - the "string" attach/detach(string) method should be in the * implementation.. and this abstract should implement the * attach/detach(Attachable) .. because if a string was used as the base * implementation - it would always work when serialized (and not registered) * */ public void detach(String serviceName) { detach(Runtime.getService(serviceName)); } /** * Detaches ALL listeners/subscribers from this service if services have * special requirements, they can override this */ public void detach() { outbox.reset(); } /** * Attachable.attach(serviceName) - routes to reference parameter * Attachable.attach(Attachable) */ public void attach(String serviceName) throws Exception { attach(Runtime.getService(serviceName)); } /** * is Attached - means there is a subscriber with that (full name) */ public boolean isAttached(String serviceName) { return getAttached().contains(serviceName); } /** * This detach when overriden "routes" to the appropriately typed * parameterized detach within a service. * * When overriden, the first thing it should do is check to see if the * referenced service is already detached. If it is already detached it should * simply return. * * If its detached to this service, it should first detach itself, modifying * its own data if necessary. The last thing it should do is call the * parameterized service's detach. This gives the other service an opportunity * to detach. e.g. * * <pre> * * public void detach(Attachable service) { * if (ServoControl.class.isAssignableFrom(service.getClass())) { * detachServoControl((ServoControl) service); * return; * } * * ... route to more detach functions .... * * error("%s doesn't know how to detach a %s", getClass().getSimpleName(), service.getClass().getSimpleName()); * } * * And within detachServoControl : * * public void detachServoControl(ServoControl service) { * // guard * if (!isAttached(service)){ * return; * } * * ... detach logic .... * * // call to detaching service * service.detach(this); * } * </pre> * * @param service * - the service to detach from this service */ @Override public void detach(Attachable service) { outbox.detach(service.getName()); } /** * the "routing" isAttached - when overridden by a service this "routes" to * the appropriate typed isAttached */ @Override public boolean isAttached(Attachable instance) { return isAttached(instance.getName()); } /** * returns all currently attached services */ @Override public Set<String> getAttached() { // return all attached return outbox.getAttached(null); } /** * returns all currently attached services to a specific publishing point */ @Override public Set<String> getAttached(String publishPoint) { return outbox.getAttached(publishPoint); } /** * This attach when overriden "routes" to the appropriately typed * parameterized attach within a service. * * When overriden, the first thing it should do is check to see if the * referenced service is already attached. If it is already attached it should * simply return. * * If its attached to this service, it should first attach itself, modifying * its own data if necessary. The last thing it should do is call the * parameterized service's attach. This gives the other service an opportunity * to attach. e.g. * * <pre> * * public void attach(Attachable service) { * if (ServoControl.class.isAssignableFrom(service.getClass())) { * attachServoControl((ServoControl) service); * return; * } * * ... route to more attach functions .... * * error("%s doesn't know how to attach a %s", getClass().getSimpleName(), service.getClass().getSimpleName()); * } * * And within attachServoControl : * * public void attachServoControl(ServoControl service) { * // guard * if (!isAttached(service)){ * return; * } * * ... attach logic .... * * // call to attaching service * service.attach(this); * } * </pre> * * @param service * - the service to attach from this service */ @Override public void attach(Attachable service) throws Exception { warn(String.format("Service.attach does not know how to attach %s to a %s", service.getClass().getSimpleName(), this.getClass().getSimpleName())); } public boolean setVirtual(boolean b) { this.isVirtual = b; broadcastState(); return isVirtual; } public boolean isVirtual() { return isVirtual; } /** * a convenience method for a Service which always attempts to find a file * with the same ordered precedence * * 1. check data/{MetaData} first (users data directory) 2. check * resource/{MetaData} (mrl's static resource directory) 3. check absolute * path * * @param filename * - file name to get * @return the file to returned or null if does not exist */ public File getFile(String filename) { File file = new File(getDataDir() + fs + filename); if (file.exists()) { log.info("found file in data directory - {}", file.getAbsolutePath()); return file; } file = new File(getResourceDir() + fs + filename); if (file.exists()) { log.info("found file in resource directory - {}", file.getAbsolutePath()); return file; } file = new File(filename); if (file.exists()) { log.info("found file - {}", file.getAbsolutePath()); return file; } error("could not find file {}", file.getAbsolutePath()); return file; } /** * Called by Runtime when system is shutting down a service can use this * method when it has to do some "ordered" cleanup. */ public void preShutdown() { } /** * determines if current process has internet access - moved to Service * recently because it may become Service specific * * @return - true if internet is available */ public static boolean hasInternet() { return Runtime.getPublicGateway() != null; } /** * true when no display is available - moved from Runtime to Service because * it may become Service specific * * @return - true when no display is available */ static public boolean isHeadless() { return java.awt.GraphicsEnvironment.isHeadless(); } public void setOrder(int creationCount) { this.creationOrder = creationCount; } @Deprecated public String getSwagger() { return null; } public String getId() { return id; } public String getFullName() { return String.format("%s@%s", name, id); } public void copyResource(String src, String dest) throws IOException { FileIO.copy(getResourceDir() + File.separator + src, dest); } public void setId(String id) { this.id = id; } /** * non parameter version for use within a Service * * @return bytes of png image * */ public byte[] getServiceIcon() { return getServiceIcon(getClass().getSimpleName()); } /** * static class version for use when class is available "preferred" * * @param serviceType * the type of service * @return the bytes representing it's icon (png) * */ public static byte[] getServiceIcon(Class<?> serviceType) { return getServiceIcon(serviceType.getSimpleName()); } /** * One place to get the ServiceIcons so that we can avoid a lot of strings * with "resource/Servo.png" * * @param serviceType * name of the service type * @return byte array of the icon image (png) * */ public static byte[] getServiceIcon(String serviceType) { try { // this is bad (making a string with resource root // - but at least its only String path = getResourceRoot() + fs + serviceType + ".png"; return Files.readAllBytes(Paths.get(path)); } catch (Exception e) { log.warn("getServiceIcon threw", e); } return null; } public static String getServiceScript(Class<?> clazz) { return getServiceScript(clazz.getSimpleName()); } public static String getServiceScript(String serviceType) { return getResourceAsString(serviceType, String.format("%s.py", serviceType)); } public String getServiceScript() { return getServiceScript(getClass()); } public String getResourceImage(String imageFile) { String path = FileIO.gluePaths(getResourceDir(), imageFile); return Util.getImageAsBase64(path); } /** * Determine if the service is operating in dev mode. isJar() is no longer * appropriate - as some services are modular and can be operating outside in * develop mode in a different repo with a "runtime" myrobotlab.jar. * * @return true if running inside an IDE * */ public boolean isDev() { // 2 folders to check // src/resource/{MetaData} for services still bundled with myrobotlab.jar // and // ../{MetaData}/resource/{MetaData} for services in their own repo File check = new File(FileIO.gluePaths("src/resource", simpleName)); if (check.exists()) { return true; } check = new File(FileIO.gluePaths(String.format("../%s/resource", simpleName), simpleName)); if (check.exists()) { return true; } return false; } public String localize(String key) { return localize(key, (Object[]) null); } /** * String format template processing localization * * @param key * lookup key * @param args * var args * @return localized string for key * */ public String localize(String key, Object... args) { log.debug("{} current locale is {}", getName(), getLocale()); log.debug("{} localization size {}", getName(), localization.size()); if (key == null) { log.error("localize(null) not allowed"); return null; } key = key.toUpperCase(); Object prop = localization.get(key); if (prop == null) { prop = defaultLocalization.get(key); } if (prop == null) { Runtime runtime = Runtime.getInstance(); // tried to resolve local to this service and failed if (this != runtime) { // if we are not runtime - we ask runtime prop = runtime.localize(key, args); } else if (this == runtime) { // if we are runtime - we try default en prop = runtime.localizeDefault(key); } } if (prop == null) { log.error("please help us get a good translation for {} in {}", key, Runtime.getInstance().getLocale().getTag()); return null; } if (args == null) { return prop.toString(); } else { return String.format(prop.toString(), args); } } public void loadLocalizations() { if (defaultLocalization == null) { // default is always english :P defaultLocalization = Locale.loadLocalizations(FileIO.gluePaths(getResourceDir(), "localization/en.properties")); } localization = Locale.loadLocalizations(FileIO.gluePaths(getResourceDir(), "localization/" + locale.getLanguage() + ".properties")); } /** * set the current locale for this service - initial locale would have been * set by Runtimes locale * */ public void setLocale(String code) { locale = new Locale(code); log.info("{} new locale is {}", getName(), code); loadLocalizations(); broadcastState(); } /** * @return get country tag of current locale */ public String getCountry() { return locale.getCountry(); } /** * Java does regions string codes differently than other systems en_US vs * en-US ... seems like there has been a lot of confusion on which delimiter * to use This function is used to simplify all of that - since we are * primarily interested in language and do not usually need the distinction * between regions in this context * * @return the language from the locale * */ public String getLanguage() { return locale.getLanguage(); } /** * @return the current locale */ public Locale getLocale() { return locale; } /** * @return get country name of current locale */ public String getDisplayLanguage() { return locale.getDisplayLanguage(); } /** * @return get current locale tag - this is of the form en-BR en-US including * region */ public String getLocaleTag() { return locale.getTag(); } public boolean hasInterface(String interfaze) { // probably a bad idea - but nice for lazy people if (!interfaze.contains(".")) { interfaze = String.format("org.myrobotlab.service.interfaces.%s", interfaze); } return interfaceSet.containsKey(interfaze); } @Override public boolean hasInterface(Class<?> interfaze) { return hasInterface(interfaze.getCanonicalName()); } public Set<String> getInterfaceNames() { Set<String> fn = new TreeSet<>(); Class<?>[] faces = getClass().getInterfaces(); for (Class<?> c : faces) { fn.add(c.getCanonicalName()); } return fn; } // a "helper" strongly typed Java function @Override public boolean isType(Class<?> clazz) { return isType(clazz.getCanonicalName()); } /** * This function does a type comparison of the service and a string passed in. * It's important that this does not use getClass() to resolve the type, * instead to support polyglot proxies - it should be using a string to * compare types */ @Override public boolean isType(String clazz) { // probably a bad idea - but nice for lazy people if (!clazz.contains(".")) { clazz = String.format("org.myrobotlab.service.%s", clazz); } return serviceClass.equals(clazz); } @Override public void onRegistered(Registration registration) { // service life-cycle callback - override if interested in these events } @Override public void onCreated(String fullname) { // service life-cycle callback - override if interested in these events } @Override public void onStarted(String fullname) { // service life-cycle callback - override if interested in these events } @Override public void onStopped(String fullname) { // service life-cycle callback - override if interested in these events } @Override public void onReleased(String fullname) { // service life-cycle callback - override if interested in these events } public boolean isStarted(String peerKey) { ServiceInterface si = getPeer(peerKey); if (si == null || !si.isRunning()) { return false; } return true; } @Override public int compareTo(ServiceInterface o) { if (this.creationOrder == o.getCreationOrder()) { return 0; } if (this.creationOrder < o.getCreationOrder()) { return -1; } return 1; } public int getCreationOrder() { return creationOrder; } public boolean isPeerStarted(String peerKey) { if (serviceType.peers != null) { if (!serviceType.peers.containsKey(peerKey)) { return false; } ServiceReservation sr = serviceType.peers.get(peerKey); return "started".equals(sr.state); } return false; } }
package org.myrobotlab.service; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.alicebot.ab.AIMLMap; import org.alicebot.ab.AIMLSet; import org.alicebot.ab.Bot; import org.alicebot.ab.Category; import org.alicebot.ab.Chat; import org.alicebot.ab.Predicates; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.programab.ChatData; import org.myrobotlab.programab.OOBPayload; import org.myrobotlab.service.interfaces.TextListener; import org.myrobotlab.service.interfaces.TextPublisher; import org.slf4j.Logger; public class ProgramAB extends Service implements TextListener, TextPublisher { transient public final static Logger log = LoggerFactory.getLogger(ProgramAB.class); public static class Response { public String session; public String msg; transient public List<OOBPayload> payloads; // FIXME - timestamps are usually longs System.currentTimeMillis() public Date timestamp; public Response(String session, String msg, List<OOBPayload> payloads, Date timestamp) { this.session = session; this.msg = msg; this.payloads = payloads; this.timestamp = timestamp; } public String toString() { return String.format("%d %s %s", timestamp.getTime(), session, msg); } } transient Bot bot = null; HashSet<String> bots = new HashSet<String>(); private String path = "ProgramAB"; public boolean aimlError = false; /** * botName - is un-initialized to preserve serialization stickyness */ // String botName; // This is the username that is chatting with the bot. // String currentSession = "default"; // Session is a user and a bot. so the key to the session should be the // username, and the bot name. transient HashMap<String, ChatData> sessions = new HashMap<String, ChatData>(); // TODO: better parsing than a regex... transient Pattern oobPattern = Pattern.compile("<oob>.*?</oob>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); transient Pattern mrlPattern = Pattern.compile("<mrl>.*?</mrl>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); // a guaranteed bot we have private String currentBotName = "alice2"; // this is the username that is chatting with the bot. private String currentUserName = "default"; public boolean loading = false; static final long serialVersionUID = 1L; static int savePredicatesInterval = 60 * 1000 * 5; // every 5 minutes public String wasCleanyShutdowned; public ProgramAB(String name) { super(name); // Tell programAB to persist it's learned predicates about people // every 30 seconds. addTask("savePredicates", savePredicatesInterval, 0, "savePredicates"); // TODO: Lazy load this! // look for local bots defined File programAbDir = new File(String.format("%s/bots", getPath())); if (!programAbDir.exists() || !programAbDir.isDirectory()) { log.info("%s does not exist !!!"); } else { File[] listOfFiles = programAbDir.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { // System.out.println("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { bots.add(listOfFiles[i].getName()); } } } } public void addOOBTextListener(TextListener service) { addListener("publishOOBText", service.getName(), "onOOBText"); } public void addResponseListener(Service service) { addListener("publishResponse", service.getName(), "onResponse"); } public void addTextListener(TextListener service) { addListener("publishText", service.getName(), "onText"); } public void addTextPublisher(TextPublisher service) { subscribe(service.getName(), "publishText"); } private void cleanOutOfDateAimlIFFiles(String botName) { String aimlPath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "aiml"; String aimlIFPath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "aimlif"; aimlError = false; log.info("AIML FILES:"); File folder = new File(aimlPath); File folderaimlIF = new File(aimlIFPath); if (!folder.exists()) { log.error("{} does not exist", aimlPath); aimlError = true; return; } if (wasCleanyShutdowned == null || wasCleanyShutdowned.isEmpty()) { wasCleanyShutdowned = "firstStart"; } if (wasCleanyShutdowned.equals("nok")) { if (folderaimlIF.exists()) { // warn("Bad previous shutdown, ProgramAB need to recompile AimlIf // files. Don't worry."); log.info("Bad previous shutdown, ProgramAB need to recompile AimlIf files. Don't worry."); for (File f : folderaimlIF.listFiles()) { f.delete(); } } } log.info(folder.getAbsolutePath()); HashMap<String, Long> modifiedDates = new HashMap<String, Long>(); for (File f : folder.listFiles()) { log.info(f.getAbsolutePath()); // TODO: better stripping of the file extension String aiml = f.getName().replace(".aiml", ""); modifiedDates.put(aiml, f.lastModified()); } log.info("AIMLIF FILES:"); folderaimlIF = new File(aimlIFPath); if (!folderaimlIF.exists()) { // TODO: throw an exception warn / log ? log.info("aimlif directory missing,creating it. " + folderaimlIF.getAbsolutePath()); folderaimlIF.mkdirs(); return; } for (File f : folderaimlIF.listFiles()) { log.info(f.getAbsolutePath()); // TODO: better stripping of the file extension String aimlIF = f.getName().replace(".aiml.csv", ""); Long lastMod = modifiedDates.get(aimlIF); if (lastMod != null) { if (f.lastModified() < lastMod) { // the AIMLIF file is newer than the AIML file. // delete the AIMLIF file so ProgramAB recompiles it // properly. log.info("Deleteing AIMLIF file because the original AIML file was modified. {}", aimlIF); f.delete(); // edit moz4r : we need to change the last modification date to aiml // folder for recompilation sleep(1000); String fil = aimlPath + File.separator + "folder_updated"; File file = new File(fil); file.delete(); try { PrintWriter writer = new PrintWriter(fil, "UTF-8"); writer.println(lastMod.toString()); writer.close(); } catch (IOException e) { // do something } } } } } private String createSessionPredicateFilename(String username, String botName) { // TODO: sanitize the session label so it can be safely used as a filename String predicatePath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "config"; // just in case the directory doesn't exist.. make it. File predDir = new File(predicatePath); if (!predDir.exists()) { predDir.mkdirs(); } predicatePath += File.separator + username + ".predicates.txt"; return predicatePath; } public int getMaxConversationDelay() { return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).maxConversationDelay; } public Response getResponse(String text) { return getResponse(getCurrentUserName(), text); } /** * * @param text * - the query string to the bot brain * @param username * - the user that is sending the query * @param botName * - the name of the bot you which to get the response from * @return the response for a user from a bot given the input text. */ public Response getResponse(String username, String botName, String text) { this.setCurrentBotName(botName); return getResponse(username, text); } public Response getResponse(String username, String text) { log.info("Get Response for : user {} bot {} : {}", username, getCurrentBotName(), text); if (bot == null) { String error = "ERROR: Core not loaded, please load core before chatting."; error(error); return new Response(username, error, null, new Date()); } if (text.isEmpty()) { return new Response(username, "", null, new Date()); } String sessionKey = resolveSessionKey(username, getCurrentBotName()); if (!sessions.containsKey(sessionKey)) { startSession(getPath(), username, getCurrentBotName()); } ChatData chatData = sessions.get(sessionKey); String res = getChat(username, getCurrentBotName()).multisentenceRespond(text); // grab and update the time when this response came in. chatData.lastResponseTime = new Date(); // Check the AIML response to see if there is OOB (out of band data) // If so, publish that data independent of the text response. List<OOBPayload> payloads = null; if (chatData.processOOB) { payloads = processOOB(res); } // OOB text should not be published as part of the response text. Matcher matcher = oobPattern.matcher(res); res = matcher.replaceAll("").trim(); Response response = new Response(username, res, payloads, chatData.lastResponseTime); // Now that we've said something, lets create a timer task to wait for N // seconds // and if nothing has been said.. try say something else. // TODO: trigger a task to respond with something again // if the humans get bored if (chatData.enableAutoConversation) { // schedule one future reply. (always get the last word in..) // int numExecutions = 1; // TODO: we need a way for the task to just execute one time // it'd be good to have access to the timer here, but it's transient addTask("getResponse", chatData.maxConversationDelay, 0, "getResponse", username, text); } // EEK! clean up the API! invoke("publishResponse", response); invoke("publishResponseText", response); invoke("publishText", response.msg); info("to: %s - %s", username, res); // if (log.isDebugEnabled()) { // for (String key : sessions.get(session).predicates.keySet()) { // log.debug(session + " " + key + " " + // sessions.get(session).predicates.get(key)); // TODO: wire this in so the gui updates properly. ?? // broadcastState(); return response; } public String resolveSessionKey(String username, String botname) { return username + "-" + botname; } public void repetition_count(int val) { org.alicebot.ab.MagicNumbers.repetition_count = val; } public Chat getChat(String userName, String botName) { String sessionKey = resolveSessionKey(userName, botName); if (!sessions.containsKey(sessionKey)) { error("%s session does not exist", sessionKey); return null; } else { return sessions.get(sessionKey).chat; } } public void removePredicate(String userName, String predicateName) { removePredicate(userName, getCurrentBotName(), predicateName); } public void removePredicate(String userName, String botName, String predicateName) { Predicates preds = getChat(userName, botName).predicates; preds.remove(predicateName); } public void addToSet(String setName, String setValue) { // add to the set for the bot. AIMLSet updateSet = bot.setMap.get(setName); setValue = setValue.toUpperCase().trim(); if (updateSet != null) { updateSet.add(setValue); // persist to disk. updateSet.writeAIMLSet(); } else { log.info("Unknown AIML set: {}. A new set will be created. ", setName); // TODO: should we create a new set ? or just log this warning? // The AIML Set doesn't exist. Lets create a new one AIMLSet newSet = new AIMLSet(setName, bot); newSet.add(setValue); newSet.writeAIMLSet(); } } public void addToMap(String mapName, String mapKey, String mapValue) { // add an entry to the map. AIMLMap updateMap = bot.mapMap.get(mapName); mapKey = mapKey.toUpperCase().trim(); if (updateMap != null) { updateMap.put(mapKey, mapValue); // persist to disk! updateMap.writeAIMLMap(); } else { log.info("Unknown AIML map: {}. A new MAP will be created. ", mapName); // dynamically create new maps?! AIMLMap newMap = new AIMLMap(mapName, bot); newMap.put(mapKey, mapValue); newMap.writeAIMLMap(); } } public void setPredicate(String username, String predicateName, String predicateValue) { Predicates preds = getChat(username, getCurrentBotName()).predicates; preds.put(predicateName, predicateValue); } public void unsetPredicate(String username, String predicateName) { Predicates preds = getChat(username, getCurrentBotName()).predicates; preds.remove(predicateName); } public String getPredicate(String username, String predicateName) { Predicates preds = getChat(username, getCurrentBotName()).predicates; return preds.get(predicateName); } /** * Only respond if the last response was longer than delay ms ago * * @param session * - current session/username * @param text * - text to get a response for * @param delay * - min amount of time that must have transpired since the last * response. * @return the response */ public Response getResponse(String session, String text, Long delay) { ChatData chatData = sessions.get(session); long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime(); if (delta > delay) { return getResponse(session, text); } else { return null; } } public boolean isEnableAutoConversation() { return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).enableAutoConversation; } public boolean isProcessOOB() { return sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).processOOB; } /** * Return a list of all patterns that the AIML Bot knows to match against. * * @param botName * the bots name from which to return it's patterns. * @return a list of all patterns loaded into the aiml brain */ public ArrayList<String> listPatterns(String botName) { ArrayList<String> patterns = new ArrayList<String>(); for (Category c : bot.brain.getCategories()) { patterns.add(c.getPattern()); } return patterns; } /** * Return the number of milliseconds since the last response was given -1 if a * response has never been given. * * @return milliseconds */ public long millisecondsSinceLastResponse() { ChatData chatData = sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())); if (chatData.lastResponseTime == null) { return -1; } long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime(); return delta; } @Override public void onText(String text) { // What else should we do here? seems reasonable to just do this. // this should actually call getResponse // on input, get the proper response // Response resp = getResponse(text); getResponse(text); // push that to the next end point. // invoke("publishText", resp.msg); } private OOBPayload parseOOB(String oobPayload) { // TODO: fix the damn double encoding issue. // we have user entered text in the service/method // and params values. // grab the service Pattern servicePattern = Pattern.compile("<service>(.*?)</service>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher serviceMatcher = servicePattern.matcher(oobPayload); serviceMatcher.find(); String serviceName = serviceMatcher.group(1); Pattern methodPattern = Pattern.compile("<method>(.*?)</method>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher methodMatcher = methodPattern.matcher(oobPayload); methodMatcher.find(); String methodName = methodMatcher.group(1); Pattern paramPattern = Pattern.compile("<param>(.*?)</param>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher paramMatcher = paramPattern.matcher(oobPayload); ArrayList<String> params = new ArrayList<String>(); while (paramMatcher.find()) { // We found some OOB text. // assume only one OOB in the text? String param = paramMatcher.group(1); params.add(param); } OOBPayload payload = new OOBPayload(serviceName, methodName, params); // log.info(payload.toString()); return payload; // JAXB stuff blows up because the response from program ab is already // xml decoded! // JAXBContext jaxbContext; // try { // jaxbContext = JAXBContext.newInstance(OOBPayload.class); // Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); // log.info("OOB PAYLOAD :" + oobPayload); // Reader r = new StringReader(oobPayload); // OOBPayload oobMsg = (OOBPayload) jaxbUnmarshaller.unmarshal(r); // return oobMsg; // } catch (JAXBException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // log.info("OOB tag found, but it's not an MRL tag. {}", oobPayload); // return null; } private List<OOBPayload> processOOB(String text) { // Find any oob tags ArrayList<OOBPayload> payloads = new ArrayList<OOBPayload>(); Matcher oobMatcher = oobPattern.matcher(text); while (oobMatcher.find()) { // We found some OOB text. // assume only one OOB in the text? String oobPayload = oobMatcher.group(0); Matcher mrlMatcher = mrlPattern.matcher(oobPayload); while (mrlMatcher.find()) { String mrlPayload = mrlMatcher.group(0); OOBPayload payload = parseOOB(mrlPayload); payloads.add(payload); // TODO: maybe we dont' want this? // Notifiy endpoints invoke("publishOOBText", mrlPayload); // grab service and invoke method. ServiceInterface s = Runtime.getService(payload.getServiceName()); if (s == null) { log.warn("Service name in OOB/MRL tag unknown. {}", mrlPayload); return null; } // TODO: should you be able to be synchronous for this // execution? Object result = null; if (payload.getParams() != null) { result = s.invoke(payload.getMethodName(), payload.getParams().toArray()); } else { result = s.invoke(payload.getMethodName()); } log.info("OOB PROCESSING RESULT: {}", result); } } if (payloads.size() > 0) { return payloads; } else { return null; } } /* * If a response comes back that has an OOB Message, publish that separately */ public String publishOOBText(String oobText) { return oobText; } /* * publishing method of the pub sub pair - with addResponseListener allowing * subscriptions pub/sub routines have the following pattern * * publishing routine -&gt; publishX - must be invoked to provide data to * subscribers subscription routine -&gt; addXListener - simply adds a Service * listener to the notify framework any service which subscribes must * implement -&gt; onX(data) - this is where the data will be sent (the * call-back) * */ public Response publishResponse(Response response) { return response; } /* * Test only publishing point - for simple consumers */ public String publishResponseText(Response response) { return response.msg; } @Override public String publishText(String text) { // clean up whitespaces & cariage return text = text.replaceAll("\\n", " "); text = text.replaceAll("\\r", " "); text = text.replaceAll("\\s{2,}", " "); return text; } public void reloadSession(String session, String botName) { reloadSession(getPath(), session, botName); } public void reloadSession(String path, String username, String botname) { reloadSession(path, username, botname, false); } public void reloadSession(String path, String username, String botname, Boolean killAimlIf) { loading = true; broadcastState(); // kill the bot writeAndQuit(killAimlIf); // kill the session String sessionKey = resolveSessionKey(username, botname); if (sessions.containsKey(sessionKey)) { // TODO: will garbage collection clean up the bot now ? // Or are there other handles to it? sessions.remove(sessionKey); } bot = null; // TODO: we should make sure we keep the same path as before. startSession(path, username, getCurrentBotName()); } /** * Persist the predicates for all known sessions in the robot. * */ public void savePredicates() throws IOException { for (String session : sessions.keySet()) { // TODO: better parsing of this. String[] parts = session.split("-"); String username = parts[0]; String botname = session.substring(username.length() + 1); String sessionPredicateFilename = createSessionPredicateFilename(username, botname); File sessionPredFile = new File(sessionPredicateFilename); Chat chat = getChat(username, botname); // overwrite the original file , this should always be a full set. log.info("Writing predicate file for session {}", session); FileWriter predWriter = new FileWriter(sessionPredFile, false); for (String predicate : chat.predicates.keySet()) { String value = chat.predicates.get(predicate); predWriter.write(predicate + ":" + value + "\n"); } predWriter.close(); } log.info("Done saving predicates."); } public void setEnableAutoConversation(boolean enableAutoConversation) { sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).enableAutoConversation = enableAutoConversation; } public void setMaxConversationDelay(int maxConversationDelay) { sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).maxConversationDelay = maxConversationDelay; } public void setProcessOOB(boolean processOOB) { sessions.get(resolveSessionKey(getCurrentUserName(), getCurrentBotName())).processOOB = processOOB; } public void startSession() { startSession(null); } public void startSession(String session) { startSession(session, getCurrentBotName()); } public Set<String> getSessionNames() { return sessions.keySet(); } /** * Load the AIML 2.0 Bot config and start a chat session. This must be called * after the service is created. * * @param session * - The new session name * @param botName * - The name of the bot to load. (example: alice2) */ public void startSession(String session, String botName) { startSession(getPath(), session, botName); } public void startSession(String path, String userName, String botName) { loading = true; this.setPath(path); info("starting Chat Session path:%s username:%s botname:%s", path, userName, botName); this.setCurrentBotName(botName); this.setCurrentUserName(userName); broadcastState(); // Session is between a user and a bot. key is compound. String sessionKey = resolveSessionKey(userName, botName); if (sessions.containsKey(sessionKey)) { warn("session %s already created", sessionKey); return; } if (!getSessionNames().isEmpty()) { wasCleanyShutdowned = "ok"; } cleanOutOfDateAimlIFFiles(botName); wasCleanyShutdowned = "nok"; // TODO: manage the bots in a collective pool/hash map. if (bot == null) { bot = new Bot(botName, path); } else if (!botName.equalsIgnoreCase(bot.name)) { bot = new Bot(botName, path); } Chat chat = new Chat(bot); // for (Category c : bot.brain.getCategories()) { // log.info(c.getPattern()); // String resp = chat.multisentenceRespond("hello"); // load session specific predicates, these override the default ones. String sessionPredicateFilename = createSessionPredicateFilename(userName, botName); chat.predicates.getPredicateDefaults(sessionPredicateFilename); sessions.put(resolveSessionKey(getCurrentUserName(), getCurrentBotName()), new ChatData(chat)); // lets test if the robot knows the name of the person in the session String name = chat.predicates.get("name").trim(); // TODO: this implies that the default value for "name" is default // "Friend" if (name == null || "Friend".equalsIgnoreCase(name) || "unknown".equalsIgnoreCase(name)) { // TODO: find another interface that's simpler to use for this // create a string that represents the predicates file String inputPredicateStream = "name:" + userName; // load those predicates chat.predicates.getPredicateDefaultsFromInputStream(FileIO.toInputStream(inputPredicateStream)); } // this.currentBotName = botName; // String userName = chat.predicates.get("name"); log.info("Started session for bot name:{} , username:{}", botName, userName); // TODO: to make sure if the start session is updated, that the button // updates in the gui ? this.save(); loading = false; broadcastState(); } public void setPath(String path) { this.path = path; } public void setCurrentBotName(String currentBotName) { this.currentBotName = currentBotName; } /** * setUsername will check if username correspond to current session If no, a * new session is started * * @param username * - The new username * @return boolean - True if username changed * @throws IOException */ public boolean setUsername(String username) { if (username.isEmpty()) { log.error("chatbot username is empty"); return false; } if (getSessionNames().isEmpty()) { log.info(username + " first session started"); startSession(username); return false; } try { savePredicates(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (username.equalsIgnoreCase(this.getCurrentUserName())) { log.info(username + " already connected"); return false; } if (!username.equalsIgnoreCase(this.getCurrentUserName())) { startSession(this.getPath(), username, this.getCurrentBotName()); setPredicate(username, "name", username); setPredicate("default", "lastUsername", username); // robot name is stored inside default.predicates, not inside system.prop setPredicate(username, "botname", getPredicate("default", "botname")); try { savePredicates(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(username + " session started"); return true; } return false; } public void writeAIML() { bot.writeAIMLFiles(); } public void writeAIMLIF() { bot.writeAIMLIFFiles(); } public void writeAndQuit() { writeAndQuit(false); } /** * writeAndQuit will clean shutdown BOT so next stratup is sync & faaaast * * @param killAimlIf * - Delete aimlif and restart bot from aiml - Useful to push aiml * modifications in realtime - Without restart whole script */ public void writeAndQuit(Boolean killAimlIf) { if (bot == null) { log.info("no bot - don't need to write and quit"); return; } try { savePredicates(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String fil = bot.aimlif_path + File.separator + "folder_updated"; if (!killAimlIf) { bot.writeQuit(); wasCleanyShutdowned = "ok"; // edit moz4r : we need to change the last modification date to aimlif // folder because at this time all is compilated. // so programAb don't need to load AIML at startup sleep(1000); File folder = new File(bot.aimlif_path); for (File f : folder.listFiles()) { f.setLastModified(System.currentTimeMillis()); } } else { fil = bot.aiml_path + File.separator + "folder_updated"; } File file = new File(fil); file.delete(); try { PrintWriter writer = new PrintWriter(fil, "UTF-8"); writer.println(""); writer.close(); } catch (IOException e) { log.error("PrintWriter error"); } } public void attach(Attachable attachable) { if (attachable instanceof TextPublisher) { addTextPublisher((TextPublisher) attachable); } else if (attachable instanceof TextListener){ addListener("publishText", attachable.getName(), "onText"); } else { log.error("don't know how to attach a {}", attachable.getName()); } } @Override public void stopService() { try { savePredicates(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } writeAndQuit(); super.stopService(); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(ProgramAB.class.getCanonicalName()); meta.addDescription("AIML 2.0 Reference interpreter based on Program AB"); meta.addCategory("intelligence"); meta.addDependency("program-ab", "program-ab-data", "0.0.4.1", "zip"); meta.addDependency("program-ab", "program-ab-kw", "0.0.4.1"); meta.addDependency("org.json", "json", "20090211"); return meta; } public static void main(String s[]) throws IOException { try { LoggingFactory.init("INFO"); Runtime.start("gui", "SwingGui"); // Runtime.start("webgui", "WebGui"); ProgramAB brain = (ProgramAB) Runtime.start("brain", "ProgramAB"); // brain.startSession("default", "alice2"); WebkitSpeechRecognition ear = (WebkitSpeechRecognition) Runtime.start("ear", "WebkitSpeechRecognition"); MarySpeech mouth = (MarySpeech) Runtime.start("mouth", "MarySpeech"); // mouth.attach(ear); ear.attach(mouth); // ear.addMouth(mouth); brain.attach(ear); mouth.attach(brain); brain.startSession("default", "Alice2"); // ear.startListening(); // FIXME - make this work // brain.attach(mouth); // ear.attach(mouth); // FIXME !!! - make this work // ear.attach(mouth); // brain.addTextPublisher(service); // ear.attach(brain); /* * log.info(brain.getResponse("hi there").toString()); * log.info(brain.getResponse("").toString()); * log.info(brain.getResponse("test").toString()); * log.info(brain.getResponse("").toString()); brain.setUsername("test"); */ brain.savePredicates(); } catch (Exception e) { log.error("main threw", e); } } public String getPath() { return path; } public String getCurrentUserName() { return currentUserName; } public void setCurrentUserName(String currentUserName) { this.currentUserName = currentUserName; } public String getCurrentBotName() { return currentBotName; } }
package org.normandra.graph; import org.normandra.EntityManager; import org.normandra.NormandraException; import org.normandra.meta.EntityMeta; import org.normandra.meta.GraphMeta; import java.util.*; /** * a graph manager api * * @date 5/30/17. */ public class GraphManager extends EntityManager { private final Graph graph; private final GraphMeta meta; public GraphManager(final Graph db, final GraphMeta meta) { super(db, meta); this.graph = db; this.meta = meta; } @Override public Graph getSession() { return this.graph; } public GraphMeta getMeta() { return this.meta; } /** * Add entity as node to graph database. * * @param entity registered entity * @param <T> * @return Node instance if created, else null. * @throws NormandraException */ public <T> Node<T> addNode(final T entity) throws NormandraException { if (null == entity) { return null; } final EntityMeta meta = this.meta.getNodeMeta(entity.getClass()); if (null == meta) { throw new IllegalArgumentException("Entity [" + entity.getClass() + "] is not node type."); } return this.graph.addNode(meta, entity); } /** * Query node by entity id. * * @param clazz registered entity * @param key entity key * @param <T> * @return Node instance if found, else null. * @throws NormandraException */ public <T> Node<T> getNode(final Class<T> clazz, final Object key) throws NormandraException { if (null == clazz || null == key) { return null; } final EntityMeta meta = this.meta.getNodeMeta(clazz); if (null == meta) { throw new IllegalArgumentException("Entity [" + clazz + "] is not node type."); } return this.graph.getNode(meta, key); } /** * Query nodes by set of entity ids. * * @param clazz registered entity * @param keys set of entity keys * @param <T> * @return Collection of nodes matching one or more keys. * @throws NormandraException */ public <T> Collection<Node> getNodes(final Class<T> clazz, final Iterable<?> keys) throws NormandraException { if (null == clazz || null == keys) { return Collections.emptyList(); } final EntityMeta meta = this.meta.getNodeMeta(clazz); if (null == meta) { throw new IllegalArgumentException("Entity [" + clazz + "] is not node type."); } final Set<Object> filteredKeys = new HashSet<>(); for (final Object key : keys) { if (key != null) { filteredKeys.add(key); } } if (filteredKeys.isEmpty()) { return Collections.emptyList(); } return this.graph.getNodes(meta, filteredKeys); } public <T> Collection<Node> getNodes(final Class<T> clazz, final Object... keys) throws NormandraException { return getNodes(clazz, Arrays.asList(keys)); } /** * Query edge by entity id. * * @param clazz * @param key * @param <T> * @return * @throws NormandraException */ public <T> Edge<T> getEdge(final Class<T> clazz, final Object key) throws NormandraException { if (null == clazz || null == key) { return null; } final EntityMeta meta = this.meta.getEdgeMeta(clazz); if (null == meta) { throw new IllegalArgumentException("Entity [" + clazz + "] is not edge type."); } return this.graph.getEdge(meta, key); } }
package org.oscii.detokenize; import cc.mallet.classify.Classification; import cc.mallet.classify.Classifier; import cc.mallet.classify.ClassifierTrainer; import cc.mallet.classify.MaxEntL1Trainer; import cc.mallet.pipe.*; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import edu.stanford.nlp.mt.process.Preprocessor; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.Sequence; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * A classification-based detokenizer. */ public class Detokenizer { private static final double L1_WEIGHT = 0.1; Classifier classifier; // Weights private Detokenizer(Classifier classifier) { this.classifier = classifier; } /* * Save to a file. */ public void save(File file) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject (classifier); oos.close(); } /* * Load from a file. */ public static Detokenizer load(File file) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream (new FileInputStream (file)); Classifier classifier = (Classifier) ois.readObject(); ois.close(); return new Detokenizer(classifier); } /* * Train a detokenizer for a preprocessor by inspecting its behavior on examples. */ public static Detokenizer train(Preprocessor preprocessor, List<String> examples) { Pipe pipe = new SerialPipes(new Pipe[]{ new FeaturePipe(), new TokenSequence2FeatureSequence(), new FeatureSequence2FeatureVector(false), new Target2Label() }); InstanceList instances = new InstanceList(pipe); Iterator<Instance> labeled = toLabeledInstances(examples, preprocessor); instances.addThruPipe(labeled); ClassifierTrainer trainer = new MaxEntL1Trainer(L1_WEIGHT); Classifier classifier = trainer.train(instances); return new Detokenizer(classifier); } /* * Label a list of tokens that has been tokenized using the preprocessor. */ public List<TokenLabel> predictLabels(List<String> tokens) { InstanceList instances = new InstanceList(classifier.getInstancePipe()); Stream<Integer> range = IntStream.range(0, tokens.size()).boxed(); Iterator<Instance> unlabeled = range.map(i -> Token.unlabeledInstance(i, tokens)).iterator(); instances.addThruPipe(unlabeled); List<Classification> predictions = classifier.classify(instances); List<TokenLabel> labels = predictions.stream().map(Detokenizer::getLabel).collect(toList()); return labels; } /* * Generate labeled training data from a preprocessor. */ private static Iterator<Instance> toLabeledInstances(List<String> examples, Preprocessor preprocessor) { Labeler labeler = new Labeler(); List<Instance> instances = new ArrayList<>(); examples.forEach(ex -> { List<String> tokens = tokenize(preprocessor, ex); List<TokenLabel> labels = labeler.getLabels(ex, tokens); for (int i = 0; i < tokens.size(); i++) { TokenLabel label = labels.get(i); instances.add(Token.labeledInstance(i, tokens, label)); } }); return instances.iterator(); } /* * Extract the best label from a classifier prediction. */ private static TokenLabel getLabel(Classification c) { return (TokenLabel) c.getLabeling().getBestLabel().getEntry(); } public static List<String> tokenize(Preprocessor preprocessor, String sentence) { Sequence<IString> tokenSequence = preprocessor.process(sentence); List<String> tokens = new ArrayList<>(tokenSequence.size()); tokenSequence.forEach(t -> tokens.add(t.toString())); return tokens; } }
package org.vetmeduni.tools; import htsjdk.samtools.SAMException; import htsjdk.samtools.SAMProgramRecord; import htsjdk.samtools.util.Log; import org.apache.commons.cli.*; import org.vetmeduni.readtools.Main; import org.vetmeduni.readtools.ProjectProperties; import java.io.IOException; import java.io.PrintWriter; import static org.vetmeduni.tools.ToolNames.ToolException; public abstract class AbstractTool implements Tool { /** * Implementation that use {@link #runThrowingExceptions(org.apache.commons.cli.CommandLine)} and handle or the know * exceptions: {@link org.vetmeduni.tools.ToolNames.ToolException} if there is some problem parsing the command * line, {@link java.io.IOException} if there are problems with the files * * @param args arguments that comes directly from the command line and need to be parsed * * @return 0 if there is no exception, 1 if there is a known exception, 2 otherwise */ @Override public int run(String[] args) { try { final CommandLine cmd = programParser(args); runThrowingExceptions(cmd); } catch (ToolException e) { // This exceptions comes from the command line parsing printUsage(e.getMessage()); return 1; } catch (SAMException | IOException e) { // this are expected errors: IO if the user provides bad inputs, SAM if there are problems in the files logger.error(e.getMessage()); logger.debug(e); return 1; } catch (Exception e) { // unexpected exceptions return a different error code logger.debug(e); logger.error(e.getMessage()); return 2; } return 0; } /** * Run the current tool and throw exceptions that will be handle by {@link #run(String[])}. See {@link * #run(String[])} for the exceptions that are handle * * @param cmd the already parsed command line with the programParser * * @throws Exception */ protected abstract void runThrowingExceptions(final CommandLine cmd) throws Exception; /** * Function that returns the options for the program * * @return the program options */ protected abstract Options programOptions(); /** * Help option (common for all the tools) */ private static final Options helpOption = new Options().addOption(Option.builder("h"). longOpt("help").desc("Print this message and exit").build()); /** * The logger to use in the tools */ protected final Log logger; /** * Constructor for the abstract tool that start the logger */ public AbstractTool() { logger = Log.getInstance(this.getClass()); } /** * Log the command line (with the known options) * * @param cmd the already parsed command line with the programParser */ protected void logCmdLine(CommandLine cmd) { logger.info("Running ", this.getClass().getSimpleName(), " with arguments: ", getCmdLineString(cmd)); } /** * Get the arguments with the string * * @param cmd the already parsed command line with the programParser * * @return the string with the arguments in the command line properly formatted */ protected String getCmdLineString(CommandLine cmd) { StringBuilder builder = new StringBuilder(""); for (Option opt : cmd.getOptions()) { if (opt.hasArg()) { for (String val : opt.getValues()) { builder.append(" builder.append(opt.getLongOpt()); builder.append(" "); builder.append(val); builder.append(" "); } } else { builder.append(" builder.append(opt.getLongOpt()); builder.append(" "); } } return builder.toString(); } /** * Output to System.err the help for this tool (with the full description) */ protected void help() { ToolNames tool = ToolNames.valueOf(this.getClass().getSimpleName()); HelpFormatter formatter = new HelpFormatter(); PrintWriter writer = new PrintWriter(System.err); Main.printProgramHeader(writer); writer.println(); writer.println(String.format("%s: %s", tool, tool.shortDescription)); writer.println(" formatter.printWrapped(writer, formatter.getWidth(), tool.fullDescription); writer.println(" formatter.printHelp(writer, formatter.getWidth(), usage(), "\n", programOptions(), formatter.getLeftPadding(), formatter.getDescPadding(), "", true); writer.close(); } /** * Get the usage for this tool (without arguments) * * @return the usage for Main following by the tool name */ protected String usage() { return Main.usageMain() + " " + this.getClass().getSimpleName(); } /** * Print the usage with an error message * * @param error the error message */ protected void printUsage(String error) { HelpFormatter formatter = new HelpFormatter(); PrintWriter writer = new PrintWriter(System.err); formatter.printUsage(writer, formatter.getWidth(), usage(), programOptions()); writer.println("error: " + error); writer.close(); } /** * Parse the command line to obtain the arguments * * @param args the arguments passed to the tool * * @return the command line representation */ public CommandLine programParser(String[] args) { try { CommandLine hasHelp = new DefaultParser().parse(helpOption, args, true); if (hasHelp.hasOption("h")) { help(); } CommandLine command = new DefaultParser().parse(programOptions(), args); logger.info(ProjectProperties.getFormattedNameWithVersion()); return command; } catch (ParseException exp) { printUsage(exp.getMessage()); } return null; } /** * Get the tool record for a SAM header * * @param cmd the already parsed command line with the programParser * * @return the program record with the tool */ public SAMProgramRecord getToolProgramRecord(CommandLine cmd) { SAMProgramRecord toReturn = new SAMProgramRecord(String.format("%s %s", ProjectProperties.getName(), this.getClass().getSimpleName())); toReturn.setProgramName(ProjectProperties.getName()); toReturn.setProgramVersion(ProjectProperties.getFormattedVersion()); toReturn.setCommandLine(getCmdLineString(cmd)); return toReturn; } }
package pl.luwi.series.reducer; import de.micromata.opengis.kml.v_2_2_0.*; import de.micromata.opengis.kml.v_2_2_0.Polygon; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import org.w3c.dom.Document; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.util.ArrayList; import java.util.List; import static pl.luwi.series.reducer.PointImpl.p; public class MainClass { public static void main(String[] args){ Kml kml = Kml.unmarshal(new File("C:\\Users\\maedeh.hesabgar\\Desktop\\london\\london\\ca_on_neighbourhood_london_stoneybrook.kml")); final Placemark placemark = (Placemark) kml.getFeature(); final Polygon polygon = (Polygon) placemark.getGeometry(); final Boundary outerBoundaryIs = polygon.getOuterBoundaryIs(); LinearRing linearRing = outerBoundaryIs.getLinearRing(); List<Coordinate> coordinates = linearRing.getCoordinates(); System.out.print(coordinates.size()); List<Point> myPoints= new ArrayList<Point>(); for(Coordinate coordinate : coordinates) { if(coordinate != null) { System.out.println("Longitude: " + coordinate.getLongitude()); System.out.println("Latitude : " + coordinate.getLatitude()); System.out.println(""); myPoints.add(p(coordinate.getLatitude(),coordinate.getLongitude())); } } myPoints.remove(myPoints.size()-1); Double epsilon = EpsilonHelper.avg(EpsilonHelper.deviations(myPoints)); List<Point> reduced1 = SeriesReducer.reduce(myPoints, epsilon); reduced1.add(reduced1.get(0)); System.out.println(reduced1.size()); String pointCoordinates = ""; for(Point p:reduced1){ pointCoordinates = pointCoordinates + p.getY() + "," + p.getX() + " "; } DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("kml"); rootElement.setAttribute("xmlns","http: doc.appendChild(rootElement); // placeMark element Element writingPlacemark = doc.createElement("Placemark"); rootElement.appendChild(writingPlacemark); writingPlacemark.setAttribute("id","ca_on_neighbourhood_london_airport"); // polygon element Element writingPolygon = doc.createElement("Polygon"); writingPlacemark.appendChild(writingPolygon); // outerBoundaryIs element Element writingouterBoundaryIs = doc.createElement("outerBoundaryIs"); writingPolygon.appendChild(writingouterBoundaryIs); // LinearRing element Element writingLinearRing = doc.createElement("LinearRing"); writingouterBoundaryIs.appendChild(writingLinearRing); // coordinates element Element writingcoordinates = doc.createElement("coordinates"); writingcoordinates.appendChild(doc.createTextNode(pointCoordinates)); writingLinearRing.appendChild(writingcoordinates); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = null; transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("HelloKml.kml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
package redis.clients.jedis; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.params.geo.GeoRadiusParam; import redis.clients.jedis.params.sortedset.ZAddParams; import redis.clients.jedis.params.sortedset.ZIncrByParams; import redis.clients.jedis.commands.JedisClusterCommands; import redis.clients.jedis.commands.JedisClusterScriptingCommands; import redis.clients.jedis.commands.MultiKeyJedisClusterCommands; import redis.clients.util.KeyMergeUtil; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.params.set.SetParams; import redis.clients.util.JedisClusterHashTagUtil; import redis.clients.util.SafeEncoder; public class JedisCluster extends BinaryJedisCluster implements JedisClusterCommands, MultiKeyJedisClusterCommands, JedisClusterScriptingCommands { public static enum Reset { SOFT, HARD } public JedisCluster(HostAndPort node) { this(Collections.singleton(node)); } public JedisCluster(HostAndPort node, int timeout) { this(Collections.singleton(node), timeout); } public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { this(Collections.singleton(node), timeout, maxAttempts); } public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), poolConfig); } public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, poolConfig); } public JedisCluster(HostAndPort node, int timeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); } public JedisCluster(Set<HostAndPort> nodes) { this(nodes, DEFAULT_TIMEOUT); } public JedisCluster(Set<HostAndPort> nodes, int timeout) { this(nodes, timeout, DEFAULT_MAX_ATTEMPTS); } public JedisCluster(Set<HostAndPort> nodes, int timeout, int maxAttempts) { this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig()); } public JedisCluster(Set<HostAndPort> nodes, final GenericObjectPoolConfig poolConfig) { this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS, poolConfig); } public JedisCluster(Set<HostAndPort> nodes, int timeout, final GenericObjectPoolConfig poolConfig) { this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, timeout, maxAttempts, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); } @Override public String set(final String key, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value); } }.run(key); } @Override public String set(final String key, final String value, final SetParams params) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value, params); } }.run(key); } @Override public String get(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.get(key); } }.run(key); } @Override public Boolean exists(final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.exists(key); } }.run(key); } @Override public Long exists(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.exists(keys); } }.run(keys.length, keys); } @Override public Long persist(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.persist(key); } }.run(key); } @Override public String type(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.type(key); } }.run(key); } @Override public Long expire(final String key, final int seconds) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expire(key, seconds); } }.run(key); } @Override public Long pexpire(final String key, final long milliseconds) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpire(key, milliseconds); } }.run(key); } @Override public Long expireAt(final String key, final long unixTime) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expireAt(key, unixTime); } }.run(key); } @Override public Long pexpireAt(final String key, final long millisecondsTimestamp) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpireAt(key, millisecondsTimestamp); } }.run(key); } @Override public Long ttl(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.ttl(key); } }.run(key); } @Override public Long pttl(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pttl(key); } }.run(key); } @Override public Long touch(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(key); } }.run(key); } @Override public Long touch(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(keys); } }.run(keys.length, keys); } @Override public Boolean setbit(final String key, final long offset, final boolean value) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.run(key); } @Override public Boolean setbit(final String key, final long offset, final String value) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.run(key); } @Override public Boolean getbit(final String key, final long offset) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.getbit(key, offset); } }.run(key); } @Override public Long setrange(final String key, final long offset, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setrange(key, offset, value); } }.run(key); } @Override public String getrange(final String key, final long startOffset, final long endOffset) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.getrange(key, startOffset, endOffset); } }.run(key); } @Override public String getSet(final String key, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.getSet(key, value); } }.run(key); } @Override public Long setnx(final String key, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setnx(key, value); } }.run(key); } @Override public String setex(final String key, final int seconds, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.setex(key, seconds, value); } }.run(key); } @Override public String psetex(final String key, final long milliseconds, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.psetex(key, milliseconds, value); } }.run(key); } @Override public Long decrBy(final String key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decrBy(key, integer); } }.run(key); } @Override public Long decr(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decr(key); } }.run(key); } @Override public Long incrBy(final String key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incrBy(key, integer); } }.run(key); } @Override public Double incrByFloat(final String key, final double value) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.incrByFloat(key, value); } }.run(key); } @Override public Long incr(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incr(key); } }.run(key); } @Override public Long append(final String key, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.append(key, value); } }.run(key); } @Override public String substr(final String key, final int start, final int end) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.substr(key, start, end); } }.run(key); } @Override public Long hset(final String key, final String field, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hset(key, field, value); } }.run(key); } @Override public String hget(final String key, final String field) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.hget(key, field); } }.run(key); } @Override public Long hsetnx(final String key, final String field, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hsetnx(key, field, value); } }.run(key); } @Override public String hmset(final String key, final Map<String, String> hash) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.hmset(key, hash); } }.run(key); } @Override public List<String> hmget(final String key, final String... fields) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.hmget(key, fields); } }.run(key); } @Override public Long hincrBy(final String key, final String field, final long value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hincrBy(key, field, value); } }.run(key); } @Override public Boolean hexists(final String key, final String field) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.hexists(key, field); } }.run(key); } @Override public Long hdel(final String key, final String... field) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hdel(key, field); } }.run(key); } @Override public Long hlen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hlen(key); } }.run(key); } @Override public Set<String> hkeys(final String key) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.hkeys(key); } }.run(key); } @Override public List<String> hvals(final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.hvals(key); } }.run(key); } @Override public Map<String, String> hgetAll(final String key) { return new JedisClusterCommand<Map<String, String>>(connectionHandler, maxAttempts) { @Override public Map<String, String> execute(Jedis connection) { return connection.hgetAll(key); } }.run(key); } @Override public Long rpush(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpush(key, string); } }.run(key); } @Override public Long lpush(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpush(key, string); } }.run(key); } @Override public Long llen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.llen(key); } }.run(key); } @Override public List<String> lrange(final String key, final long start, final long end) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.lrange(key, start, end); } }.run(key); } @Override public String ltrim(final String key, final long start, final long end) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.ltrim(key, start, end); } }.run(key); } @Override public String lindex(final String key, final long index) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lindex(key, index); } }.run(key); } @Override public String lset(final String key, final long index, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lset(key, index, value); } }.run(key); } @Override public Long lrem(final String key, final long count, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lrem(key, count, value); } }.run(key); } @Override public String lpop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lpop(key); } }.run(key); } @Override public String rpop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rpop(key); } }.run(key); } @Override public Long sadd(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sadd(key, member); } }.run(key); } @Override public Set<String> smembers(final String key) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.smembers(key); } }.run(key); } @Override public Long srem(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.srem(key, member); } }.run(key); } @Override public String spop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.spop(key); } }.run(key); } @Override public Set<String> spop(final String key, final long count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.spop(key, count); } }.run(key); } @Override public Long scard(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.scard(key); } }.run(key); } @Override public Boolean sismember(final String key, final String member) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.sismember(key, member); } }.run(key); } @Override public String srandmember(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.srandmember(key); } }.run(key); } @Override public List<String> srandmember(final String key, final int count) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.srandmember(key, count); } }.run(key); } @Override public Long strlen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.strlen(key); } }.run(key); } @Override public Long zadd(final String key, final double score, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member); } }.run(key); } @Override public Long zadd(final String key, final double score, final String member, final ZAddParams params) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member, params); } }.run(key); } @Override public Long zadd(final String key, final Map<String, Double> scoreMembers) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers); } }.run(key); } @Override public Long zadd(final String key, final Map<String, Double> scoreMembers, final ZAddParams params) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers, params); } }.run(key); } @Override public Set<String> zrange(final String key, final long start, final long end) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrange(key, start, end); } }.run(key); } @Override public Long zrem(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrem(key, member); } }.run(key); } @Override public Double zincrby(final String key, final double score, final String member) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, score, member); } }.run(key); } @Override public Double zincrby(final String key, final double score, final String member, final ZIncrByParams params) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, score, member, params); } }.run(key); } @Override public Long zrank(final String key, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrank(key, member); } }.run(key); } @Override public Long zrevrank(final String key, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrevrank(key, member); } }.run(key); } @Override public Set<String> zrevrange(final String key, final long start, final long end) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrange(key, start, end); } }.run(key); } @Override public Set<Tuple> zrangeWithScores(final String key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeWithScores(key, start, end); } }.run(key); } @Override public Set<Tuple> zrevrangeWithScores(final String key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeWithScores(key, start, end); } }.run(key); } @Override public Long zcard(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcard(key); } }.run(key); } @Override public Double zscore(final String key, final String member) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zscore(key, member); } }.run(key); } @Override public List<String> sort(final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.sort(key); } }.run(key); } @Override public List<String> sort(final String key, final SortingParams sortingParameters) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.sort(key, sortingParameters); } }.run(key); } @Override public Long zcount(final String key, final double min, final double max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.run(key); } @Override public Long zcount(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final double min, final double max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final String min, final String max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final double max, final double min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final String max, final String min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(key); } @Override public Long zremrangeByRank(final String key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByRank(key, start, end); } }.run(key); } @Override public Long zremrangeByScore(final String key, final double start, final double end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.run(key); } @Override public Long zremrangeByScore(final String key, final String start, final String end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.run(key); } @Override public Long zlexcount(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zlexcount(key, min, max); } }.run(key); } @Override public Set<String> zrangeByLex(final String key, final String min, final String max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByLex(key, min, max); } }.run(key); } @Override public Set<String> zrangeByLex(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByLex(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByLex(final String key, final String max, final String min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min); } }.run(key); } @Override public Set<String> zrevrangeByLex(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min, offset, count); } }.run(key); } @Override public Long zremrangeByLex(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByLex(key, min, max); } }.run(key); } @Override public Long linsert(final String key, final LIST_POSITION where, final String pivot, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.linsert(key, where, pivot, value); } }.run(key); } @Override public Long lpushx(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpushx(key, string); } }.run(key); } @Override public Long rpushx(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpushx(key, string); } }.run(key); } @Override public Long del(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.run(key); } @Override public Long unlink(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(key); } }.run(key); } @Override public Long unlink(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(keys); } }.run(keys.length, keys); } @Override public String echo(final String string) { // note that it'll be run from arbitary node return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.echo(string); } }.run(string); } @Override public Long bitcount(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key); } }.run(key); } @Override public Long bitcount(final String key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key, start, end); } }.run(key); } @Override public ScanResult<String> scan(final String cursor, final ScanParams params) { String matchPattern = null; if (params == null || (matchPattern = params.match()) == null || matchPattern.isEmpty()) { throw new IllegalArgumentException(JedisCluster.class.getSimpleName() + " only supports SCAN commands with non-empty MATCH patterns"); } if (JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) { return new JedisClusterCommand< ScanResult<String>>(connectionHandler, maxAttempts) { @Override public ScanResult<String> execute(Jedis connection) { return connection.scan(cursor, params); } }.run(matchPattern); } else { throw new IllegalArgumentException(JedisCluster.class.getSimpleName() + " only supports SCAN commands with MATCH patterns containing hash-tags ( curly-brackets enclosed strings )"); } } @Override public ScanResult<Entry<String, String>> hscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<Entry<String, String>>>(connectionHandler, maxAttempts) { @Override public ScanResult<Entry<String, String>> execute(Jedis connection) { return connection.hscan(key, cursor); } }.run(key); } @Override public ScanResult<String> sscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<String>>(connectionHandler, maxAttempts) { @Override public ScanResult<String> execute(Jedis connection) { return connection.sscan(key, cursor); } }.run(key); } @Override public ScanResult<Tuple> zscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler, maxAttempts) { @Override public ScanResult<Tuple> execute(Jedis connection) { return connection.zscan(key, cursor); } }.run(key); } @Override public Long pfadd(final String key, final String... elements) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfadd(key, elements); } }.run(key); } @Override public long pfcount(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(key); } }.run(key); } @Override public List<String> blpop(final int timeout, final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.blpop(timeout, key); } }.run(key); } @Override public List<String> brpop(final int timeout, final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.brpop(timeout, key); } }.run(key); } @Override public Long del(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(keys); } }.run(keys.length, keys); } @Override public List<String> blpop(final int timeout, final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.blpop(timeout, keys); } }.run(keys.length, keys); } @Override public List<String> brpop(final int timeout, final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.brpop(timeout, keys); } }.run(keys.length, keys); } @Override public List<String> mget(final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.mget(keys); } }.run(keys.length, keys); } @Override public String mset(final String... keysvalues) { String[] keys = new String[keysvalues.length / 2]; for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { keys[keyIdx] = keysvalues[keyIdx * 2]; } return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.mset(keysvalues); } }.run(keys.length, keys); } @Override public Long msetnx(final String... keysvalues) { String[] keys = new String[keysvalues.length / 2]; for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { keys[keyIdx] = keysvalues[keyIdx * 2]; } return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.msetnx(keysvalues); } }.run(keys.length, keys); } @Override public String rename(final String oldkey, final String newkey) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rename(oldkey, newkey); } }.run(2, oldkey, newkey); } @Override public Long renamenx(final String oldkey, final String newkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.renamenx(oldkey, newkey); } }.run(2, oldkey, newkey); } @Override public String rpoplpush(final String srckey, final String dstkey) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rpoplpush(srckey, dstkey); } }.run(2, srckey, dstkey); } @Override public Set<String> sdiff(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sdiff(keys); } }.run(keys.length, keys); } @Override public Long sdiffstore(final String dstkey, final String... keys) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sdiffstore(dstkey, keys); } }.run(mergedKeys.length, mergedKeys); } @Override public Set<String> sinter(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sinter(keys); } }.run(keys.length, keys); } @Override public Long sinterstore(final String dstkey, final String... keys) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sinterstore(dstkey, keys); } }.run(mergedKeys.length, mergedKeys); } @Override public Long smove(final String srckey, final String dstkey, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.smove(srckey, dstkey, member); } }.run(2, srckey, dstkey); } @Override public Long sort(final String key, final SortingParams sortingParameters, final String dstkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, sortingParameters, dstkey); } }.run(2, key, dstkey); } @Override public Long sort(final String key, final String dstkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, dstkey); } }.run(2, key, dstkey); } @Override public Set<String> sunion(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sunion(keys); } }.run(keys.length, keys); } @Override public Long sunionstore(final String dstkey, final String... keys) { String[] wholeKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sunionstore(dstkey, keys); } }.run(wholeKeys.length, wholeKeys); } @Override public Long zinterstore(final String dstkey, final String... sets) { String[] wholeKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, sets); } }.run(wholeKeys.length, wholeKeys); } @Override public Long zinterstore(final String dstkey, final ZParams params, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, params, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public Long zunionstore(final String dstkey, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public Long zunionstore(final String dstkey, final ZParams params, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, params, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public String brpoplpush(final String source, final String destination, final int timeout) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.brpoplpush(source, destination, timeout); } }.run(2, source, destination); } @Override public Long publish(final String channel, final String message) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.publish(channel, message); } }.runWithAnyNode(); } @Override public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.subscribe(jedisPubSub, channels); return 0; } }.runWithAnyNode(); } @Override public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) { new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.psubscribe(jedisPubSub, patterns); return 0; } }.runWithAnyNode(); } @Override public Long bitop(final BitOP op, final String destKey, final String... srcKeys) { String[] mergedKeys = KeyMergeUtil.merge(destKey, srcKeys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitop(op, destKey, srcKeys); } }.run(mergedKeys.length, mergedKeys); } @Override public String pfmerge(final String destkey, final String... sourcekeys) { String[] mergedKeys = KeyMergeUtil.merge(destkey, sourcekeys); return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.pfmerge(destkey, sourcekeys); } }.run(mergedKeys.length, mergedKeys); } @Override public long pfcount(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(keys); } }.run(keys.length, keys); } @Override public Object eval(final String script, final int keyCount, final String... params) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); } }.run(keyCount, params); } @Override public Object eval(final String script, final String key) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script); } }.run(key); } @Override public Object eval(final String script, final List<String> keys, final List<String> args) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keys, args); } }.run(keys.size(), keys.toArray(new String[keys.size()])); } @Override public Object evalsha(final String sha1, final int keyCount, final String... params) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keyCount, params); } }.run(keyCount, params); } @Override public Object evalsha(final String sha1, final List<String> keys, final List<String> args) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keys, args); } }.run(keys.size(), keys.toArray(new String[keys.size()])); } @Override public Object evalsha(final String sha1, final String key) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1); } }.run(key); } @Override public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); } @Override public List<Boolean> scriptExists(final String key, final String... sha1) { return new JedisClusterCommand<List<Boolean>>(connectionHandler, maxAttempts) { @Override public List<Boolean> execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); } @Override public String scriptLoad(final String script, final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.scriptLoad(script); } }.run(key); } @Override public Long geoadd(final String key, final double longitude, final double latitude, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, longitude, latitude, member); } }.run(key); } @Override public Long geoadd(final String key, final Map<String, GeoCoordinate> memberCoordinateMap) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, memberCoordinateMap); } }.run(key); } @Override public Double geodist(final String key, final String member1, final String member2) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2); } }.run(key); } @Override public Double geodist(final String key, final String member1, final String member2, final GeoUnit unit) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2, unit); } }.run(key); } @Override public List<String> geohash(final String key, final String... members) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.geohash(key, members); } }.run(key); } @Override public List<GeoCoordinate> geopos(final String key, final String... members) { return new JedisClusterCommand<List<GeoCoordinate>>(connectionHandler, maxAttempts) { @Override public List<GeoCoordinate> execute(Jedis connection) { return connection.geopos(key, members); } }.run(key); } @Override public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit); } }.run(key); } @Override public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit, param); } }.run(key); } @Override public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit); } }.run(key); } @Override public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit, param); } }.run(key); } @Override public List<Long> bitfield(final String key, final String... arguments) { return new JedisClusterCommand<List<Long>>(connectionHandler, maxAttempts) { @Override public List<Long> execute(Jedis connection) { return connection.bitfield(key, arguments); } }.run(key); } @Override public Long hstrlen(final String key, final String field) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hstrlen(key, field); } }.run(key); } }
package redis.clients.jedis; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.params.geo.GeoRadiusParam; import redis.clients.jedis.params.sortedset.ZAddParams; import redis.clients.jedis.params.sortedset.ZIncrByParams; import redis.clients.jedis.commands.JedisClusterCommands; import redis.clients.jedis.commands.JedisClusterScriptingCommands; import redis.clients.jedis.commands.MultiKeyJedisClusterCommands; import redis.clients.util.KeyMergeUtil; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.params.set.SetParams; import redis.clients.util.JedisClusterHashTagUtil; import redis.clients.util.SafeEncoder; public class JedisCluster extends BinaryJedisCluster implements JedisClusterCommands, MultiKeyJedisClusterCommands, JedisClusterScriptingCommands { public JedisCluster(HostAndPort node) { this(Collections.singleton(node)); } public JedisCluster(HostAndPort node, int timeout) { this(Collections.singleton(node), timeout); } public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { this(Collections.singleton(node), timeout, maxAttempts); } public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), poolConfig); } public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, poolConfig); } public JedisCluster(HostAndPort node, int timeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); } public JedisCluster(Set<HostAndPort> nodes) { this(nodes, DEFAULT_TIMEOUT); } public JedisCluster(Set<HostAndPort> nodes, int timeout) { this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS); } public JedisCluster(Set<HostAndPort> nodes, int timeout, int maxAttempts) { this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig()); } public JedisCluster(Set<HostAndPort> nodes, final GenericObjectPoolConfig poolConfig) { this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, poolConfig); } public JedisCluster(Set<HostAndPort> nodes, int timeout, final GenericObjectPoolConfig poolConfig) { this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, timeout, maxAttempts, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig); } public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, final GenericObjectPoolConfig poolConfig) { super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); } @Override public String set(final String key, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value); } }.run(key); } @Override public String set(final String key, final String value, final SetParams params) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value, params); } }.run(key); } @Override public String get(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.get(key); } }.run(key); } @Override public Boolean exists(final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.exists(key); } }.run(key); } @Override public Long exists(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.exists(keys); } }.run(keys.length, keys); } @Override public Long persist(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.persist(key); } }.run(key); } @Override public String type(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.type(key); } }.run(key); } @Override public Long expire(final String key, final int seconds) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expire(key, seconds); } }.run(key); } @Override public Long pexpire(final String key, final long milliseconds) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpire(key, milliseconds); } }.run(key); } @Override public Long expireAt(final String key, final long unixTime) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expireAt(key, unixTime); } }.run(key); } @Override public Long pexpireAt(final String key, final long millisecondsTimestamp) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpireAt(key, millisecondsTimestamp); } }.run(key); } @Override public Long ttl(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.ttl(key); } }.run(key); } @Override public Long pttl(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pttl(key); } }.run(key); } @Override public Long touch(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(key); } }.run(key); } @Override public Long touch(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(keys); } }.run(keys.length, keys); } @Override public Boolean setbit(final String key, final long offset, final boolean value) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.run(key); } @Override public Boolean setbit(final String key, final long offset, final String value) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); } }.run(key); } @Override public Boolean getbit(final String key, final long offset) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.getbit(key, offset); } }.run(key); } @Override public Long setrange(final String key, final long offset, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setrange(key, offset, value); } }.run(key); } @Override public String getrange(final String key, final long startOffset, final long endOffset) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.getrange(key, startOffset, endOffset); } }.run(key); } @Override public String getSet(final String key, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.getSet(key, value); } }.run(key); } @Override public Long setnx(final String key, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setnx(key, value); } }.run(key); } @Override public String setex(final String key, final int seconds, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.setex(key, seconds, value); } }.run(key); } @Override public String psetex(final String key, final long milliseconds, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.psetex(key, milliseconds, value); } }.run(key); } @Override public Long decrBy(final String key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decrBy(key, integer); } }.run(key); } @Override public Long decr(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decr(key); } }.run(key); } @Override public Long incrBy(final String key, final long integer) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incrBy(key, integer); } }.run(key); } @Override public Double incrByFloat(final String key, final double value) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.incrByFloat(key, value); } }.run(key); } @Override public Long incr(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incr(key); } }.run(key); } @Override public Long append(final String key, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.append(key, value); } }.run(key); } @Override public String substr(final String key, final int start, final int end) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.substr(key, start, end); } }.run(key); } @Override public Long hset(final String key, final String field, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hset(key, field, value); } }.run(key); } @Override public String hget(final String key, final String field) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.hget(key, field); } }.run(key); } @Override public Long hsetnx(final String key, final String field, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hsetnx(key, field, value); } }.run(key); } @Override public String hmset(final String key, final Map<String, String> hash) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.hmset(key, hash); } }.run(key); } @Override public List<String> hmget(final String key, final String... fields) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.hmget(key, fields); } }.run(key); } @Override public Long hincrBy(final String key, final String field, final long value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hincrBy(key, field, value); } }.run(key); } @Override public Boolean hexists(final String key, final String field) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.hexists(key, field); } }.run(key); } @Override public Long hdel(final String key, final String... field) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hdel(key, field); } }.run(key); } @Override public Long hlen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hlen(key); } }.run(key); } @Override public Set<String> hkeys(final String key) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.hkeys(key); } }.run(key); } @Override public List<String> hvals(final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.hvals(key); } }.run(key); } @Override public Map<String, String> hgetAll(final String key) { return new JedisClusterCommand<Map<String, String>>(connectionHandler, maxAttempts) { @Override public Map<String, String> execute(Jedis connection) { return connection.hgetAll(key); } }.run(key); } @Override public Long rpush(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpush(key, string); } }.run(key); } @Override public Long lpush(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpush(key, string); } }.run(key); } @Override public Long llen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.llen(key); } }.run(key); } @Override public List<String> lrange(final String key, final long start, final long end) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.lrange(key, start, end); } }.run(key); } @Override public String ltrim(final String key, final long start, final long end) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.ltrim(key, start, end); } }.run(key); } @Override public String lindex(final String key, final long index) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lindex(key, index); } }.run(key); } @Override public String lset(final String key, final long index, final String value) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lset(key, index, value); } }.run(key); } @Override public Long lrem(final String key, final long count, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lrem(key, count, value); } }.run(key); } @Override public String lpop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lpop(key); } }.run(key); } @Override public String rpop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rpop(key); } }.run(key); } @Override public Long sadd(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sadd(key, member); } }.run(key); } @Override public Set<String> smembers(final String key) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.smembers(key); } }.run(key); } @Override public Long srem(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.srem(key, member); } }.run(key); } @Override public String spop(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.spop(key); } }.run(key); } @Override public Set<String> spop(final String key, final long count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.spop(key, count); } }.run(key); } @Override public Long scard(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.scard(key); } }.run(key); } @Override public Boolean sismember(final String key, final String member) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.sismember(key, member); } }.run(key); } @Override public String srandmember(final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.srandmember(key); } }.run(key); } @Override public List<String> srandmember(final String key, final int count) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.srandmember(key, count); } }.run(key); } @Override public Long strlen(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.strlen(key); } }.run(key); } @Override public Long zadd(final String key, final double score, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member); } }.run(key); } @Override public Long zadd(final String key, final double score, final String member, final ZAddParams params) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member, params); } }.run(key); } @Override public Long zadd(final String key, final Map<String, Double> scoreMembers) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers); } }.run(key); } @Override public Long zadd(final String key, final Map<String, Double> scoreMembers, final ZAddParams params) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers, params); } }.run(key); } @Override public Set<String> zrange(final String key, final long start, final long end) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrange(key, start, end); } }.run(key); } @Override public Long zrem(final String key, final String... member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrem(key, member); } }.run(key); } @Override public Double zincrby(final String key, final double score, final String member) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, score, member); } }.run(key); } @Override public Double zincrby(final String key, final double score, final String member, final ZIncrByParams params) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, score, member, params); } }.run(key); } @Override public Long zrank(final String key, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrank(key, member); } }.run(key); } @Override public Long zrevrank(final String key, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrevrank(key, member); } }.run(key); } @Override public Set<String> zrevrange(final String key, final long start, final long end) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrange(key, start, end); } }.run(key); } @Override public Set<Tuple> zrangeWithScores(final String key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeWithScores(key, start, end); } }.run(key); } @Override public Set<Tuple> zrevrangeWithScores(final String key, final long start, final long end) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeWithScores(key, start, end); } }.run(key); } @Override public Long zcard(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcard(key); } }.run(key); } @Override public Double zscore(final String key, final String member) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zscore(key, member); } }.run(key); } @Override public List<String> sort(final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.sort(key); } }.run(key); } @Override public List<String> sort(final String key, final SortingParams sortingParameters) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.sort(key, sortingParameters); } }.run(key); } @Override public Long zcount(final String key, final double min, final double max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.run(key); } @Override public Long zcount(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final double min, final double max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final String min, final String max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final double max, final double min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final String max, final String min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); } }.run(key); } @Override public Set<String> zrangeByScore(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByScore(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); } }.run(key); } @Override public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(key); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) { @Override public Set<Tuple> execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(key); } @Override public Long zremrangeByRank(final String key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByRank(key, start, end); } }.run(key); } @Override public Long zremrangeByScore(final String key, final double start, final double end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.run(key); } @Override public Long zremrangeByScore(final String key, final String start, final String end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, start, end); } }.run(key); } @Override public Long zlexcount(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zlexcount(key, min, max); } }.run(key); } @Override public Set<String> zrangeByLex(final String key, final String min, final String max) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByLex(key, min, max); } }.run(key); } @Override public Set<String> zrangeByLex(final String key, final String min, final String max, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrangeByLex(key, min, max, offset, count); } }.run(key); } @Override public Set<String> zrevrangeByLex(final String key, final String max, final String min) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min); } }.run(key); } @Override public Set<String> zrevrangeByLex(final String key, final String max, final String min, final int offset, final int count) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min, offset, count); } }.run(key); } @Override public Long zremrangeByLex(final String key, final String min, final String max) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByLex(key, min, max); } }.run(key); } @Override public Long linsert(final String key, final LIST_POSITION where, final String pivot, final String value) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.linsert(key, where, pivot, value); } }.run(key); } @Override public Long lpushx(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpushx(key, string); } }.run(key); } @Override public Long rpushx(final String key, final String... string) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpushx(key, string); } }.run(key); } @Override public Long del(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.run(key); } @Override public Long del(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(keys); } }.run(keys.length, keys); } @Override public Long unlink(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(key); } }.run(key); } @Override public Long unlink(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(keys); } }.run(keys.length, keys); } @Override public String echo(final String string) { // note that it'll be run from arbitary node return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.echo(string); } }.run(string); } @Override public Long bitcount(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key); } }.run(key); } @Override public Long bitcount(final String key, final long start, final long end) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key, start, end); } }.run(key); } @Override public ScanResult<String> scan(final String cursor, final ScanParams params) { String matchPattern = null; if (params == null || (matchPattern = params.match()) == null || matchPattern.isEmpty()) { throw new IllegalArgumentException(JedisCluster.class.getSimpleName() + " only supports SCAN commands with non-empty MATCH patterns"); } if (JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) { return new JedisClusterCommand< ScanResult<String>>(connectionHandler, maxAttempts) { @Override public ScanResult<String> execute(Jedis connection) { return connection.scan(cursor, params); } }.run(matchPattern); } else { throw new IllegalArgumentException(JedisCluster.class.getSimpleName() + " only supports SCAN commands with MATCH patterns containing hash-tags ( curly-brackets enclosed strings )"); } } @Override public ScanResult<Entry<String, String>> hscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<Entry<String, String>>>(connectionHandler, maxAttempts) { @Override public ScanResult<Entry<String, String>> execute(Jedis connection) { return connection.hscan(key, cursor); } }.run(key); } @Override public ScanResult<String> sscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<String>>(connectionHandler, maxAttempts) { @Override public ScanResult<String> execute(Jedis connection) { return connection.sscan(key, cursor); } }.run(key); } @Override public ScanResult<Tuple> zscan(final String key, final String cursor) { return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler, maxAttempts) { @Override public ScanResult<Tuple> execute(Jedis connection) { return connection.zscan(key, cursor); } }.run(key); } @Override public Long pfadd(final String key, final String... elements) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfadd(key, elements); } }.run(key); } @Override public Long pfcount(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(key); } }.run(key); } @Override public List<String> blpop(final int timeout, final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.blpop(timeout, key); } }.run(key); } @Override public List<String> brpop(final int timeout, final String key) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.brpop(timeout, key); } }.run(key); } @Override public List<String> blpop(final int timeout, final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.blpop(timeout, keys); } }.run(keys.length, keys); } @Override public List<String> brpop(final int timeout, final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.brpop(timeout, keys); } }.run(keys.length, keys); } @Override public List<String> mget(final String... keys) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.mget(keys); } }.run(keys.length, keys); } @Override public String mset(final String... keysvalues) { String[] keys = new String[keysvalues.length / 2]; for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { keys[keyIdx] = keysvalues[keyIdx * 2]; } return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.mset(keysvalues); } }.run(keys.length, keys); } @Override public Long msetnx(final String... keysvalues) { String[] keys = new String[keysvalues.length / 2]; for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { keys[keyIdx] = keysvalues[keyIdx * 2]; } return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.msetnx(keysvalues); } }.run(keys.length, keys); } @Override public String rename(final String oldkey, final String newkey) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rename(oldkey, newkey); } }.run(2, oldkey, newkey); } @Override public Long renamenx(final String oldkey, final String newkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.renamenx(oldkey, newkey); } }.run(2, oldkey, newkey); } @Override public String rpoplpush(final String srckey, final String dstkey) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rpoplpush(srckey, dstkey); } }.run(2, srckey, dstkey); } @Override public Set<String> sdiff(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sdiff(keys); } }.run(keys.length, keys); } @Override public Long sdiffstore(final String dstkey, final String... keys) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sdiffstore(dstkey, keys); } }.run(mergedKeys.length, mergedKeys); } @Override public Set<String> sinter(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sinter(keys); } }.run(keys.length, keys); } @Override public Long sinterstore(final String dstkey, final String... keys) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sinterstore(dstkey, keys); } }.run(mergedKeys.length, mergedKeys); } @Override public Long smove(final String srckey, final String dstkey, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.smove(srckey, dstkey, member); } }.run(2, srckey, dstkey); } @Override public Long sort(final String key, final SortingParams sortingParameters, final String dstkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, sortingParameters, dstkey); } }.run(2, key, dstkey); } @Override public Long sort(final String key, final String dstkey) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, dstkey); } }.run(2, key, dstkey); } @Override public Set<String> sunion(final String... keys) { return new JedisClusterCommand<Set<String>>(connectionHandler, maxAttempts) { @Override public Set<String> execute(Jedis connection) { return connection.sunion(keys); } }.run(keys.length, keys); } @Override public Long sunionstore(final String dstkey, final String... keys) { String[] wholeKeys = KeyMergeUtil.merge(dstkey, keys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sunionstore(dstkey, keys); } }.run(wholeKeys.length, wholeKeys); } @Override public Long zinterstore(final String dstkey, final String... sets) { String[] wholeKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, sets); } }.run(wholeKeys.length, wholeKeys); } @Override public Long zinterstore(final String dstkey, final ZParams params, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, params, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public Long zunionstore(final String dstkey, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public Long zunionstore(final String dstkey, final ZParams params, final String... sets) { String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, params, sets); } }.run(mergedKeys.length, mergedKeys); } @Override public String brpoplpush(final String source, final String destination, final int timeout) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.brpoplpush(source, destination, timeout); } }.run(2, source, destination); } @Override public Long publish(final String channel, final String message) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.publish(channel, message); } }.runWithAnyNode(); } @Override public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.subscribe(jedisPubSub, channels); return 0; } }.runWithAnyNode(); } @Override public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) { new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.psubscribe(jedisPubSub, patterns); return 0; } }.runWithAnyNode(); } @Override public Long bitop(final BitOP op, final String destKey, final String... srcKeys) { String[] mergedKeys = KeyMergeUtil.merge(destKey, srcKeys); return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitop(op, destKey, srcKeys); } }.run(mergedKeys.length, mergedKeys); } @Override public String pfmerge(final String destkey, final String... sourcekeys) { String[] mergedKeys = KeyMergeUtil.merge(destkey, sourcekeys); return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.pfmerge(destkey, sourcekeys); } }.run(mergedKeys.length, mergedKeys); } @Override public Long pfcount(final String... keys) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(keys); } }.run(keys.length, keys); } @Override public Object eval(final String script, final int keyCount, final String... params) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); } }.run(keyCount, params); } @Override public Object eval(final String script, final String key) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script); } }.run(key); } @Override public Object eval(final String script, final List<String> keys, final List<String> args) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keys, args); } }.run(keys.size(), keys.toArray(new String[keys.size()])); } @Override public Object evalsha(final String sha1, final int keyCount, final String... params) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keyCount, params); } }.run(keyCount, params); } @Override public Object evalsha(final String sha1, final List<String> keys, final List<String> args) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keys, args); } }.run(keys.size(), keys.toArray(new String[keys.size()])); } @Override public Object evalsha(final String sha1, final String key) { return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1); } }.run(key); } @Override public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); } @Override public List<Boolean> scriptExists(final String key, final String... sha1) { return new JedisClusterCommand<List<Boolean>>(connectionHandler, maxAttempts) { @Override public List<Boolean> execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); } @Override public String scriptLoad(final String script, final String key) { return new JedisClusterCommand<String>(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.scriptLoad(script); } }.run(key); } @Override public Long geoadd(final String key, final double longitude, final double latitude, final String member) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, longitude, latitude, member); } }.run(key); } @Override public Long geoadd(final String key, final Map<String, GeoCoordinate> memberCoordinateMap) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, memberCoordinateMap); } }.run(key); } @Override public Double geodist(final String key, final String member1, final String member2) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2); } }.run(key); } @Override public Double geodist(final String key, final String member1, final String member2, final GeoUnit unit) { return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2, unit); } }.run(key); } @Override public List<String> geohash(final String key, final String... members) { return new JedisClusterCommand<List<String>>(connectionHandler, maxAttempts) { @Override public List<String> execute(Jedis connection) { return connection.geohash(key, members); } }.run(key); } @Override public List<GeoCoordinate> geopos(final String key, final String... members) { return new JedisClusterCommand<List<GeoCoordinate>>(connectionHandler, maxAttempts) { @Override public List<GeoCoordinate> execute(Jedis connection) { return connection.geopos(key, members); } }.run(key); } @Override public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit); } }.run(key); } @Override public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit, param); } }.run(key); } @Override public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit); } }.run(key); } @Override public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) { @Override public List<GeoRadiusResponse> execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit, param); } }.run(key); } @Override public List<Long> bitfield(final String key, final String... arguments) { return new JedisClusterCommand<List<Long>>(connectionHandler, maxAttempts) { @Override public List<Long> execute(Jedis connection) { return connection.bitfield(key, arguments); } }.run(key); } @Override public Long hstrlen(final String key, final String field) { return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hstrlen(key, field); } }.run(key); } }
package scrum.client; import ilarkesto.gwt.client.ADataTransferObject; import ilarkesto.gwt.client.AGwtEntity; import ilarkesto.gwt.client.GwtLogger; import java.util.LinkedList; import scrum.client.admin.User; import scrum.client.collaboration.ChatMessage; import scrum.client.collaboration.ChatWidget; import scrum.client.dnd.DndManager; import scrum.client.project.Project; import scrum.client.workspace.Ui; import scrum.client.workspace.WorkareaWidget; import scrum.client.workspace.WorkspaceWidget; import com.google.gwt.user.client.ui.RootPanel; public class ScrumGwtApplication extends GScrumGwtApplication { private Dao dao = new Dao(); private User user; private Project project; private LinkedList<ChatMessage> chatMessages; private DndManager dndManager; private Ui ui; private boolean developmentMode; private long lastDataReceiveTime = System.currentTimeMillis(); private PingTimer pingTimer; /** * Application entry point. */ public void onModuleLoad() { // workaround for GWT issue 1813 RootPanel.get().getElement().getStyle().setProperty("position", "relative"); ui = Ui.get(); ui.update(); RootPanel.get("workspace").add(ui); ui.lock("Loading..."); callPing(new Runnable() { public void run() { ui.showLogin(); } }); pingTimer = new PingTimer(); pingTimer.scheduleRepeating(15000); } public ChatMessage postSystemMessage(String text, boolean distribute) { return postMessage(null, text, distribute); } public ChatMessage postMessage(String text) { return postMessage(user, text, true); } private ChatMessage postMessage(User author, String text, boolean distribute) { ChatMessage msg = new ChatMessage(getProject(), author, text); addChatMessage(msg); if (distribute) getDao().createChatMessage(msg); return msg; } public LinkedList<ChatMessage> getChatMessages() { return chatMessages; } void addChatMessage(ChatMessage msg) { if (project == null || !msg.isProject(project)) return; if (chatMessages.contains(msg)) return; chatMessages.add(msg); if (chatMessages.size() > 50) chatMessages.remove(0); ChatWidget.get().update(); } public User getUser() { return user; } public Ui getUi() { return ui; } public boolean isDevelopmentMode() { return developmentMode; } public long getLastDataReceiveTime() { return lastDataReceiveTime; } @Override protected void handleDataFromServer(ADataTransferObject adata) { super.handleDataFromServer(adata); DataTransferObject data = (DataTransferObject) adata; if (data.containsEntities()) { lastDataReceiveTime = System.currentTimeMillis(); pingTimer.schedule(); } if (data.entityIdBase != null) { getDao().setEntityIdBase(data.entityIdBase); GwtLogger.DEBUG("entityIdBase:", data.entityIdBase); } if (data.developmentMode != null) { developmentMode = data.developmentMode; } if (data.isUserSet()) { user = getDao().getUser(data.getUserId()); } } @Override protected void handleCommunicationError(Throwable ex) { GwtLogger.ERROR("Communication Error:", ex); if (project != null) { postSystemMessage("Communication Error: " + ex.getMessage(), false); } else { ui.lock("Error: " + ex.getMessage()); } } public void openProject(Project project) { Ui.get().lock("Loading project..."); this.project = project; this.chatMessages = new LinkedList<ChatMessage>(); callSelectProject(project.getId(), new Runnable() { public void run() { Ui.get().unlock(); Ui.get().showWorkspace(); WorkareaWidget.get().showProjectOverview(); } }); postSystemMessage(user.getName() + " logged in.", true); } public void closeProject() { callCloseProject(); this.project = null; Dao dao = getDao(); dao.clearChatMessages(); dao.clearImpediments(); dao.clearQualitys(); dao.clearRequirements(); dao.clearRisks(); dao.clearSprints(); dao.clearTasks(); Ui.get().showStartPage(); } public void showEntityByReference(final String reference) { AGwtEntity entity = getDao().getEntityByReference(reference); if (entity != null) { WorkareaWidget.get().showEntity(entity); return; } ui.lock("Searching for " + reference); callRequestEntityByReference(reference, new Runnable() { public void run() { AGwtEntity entity = getDao().getEntityByReference(reference); if (entity == null) { ui.unlock(); postSystemMessage("Object does not exist: " + reference, false); return; } ui.unlock(); WorkareaWidget.get().showEntity(entity); } }); } public Project getProject() { return project; } @Override public Dao getDao() { return dao; } public static ScrumGwtApplication get() { return (ScrumGwtApplication) singleton; } public DndManager getDndManager() { if (dndManager == null) { dndManager = new DndManager(); } return dndManager; } public void logout() { Ui.get().lock("logging out"); ScrumGwtApplication.get().callLogout(); closeProject(); user = null; getDao().clearAllEntities(); Ui.get().showLogin(); } public WorkspaceWidget getWorkspaceWidget() { return getUi().getWorkspace(); } }
package seedu.address.model; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javafx.collections.transformation.FilteredList; import me.xdrop.fuzzywuzzy.FuzzySearch; import seedu.address.commons.core.ComponentManager; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.core.UnmodifiableObservableList; import seedu.address.commons.events.model.AddressBookChangedEvent; import seedu.address.commons.util.CollectionUtil; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.Task; import seedu.address.model.task.UniqueTaskList; import seedu.address.model.task.UniqueTaskList.TaskNotFoundException; /** * Represents the in-memory model of the address book data. * All changes to any model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private List<AddressBook> addressBookStates; private AddressBook currentAddressBook; private int currentAddressBookStateIndex; private static final int MATCHING_INDEX = 35; public FilteredList<ReadOnlyTask> nonFloatingTasks; public FilteredList<ReadOnlyTask> floatingTasks; public FilteredList<ReadOnlyTask> completedTasks; /** * Initializes a ModelManager with the given addressBook and userPrefs. */ public ModelManager(ReadOnlyAddressBook addressBook, UserPrefs userPrefs) { super(); assert !CollectionUtil.isAnyNull(addressBook, userPrefs); logger.fine("Initializing with address book: " + addressBook + " and user prefs " + userPrefs); this.addressBookStates = new ArrayList<AddressBook>(); this.addressBookStates.add(new AddressBook(addressBook)); this.currentAddressBookStateIndex = 0; this.currentAddressBook = new AddressBook(this.addressBookStates.get(this.currentAddressBookStateIndex)); setAddressBookState(); } public ModelManager() { this(new AddressBook(), new UserPrefs()); } public void setAddressBookState() { this.nonFloatingTasks = new FilteredList<>(this.currentAddressBook.getTaskList()); this.floatingTasks = new FilteredList<>(this.currentAddressBook.getTaskList()); this.completedTasks = new FilteredList<>(this.currentAddressBook.getTaskList()); updateFilteredListToShowAllNonFloating(); updateFilteredListToShowAllFloatingTasks(); updateFilteredListToShowAllCompletedTasks(); } /** * Records the current state of AddressBook to facilitate state transition. */ private void recordCurrentStateOfAddressBook() { this.currentAddressBookStateIndex++; this.addressBookStates = new ArrayList<AddressBook>(this.addressBookStates.subList(0, this.currentAddressBookStateIndex)); this.addressBookStates.add(new AddressBook(this.currentAddressBook)); } @Override public void resetData(ReadOnlyAddressBook newData) { this.currentAddressBook.resetData(newData); recordCurrentStateOfAddressBook(); indicateAddressBookChanged(); } @Override public ReadOnlyAddressBook getAddressBook() { return this.currentAddressBook; } /** Raises an event to indicate the model has changed */ private void indicateAddressBookChanged() { raise(new AddressBookChangedEvent(this.currentAddressBook)); } /** Raises an event to indicate the model and its state have changed */ private void indicateAddressBookStateChanged() { AddressBookChangedEvent abce = new AddressBookChangedEvent(this.currentAddressBook); abce.setFloatingTasks(getFloatingTaskList()); abce.setNonFloatingTasks(getNonFloatingTaskList()); abce.setCompletedTasks(getCompletedTaskList()); raise(abce); } @Override public void setAddressBookStateForwards() throws StateLimitReachedException { if (this.currentAddressBookStateIndex >= this.addressBookStates.size() - 1) { throw new StateLimitReachedException(); } this.currentAddressBookStateIndex++; this.currentAddressBook = new AddressBook(this.addressBookStates.get(this.currentAddressBookStateIndex)); setAddressBookState(); indicateAddressBookStateChanged(); } @Override public void setAddressBookStateBackwards() throws StateLimitReachedException { if (this.currentAddressBookStateIndex <= 0) { throw new StateLimitReachedException(); } this.currentAddressBookStateIndex this.currentAddressBook = new AddressBook(this.addressBookStates.get(this.currentAddressBookStateIndex)); setAddressBookState(); indicateAddressBookStateChanged(); } @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { this.currentAddressBook.removeTask(target); recordCurrentStateOfAddressBook(); indicateAddressBookChanged(); } @Override public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException { this.currentAddressBook.addTask(task); recordCurrentStateOfAddressBook(); indicateAddressBookChanged(); } @Override public void updateTask(String targetList, int taskListIndex, ReadOnlyTask editedTask) throws UniqueTaskList.DuplicateTaskException { assert editedTask != null; int addressBookIndex = 0; switch (targetList) { case Task.TASK_NAME_FLOATING: addressBookIndex = this.floatingTasks.getSourceIndex(taskListIndex); break; case Task.TASK_NAME_COMPLETED: addressBookIndex = this.completedTasks.getSourceIndex(taskListIndex); break; case Task.TASK_NAME_NON_FLOATING: addressBookIndex = this.nonFloatingTasks.getSourceIndex(taskListIndex); break; default: addressBookIndex = this.nonFloatingTasks.getSourceIndex(taskListIndex); break; } this.currentAddressBook.updateTask(addressBookIndex, editedTask); recordCurrentStateOfAddressBook(); indicateAddressBookChanged(); } @Override public UnmodifiableObservableList<ReadOnlyTask> getNonFloatingTaskList() { return new UnmodifiableObservableList<>(this.nonFloatingTasks); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFloatingTaskList() { return new UnmodifiableObservableList<>(this.floatingTasks); } @Override public UnmodifiableObservableList<ReadOnlyTask> getCompletedTaskList() { return new UnmodifiableObservableList<>(this.completedTasks); } @Override public void updateFilteredListToShowAllNonFloating() { this.nonFloatingTasks.setPredicate(new PredicateExpression(new TaskIsNotFloatingQualifier())::satisfies); } @Override public void updateFilteredListToShowAllFloatingTasks() { this.floatingTasks.setPredicate(new PredicateExpression(new TaskIsFloatingQualifier())::satisfies); } @Override public void updateFilteredListToShowAllCompletedTasks() { this.completedTasks.setPredicate(new PredicateExpression(new TaskIsCompleteQualifier())::satisfies); } @Override public void updateFilteredListToShowFilteredNonFloatingTasks(Set<String> keywords) { this.nonFloatingTasks.setPredicate(new PredicateExpression(new NameNonFloatingTaskQualifier(keywords))::satisfies); } @Override public void updateFilteredListToShowFilteredFloatingTasks(Set<String> keywords) { this.floatingTasks.setPredicate(new PredicateExpression(new NameFloatingTaskQualifier(keywords))::satisfies); } @Override public void updateFilteredListToShowFilteredCompletedTasks(Set<String> keywords) { this.completedTasks.setPredicate(new PredicateExpression(new NameCompletedTaskQualifier(keywords))::satisfies); } @Override public void updateFilteredTaskList(Set<String> keywords) { updateFilteredListToShowFilteredNonFloatingTasks(keywords); updateFilteredListToShowFilteredFloatingTasks(keywords); updateFilteredListToShowFilteredCompletedTasks(keywords); } interface Expression { boolean satisfies(ReadOnlyTask task); String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask task) { return qualifier.run(task); } @Override public String toString() { return qualifier.toString(); } } interface Qualifier { boolean run(ReadOnlyTask task); String toString(); } private class NameFloatingTaskQualifier implements Qualifier { private Set<String> nameKeyWords; private FuzzyFinder fuzzyFinder; NameFloatingTaskQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; this.fuzzyFinder = new FuzzyFinder(); } @Override public boolean run(ReadOnlyTask task) { boolean isKeywordPresent = fuzzyFinder.check(task, nameKeyWords); boolean isFloatingTask = !task.isCompleted() && task.isFloating(); return isFloatingTask && isKeywordPresent; } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } private class NameNonFloatingTaskQualifier implements Qualifier { private Set<String> nameKeyWords; private FuzzyFinder fuzzyFinder; NameNonFloatingTaskQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; this.fuzzyFinder = new FuzzyFinder(); } @Override public boolean run(ReadOnlyTask task) { boolean isKeywordPresent = fuzzyFinder.check(task, nameKeyWords); boolean isNonFloatingTask = !task.isCompleted() && !task.isFloating(); return isNonFloatingTask && isKeywordPresent; } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } private class NameCompletedTaskQualifier implements Qualifier { private Set<String> nameKeyWords; private FuzzyFinder fuzzyFinder; NameCompletedTaskQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; this.fuzzyFinder = new FuzzyFinder(); } @Override public boolean run(ReadOnlyTask task) { boolean isKeywordPresent = fuzzyFinder.check(task, nameKeyWords); boolean isCompletedTask = task.isCompleted(); return isCompletedTask && isKeywordPresent; } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } private class FuzzyFinder { public boolean check(ReadOnlyTask task, Set<String> nameKeyWords) { return nameKeyWords.stream() .filter(keyword -> fuzzyFind(task.getTitle().title.toLowerCase(), keyword.toLowerCase())) .findAny() .isPresent(); } public boolean fuzzyFind(String title, String keyword) { return FuzzySearch.ratio(title, keyword) > MATCHING_INDEX; } } private class TaskIsFloatingQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask task) { return !task.isCompleted() && task.isFloating(); } } private class TaskIsNotFloatingQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask task) { return !task.isCompleted() && !task.isFloating(); } } private class TaskIsCompleteQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask task) { return task.isCompleted(); } } }
package systems.crigges.jmpq3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import systems.crigges.jmpq3.BlockTable.Block; import systems.crigges.jmpq3.security.MPQEncryption; import systems.crigges.jmpq3.security.MPQHashGenerator; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.channels.NonWritableChannelException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.file.*; import java.util.*; import static systems.crigges.jmpq3.MpqFile.*; /** * Provides an interface for using MPQ archive files. MPQ archive files contain * a virtual file system used by some old games to hold data, primarily those * from Blizzard Entertainment. * <p> * MPQ archives are not intended as a general purpose file system. File access * and reading is highly efficient. File manipulation and writing is not * efficient and may require rebuilding a large portion of the archive file. * Empty directories are not supported. The full contents of the archive might * not be discoverable, but such files can still be accessed if their full path * is known. File attributes are optional. * <p> * For platform independence the implementation is pure Java. */ public class JMpqEditor implements AutoCloseable { private Logger log = LoggerFactory.getLogger(this.getClass().getName()); public static final int ARCHIVE_HEADER_MAGIC = ByteBuffer.wrap(new byte[]{'M', 'P', 'Q', 0x1A}).order(ByteOrder.LITTLE_ENDIAN).getInt(); public static final int USER_DATA_HEADER_MAGIC = ByteBuffer.wrap(new byte[]{'M', 'P', 'Q', 0x1B}).order(ByteOrder.LITTLE_ENDIAN).getInt(); /** * Encryption key for hash table data. */ private static final int KEY_HASH_TABLE; /** * Encryption key for block table data. */ private static final int KEY_BLOCK_TABLE; static { final MPQHashGenerator hasher = MPQHashGenerator.getFileKeyGenerator(); hasher.process("(hash table)"); KEY_HASH_TABLE = hasher.getHash(); hasher.reset(); hasher.process("(block table)"); KEY_BLOCK_TABLE = hasher.getHash(); } public static File tempDir; private AttributesFile attributes; /** MPQ format version 0 forced compatibility is being used. */ private final boolean legacyCompatibility; /** The fc. */ private FileChannel fc; /** The header offset. */ private long headerOffset = -1; /** The header size. */ private int headerSize; /** The archive size. */ private long archiveSize; /** The format version. */ private int formatVersion; /** The sector size shift */ private int sectorSizeShift; /** The disc block size. */ private int discBlockSize; /** The hash table file position. */ private long hashPos; /** The block table file position. */ private long blockPos; /** The hash size. */ private int hashSize; /** The block size. */ private int blockSize; /** The hash table. */ private HashTable hashTable; /** The block table. */ private BlockTable blockTable; /** The list file. */ private Listfile listFile; /** The internal filename. */ private IdentityHashMap<ByteBuffer, String> internalFilename = new IdentityHashMap<>(); /** The files to add. */ // BuildData private ArrayList<ByteBuffer> filesToAdd = new ArrayList<>(); /** The keep header offset. */ private boolean keepHeaderOffset = true; /** The new header size. */ private int newHeaderSize; /** The new archive size. */ private long newArchiveSize; /** The new format version. */ private int newFormatVersion; /** The new disc block size. */ private int newSectorSizeShift; /** The new disc block size. */ private int newDiscBlockSize; /** The new hash pos. */ private long newHashPos; /** The new block pos. */ private long newBlockPos; /** The new hash size. */ private int newHashSize; /** The new block size. */ private int newBlockSize; /** If write operations are supported on the archive. */ private boolean canWrite; public JMpqEditor(Path mpqArchive, MPQOpenOption... openOptions) throws JMpqException { // process open options canWrite = !Arrays.asList(openOptions).contains(MPQOpenOption.READ_ONLY); legacyCompatibility = Arrays.asList(openOptions).contains(MPQOpenOption.FORCE_V0); try { setupTempDir(); final OpenOption[] fcOptions = canWrite ? new OpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE} : new OpenOption[]{StandardOpenOption.READ}; fc = FileChannel.open(mpqArchive, fcOptions); headerOffset = searchHeader(); readHeaderSize(); readHeader(); checkLegacyCompat(); readHashTable(); readBlockTable(); readListFile(); readAttributesFile(); } catch (IOException e) { throw new JMpqException(mpqArchive.toAbsolutePath().toString() + ": " + e.getMessage()); } } /** * See {@link #JMpqEditor(Path, MPQOpenOption...)} } * * @param mpqArchive a MPQ archive file. * @param openOptions options to use when opening the archive. * @throws JMpqException if mpq is damaged or not supported. */ public JMpqEditor(File mpqArchive, MPQOpenOption... openOptions) throws IOException { this(mpqArchive.toPath(), openOptions); } /** * See {@link #JMpqEditor(Path, MPQOpenOption...)} } * Kept for backwards compatibility, but deprecated * * @param mpqArchive a MPQ archive file. * @throws JMpqException if mpq is damaged or not supported. */ @Deprecated public JMpqEditor(File mpqArchive) throws IOException { this(mpqArchive.toPath(), MPQOpenOption.FORCE_V0); } private void checkLegacyCompat() throws IOException { if (legacyCompatibility) { // limit end of archive by end of file archiveSize = Math.min(archiveSize, fc.size() - headerOffset); // limit block table size by end of archive blockSize = (int) (Math.min(blockSize, (archiveSize - blockPos) / 16)); } } private void readAttributesFile() { if (hasFile("(attributes)")) { try { attributes = new AttributesFile(extractFileAsBytes("(attributes)")); } catch (Exception e) { } } } private void readListFile() throws IOException { if (hasFile("(listfile)")) { try { File tempFile = File.createTempFile("list", "file", JMpqEditor.tempDir); tempFile.deleteOnExit(); extractFile("(listfile)", tempFile); listFile = new Listfile(Files.readAllBytes(tempFile.toPath())); } catch (Exception e) { loadDefaultListFile(); } } else { loadDefaultListFile(); } } private void readBlockTable() throws IOException { ByteBuffer blockBuffer = ByteBuffer.allocate(blockSize * 16).order(ByteOrder.LITTLE_ENDIAN); fc.position(headerOffset + blockPos); readFully(blockBuffer, fc); blockBuffer.rewind(); blockTable = new BlockTable(blockBuffer); } private void readHashTable() throws IOException { // read hash table ByteBuffer hashBuffer = ByteBuffer.allocate(hashSize * 16); fc.position(headerOffset + hashPos); readFully(hashBuffer, fc); hashBuffer.rewind(); // decrypt hash table final MPQEncryption decrypt = new MPQEncryption(KEY_HASH_TABLE, true); decrypt.processSingle(hashBuffer); hashBuffer.rewind(); // create hash table hashTable = new HashTable(hashSize); hashTable.readFromBuffer(hashBuffer); } private void readHeaderSize() throws IOException { // probe to sample file with ByteBuffer probe = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); // read header size fc.position(headerOffset + 4); readFully(probe, fc); headerSize = probe.getInt(0); if (legacyCompatibility) { // force version 0 header size headerSize = 32; } else if (headerSize < 32 || 208 < headerSize) { // header too small or too big throw new JMpqException("Bad header size."); } } private void setupTempDir() throws JMpqException { try { Path path = Paths.get(System.getProperty("java.io.tmpdir") + "jmpq"); JMpqEditor.tempDir = path.toFile(); if (!JMpqEditor.tempDir.exists()) Files.createDirectory(path); File[] files = JMpqEditor.tempDir.listFiles(); for (File f : files) { // Delete existing tempfiles that are older than 1 day if ((System.currentTimeMillis() - f.lastModified()) > 1000 * 60 * 60 * 24) { f.delete(); } } } catch (IOException e) { try { JMpqEditor.tempDir = Files.createTempDirectory("jmpq").toFile(); } catch (IOException e1) { throw new JMpqException(e1); } } } /** * Loads a default listfile for mpqs that have none * Makes the archive readonly. */ private void loadDefaultListFile() throws IOException { log.warn("The mpq doesn't come with a listfile so it cannot be rebuild"); InputStream resource = getClass().getClassLoader().getResourceAsStream("DefaultListfile.txt"); if (resource != null) { File tempFile = File.createTempFile("jmpq", "lf", tempDir); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { //copy stream byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = resource.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } listFile = new Listfile(Files.readAllBytes(tempFile.toPath())); canWrite = false; } } /** * Searches the file for the MPQ archive header. * * @return the file position at which the MPQ archive starts. * @throws IOException if an error occurs while searching. * @throws JMpqException if file does not contain a MPQ archive. */ private long searchHeader() throws IOException { // probe to sample file with ByteBuffer probe = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); final long fileSize = fc.size(); for (long filePos = 0; filePos + probe.capacity() < fileSize; filePos += 0x200) { probe.rewind(); fc.position(filePos); readFully(probe, fc); final int sample = probe.getInt(0); if (sample == ARCHIVE_HEADER_MAGIC) { // found archive header return filePos; } else if (sample == USER_DATA_HEADER_MAGIC && !legacyCompatibility) { // MPQ user data header with redirect to MPQ header // ignore in legacy compatibility mode // TODO process these in some meaningful way probe.rewind(); fc.position(filePos + 8); readFully(probe, fc); // add header offset and align filePos += (probe.getInt(0) & 0xFFFFFFFFL); filePos &= ~(0x200 - 1); } } throw new JMpqException("No MPQ archive in file."); } /** * Read the MPQ archive header from the header chunk. */ private void readHeader() throws IOException { ByteBuffer buffer = ByteBuffer.allocate(headerSize).order(ByteOrder.LITTLE_ENDIAN); readFully(buffer, fc); buffer.rewind(); archiveSize = buffer.getInt() & 0xFFFFFFFFL; formatVersion = buffer.getShort(); if (legacyCompatibility) { // force version 0 interpretation formatVersion = 0; } sectorSizeShift = buffer.getShort(); discBlockSize = 512 * (1 << sectorSizeShift); hashPos = buffer.getInt() & 0xFFFFFFFFL; blockPos = buffer.getInt() & 0xFFFFFFFFL; hashSize = buffer.getInt(); blockSize = buffer.getInt(); // version 1 extension if (formatVersion >= 1) { // TODO add high block table support buffer.getLong(); // high 16 bits of file pos hashPos |= (buffer.getShort() & 0xFFFFL) << 32; blockPos |= (buffer.getShort() & 0xFFFFL) << 32; } // version 2 extension if (formatVersion >= 2) { // 64 bit archive size archiveSize = buffer.getLong(); // TODO add support for BET and HET tables buffer.getLong(); buffer.getLong(); } // version 3 extension if (formatVersion >= 3) { // TODO add support for compression and checksums buffer.getLong(); buffer.getLong(); buffer.getLong(); buffer.getLong(); buffer.getLong(); buffer.getInt(); final byte[] md5 = new byte[16]; buffer.get(md5); buffer.get(md5); buffer.get(md5); buffer.get(md5); buffer.get(md5); buffer.get(md5); } } /** * Write header. * * @param buffer the buffer */ private void writeHeader(MappedByteBuffer buffer) { buffer.putInt(newHeaderSize); buffer.putInt((int) newArchiveSize); buffer.putShort((short) newFormatVersion); buffer.putShort((short) newSectorSizeShift); buffer.putInt((int) newHashPos); buffer.putInt((int) newBlockPos); buffer.putInt(newHashSize); buffer.putInt(newBlockSize); // TODO add full write support for versions above 1 } /** * Calc new table size. */ private void calcNewTableSize() { int target = listFile.getFiles().size() + 2; int current = 2; while (current < target) { current *= 2; } newHashSize = current * 2; newBlockSize = listFile.getFiles().size() + 2; } /** * Extract all files. * * @param dest the dest * @throws JMpqException the j mpq exception */ public void extractAllFiles(File dest) throws JMpqException { if (!dest.isDirectory()) { throw new JMpqException("Destination location isn't a directory"); } if (hasFile("(listfile)") && listFile != null) { for (String s : listFile.getFiles()) { log.debug("extracting: " + s); File temp = new File(dest.getAbsolutePath() + "\\" + s); temp.getParentFile().mkdirs(); if (hasFile(s)) { // Prevent exception due to nonexistent listfile entries try { extractFile(s, temp); } catch (JMpqException e) { log.warn("File possibly corrupted and could not be extracted: " + s); } } } if (hasFile("(attributes)")) { File temp = new File(dest.getAbsolutePath() + "\\" + "(attributes)"); extractFile("(attributes)", temp); } File temp = new File(dest.getAbsolutePath() + "\\" + "(listfile)"); extractFile("(listfile)", temp); } else { ArrayList<Block> blocks = blockTable.getAllVaildBlocks(); try { int i = 0; for (Block b : blocks) { if ((b.getFlags() & MpqFile.ENCRYPTED) == MpqFile.ENCRYPTED) { continue; } ByteBuffer buf = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN); fc.position(headerOffset + b.getFilePos()); readFully(buf, fc); buf.rewind(); MpqFile f = new MpqFile(buf, b, discBlockSize, ""); f.extractToFile(new File(dest.getAbsolutePath() + "\\" + i)); i++; } } catch (IOException e) { throw new JMpqException(e); } } } /** * Gets the total file count. * * @return the total file count * @throws JMpqException the j mpq exception */ public int getTotalFileCount() throws JMpqException { return blockTable.getAllVaildBlocks().size(); } /** * Extracts the specified file out of the mpq to the target location. * * @param name name of the file * @param dest destination to that the files content is written * @throws JMpqException if file is not found or access errors occur */ public void extractFile(String name, File dest) throws JMpqException { try { MpqFile f = getMpqFile(name); f.extractToFile(dest); } catch (Exception e) { throw new JMpqException(e); } } /** * Extracts the specified file out of the mpq to the target location. * * @param name name of the file * @throws JMpqException if file is not found or access errors occur */ public byte[] extractFileAsBytes(String name) throws JMpqException { try { MpqFile f = getMpqFile(name); return f.extractToBytes(); } catch (IOException e) { throw new JMpqException(e); } } public String extractFileAsString(String name) throws JMpqException { try { byte[] f = extractFileAsBytes(name); return new String(f); } catch (IOException e) { throw new JMpqException(e); } } /** * Checks for file. * * @param name the name * @return true, if successful */ public boolean hasFile(String name) { try { hashTable.getBlockIndexOfFile(name); } catch (IOException e) { return false; } return true; } /** * Gets the file names. * * @return the file names */ public List<String> getFileNames() { return new ArrayList<>(listFile.getFiles()); } /** * Extracts the specified file out of the mpq and writes it to the target * outputstream. * * @param name name of the file * @param dest the outputstream where the file's content is written * @throws JMpqException if file is not found or access errors occur */ public void extractFile(String name, OutputStream dest) throws JMpqException { try { MpqFile f = getMpqFile(name); f.extractToOutputStream(dest); } catch (IOException e) { throw new JMpqException(e); } } /** * Gets the mpq file. * * @param name the name * @return the mpq file * @throws IOException Signals that an I/O exception has occurred. */ public MpqFile getMpqFile(String name) throws IOException { int pos = hashTable.getBlockIndexOfFile(name); Block b = blockTable.getBlockAtPos(pos); ByteBuffer buffer = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN); fc.position(headerOffset + b.getFilePos()); readFully(buffer, fc); buffer.rewind(); return new MpqFile(buffer, b, discBlockSize, name); } /** * Deletes the specified file out of the mpq once you rebuild the mpq. * * @param name of the file inside the mpq * @throws JMpqException if file is not found or access errors occur */ public void deleteFile(String name) { if (!canWrite) { throw new NonWritableChannelException(); } listFile.removeFile(name); } /** * Inserts the specified byte array into the mpq once you close the editor. * * @param name of the file inside the mpq * @param input the input byte array * @throws JMpqException if file is not found or access errors occur */ public void insertByteArray(String name, byte[] input) throws NonWritableChannelException { if (!canWrite) { throw new NonWritableChannelException(); } listFile.addFile(name); ByteBuffer data = ByteBuffer.wrap(input); filesToAdd.add(data); internalFilename.put(data, name); } /** * Inserts the specified file into the mpq once you close the editor. * * @param name of the file inside the mpq * @param file the file * @param backupFile if true the editors creates a copy of the file to add, so * further changes won't affect the resulting mpq * @throws JMpqException if file is not found or access errors occur */ public void insertFile(String name, File file, boolean backupFile) throws IOException { if (!canWrite) { throw new NonWritableChannelException(); } try { listFile.addFile(name); if (backupFile) { File temp = File.createTempFile("jmpq", "backup", JMpqEditor.tempDir); temp.deleteOnExit(); Files.copy(file.toPath(), temp.toPath(), StandardCopyOption.REPLACE_EXISTING); ByteBuffer data = ByteBuffer.wrap(Files.readAllBytes(temp.toPath())); filesToAdd.add(data); internalFilename.put(data, name); } else { ByteBuffer data = ByteBuffer.wrap(Files.readAllBytes(file.toPath())); filesToAdd.add(data); internalFilename.put(data, name); } } catch (IOException e) { throw new JMpqException(e); } } public void close() throws IOException { close(true, true, false); } /** * @param buildListfile whether or not to add a (listfile) to this mpq * @param buildAttributes whether or not to add a (attributes) file to this mpq * @throws IOException */ public void close(boolean buildListfile, boolean buildAttributes, boolean recompress) throws IOException { // only rebuild if allowed if (!canWrite || ! fc.isOpen()) { fc.close(); log.debug("closed readonly mpq."); return; } long t = System.nanoTime(); log.debug("Building mpq"); if (listFile == null) { fc.close(); return; } File temp = File.createTempFile("jmpq", "temp", JMpqEditor.tempDir); temp.deleteOnExit(); FileChannel writeChannel = FileChannel.open(temp.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ); ByteBuffer headerReader = ByteBuffer.allocate((int) ((keepHeaderOffset ? headerOffset : 0) + 4)).order(ByteOrder.LITTLE_ENDIAN); fc.position((keepHeaderOffset ? 0 : headerOffset)); readFully(headerReader, fc); headerReader.rewind(); writeChannel.write(headerReader); newFormatVersion = formatVersion; switch (newFormatVersion) { case 0: newHeaderSize = 32; break; case 1: newHeaderSize = 44; break; case 2: case 3: newHeaderSize = 208; break; } newSectorSizeShift = sectorSizeShift; newDiscBlockSize = discBlockSize; calcNewTableSize(); ArrayList<Block> newBlocks = new ArrayList<>(); ArrayList<String> newFiles = new ArrayList<>(); ArrayList<String> existingFiles = new ArrayList<>(listFile.getFiles()); sortListfileEntries(existingFiles); log.debug("Sorted blocks"); if (attributes != null) { attributes.setNames(existingFiles); } long currentPos = (keepHeaderOffset ? headerOffset : 0) + headerSize; for (ByteBuffer file : filesToAdd) { existingFiles.remove(internalFilename.get(file)); } for (String existingName : existingFiles) { if (recompress && !existingName.endsWith("wav")) { ByteBuffer extracted = ByteBuffer.wrap(extractFileAsBytes(existingName)); internalFilename.put(extracted, existingName); filesToAdd.add(extracted); } else { newFiles.add(existingName); int pos = hashTable.getBlockIndexOfFile(existingName); Block b = blockTable.getBlockAtPos(pos); ByteBuffer buf = ByteBuffer.allocate(b.getCompressedSize()).order(ByteOrder.LITTLE_ENDIAN); fc.position(headerOffset + b.getFilePos()); readFully(buf, fc); buf.rewind(); MpqFile f = new MpqFile(buf, b, discBlockSize, existingName); MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, b.getCompressedSize()); Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, b.getFlags()); newBlocks.add(newBlock); f.writeFileAndBlock(newBlock, fileWriter); currentPos += b.getCompressedSize(); } } log.debug("Added existing files"); HashMap<String, ByteBuffer> newFileMap = new HashMap<>(); for (ByteBuffer newFile : filesToAdd) { newFiles.add(internalFilename.get(newFile)); newFileMap.put(internalFilename.get(newFile), newFile); MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, newFile.limit() * 2); Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, 0); newBlocks.add(newBlock); MpqFile.writeFileAndBlock(newFile.array(), newBlock, fileWriter, newDiscBlockSize, recompress); currentPos += newBlock.getCompressedSize(); log.debug("Added file " + internalFilename.get(newFile)); } log.debug("Added new files"); if (buildListfile) { // Add listfile newFiles.add("(listfile)"); byte[] listfileArr = listFile.asByteArray(); MappedByteBuffer fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, listfileArr.length * 2); Block newBlock = new Block(currentPos - (keepHeaderOffset ? headerOffset : 0), 0, 0, EXISTS | COMPRESSED | ENCRYPTED | ADJUSTED_ENCRYPTED); newBlocks.add(newBlock); MpqFile.writeFileAndBlock(listfileArr, newBlock, fileWriter, newDiscBlockSize, "(listfile)", recompress); currentPos += newBlock.getCompressedSize(); log.debug("Added listfile"); } // if (attributes != null) { // newFiles.add("(attributes)"); // // Only generate attributes file when there has been one before // AttributesFile attributesFile = new AttributesFile(newFiles.size()); // // Generate new values // long time = (new Date().getTime() + 11644473600000L) * 10000L; // for (int i = 0; i < newFiles.size() - 1; i++) { // String name = newFiles.get(i); // int entry = attributes.getEntry(name); // if (newFileMap.containsKey(name)){ // // new file // attributesFile.setEntry(i, getCrc32(newFileMap.get(name)), time); // }else if (entry >= 0) { // // has timestamp // attributesFile.setEntry(i, getCrc32(name), // attributes.getTimestamps()[entry]); // } else { // // doesnt have timestamp // attributesFile.setEntry(i, getCrc32(name), time); // // newfiles don't contain the attributes file yet, hence -1 // System.out.println("added attributes"); // byte[] attrArr = attributesFile.buildFile(); // fileWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, // attrArr.length); // newBlock = new Block(currentPos - headerOffset, 0, 0, EXISTS | // COMPRESSED | ENCRYPTED | ADJUSTED_ENCRYPTED); // newBlocks.add(newBlock); // MpqFile.writeFileAndBlock(attrArr, newBlock, fileWriter, // newDiscBlockSize, "(attributes)"); // currentPos += newBlock.getCompressedSize(); newBlockSize = newBlocks.size(); newHashPos = currentPos - (keepHeaderOffset ? headerOffset : 0); newBlockPos = newHashPos + newHashSize * 16; // generate new hash table final int hashSize = newHashSize; HashTable hashTable = new HashTable(hashSize); int blockIndex = 0; for (String file : newFiles) { hashTable.setFileBlockIndex(file, HashTable.DEFAULT_LOCALE, blockIndex++); } // prepare hashtable for writing final ByteBuffer hashTableBuffer = ByteBuffer.allocate(hashSize * 16); hashTable.writeToBuffer(hashTableBuffer); hashTableBuffer.flip(); // encrypt hash table final MPQEncryption encrypt = new MPQEncryption(KEY_HASH_TABLE, false); encrypt.processSingle(hashTableBuffer); hashTableBuffer.flip(); // write out hash table writeChannel.position(currentPos); writeFully(hashTableBuffer, writeChannel); currentPos = writeChannel.position(); // write out block table MappedByteBuffer blocktableWriter = writeChannel.map(MapMode.READ_WRITE, currentPos, newBlockSize * 16); blocktableWriter.order(ByteOrder.LITTLE_ENDIAN); BlockTable.writeNewBlocktable(newBlocks, newBlockSize, blocktableWriter); currentPos += newBlockSize * 16; newArchiveSize = currentPos + 1 - (keepHeaderOffset ? headerOffset : 0); MappedByteBuffer headerWriter = writeChannel.map(MapMode.READ_WRITE, (keepHeaderOffset ? headerOffset : 0) + 4, headerSize + 4); headerWriter.order(ByteOrder.LITTLE_ENDIAN); writeHeader(headerWriter); MappedByteBuffer tempReader = writeChannel.map(MapMode.READ_WRITE, 0, currentPos + 1); tempReader.position(0); fc.position(0); fc.write(tempReader); fc.truncate(fc.position()); fc.close(); writeChannel.close(); t = System.nanoTime() - t; log.debug("Rebuild complete. Took: " + (t / 1000000) + "ms"); } private void sortListfileEntries(ArrayList<String> remainingFiles) { // Sort entries to preserve block table order remainingFiles.sort((o1, o2) -> { int pos1 = 999999999; int pos2 = 999999999; try { pos1 = hashTable.getBlockIndexOfFile(o1); } catch (IOException ignored) { } try { pos2 = hashTable.getBlockIndexOfFile(o2); } catch (IOException ignored) { } return pos1 - pos2; }); } /** * Utility method to fill a buffer from the given channel. * * @param buffer buffer to fill. * @param src channel to fill from. * @throws IOException if an exception occurs when reading. * @throws EOFException if EoF is encountered before buffer is full or channel is non * blocking. */ private static void readFully(ByteBuffer buffer, ReadableByteChannel src) throws IOException { while (buffer.hasRemaining()) { if (src.read(buffer) < 1) throw new EOFException("Cannot read enough bytes."); } } /** * Utility method to write out a buffer to the given channel. * * @param buffer buffer to write out. * @param dest channel to write to. * @throws IOException if an exception occurs when writing. */ private static void writeFully(ByteBuffer buffer, WritableByteChannel dest) throws IOException { while (buffer.hasRemaining()) { if (dest.write(buffer) < 1) throw new EOFException("Cannot write enough bytes."); } } /** * @return Whether the map can be modified or not */ public boolean isCanWrite() { return canWrite; } /** * Whether or not to keep the data before the actual mpq in the file * * @param keepHeaderOffset */ public void setKeepHeaderOffset(boolean keepHeaderOffset) { this.keepHeaderOffset = keepHeaderOffset; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "JMpqEditor [headerSize=" + headerSize + ", archiveSize=" + archiveSize + ", formatVersion=" + formatVersion + ", discBlockSize=" + discBlockSize + ", hashPos=" + hashPos + ", blockPos=" + blockPos + ", hashSize=" + hashSize + ", blockSize=" + blockSize + ", hashMap=" + hashTable + "]"; } }
package net.time4j.calendar.frenchrev; import net.time4j.GeneralTimestamp; import net.time4j.Moment; import net.time4j.PlainDate; import net.time4j.PlainTime; import net.time4j.SystemClock; import net.time4j.Weekday; import net.time4j.Weekmodel; import net.time4j.base.MathUtils; import net.time4j.base.TimeSource; import net.time4j.calendar.StdCalendarElement; import net.time4j.calendar.service.DualYearOfEraElement; import net.time4j.calendar.service.StdEnumDateElement; import net.time4j.calendar.service.StdIntegerDateElement; import net.time4j.calendar.service.StdWeekdayElement; import net.time4j.engine.AttributeQuery; import net.time4j.engine.BasicElement; import net.time4j.engine.CalendarDays; import net.time4j.engine.CalendarEra; import net.time4j.engine.CalendarSystem; import net.time4j.engine.Calendrical; import net.time4j.engine.ChronoDisplay; import net.time4j.engine.ChronoElement; import net.time4j.engine.ChronoEntity; import net.time4j.engine.ChronoException; import net.time4j.engine.ChronoMerger; import net.time4j.engine.ChronoUnit; import net.time4j.engine.Chronology; import net.time4j.engine.ElementRule; import net.time4j.engine.EpochDays; import net.time4j.engine.FormattableElement; import net.time4j.engine.IntElementRule; import net.time4j.engine.StartOfDay; import net.time4j.engine.TimeAxis; import net.time4j.engine.UnitRule; import net.time4j.engine.ValidationElement; import net.time4j.format.Attributes; import net.time4j.format.CalendarText; import net.time4j.format.CalendarType; import net.time4j.format.Leniency; import net.time4j.format.NumberSystem; import net.time4j.format.OutputContext; import net.time4j.format.TextAccessor; import net.time4j.format.TextElement; import net.time4j.format.TextWidth; import net.time4j.tz.TZID; import net.time4j.tz.Timezone; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.text.ParsePosition; import java.util.Collections; import java.util.List; import java.util.Locale; @CalendarType("extra/frenchrev") public final class FrenchRepublicanCalendar extends Calendrical<FrenchRepublicanCalendar.Unit, FrenchRepublicanCalendar> { // value chosen in order to make withEndOfFranciade() always working for equinox algorithm static final int MAX_YEAR = 1202; // < 3000 - 1792 + 1 private static final int YEAR_INDEX = 0; private static final int DECADE_INDEX = 1; private static final int DAY_OF_MONTH_INDEX = 2; private static final int DAY_OF_YEAR_INDEX = 3; /** * <p>Represents the Republican era of the French revolution. </p> */ /*[deutsch] * <p>Repr&auml;sentiert die republikanische &Auml;ra der franz&ouml;sischen Revolution. </p> */ @FormattableElement(format = "G", dynamic = true) public static final ChronoElement<FrenchRepublicanEra> ERA = new StdEnumDateElement<>("ERA", FrenchRepublicanCalendar.class, FrenchRepublicanEra.class, 'G'); /** * <p>Represents the republican year since 1792-09-22 (in range 1-1202). </p> * * <p>The year is printed as roman number when using a pattern and the French language. </p> */ /*[deutsch] * <p>Repr&auml;sentiert das republikanische Jahr gez&auml;hlt seit 1792-09-22 (im Bereich 1-1202). </p> * * <p>Das Jahr wird als r&ouml;mische Zahl formatiert, wenn ein Formatmuster und die franz&ouml;sische * Sprache verwendet werden. </p> */ @FormattableElement(format = "Y", alt = "y", dynamic = true) public static final StdCalendarElement<Integer, FrenchRepublicanCalendar> YEAR_OF_ERA = new YearOfEraElement(); private static final SansculottidesAccess SANSCULOTTIDES_ACCESS = new SansculottidesAccess(); private static final DayOfDecadeAccess DAY_OF_DECADE_ACCESS = new DayOfDecadeAccess(); /** * <p>Represents the complementary days of the French revolutionary calendar. </p> * * <p><strong>Warning:</strong> A French republican date does usually not have a complementary day * so any access via {@code get(SANSCULOTTIDES)} will throw an exception unless * users make sure that the day in question is indeed a complementary day. </p> * * <p>However, it is always possible to query the date for the minimum or maximum complementary day * or to set the date to a complementary day even if the actual date is not a complementary day. </p> * * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Repr&auml;sentiert die Erg&auml;nzungstage des franz&ouml;sischen Revolutionskalenders. </p> * * <p><strong>Warnung:</strong> Ein franz&ouml;sisches Republikdatum hat meistens keinen * Erg&auml;nzungstag, so da&szlig; jeder Zugriff via {@code get(SANSCULOTTIDES)} eine * Ausnahme werfen w&uuml;rde, es sei denn, Anwender stellen sicher, da&szlig; der aktuelle * Tag tats&auml;chlich ein Erg&auml;nzungstag ist. </p> * * <p>Allerdings ist es immer m&ouml;glich, das aktuelle Datum nach dem minimalen oder maximalen * Erg&auml;nzungstag zu fragen oder das aktuelle Datum auf einen Erg&auml;nzungstag zu setzen, * selbst wenn das Datum kein Erg&auml;nzungstag ist. </p> * * @see #hasSansculottides() * @see #hasMonth() */ @FormattableElement(format = "S", alt = "s", dynamic = true) public static final ChronoElement<Sansculottides> SANSCULOTTIDES = SANSCULOTTIDES_ACCESS; /** * <p>Represents the month (Vend&eacute;miaire - Fructidor) if available. </p> * * <p><strong>Warning:</strong> A French republican date does not always have a month. If the * date is a complementary day (Sansculottides) then any access via {@code get(MONTH_OF_YEAR)} * to this element will be rejected by raising an exception. Users have first to make sure * that the date is not such a complementary day. </p> * * <p>However, it is always possible to query the date for the minimum or maximum month * or to set the date to a month-related day even if the actual date is a complementary day. </p> * * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Repr&auml;sentiert den Monat (Vend&eacute;miaire - Fructidor), wenn vorhanden. </p> * * <p><strong>Warnung:</strong> Ein franz&ouml;sisches Republikdatum hat nicht immer einen Monat. Wenn * es einen Erg&auml;nzungstag darstellt (Sansculottides), dann wird jeder Zugriff per {@code get(MONTH_OF_YEAR)} * auf dieses Element mit einer Ausnahme quittiert. Anwender m&uuml;ssen zuerst sicherstellen, da&szlig; das Datum * kein solcher Erg&auml;nzungstag ist. </p> * * <p>Allerdings ist es immer m&ouml;glich, das aktuelle Datum nach dem minimalen oder maximalen * Monat zu fragen oder das aktuelle Datum auf einen monatsbezogenen Tag zu setzen, * selbst wenn das Datum ein Erg&auml;nzungstag ist. </p> * * @see #hasSansculottides() * @see #hasMonth() */ @FormattableElement(format = "M", alt = "m", dynamic = true) public static final StdCalendarElement<FrenchRepublicanMonth, FrenchRepublicanCalendar> MONTH_OF_YEAR = new StdEnumDateElement<>( "MONTH_OF_YEAR", FrenchRepublicanCalendar.class, FrenchRepublicanMonth.class, 'M'); /** * <p>Yields the decade of republican month if available. </p> * * <p><strong>Warning:</strong> A French republican date does not always have a decade. If the * date is a complementary day (Sansculottides) then any access to this element will be rejected * by raising an exception. Users have first to make sure that the date is not such a complementary * day. </p> * * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Repr&auml;sentiert die Dekade des Monats, wenn vorhanden. </p> * * <p><strong>Warnung:</strong> Ein franz&ouml;sisches Republikdatum hat nicht immer eine Dekade. Wenn * es einen Erg&auml;nzungstag darstellt (Sansculottides), dann wird jeder Zugriff auf dieses Element * mit einer Ausnahme quittiert. Anwender m&uuml;ssen zuerst sicherstellen, da&szlig; das Datum * kein solcher Erg&auml;nzungstag ist. </p> * * @see #hasSansculottides() * @see #hasMonth() */ public static final StdCalendarElement<Integer, FrenchRepublicanCalendar> DECADE_OF_MONTH = new StdIntegerDateElement<>("DECADE_OF_MONTH", FrenchRepublicanCalendar.class, 1, 3, '\u0000'); /** * <p>Represents the days of decade which consists of ten days. </p> * * <p><strong>Warning:</strong> A French republican date does not always have a day of decade. If the * date is a complementary day (Sansculottides) then any access to this element will be rejected * by raising an exception. Users have first to make sure that the date is not such a complementary * day. </p> * * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Repr&auml;sentiert die Dekadentage des franz&ouml;sischen Revolutionskalenders. </p> * * <p><strong>Warnung:</strong> Ein franz&ouml;sisches Republikdatum hat nicht immer einen Dekadentag. Wenn * es einen Erg&auml;nzungstag darstellt (Sansculottides), dann wird jeder Zugriff auf dieses Element * mit einer Ausnahme quittiert. Anwender m&uuml;ssen zuerst sicherstellen, da&szlig; das Datum * kein solcher Erg&auml;nzungstag ist. </p> * * @see #hasSansculottides() * @see #hasMonth() */ @FormattableElement(format = "C", alt = "c", dynamic = true) public static final ChronoElement<DayOfDecade> DAY_OF_DECADE = DAY_OF_DECADE_ACCESS; /** * <p>Represents the day of month if available. </p> * * <p><strong>Warning:</strong> A French republican date does not always have a month. If the * date is a complementary day (Sansculottides) then any access to this element will be rejected * by raising an exception. Users have first to make sure that the date is not such a complementary * day. </p> * * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Repr&auml;sentiert den Tag des Monats, wenn vorhanden. </p> * * <p><strong>Warnung:</strong> Ein franz&ouml;sisches Republikdatum hat nicht immer einen Monat. Wenn * es einen Erg&auml;nzungstag darstellt (Sansculottides), dann wird jeder Zugriff auf dieses Element * mit einer Ausnahme quittiert. Anwender m&uuml;ssen zuerst sicherstellen, da&szlig; das Datum * kein solcher Erg&auml;nzungstag ist. </p> * * @see #hasSansculottides() * @see #hasMonth() */ @FormattableElement(format = "D", alt = "d", dynamic = true) public static final StdCalendarElement<Integer, FrenchRepublicanCalendar> DAY_OF_MONTH = new StdIntegerDateElement<>("DAY_OF_MONTH", FrenchRepublicanCalendar.class, 1, 30, 'D'); /** * <p>Represents the day of year. </p> */ /*[deutsch] * <p>Repr&auml;sentiert den Tag des Jahres. </p> */ public static final StdCalendarElement<Integer, FrenchRepublicanCalendar> DAY_OF_YEAR = new StdIntegerDateElement<>("DAY_OF_YEAR", FrenchRepublicanCalendar.class, 1, 365, '\u0000'); /** * <p>Represents the day of week where the week is seven days long. </p> * * <p>If the day-of-week is set to a new value then Time4J handles the calendar week * as starting on Sunday. </p> * * @see #DAY_OF_DECADE */ /*[deutsch] * <p>Repr&auml;sentiert den Tag der Woche, die 7 Tage lang ist. </p> * * <p>Wenn der Tag der Woche auf einen neuen Wert gesetzt wird, behandelt Time4J die * Kalenderwoche so, da&szlig; sie am Sonntag beginnt. </p> * * @see #DAY_OF_DECADE */ @FormattableElement(format = "E", dynamic = true) public static final StdCalendarElement<Weekday, FrenchRepublicanCalendar> DAY_OF_WEEK = new StdWeekdayElement<>(FrenchRepublicanCalendar.class, getDefaultWeekmodel()); private static final CalendarSystem<FrenchRepublicanCalendar> CALSYS; private static final TimeAxis<FrenchRepublicanCalendar.Unit, FrenchRepublicanCalendar> ENGINE; private static final FrenchRepublicanAlgorithm DEFAULT_ALGORITHM = FrenchRepublicanAlgorithm.EQUINOX; static { CALSYS = new Transformer(); TimeAxis.Builder<FrenchRepublicanCalendar.Unit, FrenchRepublicanCalendar> builder = TimeAxis.Builder.setUp( FrenchRepublicanCalendar.Unit.class, FrenchRepublicanCalendar.class, new Merger(), CALSYS) .appendElement( ERA, new EraRule()) .appendElement( YEAR_OF_ERA, new IntegerRule(YEAR_INDEX), Unit.YEARS) .appendElement( SANSCULOTTIDES, SANSCULOTTIDES_ACCESS) .appendElement( MONTH_OF_YEAR, new MonthRule(), Unit.MONTHS) .appendElement( DECADE_OF_MONTH, new IntegerRule(DECADE_INDEX), Unit.DECADES) .appendElement( DAY_OF_MONTH, new IntegerRule(DAY_OF_MONTH_INDEX), Unit.DAYS) .appendElement( DAY_OF_YEAR, new IntegerRule(DAY_OF_YEAR_INDEX), Unit.DAYS) .appendElement( DAY_OF_WEEK, new WeekdayRule(), Unit.DAYS) .appendElement( DAY_OF_DECADE, DAY_OF_DECADE_ACCESS) .appendUnit( Unit.YEARS, new FUnitRule(Unit.YEARS), Unit.YEARS.getLength()) .appendUnit( Unit.MONTHS, new FUnitRule(Unit.MONTHS), Unit.MONTHS.getLength()) .appendUnit( Unit.DECADES, new FUnitRule(Unit.DECADES), Unit.DECADES.getLength()) .appendUnit( Unit.WEEKS, new FUnitRule(Unit.WEEKS), Unit.WEEKS.getLength(), Collections.singleton(Unit.DAYS)) .appendUnit( Unit.DAYS, new FUnitRule(Unit.DAYS), Unit.DAYS.getLength(), Collections.singleton(Unit.WEEKS)); ENGINE = builder.build(); } private static final long serialVersionUID = -6054794927532842783L; private transient final int fyear; private transient final int fdoy; // also called by FrenchRepublicanAlgorithm-enum FrenchRepublicanCalendar( int fyear, int fdoy ) { super(); this.fyear = fyear; this.fdoy = fdoy; } public static FrenchRepublicanCalendar of( int year, FrenchRepublicanMonth month, int dayOfMonth ) { return FrenchRepublicanCalendar.of(year, month.getValue(), dayOfMonth); } public static FrenchRepublicanCalendar of( int year, int month, int dayOfMonth ) { if ((year < 1) || (year > MAX_YEAR) || (month < 1) || (month > 12) || (dayOfMonth < 1) || (dayOfMonth > 30)) { throw new IllegalArgumentException( "Invalid French republican date: year=" + year + ", month=" + month + ", day=" + dayOfMonth); } return new FrenchRepublicanCalendar(year, (month - 1) * 30 + dayOfMonth); } public static FrenchRepublicanCalendar of( int year, Sansculottides sansculottides ) { if ((year < 1) || (year > MAX_YEAR)) { throw new IllegalArgumentException("Year out of range: " + year); } else if ((sansculottides == Sansculottides.LEAP_DAY) && !isLeapYear(year)) { throw new IllegalArgumentException("Day of Revolution only exists in leap years: " + year); } return new FrenchRepublicanCalendar(year, 360 + sansculottides.getValue()); } /** * <p>Obtains the current calendar date in system time. </p> * * <p>Convenient short-cut for: {@code SystemClock.inLocalView().now(FrenchRepublicanCalendar.axis())}. </p> * * @return current calendar date in system time zone using the system clock * @see SystemClock#inLocalView() * @see net.time4j.ZonalClock#now(Chronology) */ /*[deutsch] * <p>Ermittelt das aktuelle Kalenderdatum in der Systemzeit. </p> * * <p>Bequeme Abk&uuml;rzung f&uuml;r: * {@code SystemClock.inLocalView().now(FrenchRepublicanCalendar.axis())}. </p> * * @return current calendar date in system time zone using the system clock * @see SystemClock#inLocalView() * @see net.time4j.ZonalClock#now(net.time4j.engine.Chronology) */ public static FrenchRepublicanCalendar nowInSystemTime() { return SystemClock.inLocalView().now(FrenchRepublicanCalendar.axis()); } /** * <p>Yields the republican era. </p> * * @return {@link FrenchRepublicanEra#REPUBLICAN} */ /*[deutsch] * <p>Liefert die republikanische &Auml;ra. </p> * * @return {@link FrenchRepublicanEra#REPUBLICAN} */ public FrenchRepublicanEra getEra() { return FrenchRepublicanEra.REPUBLICAN; } /** * <p>Yields the republican year. </p> * * @return int */ /*[deutsch] * <p>Liefert das republikanische Jahr. </p> * * @return int */ public int getYear() { return this.fyear; } /** * <p>Yields the republican month if available. </p> * * @return month enum * @throws ChronoException if this date is a complementary day * @see #MONTH_OF_YEAR * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Liefert den republikanischen Monat, wenn vorhanden. </p> * * @return month enum * @throws ChronoException if this date is a complementary day * @see #MONTH_OF_YEAR * @see #hasSansculottides() * @see #hasMonth() */ public FrenchRepublicanMonth getMonth() { if (this.fdoy > 360) { throw new ChronoException( "Complementary days (sansculottides) do not represent any month: " + this.toString()); } int m = ((this.fdoy - 1) / 30) + 1; return FrenchRepublicanMonth.valueOf(m); } /** * <p>Yields the decade of current republican month if available. </p> * * @return int (1, 2 or 3) * @throws ChronoException if this date is a complementary day * @see #DECADE_OF_MONTH * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Liefert die Dekade des aktuellen republikanischen Monats, wenn vorhanden. </p> * * @return int (1, 2 or 3) * @throws ChronoException if this date is a complementary day * @see #DECADE_OF_MONTH * @see #hasSansculottides() * @see #hasMonth() */ public int getDecade() { if (this.fdoy > 360) { throw new ChronoException( "Complementary days (sansculottides) do not represent any decade: " + this.toString()); } return (((this.fdoy - 1) % 30) / 10) + 1; } /** * <p>Yields the day of month if available. </p> * * @return int (1-30) * @throws ChronoException if this date is a complementary day * @see #DAY_OF_MONTH * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Liefert den Tag des Monats, wenn vorhanden. </p> * * @return int (1-30) * @throws ChronoException if this date is a complementary day * @see #DAY_OF_MONTH * @see #hasSansculottides() * @see #hasMonth() */ public int getDayOfMonth() { if (this.fdoy > 360) { throw new ChronoException( "Complementary days (sansculottides) are not part of any month: " + this.toString()); } return ((this.fdoy - 1) % 30) + 1; } /** * <p>Yields the day of decade if available (ten-day-week). </p> * * @return enum * @throws ChronoException if this date is a complementary day * @see #DAY_OF_DECADE * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Liefert den Tag des Monats, wenn vorhanden (Zehn-Tage-Woche). </p> * * @return enum * @throws ChronoException if this date is a complementary day * @see #DAY_OF_DECADE * @see #hasSansculottides() * @see #hasMonth() */ public DayOfDecade getDayOfDecade() { if (this.hasSansculottides()) { throw new ChronoException("Day of decade does not exist on sansculottides: " + this.toString()); } return DayOfDecade.valueOf(((this.fdoy - 1) % 10) + 1); } /** * <p>Determines the day of standard-week (with seven days). </p> * * @return Weekday */ /*[deutsch] * <p>Ermittelt den Wochentag bezogen auf eine 7-Tage-Woche. </p> * * @return Weekday */ public Weekday getDayOfWeek() { long utcDays = CALSYS.transform(this); return Weekday.valueOf(MathUtils.floorModulo(utcDays + 5, 7) + 1); } /** * <p>Yields the day of year. </p> * * @return int */ /*[deutsch] * <p>Liefert den Tag des Jahres. </p> * * @return int */ public int getDayOfYear() { return this.fdoy; } /** * <p>Yields the complementary day if available. </p> * * @return Sansculottides enum * @throws ChronoException if this date is not a complementary day * @see #hasSansculottides() * @see #hasMonth() */ /*[deutsch] * <p>Liefert den Erg&auml;nzungstag, wenn vorhanden. </p> * * @return Sansculottides enum * @throws ChronoException if this date is not a complementary day * @see #hasSansculottides() * @see #hasMonth() */ public Sansculottides getSansculottides() { if (this.fdoy <= 360) { throw new ChronoException( "Not a sansculottides day: " + this.toString()); } return Sansculottides.valueOf(this.fdoy - 360); } /** * <p>Is this date a complementary day? </p> * * <p>A date in the French revolutionary calendar has either a month or is a complementary day. </p> * * @return boolean * @see #hasMonth() * @see #MONTH_OF_YEAR * @see #DAY_OF_MONTH * @see #DECADE_OF_MONTH * @see #DAY_OF_DECADE * @see #SANSCULOTTIDES */ /*[deutsch] * <p>Liegt dieses Datum auf einem Erg&auml;nzungstag? </p> * * <p>Ein Datum im franz&ouml;sischen Revolutionskalender hat entweder einen Monat * oder ist ein Erg&auml;nzungstag. </p> * * @return boolean * @see #hasMonth() * @see #MONTH_OF_YEAR * @see #DAY_OF_MONTH * @see #DECADE_OF_MONTH * @see #DAY_OF_DECADE * @see #SANSCULOTTIDES */ public boolean hasSansculottides() { return (this.fdoy > 360); } /** * <p>Does this date contain a month? </p> * * <p>A date in the French revolutionary calendar has either a month or is a complementary day. </p> * * @return boolean * @see #hasSansculottides() * @see #MONTH_OF_YEAR * @see #DAY_OF_MONTH * @see #DECADE_OF_MONTH * @see #DAY_OF_DECADE * @see #SANSCULOTTIDES */ /*[deutsch] * <p>Liegt dieses Datum in einem Monat? </p> * * <p>Ein Datum im franz&ouml;sischen Revolutionskalender hat entweder einen Monat * oder ist ein Erg&auml;nzungstag. </p> * * @return boolean * @see #hasSansculottides() * @see #MONTH_OF_YEAR * @see #DAY_OF_MONTH * @see #DECADE_OF_MONTH * @see #DAY_OF_DECADE * @see #SANSCULOTTIDES */ public boolean hasMonth() { return (this.fdoy <= 360); } /** * <p>Is the year of this date a leap year? </p> * * @return boolean */ /*[deutsch] * <p>Liegt dieses Datum in einem Schaltjahr? </p> * * @return boolean */ public boolean isLeapYear() { return isLeapYear(this.fyear); } /** * <p>Is given republican year a leap year? </p> * * @param year republican year to be checked (in range 1-1202) * @return boolean */ /*[deutsch] * <p>Ist das angegebene republikanische Jahr ein Schaltjahr? </p> * * @param year republican year to be checked (in range 1-1202) * @return boolean */ public static boolean isLeapYear(int year) { return DEFAULT_ALGORITHM.isLeapYear(year); } /** * <p>Queries if given parameter values form a well defined calendar date. </p> * * @param year the year of era to be checked * @param month the month to be checked * @param dayOfMonth the day of month to be checked * @return {@code true} if valid else {@code false} * @see #of(int, int, int) * @since 3.34/4.29 */ /*[deutsch] * <p>Pr&uuml;ft, ob die angegebenen Parameter ein wohldefiniertes Kalenderdatum beschreiben. </p> * * @param year the year of era to be checked * @param month the month to be checked * @param dayOfMonth the day of month to be checked * @return {@code true} if valid else {@code false} * @see #of(int, int, int) * @since 3.34/4.29 */ public static boolean isValid( int year, int month, int dayOfMonth ) { return ( (year >= 1) && (year <= MAX_YEAR) && (month >= 1) && (month <= 12) && (dayOfMonth >= 1) && (dayOfMonth <= 30)); } public Date getDate(FrenchRepublicanAlgorithm algorithm) { if (algorithm == DEFAULT_ALGORITHM) { return new Date(this, DEFAULT_ALGORITHM); } long utcDays = DEFAULT_ALGORITHM.transform(this); return new Date(algorithm.transform(utcDays), algorithm); } /** * <p>Creates a new local timestamp with this date and given wall time. </p> * * <p>If the time {@link PlainTime#midnightAtEndOfDay() T24:00} is used * then the resulting timestamp will automatically be normalized such * that the timestamp will contain the following day instead. </p> * * @param time wall time * @return general timestamp as composition of this date and given time */ /*[deutsch] * <p>Erzeugt einen allgemeinen Zeitstempel mit diesem Datum und der angegebenen Uhrzeit. </p> * * <p>Wenn {@link PlainTime#midnightAtEndOfDay() T24:00} angegeben wird, * dann wird der Zeitstempel automatisch so normalisiert, da&szlig; er auf * den n&auml;chsten Tag verweist. </p> * * @param time wall time * @return general timestamp as composition of this date and given time */ public GeneralTimestamp<FrenchRepublicanCalendar> at(PlainTime time) { return GeneralTimestamp.of(this, time); } public GeneralTimestamp<FrenchRepublicanCalendar> atTime( int hour, int minute ) { return this.at(PlainTime.of(hour, minute)); } /** * <p>Obtains the next leap day when the franciade ends. </p> * * @return end of franciade * @see Sansculottides#LEAP_DAY */ /*[deutsch] * <p>Liefert den n&auml;chsten Schalttag am Ende einer &quot;franciade&quot;. </p> * * @return end of franciade * @see Sansculottides#LEAP_DAY */ public FrenchRepublicanCalendar withEndOfFranciade() { int y = this.fyear; while (!isLeapYear(y)) { y++; } return new FrenchRepublicanCalendar(y, 366); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof FrenchRepublicanCalendar) { FrenchRepublicanCalendar that = (FrenchRepublicanCalendar) obj; return ((this.fyear == that.fyear) && (this.fdoy == that.fdoy)); } else { return false; } } @Override public int hashCode() { return (17 * this.fdoy + 37 * this.fyear); } @Override public String toString() { StringBuilder sb = new StringBuilder(32); sb.append("French-Republic-"); sb.append(NumberSystem.ROMAN.toNumeral(this.fyear)); sb.append('-'); if (this.fdoy > 360) { sb.append("Sansculottides-"); sb.append(String.valueOf(this.fdoy - 360)); } else { int m = this.getMonth().getValue(); if (m < 10) { sb.append('0'); } sb.append(m); sb.append('-'); int dom = this.getDayOfMonth(); if (dom < 10) { sb.append('0'); } sb.append(dom); } return sb.toString(); } @Override public boolean contains(ChronoElement<?> element) { if ( element == MONTH_OF_YEAR || element == DECADE_OF_MONTH || element == DAY_OF_DECADE || element == DAY_OF_MONTH ) { return this.hasMonth(); } else if (element == SANSCULOTTIDES) { return this.hasSansculottides(); } else if (this.getRegisteredElements().contains(element)) { return true; } // external element return isAccessible(this, element); } @Override public <V> boolean isValid( ChronoElement<V> element, V value ) { if (element == MONTH_OF_YEAR) { return (value != null); } else if (element == SANSCULOTTIDES) { return SANSCULOTTIDES_ACCESS.isValid(this, Sansculottides.class.cast(value)); } return super.isValid(element, value); } /** * <p>Returns the associated time axis. </p> * * @return chronology */ /*[deutsch] * <p>Liefert die zugeh&ouml;rige Zeitachse. </p> * * @return chronology */ public static TimeAxis<Unit, FrenchRepublicanCalendar> axis() { return ENGINE; } @Override protected TimeAxis<Unit, FrenchRepublicanCalendar> getChronology() { return ENGINE; } @Override protected FrenchRepublicanCalendar getContext() { return this; } // Obtains the standard week model of this calendar whose weeks historically start on Sunday. private static Weekmodel getDefaultWeekmodel() { return Weekmodel.of(Weekday.SUNDAY, 1, Weekday.SUNDAY, Weekday.SUNDAY); // historic condition } private static <V> boolean isAccessible( FrenchRepublicanCalendar fcal, ChronoElement<V> element ) { try { return fcal.isValid(element, fcal.get(element)); } catch (ChronoException ex) { return false; } } /** * @serialData Uses <a href="../../../../serialized-form.html#net.time4j.calendar.frenchrev/SPX"> * a dedicated serialization form</a> as proxy. The first byte contains * the type-ID {@code 18}. Then the year is written as int, finally * month and day-of-month as bytes. * * @return replacement object in serialization graph */ private Object writeReplace() { return new SPX(this, SPX.FRENCH_REV); } /** * @serialData Blocks because a serialization proxy is required. * @param in object input stream * @throws InvalidObjectException (always) */ private void readObject(ObjectInputStream in) throws IOException { throw new InvalidObjectException("Serialization proxy required."); } /** * <p>Defines come calendar units for the French revolutionary calendar. </p> */ /*[deutsch] * <p>Definiert einige kalendarische Zeiteinheiten f&uuml;r den franz&ouml;sischen Revolutionskalender. </p> */ public static enum Unit implements ChronoUnit { /** * <p>Years are defined as equinox years and not as tropical years. </p> */ /*[deutsch] * <p>Jahre sind als Herbstbezogene Jahre und nicht als tropische Jahre definiert. </p> */ YEARS(365.242374 * 86400.0), // length => J. Meeus and Savoie 1992, p. 42 /** * <p>The month arithmetic handles the sansculottides as extension of last month Fructidor. </p> * * <p>The resulting date is always within a republican month. Example: </p> * * <pre> * FrenchRepublicanCalendar cal = FrenchRepublicanCalendar.of(1, Sansculottides.COMPLEMENTARY_DAY_3); * FrenchRepublicanCalendar next = cal.plus(1, FrenchRepublicanCalendar.Unit.MONTHS); * System.out.println(next); // French-Republic-II-01-30 (30th of Vend&eacute;miaire II) * </pre> */ /*[deutsch] * <p>Die Monatsarithmetik behandelt die Erg&auml;nzungstage (sansculottides) als eine Erweiterung * des letzten Monats Fructidor. </p> * * <p>Das Ergebnisdatum ist immer innerhalb eines republikanischen Monats. Beispiel: </p> * * <pre> * FrenchRepublicanCalendar cal = FrenchRepublicanCalendar.of(1, Sansculottides.COMPLEMENTARY_DAY_3); * FrenchRepublicanCalendar next = cal.plus(1, FrenchRepublicanCalendar.Unit.MONTHS); * System.out.println(next); // French-Republic-II-01-30 (30th of Vend&eacute;miaire II) * </pre> */ MONTHS(30 * 86400.0), /** * <p>Decades consist of ten days where complementary days will be ignored or skipped. </p> */ /*[deutsch] * <p>Dekaden bestehen aus zehn Tagen, wobei Erg&auml;nzungstage ignoriert oder &uuml;bersprungen werden. </p> */ DECADES(10 * 86400.0), /** * <p>Weeks consist of seven days. </p> */ /*[deutsch] * <p>Wochen bestehen aus sieben Tagen. </p> */ WEEKS(7 * 86400.0), /** * <p>The universal day unit. </p> */ /*[deutsch] * <p>Die universelle Tageseinheit. </p> */ DAYS(86400.0); private transient final double length; private Unit(double length) { this.length = length; } @Override public double getLength() { return this.length; } @Override public boolean isCalendrical() { return true; } /** * <p>Calculates the difference between given calendar dates in this unit. </p> * * @param start start date (inclusive) * @param end end date (exclusive) * @return difference counted in this unit */ /*[deutsch] * <p>Berechnet die Differenz zwischen den angegebenen Datumsparametern in dieser Zeiteinheit. </p> * * @param start start date (inclusive) * @param end end date (exclusive) * @return difference counted in this unit */ public long between( FrenchRepublicanCalendar start, FrenchRepublicanCalendar end ) { return start.until(end, this); } } /** * <p>Static view of calendar date taking into account possibly different calendar algorithms. </p> * * <p>Note: Only elements registered in the French republican calendar chronology are supported. </p> * * @see #getDate(FrenchRepublicanAlgorithm) * @see FrenchRepublicanAlgorithm#attribute() * @since 3.33/4.28 */ /*[deutsch] * <p>Statische Ansicht eines Kalenderdatums, das auf verschiedenen Kalenderalgorithmen basieren kann. </p> * * <p>Hinweis: Nur in der Chronologie des franz&ouml;sischen Revolutionskalenders registrierte Elemente * werden unterst&uuml;tzt. </p> * * @see #getDate(FrenchRepublicanAlgorithm) * @see FrenchRepublicanAlgorithm#attribute() * @since 3.33/4.28 */ public static final class Date implements ChronoDisplay { private final FrenchRepublicanCalendar delegate; private final FrenchRepublicanAlgorithm algorithm; private Date( FrenchRepublicanCalendar delegate, FrenchRepublicanAlgorithm algorithm ) { super(); this.delegate = delegate; this.algorithm = algorithm; } @Override public boolean contains(ChronoElement<?> element) { return ENGINE.isRegistered(element); } @Override public <V> V get(ChronoElement<V> element) { if (element == DAY_OF_WEEK) { long utcDays = this.algorithm.transform(this.delegate); return element.getType().cast(Weekday.valueOf(MathUtils.floorModulo(utcDays + 5, 7) + 1)); } else if (element instanceof EpochDays) { EpochDays ed = EpochDays.class.cast(element); long utcDays = this.algorithm.transform(this.delegate); return element.getType().cast(Long.valueOf(ed.transform(utcDays, EpochDays.UTC))); } else if (ENGINE.isRegistered(element)) { return this.delegate.get(element); } else { throw new ChronoException("French republican dates only support registered elements."); } } @Override public int getInt(ChronoElement<Integer> element) { if (ENGINE.isRegistered(element)) { return this.delegate.getInt(element); } else { return Integer.MIN_VALUE; } } @Override public <V> V getMinimum(ChronoElement<V> element) { if (ENGINE.isRegistered(element)) { return this.delegate.getMinimum(element); } else { throw new ChronoException("French republican dates only support registered elements."); } } @Override public <V> V getMaximum(ChronoElement<V> element) { if (ENGINE.isRegistered(element)) { return this.delegate.getMaximum(element); } else { throw new ChronoException("French republican dates only support registered elements."); } } /** * <p>This date has no timezone (offset). </p> * * @return {@code false} */ /*[deutsch] * <p>Dieses Datum hat keine Zeitzone oder Verschiebung. </p> * * @return {@code false} */ @Override public boolean hasTimezone() { return false; } /** * <p>Always throws an exception. </p> * * @return (nothing) * @throws ChronoException (always) */ /*[deutsch] * <p>Wirft immer eine Ausnahme. </p> * * @return (nothing) * @throws ChronoException (always) */ @Override public TZID getTimezone() { throw new ChronoException("Timezone not available."); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof Date) { Date that = (Date) obj; if (this.algorithm != that.algorithm) { return false; } else { return this.delegate.equals(that.delegate); } } else { return false; } } @Override public int hashCode() { return 7 * this.delegate.hashCode() + 31 * this.algorithm.hashCode(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.delegate); sb.append('['); sb.append(this.algorithm); sb.append(']'); return sb.toString(); } } private static class Transformer implements CalendarSystem<FrenchRepublicanCalendar> { @Override public FrenchRepublicanCalendar transform(long utcDays) { return DEFAULT_ALGORITHM.transform(utcDays); } @Override public long transform(FrenchRepublicanCalendar date) { return DEFAULT_ALGORITHM.transform(date); } @Override public long getMinimumSinceUTC() { FrenchRepublicanCalendar min = new FrenchRepublicanCalendar(1, 1); return this.transform(min); } @Override public long getMaximumSinceUTC() { FrenchRepublicanCalendar max = new FrenchRepublicanCalendar(MAX_YEAR, 366); return this.transform(max); } @Override public List<CalendarEra> getEras() { CalendarEra era = FrenchRepublicanEra.REPUBLICAN; return Collections.singletonList(era); } } private static class YearOfEraElement extends DualYearOfEraElement<FrenchRepublicanCalendar> { private static final long serialVersionUID = 7337125729623271040L; private YearOfEraElement() { super(FrenchRepublicanCalendar.class, 1, MAX_YEAR, 'Y'); } @Override protected NumberSystem getNumberSystem(AttributeQuery attributes) { String pattern = attributes.get(Attributes.FORMAT_PATTERN, ""); if ( pattern.contains("Y") && attributes.get(Attributes.LANGUAGE, Locale.ROOT).getLanguage().equals("fr") ) { return NumberSystem.ROMAN; } return attributes.get(Attributes.NUMBER_SYSTEM, NumberSystem.ROMAN); } } private static class IntegerRule implements IntElementRule<FrenchRepublicanCalendar> { private final int index; IntegerRule(int index) { super(); this.index = index; } @Override public int getInt(FrenchRepublicanCalendar context) { switch (this.index) { case YEAR_INDEX: return context.fyear; case DECADE_INDEX: return context.getDecade(); case DAY_OF_MONTH_INDEX: return context.getDayOfMonth(); case DAY_OF_YEAR_INDEX: return context.fdoy; default: throw new UnsupportedOperationException("Unknown element index: " + this.index); } } @Override public boolean isValid(FrenchRepublicanCalendar context, int value) { if ((this.index == DAY_OF_MONTH_INDEX || this.index == DECADE_INDEX) && context.hasSansculottides()) { return false; } int min = this.getMin(context); int max = this.getMax(context); return ((min <= value) && (max >= value)); } @Override public FrenchRepublicanCalendar withValue(FrenchRepublicanCalendar context, int value, boolean lenient) { if ((this.index == DAY_OF_MONTH_INDEX) && context.hasSansculottides()) { throw new IllegalArgumentException("Day of month not defined on sansculottides: " + value); } else if ((this.index == DECADE_INDEX) && context.hasSansculottides()) { throw new IllegalArgumentException("Decade of month not defined on sansculottides: " + value); } else if (!this.isValid(context, value)) { throw new IllegalArgumentException("Out of range: " + value); } switch (this.index) { case YEAR_INDEX: int dmax = DEFAULT_ALGORITHM.isLeapYear(value) ? 366 : 365; return new FrenchRepublicanCalendar(value, Math.min(context.fdoy, dmax)); case DECADE_INDEX: int dom = (value - 1) * 10 + ((context.getDayOfMonth() - 1) % 10) + 1; return FrenchRepublicanCalendar.of(context.fyear, context.getMonth(), dom); case DAY_OF_MONTH_INDEX: return FrenchRepublicanCalendar.of(context.fyear, context.getMonth(), value); case DAY_OF_YEAR_INDEX: return new FrenchRepublicanCalendar(context.fyear, value); default: throw new UnsupportedOperationException("Unknown element index: " + this.index); } } @Override public Integer getValue(FrenchRepublicanCalendar context) { return Integer.valueOf(this.getInt(context)); } @Override public Integer getMinimum(FrenchRepublicanCalendar context) { return Integer.valueOf(this.getMin(context)); } @Override public Integer getMaximum(FrenchRepublicanCalendar context) { return Integer.valueOf(this.getMax(context)); } @Override public boolean isValid( FrenchRepublicanCalendar context, Integer value ) { return ((value != null) && this.isValid(context, value.intValue())); } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, Integer value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing new value."); } return this.withValue(context, value.intValue(), lenient); } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { if (this.index == YEAR_INDEX) { return MONTH_OF_YEAR; } else if (this.index == DECADE_INDEX) { return DAY_OF_DECADE; } return null; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { if (this.index == YEAR_INDEX) { return SANSCULOTTIDES; } else if (this.index == DECADE_INDEX) { return DAY_OF_DECADE; } return null; } private int getMin(FrenchRepublicanCalendar context) { switch (this.index) { case YEAR_INDEX: case DAY_OF_YEAR_INDEX: return 1; case DECADE_INDEX: case DAY_OF_MONTH_INDEX: if (context.hasSansculottides()) { throw new ChronoException( "Complementary days (sansculottides) are not part of any month or decade: " + context); } else { return 1; } default: throw new UnsupportedOperationException("Unknown element index: " + this.index); } } private int getMax(FrenchRepublicanCalendar context) { switch (this.index) { case YEAR_INDEX: return MAX_YEAR; case DECADE_INDEX: case DAY_OF_MONTH_INDEX: if (context.hasSansculottides()) { throw new ChronoException( "Complementary days (sansculottides) are not part of any month: " + context); } else { return ((this.index == DAY_OF_MONTH_INDEX) ? 30 : 3); } case DAY_OF_YEAR_INDEX: return DEFAULT_ALGORITHM.isLeapYear(context.fyear) ? 366 : 365; default: throw new UnsupportedOperationException("Unknown element index: " + this.index); } } } private static class MonthRule implements ElementRule<FrenchRepublicanCalendar, FrenchRepublicanMonth> { @Override public FrenchRepublicanMonth getValue(FrenchRepublicanCalendar context) { return context.getMonth(); } @Override public FrenchRepublicanMonth getMinimum(FrenchRepublicanCalendar context) { return FrenchRepublicanMonth.VENDEMIAIRE; } @Override public FrenchRepublicanMonth getMaximum(FrenchRepublicanCalendar context) { return FrenchRepublicanMonth.FRUCTIDOR; } @Override public boolean isValid( FrenchRepublicanCalendar context, FrenchRepublicanMonth value ) { return (value != null); } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, FrenchRepublicanMonth value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing republican month."); } else if (context.hasSansculottides()) { return FrenchRepublicanCalendar.of(context.fyear, value, 30); } else { return FrenchRepublicanCalendar.of(context.fyear, value, context.getDayOfMonth()); } } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { return DAY_OF_MONTH; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { return DAY_OF_MONTH; } } private static class EraRule implements ElementRule<FrenchRepublicanCalendar, FrenchRepublicanEra> { @Override public FrenchRepublicanEra getValue(FrenchRepublicanCalendar context) { return FrenchRepublicanEra.REPUBLICAN; } @Override public FrenchRepublicanEra getMinimum(FrenchRepublicanCalendar context) { return FrenchRepublicanEra.REPUBLICAN; } @Override public FrenchRepublicanEra getMaximum(FrenchRepublicanCalendar context) { return FrenchRepublicanEra.REPUBLICAN; } @Override public boolean isValid( FrenchRepublicanCalendar context, FrenchRepublicanEra value ) { return (value != null); } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, FrenchRepublicanEra value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing era value."); } return context; } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { return YEAR_OF_ERA; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { return YEAR_OF_ERA; } } private static class DayOfDecadeAccess extends BasicElement<DayOfDecade> implements TextElement<DayOfDecade>, ElementRule<FrenchRepublicanCalendar, DayOfDecade> { private static final long serialVersionUID = -8211850819064695450L; DayOfDecadeAccess() { super("DAY_OF_DECADE"); } @Override public char getSymbol() { return 'C'; } @Override public DayOfDecade getValue(FrenchRepublicanCalendar context) { return context.getDayOfDecade(); // may throw an exception } @Override public DayOfDecade getMinimum(FrenchRepublicanCalendar context) { if (context.hasSansculottides()) { throw new ChronoException("Cannot get minimum for day of decade on sansculottides: " + context); } return DayOfDecade.PRIMIDI; } @Override public DayOfDecade getMaximum(FrenchRepublicanCalendar context) { if (context.hasSansculottides()) { throw new ChronoException("Cannot get maximum for day of decade on sansculottides: " + context); } return DayOfDecade.DECADI; } @Override public boolean isValid( FrenchRepublicanCalendar context, DayOfDecade value ) { return (value != null) && !context.hasSansculottides(); } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, DayOfDecade value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing day of decade."); } else if (context.hasSansculottides()) { throw new IllegalArgumentException("Cannot set day of decade on sansculottides."); } int oldValue = ((context.fdoy - 1) % 10) + 1; int delta = value.getValue() - oldValue; if (delta == 0) { return context; } else { return new FrenchRepublicanCalendar(context.fyear, context.fdoy + delta); } } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { return null; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { return null; } @Override public void print( ChronoDisplay context, Appendable buffer, AttributeQuery attributes ) throws IOException, ChronoException { DayOfDecade value = context.get(this); Locale lang = attributes.get(Attributes.LANGUAGE, Locale.ROOT); buffer.append(this.accessor(lang, attributes).print(value)); } @Override public DayOfDecade parse( CharSequence text, ParsePosition status, AttributeQuery attributes ) { Locale lang = attributes.get(Attributes.LANGUAGE, Locale.ROOT); return this.accessor(lang, attributes).parse(text, status, this.getType(), attributes); } @Override public Class<DayOfDecade> getType() { return DayOfDecade.class; } @Override public DayOfDecade getDefaultMinimum() { return DayOfDecade.PRIMIDI; } @Override public DayOfDecade getDefaultMaximum() { return DayOfDecade.DECADI; } @Override public String getDisplayName(Locale language) { String key = "L_dayofdecade"; String lname = CalendarText.getInstance("extra/frenchrev", language).getTextForms().get(key); return ((lname == null) ? this.name() : lname); } @Override public boolean isDateElement() { return true; } @Override public boolean isTimeElement() { return false; } @Override protected boolean isSingleton() { return true; } private TextAccessor accessor( Locale lang, AttributeQuery attributes ) { TextWidth width = attributes.get(Attributes.TEXT_WIDTH, TextWidth.WIDE); OutputContext oc = attributes.get(Attributes.OUTPUT_CONTEXT, OutputContext.FORMAT); String variant = ((width == TextWidth.NARROW) ? "N" : (oc == OutputContext.FORMAT ? "w" : "W")); return CalendarText.getInstance("extra/frenchrev", lang).getTextForms(this.name(), this.getType(), variant); } } private static class SansculottidesAccess extends BasicElement<Sansculottides> implements TextElement<Sansculottides>, ElementRule<FrenchRepublicanCalendar, Sansculottides> { private static final long serialVersionUID = -6615947737325572130L; SansculottidesAccess() { super("SANSCULOTTIDES"); } @Override public char getSymbol() { return 'S'; } @Override public Sansculottides getValue(FrenchRepublicanCalendar context) { return context.getSansculottides(); // may throw an exception } @Override public Sansculottides getMinimum(FrenchRepublicanCalendar context) { return Sansculottides.COMPLEMENTARY_DAY_1; } @Override public Sansculottides getMaximum(FrenchRepublicanCalendar context) { return (context.isLeapYear() ? Sansculottides.LEAP_DAY : Sansculottides.COMPLEMENTARY_DAY_5); } @Override public boolean isValid( FrenchRepublicanCalendar context, Sansculottides value ) { if (value != null) { return (context.isLeapYear() || (value != Sansculottides.LEAP_DAY)); } return false; } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, Sansculottides value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing sansculottides value."); } return FrenchRepublicanCalendar.of(context.fyear, value); } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { return null; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { return null; } @Override public void print( ChronoDisplay context, Appendable buffer, AttributeQuery attributes ) throws IOException, ChronoException { Sansculottides value = context.get(this); Locale lang = attributes.get(Attributes.LANGUAGE, Locale.ROOT); OutputContext oc = attributes.get(Attributes.OUTPUT_CONTEXT, OutputContext.FORMAT); buffer.append(this.accessor(lang, oc).print(value)); } @Override public Sansculottides parse( CharSequence text, ParsePosition status, AttributeQuery attributes ) { int index = status.getIndex(); Locale lang = attributes.get(Attributes.LANGUAGE, Locale.ROOT); OutputContext oc = attributes.get(Attributes.OUTPUT_CONTEXT, OutputContext.FORMAT); Sansculottides result = this.accessor(lang, oc).parse(text, status, this.getType(), attributes); if ((result == null) && attributes.get(Attributes.PARSE_MULTIPLE_CONTEXT, Boolean.TRUE)) { status.setErrorIndex(-1); status.setIndex(index); oc = ((oc == OutputContext.FORMAT) ? OutputContext.STANDALONE : OutputContext.FORMAT); result = this.accessor(lang, oc).parse(text, status, this.getType(), attributes); } return result; } @Override public Class<Sansculottides> getType() { return Sansculottides.class; } @Override public Sansculottides getDefaultMinimum() { return Sansculottides.COMPLEMENTARY_DAY_1; } @Override public Sansculottides getDefaultMaximum() { return Sansculottides.COMPLEMENTARY_DAY_5; } @Override public boolean isDateElement() { return true; } @Override public boolean isTimeElement() { return false; } @Override protected boolean isSingleton() { return true; } @Override public String getDisplayName(Locale language) { String key = "L_sansculottides"; String lname = CalendarText.getInstance("extra/frenchrev", language).getTextForms().get(key); return ((lname == null) ? this.name() : lname); } private TextAccessor accessor( Locale lang, OutputContext outputContext ) { String variant = ((outputContext == OutputContext.FORMAT) ? "w" : "W"); return CalendarText.getInstance("extra/frenchrev", lang).getTextForms(this.name(), this.getType(), variant); } } private static class WeekdayRule implements ElementRule<FrenchRepublicanCalendar, Weekday> { @Override public Weekday getValue(FrenchRepublicanCalendar context) { return context.getDayOfWeek(); } @Override public Weekday getMinimum(FrenchRepublicanCalendar context) { return ((context.fyear == 1) && (context.fdoy == 1)) ? Weekday.SATURDAY : Weekday.SUNDAY; } @Override public Weekday getMaximum(FrenchRepublicanCalendar context) { return ((context.fyear == MAX_YEAR) && (context.fdoy == 366)) ? Weekday.SUNDAY : Weekday.SATURDAY; } @Override public boolean isValid( FrenchRepublicanCalendar context, Weekday value ) { if (value == null) { return false; } int w = value.getValue(FrenchRepublicanCalendar.getDefaultWeekmodel()); int wMin = this.getMinimum(context).getValue(FrenchRepublicanCalendar.getDefaultWeekmodel()); int wMax = this.getMaximum(context).getValue(FrenchRepublicanCalendar.getDefaultWeekmodel()); return ((wMin <= w) && (w <= wMax)); } @Override public FrenchRepublicanCalendar withValue( FrenchRepublicanCalendar context, Weekday value, boolean lenient ) { if (value == null) { throw new IllegalArgumentException("Missing weekday."); } Weekmodel model = getDefaultWeekmodel(); int oldValue = context.getDayOfWeek().getValue(model); int newValue = value.getValue(model); return context.plus(CalendarDays.of(newValue - oldValue)); } @Override public ChronoElement<?> getChildAtFloor(FrenchRepublicanCalendar context) { return null; } @Override public ChronoElement<?> getChildAtCeiling(FrenchRepublicanCalendar context) { return null; } } private static class Merger implements ChronoMerger<FrenchRepublicanCalendar> { @Override public FrenchRepublicanCalendar createFrom( TimeSource<?> clock, AttributeQuery attributes ) { TZID tzid; if (attributes.contains(Attributes.TIMEZONE_ID)) { tzid = attributes.get(Attributes.TIMEZONE_ID); } else if (attributes.get(Attributes.LENIENCY, Leniency.SMART).isLax()) { tzid = Timezone.ofSystem().getID(); } else { return null; } StartOfDay startOfDay = attributes.get(Attributes.START_OF_DAY, this.getDefaultStartOfDay()); return Moment.from(clock.currentTime()).toGeneralTimestamp(ENGINE, tzid, startOfDay).toDate(); } @Override public FrenchRepublicanCalendar createFrom( ChronoEntity<?> entity, AttributeQuery attributes, boolean lenient, boolean preparsing ) { FrenchRepublicanAlgorithm algorithm = attributes.get(FrenchRepublicanAlgorithm.attribute(), DEFAULT_ALGORITHM); int year = entity.getInt(YEAR_OF_ERA); if (year == Integer.MIN_VALUE) { entity.with(ValidationElement.ERROR_MESSAGE, "Missing republican year."); return null; } else if ((year < 1) || (year > MAX_YEAR)) { entity.with(ValidationElement.ERROR_MESSAGE, "Republican year out of range: " + year); return null; } FrenchRepublicanCalendar cal = null; if (entity.contains(MONTH_OF_YEAR)) { int month = entity.get(MONTH_OF_YEAR).getValue(); int dom = entity.getInt(DAY_OF_MONTH); if ((dom == Integer.MIN_VALUE) && entity.contains(DAY_OF_DECADE)) { int decade = entity.getInt(DECADE_OF_MONTH); if (decade != Integer.MIN_VALUE) { dom = (decade - 1) * 10 + entity.get(DAY_OF_DECADE).getValue(); } } if (dom != Integer.MIN_VALUE) { if ((dom >= 1) && (dom <= 30)) { cal = FrenchRepublicanCalendar.of(year, month, dom); } else { entity.with(ValidationElement.ERROR_MESSAGE, "Invalid republican date."); } } } else if (entity.contains(SANSCULOTTIDES)) { Sansculottides s = entity.get(SANSCULOTTIDES); int doy = s.getValue() + 360; if ((doy == 6) && !algorithm.isLeapYear(year)) { entity.with(ValidationElement.ERROR_MESSAGE, "Republican date is no leap year."); } else { cal = new FrenchRepublicanCalendar(year, doy); } } else { int doy = entity.getInt(DAY_OF_YEAR); if (doy != Integer.MIN_VALUE) { if ((doy >= 1) && (doy <= (algorithm.isLeapYear(year) ? 366 : 365))) { cal = new FrenchRepublicanCalendar(year, doy); } else { entity.with(ValidationElement.ERROR_MESSAGE, "Invalid republican date."); } } } if ((cal != null) && (algorithm != DEFAULT_ALGORITHM)) { cal = DEFAULT_ALGORITHM.transform(algorithm.transform(cal)); } return cal; } @Override public ChronoDisplay preformat(FrenchRepublicanCalendar context, AttributeQuery attributes) { FrenchRepublicanAlgorithm algorithm = attributes.get(FrenchRepublicanAlgorithm.attribute(), DEFAULT_ALGORITHM); if (algorithm == DEFAULT_ALGORITHM) { return context; } return context.getDate(algorithm); } @Override public int getDefaultPivotYear() { return PlainDate.axis().getDefaultPivotYear() - 1792; // not relevant for dynamic pattern type } } private static class FUnitRule implements UnitRule<FrenchRepublicanCalendar> { private final Unit unit; FUnitRule(Unit unit) { super(); this.unit = unit; } @Override public FrenchRepublicanCalendar addTo(FrenchRepublicanCalendar date, long amount) { switch (this.unit) { case YEARS: int y = MathUtils.safeCast(MathUtils.safeAdd(date.fyear, amount)); if ((y < 1) || (y > MAX_YEAR)) { throw new IllegalArgumentException("Resulting year out of bounds: " + y); } int doy = Math.min(date.fdoy, isLeapYear(y) ? 366 : 365); return new FrenchRepublicanCalendar(y, doy); case MONTHS: // interprete sansculottides as extension of fructidor long ym = MathUtils.safeAdd(ymValue(date), amount); int year = MathUtils.safeCast(MathUtils.floorDivide(ym, 12)); int month = MathUtils.floorModulo(ym, 12) + 1; int dom = (date.hasSansculottides() ? 30 : date.getDayOfMonth()); return FrenchRepublicanCalendar.of(year, month, dom); case DECADES: // interprete sansculottides as extension of last decade of fructidor long dec = MathUtils.safeAdd(decValue(date), amount); int year2 = MathUtils.safeCast(MathUtils.floorDivide(dec, 36)); int rem = MathUtils.floorModulo(dec, 36); int month2 = MathUtils.floorDivide(rem, 3) + 1; int decOfMonth = MathUtils.floorModulo(rem, 3); int dod = (((date.hasSansculottides() ? 30 : date.getDayOfMonth()) - 1) % 10) + 1; int dom2 = decOfMonth * 10 + dod; return FrenchRepublicanCalendar.of(year2, month2, dom2); case WEEKS: amount = MathUtils.safeMultiply(amount, 7); // fall-through case DAYS: long utcDays = MathUtils.safeAdd(CALSYS.transform(date), amount); return CALSYS.transform(utcDays); default: throw new UnsupportedOperationException(this.unit.name()); } } @Override public long between(FrenchRepublicanCalendar start, FrenchRepublicanCalendar end) { switch (this.unit) { case YEARS: int deltaY = end.fyear - start.fyear; if ((deltaY > 0) && (end.fdoy < start.fdoy)) { deltaY } else if ((deltaY < 0) && (end.fdoy > start.fdoy)) { deltaY++; } return deltaY; case MONTHS: // interprete sansculottides as extension of fructidor long deltaM = ymValue(end) - ymValue(start); int sdom = (start.hasSansculottides() ? (start.fdoy - 330) : start.getDayOfMonth()); int edom = (end.hasSansculottides() ? (end.fdoy - 330) : end.getDayOfMonth()); if ((deltaM > 0) && (edom < sdom)) { deltaM } else if ((deltaM < 0) && (edom > sdom)) { deltaM++; } return deltaM; case DECADES: // interprete sansculottides as extension of last decade of fructidor long deltaD = decValue(end) - decValue(start); int sdod = (start.hasSansculottides() ? (start.fdoy - 350) : start.getDayOfDecade().getValue()); int edod = (end.hasSansculottides() ? (end.fdoy - 350) : end.getDayOfDecade().getValue()); if ((deltaD > 0) && (edod < sdod)) { deltaD } else if ((deltaD < 0) && (edod > sdod)) { deltaD++; } return deltaD; case WEEKS: return FrenchRepublicanCalendar.Unit.DAYS.between(start, end) / 7; case DAYS: return CALSYS.transform(end) - CALSYS.transform(start); default: throw new UnsupportedOperationException(this.unit.name()); } } private static int ymValue(FrenchRepublicanCalendar date) { int m = (date.hasSansculottides() ? 12 : date.getMonth().getValue()); return date.fyear * 12 + m - 1; } private static int decValue(FrenchRepublicanCalendar date) { int dec = (date.hasSansculottides() ? 3 : date.getDecade()); return ymValue(date) * 3 + dec - 1; } } }
package org.opendaylight.protocol.bgp.rib.impl; import static java.util.Objects.requireNonNull; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.net.InetAddresses; import com.google.common.util.concurrent.FluentFuture; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction; import org.opendaylight.controller.md.sal.common.api.data.TransactionChain; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration; import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; import org.opendaylight.mdsal.common.api.CommitInfo; import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer; import org.opendaylight.protocol.bgp.parser.BGPDocumentedException; import org.opendaylight.protocol.bgp.parser.BGPError; import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceAttributeParser; import org.opendaylight.protocol.bgp.parser.spi.MessageUtil; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider; import org.opendaylight.protocol.bgp.rib.spi.BGPSession; import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener; import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason; import org.opendaylight.protocol.bgp.rib.spi.RIBSupport; import org.opendaylight.protocol.bgp.rib.spi.RouterIds; import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; import org.opendaylight.protocol.concepts.AbstractRegistration; import org.opendaylight.protocol.util.Ipv4Util; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.DestinationIpv4Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.destination.ipv4.Ipv4Prefixes; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.update.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationIpv4CaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.AttributesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.Nlri; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpAddPathTableType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.RouteRefresh; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.SendReceive; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.add.path.capability.AddressFamilies; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlriBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlri; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlriBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev180329.BgpPeerRpcService; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev180329.PeerContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibOut; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.ClusterIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.RouteTarget; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.SubsequentAddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.UnicastSubsequentAddressFamily; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; import org.opendaylight.yangtools.yang.binding.Notification; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into * RIB actions. */ public class BGPPeer extends AbstractPeer implements BGPSessionListener { private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class); private Set<TablesKey> tables = Collections.emptySet(); private final RIB rib; private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap<>(); private final List<RouteTarget> rtMemberships = new ArrayList<>(); private final RpcProviderRegistry rpcRegistry; private final BGPTableTypeRegistryConsumer tableTypeRegistry; private InstanceIdentifier<AdjRibOut> peerRibOutIId; @GuardedBy("this") private AbstractRegistration trackerRegistration; private final LoadingCache<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>> tablesIId = CacheBuilder.newBuilder() .build(new CacheLoader<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>>() { @Override public KeyedInstanceIdentifier<Tables, TablesKey> load(final TablesKey tablesKey) { return BGPPeer.this.peerRibOutIId.child(Tables.class, tablesKey); } }); @GuardedBy("this") private BGPSession session; @GuardedBy("this") private AdjRibInWriter ribWriter; @GuardedBy("this") private EffectiveRibInWriter effRibInWriter; private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration; private Map<TablesKey, SendReceive> addPathTableMaps = Collections.emptyMap(); private YangInstanceIdentifier peerPath; private boolean sessionUp; public BGPPeer( final BGPTableTypeRegistryConsumer tableTypeRegistry, final IpAddress neighborAddress, final String peerGroupName, final RIB rib, final PeerRole role, final ClusterIdentifier clusterId, final AsNumber localAs, final RpcProviderRegistry rpcRegistry, final Set<TablesKey> afiSafisAdvertized, final Set<TablesKey> afiSafisGracefulAdvertized) { super(rib, Ipv4Util.toStringIP(neighborAddress), peerGroupName, role, clusterId, localAs, neighborAddress, afiSafisAdvertized, afiSafisGracefulAdvertized); this.tableTypeRegistry = requireNonNull(tableTypeRegistry); this.rib = requireNonNull(rib); this.rpcRegistry = rpcRegistry; } BGPPeer( final BGPTableTypeRegistryConsumer tableTypeRegistry, final IpAddress neighborAddress, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry, final Set<TablesKey> afiSafisAdvertized, final Set<TablesKey> afiSafisGracefulAdvertized) { this(tableTypeRegistry, neighborAddress, null, rib, role, null, null, rpcRegistry, afiSafisAdvertized, afiSafisGracefulAdvertized); } private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) { if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) { final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs); attributesBuilder.setCNextHop(mpReach.getCNextHop()); return attributesBuilder.build(); } return attrs; } /** * Creates MPReach for the prefixes to be handled in the same way as linkstate routes. * * @param message Update message containing prefixes in NLRI * @return MpReachNlri with prefixes from the nlri field */ private static MpReachNlri prefixesToMpReach(final Update message) { final List<Ipv4Prefixes> prefixes = message.getNlri().stream() .map(n -> new Ipv4PrefixesBuilder().setPrefix(n.getPrefix()).setPathId(n.getPathId()).build()) .collect(Collectors.toList()); final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi( UnicastSubsequentAddressFamily.class).setAdvertizedRoutes( new AdvertizedRoutesBuilder().setDestinationType( new DestinationIpv4CaseBuilder().setDestinationIpv4( new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()); if (message.getAttributes() != null) { b.setCNextHop(message.getAttributes().getCNextHop()); } return b.build(); } /** * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes. * * @param message Update message containing withdrawn routes * @param isAnyNlriAnnounced isAnyNlriAnnounced * @return MpUnreachNlri with prefixes from the withdrawn routes field */ private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) { final List<Ipv4Prefixes> prefixes = new ArrayList<>(); message.getWithdrawnRoutes().forEach(w -> { Optional<Nlri> nlriAnounced = Optional.empty(); if (isAnyNlriAnnounced) { nlriAnounced = message.getNlri().stream().filter(n -> Objects.equal(n.getPrefix(), w.getPrefix()) && Objects.equal(n.getPathId(), w.getPathId())) .findAny(); } if (!nlriAnounced.isPresent()) { prefixes.add(new Ipv4PrefixesBuilder().setPrefix(w.getPrefix()).setPathId(w.getPathId()).build()); } }); return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class) .setWithdrawnRoutes(new WithdrawnRoutesBuilder().setDestinationType(new org.opendaylight.yang.gen.v1 .urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.update.attributes.mp.unreach.nlri .withdrawn.routes.destination.type.DestinationIpv4CaseBuilder().setDestinationIpv4( new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build(); } private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) { return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()), BgpAddPathTableType::getSendReceive))); } public synchronized void instantiateServiceInstance() { this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this); setActive(true); } @Override public synchronized FluentFuture<? extends CommitInfo> close() { final FluentFuture<? extends CommitInfo> future = releaseConnection(); closeDomChain(); setActive(false); return future; } @Override public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException { if (msg instanceof Update) { onUpdateMessage((Update) msg); } else if (msg instanceof RouteRefresh) { onRouteRefreshMessage((RouteRefresh) msg); } else { LOG.info("Ignoring unhandled message class {}", msg.getClass()); } } private void onRouteRefreshMessage(final RouteRefresh message) { final Class<? extends AddressFamily> rrAfi = message.getAfi(); final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi(); final TablesKey key = new TablesKey(rrAfi, rrSafi); final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key); if (listener != null) { listener.close(); this.adjRibOutListenerSet.remove(key); createAdjRibOutListener(key, listener.isMpSupported()); } else { LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi); } } /** * Check for presence of well known mandatory attribute LOCAL_PREF in Update message. * * @param message Update message */ private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException { if (MessageUtil.isAnyNlriPresent(message)) { final Attributes attrs = message.getAttributes(); if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) { throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF", BGPError.WELL_KNOWN_ATTR_MISSING, new byte[]{LocalPreferenceAttributeParser.TYPE}); } } } /** * Process Update message received. * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes. * * @param message Update message */ private synchronized void onUpdateMessage(final Update message) throws BGPDocumentedException { checkMandatoryAttributesPresence(message); // update AdjRibs final Attributes attrs = message.getAttributes(); MpReachNlri mpReach; final boolean isAnyNlriAnnounced = message.getNlri() != null; if (isAnyNlriAnnounced) { mpReach = prefixesToMpReach(message); } else { mpReach = MessageUtil.getMpReachNlri(attrs); } if (mpReach != null) { this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach)); } MpUnreachNlri mpUnreach; if (message.getWithdrawnRoutes() != null) { mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced); } else { mpUnreach = MessageUtil.getMpUnreachNlri(attrs); } if (mpUnreach != null) { this.ribWriter.removeRoutes(mpUnreach); } } @Override public synchronized void onSessionUp(final BGPSession session) { this.session = session; this.sessionUp = true; this.bindingChain = this.rib.createPeerChain(this); if (this.session instanceof BGPSessionStateProvider) { ((BGPSessionStateProvider) this.session).registerMessagesCounter(this); } final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes(); final Set<BgpTableType> advertizedTableTypes = session.getAdvertisedTableTypes(); final List<BgpTableType> advertizedGracefulRestartTableTypes = session.getAdvertisedGracefulRestartTableTypes(); LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, advertizedTableTypes, addPathTablesType); this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress(); this.peerId = RouterIds.createPeerId(session.getBgpId()); final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib .rev180329.bgp.rib.rib.Peer, PeerKey> peerIId = getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns .yang.bgp.rib.rev180329.bgp.rib.rib.Peer.class, new PeerKey(this.peerId)); final Set<TablesKey> setTables = advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())) .collect(Collectors.toSet()); this.tables = ImmutableSet.copyOf(setTables); this.effRibInWriter = new EffectiveRibInWriter(this, this.rib, this.rib.createPeerChain(this), peerIId, this.tables, this.tableTypeRegistry, this.rtMemberships, this.rtCache); registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter); this.peerRibOutIId = peerIId.child(AdjRibOut.class); this.effRibInWriter.init(); setAdvertizedGracefulRestartTableTypes(advertizedGracefulRestartTableTypes.stream() .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList())); this.addPathTableMaps = mapTableTypesFamilies(addPathTablesType); this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this); for (final TablesKey key : this.tables) { createAdjRibOutListener(key, true); } addBgp4Support(); this.peerPath = createPeerPath(); this.ribWriter = this.ribWriter.transform(this.peerId, this.peerPath, this.rib.getRibSupportContext(), this.tables, this.addPathTableMaps); if (this.rpcRegistry != null) { this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(this, session, this.tables)); final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib .rev180329.bgp.rib.rib.Peer, PeerKey> path = this.rib.getInstanceIdentifier() .child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib .rib.Peer.class, new PeerKey(this.peerId)); this.rpcRegistration.registerPath(PeerContext.class, path); } } //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability private synchronized void addBgp4Support() { final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); if (!this.tables.contains(key)) { final HashSet<TablesKey> newSet = new HashSet<>(this.tables); newSet.add(key); this.tables = ImmutableSet.copyOf(newSet); createAdjRibOutListener(key, false); } } private synchronized void createAdjRibOutListener(final TablesKey key, final boolean mpSupport) { final RIBSupport<?, ?, ?, ?> ribSupport = this.rib.getRibSupportContext().getRIBSupport(key); // not particularly nice if (ribSupport != null && this.session instanceof BGPSessionImpl) { final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.session).getLimiter(); final AdjRibOutListener adjRibOut = AdjRibOutListener.create(this.peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(), ribSupport, this.rib.getService(), limiter, mpSupport); this.adjRibOutListenerSet.put(key, adjRibOut); registerPrefixesSentCounter(key, adjRibOut); } } @Override public synchronized void onSessionDown(final BGPSession session, final Exception e) { if (e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) { LOG.info("Session with peer {} went down", this.name); } else { LOG.info("Session with peer {} went down", this.name, e); } releaseConnection(); } @Override public synchronized void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) { LOG.info("Session with peer {} terminated: {}", this.name, cause); releaseConnection(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", this.name) .add("tables", this.tables).toString(); } @Override public synchronized FluentFuture<? extends CommitInfo> releaseConnection() { LOG.info("Closing session with peer"); this.sessionUp = false; this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close); this.adjRibOutListenerSet.clear(); if (this.trackerRegistration != null) { this.trackerRegistration.close(); this.trackerRegistration = null; } if (this.rpcRegistration != null) { this.rpcRegistration.close(); } releaseBindingChain(); this.ribWriter.releaseChain(); // FIXME: BUG-196: support graceful if (this.effRibInWriter != null) { this.effRibInWriter.close(); } this.tables = Collections.emptySet(); this.addPathTableMaps = Collections.emptyMap(); final FluentFuture<? extends CommitInfo> future = removePeer(this.peerPath); if (this.session != null) { try { this.session.close(); } catch (final Exception e) { LOG.warn("Error closing session with peer", e); } this.session = null; } resetState(); return future; } @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") @Override public SendReceive getSupportedAddPathTables(final TablesKey tableKey) { return this.addPathTableMaps.get(tableKey); } @Override public boolean supportsTable(final TablesKey tableKey) { return this.tables.contains(tableKey) && this.sessionUp; } @Override public KeyedInstanceIdentifier<Tables, TablesKey> getRibOutIId(final TablesKey tablesKey) { return this.tablesIId.getUnchecked(tablesKey); } @Override public synchronized void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) { LOG.error("Transaction domChain failed.", cause); releaseConnection(); } @Override public synchronized void markUptodate(final TablesKey tablesKey) { this.ribWriter.markTableUptodate(tablesKey); } @Override public synchronized BGPSessionState getBGPSessionState() { if (this.session instanceof BGPSessionStateProvider) { return ((BGPSessionStateProvider) this.session).getBGPSessionState(); } return null; } @Override public synchronized BGPTimersState getBGPTimersState() { if (this.session instanceof BGPSessionStateProvider) { return ((BGPSessionStateProvider) this.session).getBGPTimersState(); } return null; } @Override public synchronized BGPTransportState getBGPTransportState() { if (this.session instanceof BGPSessionStateProvider) { return ((BGPSessionStateProvider) this.session).getBGPTransportState(); } return null; } @Override public List<RouteTarget> getMemberships() { return this.rtMemberships; } }
package org.ligoj.bootstrap; import org.ligoj.bootstrap.model.system.SystemAuthorization; import org.ligoj.bootstrap.model.system.SystemAuthorization.AuthorizationType; import org.ligoj.bootstrap.model.system.SystemRole; import org.ligoj.bootstrap.model.system.SystemRoleAssignment; import org.ligoj.bootstrap.model.system.SystemUser; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry; import org.springframework.cache.Cache; import org.springframework.context.ConfigurableApplicationContext; /** * Basic Appication test support. */ public abstract class AbstractAppTest extends AbstractJpaTest { /** * Clear all caches. */ protected void clearAllCache() { cacheManager.getCacheNames().stream().map(cacheManager::getCache).forEach(Cache::clear); } /** * Persist system user, role and assignment for user DEFAULT_USER. */ protected void persistSystemEntities() { final SystemRole role = new SystemRole(); role.setName("some"); em.persist(role); final SystemUser user = new SystemUser(); user.setLogin(DEFAULT_USER); em.persist(user); final SystemAuthorization authorization = new SystemAuthorization(); authorization.setType(AuthorizationType.API); authorization.setPattern(".*"); authorization.setRole(role); em.persist(authorization); final SystemRoleAssignment assignment = new SystemRoleAssignment(); assignment.setRole(role); assignment.setUser(user); em.persist(assignment); } /** * Destroy the given bean instance (usually a prototype instance obtained from * this factory) according to its bean definition. * <p> * Any exception that arises during destruction should be caught and logged * instead of propagated to the caller of this method. * * @param beanName * The name of the bean definition */ protected void destroySingleton(final String beanName) { try { ((DefaultSingletonBeanRegistry) ((ConfigurableApplicationContext) applicationContext).getBeanFactory()) .destroySingleton(beanName); } catch (final NoSuchBeanDefinitionException e) { // Ignore } } /** * Register a singleton within the current application context. Don't forget to * destroy this singleton with a try-finally at the end of your tests. * * @param <T> Singleton type. * @param beanName * the name of the bean definition. * @param singleton * the bean instance to register * @return The given instance. * @see #destroySingleton(String) */ protected <T> T registerSingleton(final String beanName, final T singleton) { ((SingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory()).registerSingleton(beanName, singleton); return singleton; } }
/** * Class PlotHandler is the delegate for dealing with visualizing the data * generated by the "number crunching" program, MonteCarlo. Its purpose is to * be instantiated in MonteCarlo with the data to plot, where the write() * method should then be called. Running this program and specifying in * the command line arguments the plot files previously generated will * open a graphical representation of these plots for each file. * * @author Jimi Ford * @version 2-15-2015 * */ public class PlotHandler { // private data members private final String fileName; private final int v; private final SimulationResultCollection collection; private final boolean vertexMode; private final double p; /** * Construct a new plot handler that plots average distances for a fixed * vertex count v, while varying the edge probability p * * @param plotFilePrefix prefix to be used in the name of * the plot file * @param collection collection of results of the finished set of * simulations. * @param v number of vertices used in each simulation */ public PlotHandler(String plotFilePrefix, SimulationResultCollection collection, int v) { fileName = plotFilePrefix + "-V-" + v + ".dwg"; this.v = v; this.p = 0; this.collection = collection; vertexMode = true; } /** * Save the plot information into a file to visualize by running * the main method of this class * * @throws IOException if it can't write to the file specified */ public void write() throws IOException { ListXYSeries results = new ListXYSeries(); double[] values = collection.getAveragesForV(v); for(int i = 0, p = collection.pMin; i < values.length; i++, p += collection.pInc) { results.add(p / ((double) collection.pExp), values[i]); } Plot plot = new Plot() .plotTitle (String.format ("Random Graphs, <I>V</I> = %1s", Integer.toString(v))) .xAxisTitle ("Edge Probability <I>p</I>") .xAxisTickFormat(new DecimalFormat("0.0")) .yAxisTitle ("Average Distance <I>d</I>") .yAxisTickFormat (new DecimalFormat ("0.0")) .seriesDots (Dots.circle (5)) .seriesStroke (null) .xySeries (results); Plot.write(plot, new File(fileName)); } /** * Open a GUI for each plot in order to visualize the results of a * previously run set of simulations. * * @param args each plot file generated that you wish to visualize */ public static void main(String args[]) { if(args.length < 1) { System.err.println("Must specify at least 1 plot file."); usage(); } for(int i = 0; i < args.length; i++) { try { Plot plot = Plot.read(args[i]); plot.getFrame().setVisible(true); } catch (ClassNotFoundException e) { System.err.println("Could not deserialize " + args[i]); } catch (IOException e) { System.err.println("Could not open " + args[i]); } } } /** * Print the usage message for this program and gracefully exit. */ private static void usage() { System.err.println("usage: java PlotHandler <plot-file-1> (<plot-file-2> <plot-file-3>... etc.)"); System.exit(1); } }
package checks; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; public class NlsCheck extends Check { private final Pattern patternString = Pattern.compile("[\"][^\"]*[^\\\\][\"]"); private Matcher matcher; private boolean run = false; @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void beginTree(DetailAST aRootAST) { if (!run){ return; } if (!getFileContents().getFilename().matches(".*\\.java")) { return; } int i = 0; boolean startAnnotation = false; for (String lineText : getLines()) { ++i; // Ignore strings passed as annotation parameters if (lineText.matches("^\\s*@.*")) { int parenthesesStart = lineText.indexOf("("); while (parenthesesStart != -1 && getFileContents().hasIntersectionWithComment(i, parenthesesStart, i, parenthesesStart)){ parenthesesStart = lineText.indexOf("(", parenthesesStart + 1); } if (parenthesesStart != -1){ startAnnotation = true; } } List<QuotedString> stringList = new LinkedList<>(); matcher = patternString.matcher(lineText); int j = 0; while (matcher.find()) { if (getFileContents().hasIntersectionWithComment(i, matcher.start(), i, matcher.end())) { continue; } stringList.add(new QuotedString(matcher.group(), matcher .start(), matcher.end())); } if (startAnnotation == true) { int endAnno = hasEndAnno(lineText, i, stringList); if (endAnno != -1) { startAnnotation = false; // maybe the rest of the line has quoted string List<QuotedString> tmpStringList = new LinkedList<>(); for (QuotedString quotedString : stringList) { if (quotedString.startIndex > endAnno) { tmpStringList.add(quotedString); } } stringList = tmpStringList; } else { continue; } } j = 0; for (QuotedString str : stringList) { ++j; Pattern patternNls = Pattern.compile("\\$NON-NLS-" + j + "\\$"); //$NON-NLS-1$//$NON-NLS-2$ Matcher matcherNls = patternNls.matcher(lineText); int matchNum = 0; while (matcherNls.find()) { ++matchNum; } if (matchNum != 1) { log(i, "String " + str.text + " is non-externalized.\n Please externalize it by moving it to i18n Constants/Messages interface or add //$NON-NLS-" + j + "$" + " comment to marks the string as non externalized"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } } } int hasEndAnno(String lineText, int lineNum, List<QuotedString> quotedStrings) { int startIndex = lineText.indexOf(")"); while (startIndex != -1) { boolean isValidEnd = true; for (QuotedString quoted : quotedStrings) { if (startIndex >= quoted.startIndex && startIndex <= quoted.endIndex) { isValidEnd = false; break; } } if (getFileContents().hasIntersectionWithComment(lineNum, startIndex, lineNum, startIndex)) { isValidEnd = false; } if (isValidEnd) { return startIndex; } startIndex = lineText.indexOf(")", startIndex + 1); } return -1; } private static class QuotedString { String text; int startIndex; int endIndex; public QuotedString(String text, int startIndex, int endIndex) { this.text = text; this.startIndex = startIndex; this.endIndex = endIndex; } } public void setRun(boolean run) { this.run = run; } }
package org.chromium.chrome.browser.infobar; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; /** * Layout that arranges an InfoBar's views. An InfoBarLayout consists of: * - A message describing the action that the user can take. * - A close button on the right side. * - (optional) An icon representing the infobar's purpose on the left side. * - (optional) Additional "custom" views (e.g. a checkbox and text, or a pair of spinners) * - (optional) One or two buttons with text at the bottom. * * When adding custom views, widths and heights defined in the LayoutParams will be ignored. * However, setting a minimum width in another way, like TextView.getMinWidth(), should still be * obeyed. * * Logic for what happens when things are clicked should be implemented by the InfoBarView. */ public class InfoBarLayout extends ViewGroup implements View.OnClickListener { /** * Parameters used for laying out children. */ private static class LayoutParams extends ViewGroup.LayoutParams { public int startMargin; public int endMargin; public int topMargin; public int bottomMargin; // Where this view will be laid out. These values are assigned in onMeasure() and used in // onLayout(). public int start; public int top; LayoutParams(int startMargin, int topMargin, int endMargin, int bottomMargin) { super(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); this.startMargin = startMargin; this.topMargin = topMargin; this.endMargin = endMargin; this.bottomMargin = bottomMargin; } } private static class Group { public View[] views; /** * The gravity of each view in Group. Must be either Gravity.START, Gravity.END, or * Gravity.FILL_HORIZONTAL. */ public int gravity = Gravity.START; /** Whether the views are vertically stacked. */ public boolean isStacked; void setHorizontalMode(int horizontalSpacing, int startMargin, int endMargin) { isStacked = false; for (int i = 0; i < views.length; i++) { LayoutParams lp = (LayoutParams) views[i].getLayoutParams(); lp.startMargin = i == 0 ? startMargin : horizontalSpacing; lp.topMargin = 0; lp.endMargin = i == views.length - 1 ? endMargin : 0; lp.bottomMargin = 0; } } void setVerticalMode(int verticalSpacing, int bottomMargin) { isStacked = true; for (int i = 0; i < views.length; i++) { LayoutParams lp = (LayoutParams) views[i].getLayoutParams(); lp.startMargin = 0; lp.topMargin = i == 0 ? 0 : verticalSpacing; lp.endMargin = 0; lp.bottomMargin = i == views.length - 1 ? bottomMargin : 0; } } } private static final int ROW_MAIN = 1; private static final int ROW_OTHER = 2; private final int mMargin; private final int mIconSize; private final int mMinWidth; private final int mAccentColor; private final InfoBarView mInfoBarView; private final TextView mMessageView; private final ImageButton mCloseButton; private ImageView mIconView; private Group mMainGroup; private Group mCustomGroup; private Group mButtonGroup; /** * These values are used during onMeasure() to track where the next view will be placed. * * mWidth is the infobar width. * [mStart, mEnd) is the range of unoccupied space on the current row. * mTop and mBottom are the top and bottom of the current row. * * These values, along with a view's gravity, are used to position the next view. * These values are updated after placing a view and after starting a new row. */ private int mWidth; private int mStart; private int mEnd; private int mTop; private int mBottom; /** * Constructs a layout for the specified InfoBar. After calling this, be sure to set the * message, the buttons, and/or the custom content using setMessage(), setButtons(), and * setCustomContent(). * * @param context The context used to render. * @param infoBarView InfoBarView that listens to events. * @param iconResourceId ID of the icon to use for the InfoBar. * @param message The message to show in the infobar. */ public InfoBarLayout(Context context, InfoBarView infoBarView, int iconResourceId, CharSequence message) { super(context); mInfoBarView = infoBarView; // Grab the dimensions. Resources res = getResources(); mMargin = res.getDimensionPixelOffset(R.dimen.infobar_margin); mIconSize = res.getDimensionPixelSize(R.dimen.infobar_icon_size); mMinWidth = res.getDimensionPixelSize(R.dimen.infobar_min_width); mAccentColor = res.getColor(R.color.infobar_accent_blue); // Set up the close button. Apply padding so it has a big touch target. mCloseButton = new ImageButton(context); mCloseButton.setId(R.id.infobar_close_button); mCloseButton.setImageResource(R.drawable.infobar_close_button); TypedArray a = getContext().obtainStyledAttributes( new int [] {android.R.attr.selectableItemBackground}); Drawable closeButtonBackground = a.getDrawable(0); a.recycle(); ApiCompatibilityUtils.setBackgroundForView(mCloseButton, closeButtonBackground); mCloseButton.setPadding(mMargin, mMargin, mMargin, mMargin); mCloseButton.setOnClickListener(this); mCloseButton.setContentDescription(res.getString(R.string.infobar_close)); mCloseButton.setLayoutParams(new LayoutParams(0, -mMargin, -mMargin, -mMargin)); addView(mCloseButton); // Set up the icon. if (iconResourceId != 0) { mIconView = new ImageView(context); mIconView.setImageResource(iconResourceId); mIconView.setFocusable(false); mIconView.setLayoutParams(new LayoutParams(0, 0, mMargin / 2, 0)); mIconView.getLayoutParams().width = mIconSize; mIconView.getLayoutParams().height = mIconSize; } // Set up the message view. mMessageView = (TextView) LayoutInflater.from(context).inflate(R.layout.infobar_text, null); mMessageView.setText(message, TextView.BufferType.SPANNABLE); mMessageView.setMovementMethod(LinkMovementMethod.getInstance()); mMessageView.setLinkTextColor(mAccentColor); mMessageView.setLayoutParams(new LayoutParams(0, mMargin / 4, 0, 0)); if (mIconView != null) { mMainGroup = addGroup(mIconView, mMessageView); } else { mMainGroup = addGroup(mMessageView); } } /** * Sets the message to show on the infobar. */ public void setMessage(CharSequence message) { mMessageView.setText(message, TextView.BufferType.SPANNABLE); } /** * Sets the custom content of the infobar. These views will be displayed in addition to the * standard infobar controls (icon, text, buttons). Depending on the available space, view1 and * view2 will be laid out: * - Side by side on the main row, * - Side by side on a separate row, each taking up half the width of the infobar, * - Stacked above each other on two separate rows, taking up the full width of the infobar. */ public void setCustomContent(View view1, View view2) { mCustomGroup = addGroup(view1, view2); } /** * Sets the custom content of the infobar to a single view. This view will be displayed in * addition to the standard infobar controls. Depending on the available space, the view will be * displayed: * - On the main row, start-aligned or end-aligned depending on whether there are also * buttons on the main row, OR * - On a separate row, start-aligned */ public void setCustomContent(View view) { mCustomGroup = addGroup(view); } /** * Calls setButtons(primaryText, secondaryText, null). */ public void setButtons(String primaryText, String secondaryText) { setButtons(primaryText, secondaryText, null); } /** * Adds one, two, or three buttons to the layout. * * @param primaryText Text for the primary button. * @param secondaryText Text for the secondary button, or null if there isn't a second button. * @param tertiaryText Text for the tertiary button, or null if there isn't a third button. */ public void setButtons(String primaryText, String secondaryText, String tertiaryText) { if (TextUtils.isEmpty(primaryText)) return; LayoutInflater inflater = LayoutInflater.from(getContext()); Button primaryButton = (Button) inflater.inflate(R.layout.infobar_button, null); primaryButton.setId(R.id.button_primary); primaryButton.setOnClickListener(this); primaryButton.setText(primaryText); primaryButton.setBackgroundResource(R.drawable.btn_infobar_blue); primaryButton.setTextColor(Color.WHITE); if (TextUtils.isEmpty(secondaryText)) { mButtonGroup = addGroup(primaryButton); return; } Button secondaryButton = (Button) inflater.inflate(R.layout.infobar_button, null); secondaryButton.setId(R.id.button_secondary); secondaryButton.setOnClickListener(this); secondaryButton.setText(secondaryText); secondaryButton.setTextColor(mAccentColor); if (TextUtils.isEmpty(tertiaryText)) { mButtonGroup = addGroup(secondaryButton, primaryButton); return; } Button tertiaryButton = (Button) inflater.inflate(R.layout.infobar_button, null); tertiaryButton.setId(R.id.button_tertiary); tertiaryButton.setOnClickListener(this); tertiaryButton.setText(tertiaryText); tertiaryButton.setPadding(mMargin / 2, tertiaryButton.getPaddingTop(), mMargin / 2, tertiaryButton.getPaddingBottom()); tertiaryButton.setTextColor( getContext().getResources().getColor(R.color.infobar_tertiary_button_text)); mButtonGroup = addGroup(tertiaryButton, secondaryButton, primaryButton); } /** * Adds a group of Views that are measured and laid out together. */ private Group addGroup(View... views) { Group group = new Group(); group.views = views; for (View v : views) { addView(v); } return group; } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(0, 0, 0, 0); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Place all the views in the positions already determined during onMeasure(). int width = right - left; boolean isRtl = ApiCompatibilityUtils.isLayoutRtl(this); for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); int childLeft = lp.start; int childRight = lp.start + child.getMeasuredWidth(); if (isRtl) { int tmp = width - childRight; childRight = width - childLeft; childLeft = tmp; } child.layout(childLeft, lp.top, childRight, lp.top + child.getMeasuredHeight()); } } /** * Measures *and* assigns positions to all of the views in the infobar. These positions are * saved in each view's LayoutParams (lp.start and lp.top) and used during onLayout(). All of * the interesting logic happens inside onMeasure(); onLayout() just assigns the already- * determined positions and mirrors everything for RTL, if needed. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert getLayoutParams().height == LayoutParams.WRAP_CONTENT : "InfoBar heights cannot be constrained."; // Measure all children without imposing any size constraints on them. This determines how // big each child wants to be. int unspecifiedSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); for (int i = 0; i < getChildCount(); i++) { measureChild(getChildAt(i), unspecifiedSpec, unspecifiedSpec); } // Avoid overlapping views, division by zero, infinite heights, and other fun problems that // could arise with extremely narrow infobars. mWidth = Math.max(MeasureSpec.getSize(widthMeasureSpec), mMinWidth); mTop = mBottom = 0; placeGroups(); setMeasuredDimension(mWidth, resolveSize(mBottom, heightMeasureSpec)); } /** * Assigns positions to all of the views in the infobar. The icon, text, and close button are * placed on the main row. The custom content and finally the buttons are placed on the main row * if they fit. Otherwise, they go on their own rows. */ private void placeGroups() { startRow(); placeChild(mCloseButton, Gravity.END); placeGroup(mMainGroup); int customGroupWidth = 0; if (mCustomGroup != null) { updateCustomGroupForRow(ROW_MAIN); customGroupWidth = getWidthWithMargins(mCustomGroup); } int buttonGroupWidth = 0; if (mButtonGroup != null) { updateButtonGroupForRow(ROW_MAIN); buttonGroupWidth = getWidthWithMargins(mButtonGroup); } boolean customGroupOnMainRow = customGroupWidth <= availableWidth(); boolean buttonGroupOnMainRow = customGroupWidth + buttonGroupWidth <= availableWidth(); if (mCustomGroup != null) { if (customGroupOnMainRow) { mCustomGroup.gravity = (mButtonGroup != null && buttonGroupOnMainRow) ? Gravity.START : Gravity.END; } else { startRow(); updateCustomGroupForRow(ROW_OTHER); } placeGroup(mCustomGroup); } if (mButtonGroup != null) { if (!buttonGroupOnMainRow) { startRow(); updateButtonGroupForRow(ROW_OTHER); // If the infobar consists of just a main row and a buttons row, the buttons must be // at least 32dp below the bottom of the message text. if (mCustomGroup == null) { LayoutParams lp = (LayoutParams) mMessageView.getLayoutParams(); int messageBottom = lp.top + mMessageView.getMeasuredHeight(); mTop = Math.max(mTop, messageBottom + 2 * mMargin); } } placeGroup(mButtonGroup); } startRow(); // If everything fits on a single row, center everything vertically. if (buttonGroupOnMainRow) { int layoutHeight = mBottom; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int extraSpace = layoutHeight - child.getMeasuredHeight(); LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.top = extraSpace / 2; } } } /** * Places a group of views on the current row, or stacks them over multiple rows if * group.isStacked is true. mStart, mEnd, and mBottom are updated to reflect the space taken by * the group. */ private void placeGroup(Group group) { if (group.gravity == Gravity.END) { for (int i = group.views.length - 1; i >= 0; i placeChild(group.views[i], group.gravity); if (group.isStacked && i != 0) startRow(); } } else { // group.gravity is Gravity.START or Gravity.FILL_HORIZONTAL for (int i = 0; i < group.views.length; i++) { placeChild(group.views[i], group.gravity); if (group.isStacked && i != group.views.length - 1) startRow(); } } } /** * Places a single view on the current row, and updates the view's layout parameters to remember * its position. mStart, mEnd, and mBottom are updated to reflect the space taken by the view. */ private void placeChild(View child, int gravity) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); int availableWidth = Math.max(0, mEnd - mStart - lp.startMargin - lp.endMargin); if (child.getMeasuredWidth() > availableWidth || gravity == Gravity.FILL_HORIZONTAL) { measureChildWithFixedWidth(child, availableWidth); } if (gravity == Gravity.START || gravity == Gravity.FILL_HORIZONTAL) { lp.start = mStart + lp.startMargin; mStart = lp.start + child.getMeasuredWidth() + lp.endMargin; } else { // gravity == Gravity.END lp.start = mEnd - lp.endMargin - child.getMeasuredWidth(); mEnd = lp.start - lp.startMargin; } lp.top = mTop + lp.topMargin; mBottom = Math.max(mBottom, lp.top + child.getMeasuredHeight() + lp.bottomMargin); } /** * Advances the current position to the next row and adds margins on the left, right, and top * of the new row. */ private void startRow() { mStart = mMargin; mEnd = mWidth - mMargin; mTop = mBottom + mMargin; mBottom = mTop; } private int availableWidth() { return mEnd - mStart; } /** * @return The width of the group, including the items' margins. */ private int getWidthWithMargins(Group group) { if (group.isStacked) return getWidthWithMargins(group.views[0]); int width = 0; for (View v : group.views) { width += getWidthWithMargins(v); } return width; } private int getWidthWithMargins(View child) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); return child.getMeasuredWidth() + lp.startMargin + lp.endMargin; } private void measureChildWithFixedWidth(View child, int width) { int widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); child.measure(widthSpec, heightSpec); } /** * The button group has different layout properties (margins, gravity, etc) when placed on the * main row as opposed to on a separate row. This updates the layout properties of the button * group to prepare for placing it on either the main row or a separate row. * * @param row One of ROW_MAIN or ROW_OTHER. */ private void updateButtonGroupForRow(int row) { int startEndMargin = row == ROW_MAIN ? mMargin : 0; mButtonGroup.setHorizontalMode(mMargin / 2, startEndMargin, startEndMargin); mButtonGroup.gravity = Gravity.END; if (row == ROW_OTHER && mButtonGroup.views.length >= 2) { int extraWidth = availableWidth() - getWidthWithMargins(mButtonGroup); if (extraWidth < 0) { // Group is too wide to fit on a single row, so stack the group items vertically. mButtonGroup.setVerticalMode(mMargin / 2, 0); mButtonGroup.gravity = Gravity.FILL_HORIZONTAL; } else if (mButtonGroup.views.length == 3) { // Align tertiary button at the start and the other two buttons at the end. ((LayoutParams) mButtonGroup.views[0].getLayoutParams()).endMargin += extraWidth; } } } /** * Analagous to updateButtonGroupForRow(), but for the custom group istead of the button group. */ private void updateCustomGroupForRow(int row) { int startEndMargin = row == ROW_MAIN ? mMargin : 0; mCustomGroup.setHorizontalMode(mMargin, startEndMargin, startEndMargin); mCustomGroup.gravity = Gravity.START; if (row == ROW_OTHER && mCustomGroup.views.length == 2) { int extraWidth = availableWidth() - getWidthWithMargins(mCustomGroup); if (extraWidth < 0) { // Group is too wide to fit on a single row, so stack the group items vertically. mCustomGroup.setVerticalMode(0, mMargin); mCustomGroup.gravity = Gravity.FILL_HORIZONTAL; } else { // Expand the children to take up the entire row. View view0 = mCustomGroup.views[0]; View view1 = mCustomGroup.views[1]; int extraWidth0 = extraWidth / 2; int extraWidth1 = extraWidth - extraWidth0; measureChildWithFixedWidth(view0, view0.getMeasuredWidth() + extraWidth0); measureChildWithFixedWidth(view1, view1.getMeasuredWidth() + extraWidth1); } } } /** * Listens for View clicks. * Classes that override this function MUST call this one. * @param view View that was clicked on. */ @Override public void onClick(View view) { // Disable the infobar controls unless the user clicked the tertiary button, which by // convention is the "learn more" link. if (view.getId() != R.id.button_tertiary) { mInfoBarView.setControlsEnabled(false); } if (view.getId() == R.id.infobar_close_button) { mInfoBarView.onCloseButtonClicked(); } else if (view.getId() == R.id.button_primary) { mInfoBarView.onButtonClicked(true); } else if (view.getId() == R.id.button_secondary) { mInfoBarView.onButtonClicked(false); } else if (view.getId() == R.id.button_tertiary) { mInfoBarView.onLinkClicked(); } } }
package com.yahoo.config.codegen; import static org.junit.Assert.*; import java.io.*; import java.util.List; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; /** * @author hmusum */ public class NormalizedDefinitionTest { @Test public void testNormalizingFromReader() { String def = "version=1\n" + "aString string \n" + "anInt int #comment \n" + "aStringCommentCharacterAfter string default=\"ab\" #foo\n" + "aStringWithCommentCharacter string default=\"a "aStringWithEscapedQuote string default=\"a\"b\"\n"; StringReader reader = new StringReader(def); NormalizedDefinition nd = new NormalizedDefinition(); List<String> out = null; try { nd.normalize(new BufferedReader(reader)); out = nd.getNormalizedContent(); } catch (IOException e) { e.printStackTrace(); } assertNotNull(out); assertThat(out.size(), is(6)); assertThat(out.get(0), is ("version=1\n")); assertThat(out.get(1), is ("aString string\n")); assertThat(out.get(2), is ("anInt int\n")); assertThat(out.get(3), is ("aStringCommentCharacterAfter string default=\"ab\"\n")); assertThat(out.get(4), is ("aStringWithCommentCharacter string default=\"a assertThat(out.get(5), is ("aStringWithEscapedQuote string default=\"a\"b\"\n")); reader.close(); } @Test public void testNormalizingFromFile() throws IOException { FileReader fileReader = null; try { fileReader = new FileReader("src/test/resources/configgen.allfeatures.def"); } catch (FileNotFoundException e) { e.printStackTrace(); } NormalizedDefinition nd = new NormalizedDefinition(); List<String> out = null; try { nd.normalize(new BufferedReader(fileReader)); out = nd.getNormalizedContent(); } catch (IOException e) { e.printStackTrace(); } assertNotNull(out); assertThat(out.size(), is(72)); assertNotNull(fileReader); fileReader.close(); } }
package it.unibz.inf.ontop.iq.node.impl; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.iq.IQProperties; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.IntermediateQuery; import it.unibz.inf.ontop.iq.exception.InvalidIntermediateQueryException; import it.unibz.inf.ontop.iq.exception.QueryNodeTransformationException; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.iq.node.normalization.DistinctNormalizer; import it.unibz.inf.ontop.iq.transform.IQTreeVisitingTransformer; import it.unibz.inf.ontop.iq.transform.node.HomogeneousQueryNodeTransformer; import it.unibz.inf.ontop.iq.visit.IQVisitor; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.substitution.ImmutableSubstitution; import it.unibz.inf.ontop.utils.VariableGenerator; import java.util.Optional; public class DistinctNodeImpl extends QueryModifierNodeImpl implements DistinctNode { private static final String DISTINCT_NODE_STR = "DISTINCT"; private final DistinctNormalizer normalizer; @Inject private DistinctNodeImpl(IntermediateQueryFactory iqFactory, DistinctNormalizer normalizer) { super(iqFactory); this.normalizer = normalizer; } @Override public IQTree normalizeForOptimization(IQTree child, VariableGenerator variableGenerator, IQProperties currentIQProperties) { return normalizer.normalizeForOptimization(this, child, variableGenerator, currentIQProperties); } /** * TODO: implement it seriously! (is currently blocking) */ @Override public IQTree liftIncompatibleDefinitions(Variable variable, IQTree child) { // TODO: stop blocking return iqFactory.createUnaryIQTree(this, child); } @Override public IQTree applyDescendingSubstitution(ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution, Optional<ImmutableExpression> constraint, IQTree child) { return iqFactory.createUnaryIQTree(this, child.applyDescendingSubstitution(descendingSubstitution, constraint)); } @Override public IQTree applyDescendingSubstitutionWithoutOptimizing( ImmutableSubstitution<? extends VariableOrGroundTerm> descendingSubstitution, IQTree child) { return iqFactory.createUnaryIQTree(this, child.applyDescendingSubstitutionWithoutOptimizing(descendingSubstitution)); } @Override public boolean isDistinct(IQTree child) { return true; } @Override public IQTree acceptTransformer(IQTree tree, IQTreeVisitingTransformer transformer, IQTree child) { return transformer.transformDistinct(tree, this, child); } @Override public <T> T acceptVisitor(IQVisitor<T> visitor, IQTree child) { return visitor.visitDistinct(this, child); } @Override public void validateNode(IQTree child) throws InvalidIntermediateQueryException { } @Override public IQTree removeDistincts(IQTree child, IQProperties iqProperties) { return child.removeDistincts(); } @Override public void acceptVisitor(QueryNodeVisitor visitor) { visitor.visit(this); } @Override public DistinctNode acceptNodeTransformer(HomogeneousQueryNodeTransformer transformer) throws QueryNodeTransformationException { return transformer.transform(this); } @Override public ImmutableSet<Variable> getLocalVariables() { return ImmutableSet.of(); } @Override public boolean isSyntacticallyEquivalentTo(QueryNode node) { return node instanceof DistinctNode; } @Override public ImmutableSet<Variable> getLocallyRequiredVariables() { return ImmutableSet.of(); } @Override public ImmutableSet<Variable> getRequiredVariables(IntermediateQuery query) { return ImmutableSet.of(); } @Override public ImmutableSet<Variable> getLocallyDefinedVariables() { return ImmutableSet.of(); } @Override public boolean isEquivalentTo(QueryNode queryNode) { return queryNode instanceof DistinctNode; } @Override public String toString() { return DISTINCT_NODE_STR; } @Override public DistinctNode clone() { return iqFactory.createDistinctNode(); } }
package com.sequenceiq.cloudbreak.service.network; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.domain.Subnet; public final class NetworkUtils { private NetworkUtils() { throw new IllegalStateException(); } public static List<Port> getPorts(Stack stack) { List<EndpointRule> aclRules = createACLRules(stack); List<Port> ports = new ArrayList<>(); ports.add(new Port("SSH", "22", "22", "tcp", aclRules)); ports.add(new Port("Gateway", "80", "80", "tcp", aclRules)); ports.add(new Port("Ambari", "8080", "8080", "tcp", aclRules)); ports.add(new Port("Consul", "8500", "8500", "tcp", aclRules)); ports.add(new Port("NameNode", "50070", "50070", "tcp", aclRules)); ports.add(new Port("RM Web", "8088", "8088", "tcp", aclRules)); ports.add(new Port("RM Scheduler", "8030", "8030", "tcp", aclRules)); ports.add(new Port("RM IPC", "8050", "8050", "tcp", aclRules)); ports.add(new Port("Job History Server", "19888", "19888", "tcp", aclRules)); ports.add(new Port("HBase Master", "60010", "60010", "tcp", aclRules)); ports.add(new Port("Falcon", "15000", "15000", "tcp", aclRules)); ports.add(new Port("Storm", "8744", "8744", "tcp", aclRules)); ports.add(new Port("Oozie", "11000", "11000", "tcp", aclRules)); ports.add(new Port("Container logs", "8042", "8042", "tcp", aclRules)); ports.add(new Port("Zeppelin web socket", "9999", "9999", "tcp", aclRules)); ports.add(new Port("Zeppelin ui", "9995", "9995", "tcp", aclRules)); ports.add(new Port("Kibana", "3080", "3080", "tcp", aclRules)); ports.add(new Port("Elastic Search", "9200", "9200", "tcp", aclRules)); return ports; } public static List<String> getRawPorts(Stack stack, final String protocol) { List<String> ports = new ArrayList<>(); for (Port port : getPortsByProtocol(stack, protocol)) { ports.add(port.getLocalPort()); } return ports; } public static List<Port> getPortsByProtocol(Stack stack, final String protocol) { return FluentIterable.from(getPorts(stack)).filter(new Predicate<Port>() { @Override public boolean apply(Port port) { return protocol.equals(port.getProtocol()); } }).toList(); } private static List<EndpointRule> createACLRules(Stack stack) { List<EndpointRule> rules = new LinkedList<>(); for (Subnet net : stack.getAllowedSubnets()) { rules.add(new EndpointRule(EndpointRule.Action.PERMIT.getText(), net.getCidr())); } rules.add(EndpointRule.INTERNAL_RULE); rules.add(EndpointRule.DENY_RULE); return rules; } }
package org.alt_area.batteryinfo; import android.os.BatteryManager; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); displayInfo(); private void displayInfo() { IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); String statusStr; switch (status) { case BatteryManager.BATTERY_STATUS_CHARGING: statusStr = "BATTERY_STATUS_CHARGING"; break; case BatteryManager.BATTERY_STATUS_DISCHARGING: statusStr = "BATTERY_STATUS_DISCHARGING"; break; case BatteryManager.BATTERY_STATUS_FULL: statusStr = "BATTERY_STATUS_FULL"; break; case BatteryManager.BATTERY_STATUS_NOT_CHARGING: statusStr = "BATTERY_STATUS_NOT_CHARGING"; break; case BatteryManager.BATTERY_STATUS_UNKNOWN: statusStr = "BATTERY_STATUS_UNKNOWN"; break; default: statusStr = "UNDEFINED"; } TextView view = (TextView)findViewById(R.id.info); String msgStr = "Status:" + status + "=" + statusStr; view.setText(msgStr); } }
package org.hisp.dhis.android.core.program; import android.support.annotation.Nullable; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.data.api.Field; import org.hisp.dhis.android.core.data.api.Fields; import org.hisp.dhis.android.core.data.api.NestedField; import org.hisp.dhis.android.core.dataelement.DataElement; import java.util.Date; import java.util.List; import static org.hisp.dhis.android.core.utils.Utils.safeUnmodifiableList; @AutoValue public abstract class ProgramStageSection extends BaseIdentifiableObject { private static final String SORT_ORDER = "sortOrder"; private static final String PROGRAM_INDICATORS = "programIndicators"; private static final String DATA_ELEMENTS = "dataElements"; private static final String RENDER_TYPE = "renderType"; public static final Field<ProgramStageSection, String> uid = Field.create(UID); public static final Field<ProgramStageSection, String> code = Field.create(CODE); public static final Field<ProgramStageSection, String> name = Field.create(NAME); public static final Field<ProgramStageSection, String> displayName = Field.create(DISPLAY_NAME); public static final Field<ProgramStageSection, String> created = Field.create(CREATED); public static final Field<ProgramStageSection, String> lastUpdated = Field.create(LAST_UPDATED); public static final Field<ProgramStageSection, Integer> sortOrder = Field.create(SORT_ORDER); public static final Field<ProgramStageSection, Boolean> deleted = Field.create(DELETED); public static final NestedField<ProgramStageSection, ProgramIndicator> programIndicators = NestedField.create(PROGRAM_INDICATORS); public static final NestedField<ProgramStageSection, DataElement> dataElements = NestedField.create(DATA_ELEMENTS); static final NestedField<ProgramStageSection, ProgramStageSectionRendering> renderType = NestedField.create(RENDER_TYPE); static final Fields<ProgramStageSection> allFields = Fields.<ProgramStageSection>builder().fields( uid, code, name, displayName, created, lastUpdated, sortOrder, deleted, dataElements.with(DataElement.uid), programIndicators.with(ProgramIndicator.uid, ProgramIndicator.program.with(Program.uid)), renderType ).build(); @Nullable @JsonProperty(SORT_ORDER) public abstract Integer sortOrder(); @Nullable @JsonProperty(PROGRAM_INDICATORS) public abstract List<ProgramIndicator> programIndicators(); @Nullable @JsonProperty(DATA_ELEMENTS) public abstract List<DataElement> dataElements(); @Nullable @JsonProperty(RENDER_TYPE) public abstract ProgramStageSectionRendering renderType(); @JsonCreator public static ProgramStageSection create( @JsonProperty(UID) String uid, @JsonProperty(CODE) String code, @JsonProperty(NAME) String name, @JsonProperty(DISPLAY_NAME) String displayName, @JsonProperty(CREATED) Date created, @JsonProperty(LAST_UPDATED) Date lastUpdated, @JsonProperty(SORT_ORDER) Integer sortOrder, @JsonProperty(PROGRAM_INDICATORS) List<ProgramIndicator> programIndicators, @JsonProperty(DATA_ELEMENTS) List<DataElement> dataElements, @JsonProperty(RENDER_TYPE) ProgramStageSectionRendering renderType, @JsonProperty(DELETED) Boolean deleted) { return new AutoValue_ProgramStageSection( uid, code, name, displayName, created, lastUpdated, deleted, sortOrder, safeUnmodifiableList(programIndicators), safeUnmodifiableList(dataElements), renderType ); } }
package org.appwork.utils.swing.dialog; import java.awt.Image; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.ImageIcon; import javax.swing.ListCellRenderer; import javax.swing.SwingUtilities; import org.appwork.resources.AWUTheme; import org.appwork.uio.UIOManager; import org.appwork.utils.BinaryLogic; import org.appwork.utils.interfaces.ValueConverter; import org.appwork.utils.locale._AWU; import org.appwork.utils.logging.Log; import org.appwork.utils.swing.EDTRunner; /** * A Dialog Instance which provides extended Dialog features and thus replaces * JOptionPane */ public class Dialog { public static final String LASTSELECTION = "LASTSELECTION_"; public static final String FILECHOOSER = "FILECHOOSER"; /** * Icon Key for Error Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_ERROR = "dialog/error"; /** * Icon Key for Information Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_INFO = "dialog/info"; /** * Icon Key for Question Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_QUESTION = "dialog/help"; /** * Icon Key for Warning Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_WARNING = "dialog/warning"; /** * internal singleton instance to access the instance of this class */ private static final Dialog INSTANCE = new Dialog(); /** * * @deprecated Use org.appwork.uio.UIOManager Constants instead */ @Deprecated() public static final int LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY = 1 << 12; /** * if the user pressed cancel, the return mask will contain this mask */ public static final int RETURN_CANCEL = 1 << 2; /** * if user closed the window */ public static final int RETURN_CLOSED = 1 << 6; public static final int RETURN_INTERRUPT = 1 << 8; /** * this return flag can be set in two situations:<br> * a) The user selected the {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option<br> * b) The dialog has been skipped because the DO NOT SHOW AGAIN flag has * been set previously<br> * <br> * Check {@link #RETURN_SKIPPED_BY_DONT_SHOW} to know if the dialog has been * visible or autoskipped */ public static final int RETURN_DONT_SHOW_AGAIN = 1 << 3; /** * If the user pressed OK, the return mask will contain this flag */ public static final int RETURN_OK = 1 << 1; /** * If the dialog has been skipped due to previously selected * {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option, this return flag is set. * * @see #RETURN_DONT_SHOW_AGAIN */ public static final int RETURN_SKIPPED_BY_DONT_SHOW = 1 << 4; /** * If the Timeout ({@link UIOManager#LOGIC_COUNTDOWN}) has run out, the * return mask contains this flag */ public static final int RETURN_TIMEOUT = 1 << 5; /** * If the dialog has been skiped/closed by ESC key */ public static final int RETURN_ESC = 1 << 7; /** * @return * */ public static Dialog I() { return Dialog.INSTANCE; } public static boolean isClosed(final Object value) { if (!(value instanceof Integer)) { return false; } return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_CLOSED); } public static boolean isOK(final Object value) { if (!(value instanceof Integer)) { return false; } return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_OK); } private List<? extends Image> iconList = null; /** * Do Not use an Icon. By default dialogs have an Icon */ public static final int STYLE_HIDE_ICON = 1 << 8; /** * Some dialogs are able to render HTML. Use this switch to enable html */ public static final int STYLE_HTML = 1 << 7; /** * Some dialogs are able to layout themselves in a large mode. E:g. to * display a huge text. */ public static final int STYLE_LARGE = 1 << 6; /** * Displays a Checkbox with "do not show this again" text. If the user * selects this box, the UserInteraktion class will remember the answer and * will not disturb the user with the same question (same title) */ public static final int STYLE_SHOW_DO_NOT_DISPLAY_AGAIN = 1 << 5; /** * Inputdialogs will use passwordfields instead of textfields */ public static final int STYLE_PASSWORD = 1 << 9; /** * tries to find some special markers in the text and selects an appropriate * icon * * @param text * @return */ public static ImageIcon getIconByText(final String text) { try { if (text != null && text.contains("?")) { return AWUTheme.I().getIcon(Dialog.ICON_QUESTION, 32); } else if (text != null && (text.contains("error") || text.contains("exception"))) { return AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32); } else if (text != null && text.contains("!")) { return AWUTheme.I().getIcon(Dialog.ICON_WARNING, 32); } else { return AWUTheme.I().getIcon(Dialog.ICON_INFO, 32); } } catch (final Throwable e) { Log.exception(e); return null; } } /** * Return the singleton instance of Dialog * * @return */ public static Dialog getInstance() { return Dialog.INSTANCE; } public static void main(final String[] args) throws InterruptedException { final Thread th = new Thread() { @Override public void run() { try { Dialog.getInstance().showConfirmDialog(0, "Blabla?"); System.out.println("RETURNED OK"); } catch (final DialogClosedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final DialogCanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; th.start(); Thread.sleep(5000); th.interrupt(); } /** * The max counter value for a timeout Dialog */ private int defaultTimeout = 20000; /** * Parent window for all dialogs created with abstractdialog */ private LAFManagerInterface lafManager; private DialogHandler handler = null; private DialogHandler defaultHandler; private Dialog() { defaultHandler = new DialogHandler() { @Override public <T> T showDialog(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { return Dialog.this.showDialogRaw(dialog); } }; } public DialogHandler getDefaultHandler() { return defaultHandler; } /** * @return the {@link Dialog#defaultTimeout} in ms * @see Dialog#defaultTimeout */ protected int getDefaultTimeout() { return defaultTimeout; } public DialogHandler getHandler() { return handler; } /** * @return */ public List<? extends Image> getIconList() { return iconList; } public LAFManagerInterface getLafManager() { synchronized (this) { return lafManager; } } public void initLaf() { synchronized (this) { if (lafManager != null) { lafManager.init(); setLafManager(null); } } } /** * @param countdownTime * the {@link Dialog#defaultTimeout} to set * @see Dialog#defaultTimeout */ public void setDefaultTimeout(final int countdownTime) { defaultTimeout = countdownTime; } public void setHandler(DialogHandler handler) { if (handler == null) { handler = defaultHandler; } this.handler = handler; } @Deprecated public void setIconList(final List<? extends Image> iconList) { this.iconList = iconList; } public void setLafManager(final LAFManagerInterface lafManager) { synchronized (this) { this.lafManager = lafManager; } } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param question * The Dialog is able to show a question to the user. * @param options * A list of various options to select * @param defaultSelectedIndex * The option which is selected by default * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @param renderer * A renderer to customize the Dialog. Might be null * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showComboDialog(final int flag, final String title, final String question, final Object[] options, final int defaultSelectedIndex, final ImageIcon icon, final String okOption, final String cancelOption, final ListCellRenderer renderer) throws DialogClosedException, DialogCanceledException { return this.showDialog(new ComboBoxDialog(flag, title, question, options, defaultSelectedIndex, icon, okOption, cancelOption, renderer)); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param question * The Dialog is able to show a question to the user. * @param options * A list of various options to select * @param defaultSelectedItem * The option which is selected by default * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @param renderer * A renderer to customize the Dialog. Might be null * @return * @throws DialogCanceledException * @throws DialogClosedException */ public Object showComboDialog(final int flag, final String title, final String question, final Object[] options, final Object defaultSelectedItem, final ImageIcon icon, final String okOption, final String cancelOption, final ListCellRenderer renderer) throws DialogClosedException, DialogCanceledException { int def = 0; for (int i = 0; i < options.length; i++) { if (options[i] == defaultSelectedItem) { def = i; break; } } final Integer returnIndex = this.showDialog(new ComboBoxDialog(flag, title, question, options, def, icon, okOption, cancelOption, renderer)); return options[returnIndex]; } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param question * The Dialog is able to show a question to the user. * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String question) throws DialogClosedException, DialogCanceledException { return this.showConfirmDialog(flag, _AWU.T.DIALOG_CONFIRMDIALOG_TITLE(), question, Dialog.getIconByText(question), null, null); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param question * The Dialog is able to show a question to the user. * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String title, final String question) throws DialogClosedException, DialogCanceledException { return this.showConfirmDialog(flag, title, question, Dialog.getIconByText(title + question), null, null); } /** * Requests a ConfirmDialog * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] Text for OK Button [null * for default] * @param cancelOption * Text for Cancel Button [null for default] Text for cancel * Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String title, final String message, final ImageIcon tmpicon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { final ImageIcon icon; if (tmpicon == null) { icon = Dialog.getIconByText(title + message); } else { icon = tmpicon; } return this.showDialog(new ConfirmDialog(flag, title, message, icon, okOption, cancelOption)); } /** * note: showdialog must not call init itself!! * * @param <T> * @param dialog * @return * @throws DialogClosedException * @throws DialogCanceledException */ public <T> T showDialog(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { final DialogHandler lhandler = handler; if (lhandler != null) { return lhandler.showDialog(dialog); } return this.showDialogRaw(dialog); } /** * @param dialog * @throws DialogClosedException * @throws DialogCanceledException */ protected <T> T showDialogRaw(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { if (dialog == null) { return null; } if (SwingUtilities.isEventDispatchThread()) { return this.showDialogRawInEDT(dialog); } else { return this.showDialogRawOutsideEDT(dialog); } } protected <T> T showDialogRawInEDT(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { dialog.setCallerIsEDT(true); dialog.displayDialog(); final T ret = dialog.getReturnValue(); final int mask = dialog.getReturnmask(); if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); } if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); } return ret; } protected <T> T showDialogRawOutsideEDT(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { dialog.setCallerIsEDT(false); if (Thread.interrupted()) { throw new DialogClosedException(Dialog.RETURN_INTERRUPT, new InterruptedException()); } final AtomicBoolean waitingLock = new AtomicBoolean(false); final EDTRunner edth = new EDTRunner() { @Override protected void runInEDT() { dialog.setDisposedCallback(new DisposeCallBack() { @Override public void dialogDisposed(final AbstractDialog<?> dialog) { synchronized (waitingLock) { waitingLock.set(true); waitingLock.notifyAll(); } } }); dialog.displayDialog(); } }; try { if (Thread.interrupted()) { throw new InterruptedException(); } synchronized (waitingLock) { if (waitingLock.get() == false) { waitingLock.wait(); } } } catch (final InterruptedException e) { // Use a edtrunner here. AbstractCaptcha.dispose is edt save... // however there may be several CaptchaDialog classes with // overriddden unsave dispose methods... new EDTRunner() { @Override protected void runInEDT() { try { // close dialog if open dialog.interrupt(); } catch (final Exception e) { } } }; try { throw new DialogClosedException(dialog.getReturnmask() | Dialog.RETURN_INTERRUPT, e); } catch (final IllegalStateException e1) { // if we cannot get the returnmask from the dialog throw new DialogClosedException(Dialog.RETURN_INTERRUPT, e); } } final T ret = dialog.getReturnValue(); final int mask = dialog.getReturnmask(); if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); } if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); } return ret; } /** * @param i * @param dialog_error_title * @param dialog_error_noconnection * @return */ public int showErrorDialog(final int flags, final String title, final String message) { try { return this.showConfirmDialog(flags, title, message, AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32), null, null); } catch (final DialogClosedException e) { return Dialog.RETURN_CLOSED; } catch (final DialogCanceledException e) { return Dialog.RETURN_CANCEL; } } public int showErrorDialog(final String s) { try { return this.showConfirmDialog(UIOManager.BUTTONS_HIDE_CANCEL | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN, _AWU.T.DIALOG_ERROR_TITLE(), s, AWUTheme.I().getIcon(Dialog.ICON_ERROR, 32), null, null); } catch (final DialogClosedException e) { return Dialog.RETURN_CLOSED; } catch (final DialogCanceledException e) { return Dialog.RETURN_CANCEL; } } /** * @param string * @param message * @param e */ public int showExceptionDialog(final String title, final String message, final Throwable e) { try { final ExceptionDialog dialog = new ExceptionDialog(UIOManager.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT | UIOManager.BUTTONS_HIDE_CANCEL, title, message, e, null, null); this.showDialog(dialog); } catch (final DialogClosedException e1) { return Dialog.RETURN_CLOSED; } catch (final DialogCanceledException e1) { return Dialog.RETURN_CANCEL; } return 0; } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show a question to the user. question * @param defaultvalue * defaultvalue * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException { return this.showInputDialog(flag, _AWU.T.DIALOG_INPUT_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null); } /** * Requests in Inputdialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { return this.showDialog(new InputDialog(flag, title, message, defaultMessage, icon, okOption, cancelOption)); } /** * * @param message * The Dialog is able to show a message to the user * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final String message) throws DialogClosedException, DialogCanceledException { return this.showInputDialog(0, message, null); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final int flag, final String message) { this.showMessageDialog(flag, _AWU.T.DIALOG_MESSAGE_TITLE(), message); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final int flag, final String title, final String message) { try { this.showConfirmDialog(UIOManager.BUTTONS_HIDE_CANCEL | flag, title, message, Dialog.getIconByText(title + message), null, null); } catch (final DialogClosedException e) { } catch (final DialogCanceledException e) { } } /** * * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final String message) { this.showMessageDialog(0, _AWU.T.DIALOG_MESSAGE_TITLE(), message); } /** * * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final String title, final String message) { this.showMessageDialog(0, title, message); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show 3 Passwordfields to the user. * question * @param defaultvalue * defaultvalue * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showPasswordDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException { return this.showPasswordDialog(flag, _AWU.T.DIALOG_PASSWORD_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null); } /** * Requests in MultiInputdialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ protected String showPasswordDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { return this.showDialog(new PasswordDialog(flag, title, message, icon, okOption, cancelOption)); } /** * * @param message * The Dialog is able to show a message to the user * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showPasswordDialog(final String message) throws DialogClosedException, DialogCanceledException { return this.showPasswordDialog(0, message, null); } /** * * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param def * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showTextAreaDialog(final String title, final String message, final String def) throws DialogClosedException, DialogCanceledException { return this.showDialog(new TextAreaDialog(title, message, def)); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show a slider to the user. question * @param defaultvalue * defaultvalue * @param min * Min slider value * @param max * Max slider value * @param step * slider step * @param valueConverter * TODO * @return * @throws DialogCanceledException * @throws DialogClosedException */ public long showValueDialog(final int flag, final String question, final long defaultvalue, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException { return this.showValueDialog(flag, _AWU.T.DIALOG_SLIDER_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null, min, max, step, valueConverter); } /** * Requests in ValueDialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @param min * Min slider value * @param max * Max slider value * @param step * slider step * @param valueConverter * @return * @throws DialogCanceledException * @throws DialogClosedException */ protected long showValueDialog(final int flag, final String title, final String message, final long defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException { return this.showDialog(new ValueDialog(flag, title, message, icon, okOption, cancelOption, defaultMessage, min, max, step, valueConverter)); } }
package org.bdgp.OpenHiCAMM.Modules; import java.awt.Component; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import mmcorej.TaggedImage; import org.bdgp.OpenHiCAMM.Dao; import org.bdgp.OpenHiCAMM.ImageLog; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.OpenHiCAMM; import org.bdgp.OpenHiCAMM.Util; import org.bdgp.OpenHiCAMM.ValidationError; import org.bdgp.OpenHiCAMM.WorkflowRunner; import org.bdgp.OpenHiCAMM.DB.Acquisition; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.ModuleConfig; import org.bdgp.OpenHiCAMM.DB.ROI; import org.bdgp.OpenHiCAMM.DB.Slide; import org.bdgp.OpenHiCAMM.DB.SlidePos; import org.bdgp.OpenHiCAMM.DB.SlidePosList; import org.bdgp.OpenHiCAMM.DB.Task; import org.bdgp.OpenHiCAMM.DB.Task.Status; import org.bdgp.OpenHiCAMM.DB.TaskConfig; import org.bdgp.OpenHiCAMM.DB.TaskDispatch; import org.bdgp.OpenHiCAMM.DB.WorkflowModule; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration; import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.json.JSONException; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.ImageCache; import org.micromanager.api.MultiStagePosition; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.api.StagePosition; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMSerializationException; import static org.bdgp.OpenHiCAMM.Util.where; /** * Return x/y/len/width of bounding box surrounding the ROI */ public abstract class ROIFinder implements Module, ImageLogger { protected WorkflowRunner workflowRunner; protected WorkflowModule workflowModule; protected ScriptInterface script; @Override public void initialize(WorkflowRunner workflowRunner, WorkflowModule workflowModule) { this.workflowRunner = workflowRunner; this.workflowModule = workflowModule; OpenHiCAMM mmslide = workflowRunner.getOpenHiCAMM(); this.script = mmslide.getApp(); // set initial configs workflowRunner.getModuleConfig().insertOrUpdate( new ModuleConfig(this.workflowModule.getId(), "canProduceROIs", "yes"), "id", "key"); } @Override public Status run(Task task, Map<String,Config> config, final Logger logger) { logger.fine(String.format("Running task: %s", task)); for (Config c : config.values()) { logger.fine(String.format("Using config: %s", c)); } // Get the Image record Config imageIdConf = config.get("imageId"); if (imageIdConf == null) throw new RuntimeException("No imageId task configuration was set by the slide imager!"); Integer imageId = new Integer(imageIdConf.getValue()); Dao<Image> imageDao = workflowRunner.getInstanceDb().table(Image.class); final Image image = imageDao.selectOneOrDie(where("id",imageId)); // get the tagged image TaggedImage taggedImage = getTaggedImage(image, logger); // get the image label and position name String positionName = null; try { positionName = MDUtils.getPositionName(taggedImage.tags); } catch (JSONException e) {throw new RuntimeException(e);} String imageLabel = image.getLabel(); String label = String.format("%s (%s)", positionName, imageLabel); logger.fine(String.format("%s: Using image: %s", label, image)); logger.fine(String.format("%s: Using image ID: %d", label, imageId)); Dao<Slide> slideDao = workflowRunner.getInstanceDb().table(Slide.class); Slide slide = slideDao.selectOneOrDie(where("id",image.getSlideId())); logger.fine(String.format("%s: Using slide: %s", label, slide)); try { Config imageScaleFactorConf = config.get("imageScaleFactor"); double imageScaleFactor = imageScaleFactorConf != null? new Double(imageScaleFactorConf.getValue()) : 1.0; Config pixelSizeConf = config.get("pixelSize"); if (pixelSizeConf == null) throw new RuntimeException("Config value pixelSize was not inherited!"); double pixelSize = new Double(pixelSizeConf.getValue()); pixelSize /= imageScaleFactor; logger.fine(String.format("%s: Using pixelSize: %f", label, pixelSize)); double hiResPixelSize = new Double(config.get("hiResPixelSize").getValue()); logger.fine(String.format("%s: Using hiResPixelSize: %f", label, hiResPixelSize)); double roiMarginPct = new Double(config.get("roiMarginPct").getValue()); logger.fine(String.format("%s: Using ROI margin size in percent of image size: %f", label, roiMarginPct)); int positionIndex = MDUtils.getPositionIndex(taggedImage.tags); logger.fine(String.format("%s: Using positionIndex: %d", label, positionIndex)); double overlapPct = new Double(config.get("overlapPct").getValue()); logger.fine(String.format("%s: Using percentage overlap: %f", label, overlapPct)); // get invertXAxis and invertYAxis conf values Config invertXAxisConf = config.get("invertXAxis"); boolean invertXAxis = invertXAxisConf == null || "yes".equals(invertXAxisConf.getValue()); Config invertYAxisConf = config.get("invertYAxis"); boolean invertYAxis = invertYAxisConf == null || "yes".equals(invertYAxisConf.getValue()); int imageWidth = MDUtils.getWidth(taggedImage.tags); int imageHeight = MDUtils.getHeight(taggedImage.tags); Config XPositionUmConf = config.get("XPositionUm"); double x_stage = XPositionUmConf == null? MDUtils.getXPositionUm(taggedImage.tags) : new Double(XPositionUmConf.getValue()); Config YPositionUmConf = config.get("YPositionUm"); double y_stage = YPositionUmConf == null? MDUtils.getYPositionUm(taggedImage.tags) : new Double(YPositionUmConf.getValue()); // Delete any old ROI records Dao<ROI> roiDao = this.workflowRunner.getInstanceDb().table(ROI.class); int deleted = roiDao.delete(where("imageId", imageId)); logger.fine(String.format("%s: Deleted %d old ROI records.", label, deleted)); // Fill in list of ROIs logger.fine(String.format("%s: Running process() to get list of ROIs", label)); List<ROI> rois = new ArrayList<ROI>(); try { rois = process(image, taggedImage, logger, new ImageLog.NullImageLogRunner(), config); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(String.format("Exception during ROI processing: %s", sw.toString())); return Status.ERROR; } // Convert the ROIs into a PositionList Map<MultiStagePosition,ROI> roiMap = new HashMap<MultiStagePosition,ROI>(); PositionList posList = new PositionList(); for (ROI roi : rois) { // insert the ROI record roiDao.insert(roi); // increase the ROI dimensions to add the margins int roiMarginWidth = (int)Math.floor((roiMarginPct / 100.0) * imageWidth * hiResPixelSize / pixelSize); int roiMarginHeight = (int)Math.floor((roiMarginPct / 100.0) * imageHeight * hiResPixelSize / pixelSize); int roiX1 = roi.getX1() - roiMarginWidth; int roiY1 = roi.getY1() - roiMarginHeight; int roiX2 = roi.getX2() + roiMarginWidth; int roiY2 = roi.getY2() + roiMarginHeight; // We need to potentially create a grid of Stage positions in order to capture all of the // ROI. int roiWidth = roiX2-roiX1+1; int roiHeight = roiY2-roiY1+1; int tileWidth = (int)Math.floor(((double)imageWidth * hiResPixelSize) / pixelSize); int tileHeight = (int)Math.floor(((double)imageHeight * hiResPixelSize) / pixelSize); int tileXOverlap = (int)Math.floor((overlapPct / 100.0) * tileWidth); int tileYOverlap = (int)Math.floor((overlapPct / 100.0) * tileHeight); int tileXCount = (int)Math.ceil((double)(roiWidth - tileXOverlap) / (double)(tileWidth - tileXOverlap)); int tileYCount = (int)Math.ceil((double)(roiHeight - tileYOverlap) / (double)(tileHeight - tileYOverlap)); int tileSetWidth = (tileXCount * (tileWidth - tileXOverlap)) + tileXOverlap; int tileSetHeight = (tileYCount * (tileHeight - tileYOverlap)) + tileYOverlap; int tileXOffset = (int)Math.floor( (roiX1 + ((double)roiWidth / 2.0)) - ((double)tileSetWidth / 2.0) + ((double)tileWidth / 2.0)); int tileYOffset = (int)Math.floor( (roiY1 + ((double)roiHeight / 2.0)) - ((double)tileSetHeight / 2.0) + ((double)tileHeight / 2.0)); for (int x=0; x < tileXCount; ++x) { for (int y=0; y < tileYCount; ++y) { int tileX = (x*(tileWidth - tileXOverlap)) + tileXOffset; int tileY = (y*(tileHeight - tileYOverlap)) + tileYOffset; MultiStagePosition msp = new MultiStagePosition(); StagePosition sp = new StagePosition(); sp.numAxes = 2; sp.stageName = "XYStage"; sp.x = x_stage+((tileX-(double)imageWidth/2.0)*pixelSize)*(invertXAxis? -1.0 : 1.0); sp.y = y_stage+((tileY-(double)imageHeight/2.0)*pixelSize)*(invertYAxis? -1.0 : 1.0); String mspLabel = String.format("%s.%s.ROI%d.X%d.Y%d", positionName, imageLabel, roi.getId(), x, y); msp.setProperty("stitchGroup", "ROI"+roi.getId()); msp.setProperty("ROI", new Integer(roi.getId()).toString()); msp.setProperty("tileX", new Integer(x).toString()); msp.setProperty("tileY", new Integer(y).toString()); msp.setLabel(mspLabel); msp.add(sp); msp.setDefaultXYStage("XYStage"); posList.addPosition(msp); roiMap.put(msp, roi); logger.info(String.format("%s: Storing StagePosition(label=%s, numAxes: %d, stageName: %s, x=%.2f, y=%.2f, tileX=%d, tileY=%d)", label, Util.escape(mspLabel), sp.numAxes, Util.escape(sp.stageName), sp.x, sp.y, tileX, tileY)); } } } if (posList.getNumberOfPositions() > 0) { logger.info(String.format("%s: Produced position list of %d ROIs", label, posList.getNumberOfPositions())); try { logger.fine(String.format("%s: Position List:%n%s", label, posList.serialize())); } catch (MMSerializationException e) {throw new RuntimeException(e);} } else { logger.info(String.format("%s: ROIFinder did not produce any positions for this image", label)); } Dao<SlidePosList> slidePosListDao = workflowRunner.getInstanceDb().table(SlidePosList.class); Dao<SlidePos> slidePosDao = workflowRunner.getInstanceDb().table(SlidePos.class); // First, delete any old slidepos and slideposlist records logger.fine(String.format("Deleting old position lists")); List<SlidePosList> oldSlidePosLists = slidePosListDao.select( where("slideId",slide.getId()).and("moduleId",this.workflowModule.getId()).and("taskId", task.getId())); for (SlidePosList oldSlidePosList : oldSlidePosLists) { slidePosDao.delete(where("slidePosListId",oldSlidePosList.getId())); } slidePosListDao.delete(where("slideId",slide.getId()).and("moduleId",this.workflowModule.getId()).and("taskId", task.getId())); // Create/Update SlidePosList and SlidePos DB records SlidePosList slidePosList = new SlidePosList(this.workflowModule.getId(), slide.getId(), task.getId(), posList); slidePosListDao.insert(slidePosList); logger.fine(String.format("%s: Created new SlidePosList: %s", label, slidePosList)); MultiStagePosition[] msps = posList.getPositions(); for (int i=0; i<msps.length; ++i) { ROI roi = roiMap.get(msps[i]); if (roi == null) throw new RuntimeException( String.format("Error: could not get ROI for MSP %s using roiMap", msps[i])); SlidePos slidePos = new SlidePos(slidePosList.getId(), i, roi.getId()); slidePosDao.insert(slidePos); logger.fine(String.format("%s: Created new SlidePos record for position %d: %s", label, i, slidePos)); } return Status.SUCCESS; } catch (JSONException e) { throw new RuntimeException(e); } } public TaggedImage getTaggedImage(Image image, Logger logger) { String label = image.getLabel(); // if this image is not in an acquisition, then load it as a file if (image.getAcquisitionId() == 0 && image.getPath() != null) { TaggedImage taggedImage = image.getTaggedImage(null); return taggedImage; } // Initialize the acquisition Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class); Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId())); logger.fine(String.format("%s: Using acquisition: %s", label, acquisition)); int tries = 0; final int MAX_TRIES = 30; MMAcquisition mmacquisition = null; while (tries++ < MAX_TRIES) { try { mmacquisition = acquisition.getAcquisition(acqDao); if (mmacquisition != null) break; } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(String.format("Could not open acquisition %s, trying again...: \n%s", acquisition, sw.toString())); } try { Thread.sleep(1000); } catch (InterruptedException e) { } } if (mmacquisition == null) { throw new RuntimeException(String.format("Could not open acquisition %s!", acquisition)); } // Get the image cache object ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!"); logger.fine(String.format("%s: ImageCache has following images: %s", label, imageCache.imageKeys())); logger.fine(String.format("%s: Attempting to grab image %s from imageCache", label, image)); // Get the tagged image from the image cache TaggedImage taggedImage = image.getImage(imageCache); if (taggedImage == null) throw new RuntimeException(String.format("Acqusition %s, Image %s is not in the image cache!", acquisition, image)); logger.fine(String.format("%s: Got taggedImage from ImageCache: %s", label, taggedImage)); return taggedImage; } /** * The process() method must be overridden by a subclass. This method holds the logic for ROI finding. It takes an image * and returns a list of ROIs. * @param image The input image DB record. * @param taggedImage The taggedImage object * @param logger A logger object * @param imageLog An image logger object * @param config A set of configuration key/value pairs * @return The list of ROI records. */ public abstract List<ROI> process( Image image, TaggedImage taggedImage, Logger logger, ImageLogRunner imageLog, Map<String,Config> config); @Override public String getTitle() { return this.getClass().getName(); } @Override public String getDescription() { return this.getClass().getName(); } @Override public Configuration configure() { return new Configuration() { ROIFinderDialog dialog = new ROIFinderDialog(ROIFinder.this); @Override public Config[] retrieve() { List<Config> configs = new ArrayList<Config>(); Double hiResPixelSize = (Double)dialog.hiResPixelSize.getValue(); if (hiResPixelSize != null) { configs.add(new Config(ROIFinder.this.workflowModule.getId(), "hiResPixelSize", hiResPixelSize.toString())); } Double minRoiArea = (Double)dialog.minRoiArea.getValue(); if (minRoiArea != null) { configs.add(new Config(ROIFinder.this.workflowModule.getId(), "minRoiArea", minRoiArea.toString())); } Double overlapPct = (Double)dialog.overlapPct.getValue(); if (overlapPct != null) { configs.add(new Config(ROIFinder.this.workflowModule.getId(), "overlapPct", overlapPct.toString())); } Double roiMarginPct = (Double)dialog.roiMarginPct.getValue(); if (roiMarginPct != null) { configs.add(new Config(ROIFinder.this.workflowModule.getId(), "roiMarginPct", roiMarginPct.toString())); } Double roiImageScaleFactor = (Double)dialog.roiImageScaleFactor.getValue(); if (roiImageScaleFactor != null) { configs.add(new Config(ROIFinder.this.workflowModule.getId(), "roiImageScaleFactor", roiImageScaleFactor.toString())); } return configs.toArray(new Config[0]); } @Override public Component display(Config[] configs) { Map<String,Config> confs = new HashMap<String,Config>(); for (Config c : configs) { confs.put(c.getKey(), c); } if (confs.containsKey("hiResPixelSize")) { dialog.hiResPixelSize.setValue(new Double(confs.get("hiResPixelSize").getValue())); } if (confs.containsKey("minRoiArea")) { dialog.minRoiArea.setValue(new Double(confs.get("minRoiArea").getValue())); } if (confs.containsKey("overlapPct")) { dialog.overlapPct.setValue(new Double(confs.get("overlapPct").getValue())); } if (confs.containsKey("roiMarginPct")) { dialog.roiMarginPct.setValue(new Double(confs.get("roiMarginPct").getValue())); } if (confs.containsKey("roiImageScaleFactor")) { dialog.roiImageScaleFactor.setValue(new Double(confs.get("roiImageScaleFactor").getValue())); } return dialog; } @Override public ValidationError[] validate() { List<ValidationError> errors = new ArrayList<ValidationError>(); Double hiResPixelSize = (Double)dialog.hiResPixelSize.getValue(); if (hiResPixelSize == null || hiResPixelSize == 0.0) { errors.add(new ValidationError(ROIFinder.this.workflowModule.getName(), "Please enter a nonzero value for hiResPixelSize")); } Double minRoiArea = (Double)dialog.minRoiArea.getValue(); if (minRoiArea == null || minRoiArea == 0.0) { errors.add(new ValidationError(ROIFinder.this.workflowModule.getName(), "Please enter a nonzero value for Min ROI Area")); } Double overlapPct = (Double)dialog.overlapPct.getValue(); if (overlapPct == null || overlapPct < 0.0 || overlapPct > 100.0) { errors.add(new ValidationError(ROIFinder.this.workflowModule.getName(), "Please enter a value between 0 and 100 for Tile Percent Overlap")); } Double roiMarginPct = (Double)dialog.roiMarginPct.getValue(); if (roiMarginPct == null || roiMarginPct < 0.0 || roiMarginPct > 100.0) { errors.add(new ValidationError(ROIFinder.this.workflowModule.getName(), "Please enter a value between 0 and 100 for ROI Margin Percent")); } Double roiImageScaleFactor = (Double)dialog.roiImageScaleFactor.getValue(); if (roiImageScaleFactor == null || roiImageScaleFactor <= 0.0) { errors.add(new ValidationError(ROIFinder.this.workflowModule.getName(), "Please enter a value greater than 0.0 ROI Image Scale Factor")); } return errors.toArray(new ValidationError[0]); } }; } @Override public List<Task> createTaskRecords(List<Task> parentTasks, Map<String,Config> config, Logger logger) { Dao<TaskConfig> taskConfigDao = workflowRunner.getTaskConfig(); WorkflowModule module = workflowRunner.getWorkflow().selectOneOrDie(where("id",this.workflowModule.getId())); List<Task> tasks = new ArrayList<Task>(); if (module.getParentId() != null) { for (Task parentTask : parentTasks) { workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: attaching to parent Task: %s", this.workflowModule.getName(), parentTask)); Task task = new Task(workflowModule.getId(), Status.NEW); workflowRunner.getTaskStatus().insert(task); tasks.add(task); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new task record: %s", this.workflowModule.getName(), task)); // pass along the slideId conf to any child tasks TaskConfig slideIdConf = taskConfigDao.selectOne( where("id",parentTask.getId()). and("key", "slideId")); if (slideIdConf != null) { // create taskConfig record for the slide ID TaskConfig slideId = new TaskConfig( task.getId(), "slideId", slideIdConf.getValue()); taskConfigDao.insert(slideId); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s", this.workflowModule.getName(), slideId)); } TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId()); workflowRunner.getTaskDispatch().insert(dispatch); workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new task dispatch record: %s", this.workflowModule.getName(), dispatch)); } } return tasks; } @Override public TaskType getTaskType() { return Module.TaskType.PARALLEL; } @Override public void cleanup(Task task, Map<String,Config> config, Logger logger) { } @Override public List<ImageLogRecord> logImages(final Task task, final Map<String,Config> config, final Logger logger) { List<ImageLogRecord> imageLogRecords = new ArrayList<ImageLogRecord>(); // Add an image logger instance to the workflow runner for this module imageLogRecords.add(new ImageLogRecord(task.getName(workflowRunner.getWorkflow()), task.getName(workflowRunner.getWorkflow()), new FutureTask<ImageLogRunner>(new Callable<ImageLogRunner>() { @Override public ImageLogRunner call() throws Exception { // Get the Image record Config imageIdConf = config.get("imageId"); if (imageIdConf != null) { Integer imageId = new Integer(imageIdConf.getValue()); logger.info(String.format("Using image ID: %d", imageId)); Dao<Image> imageDao = workflowRunner.getInstanceDb().table(Image.class); final Image image = imageDao.selectOneOrDie(where("id",imageId)); logger.info(String.format("Using image: %s", image)); // Initialize the acquisition Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class); Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId())); logger.info(String.format("Using acquisition: %s", acquisition)); MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao); // Get the image cache object ImageCache imageCache = mmacquisition.getImageCache(); if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!"); // Get the tagged image from the image cache TaggedImage taggedImage = image.getImage(imageCache); logger.info(String.format("Got taggedImage from ImageCache: %s", taggedImage)); ImageLogRunner imageLogRunner = new ImageLogRunner(task.getName(workflowRunner.getWorkflow())); ROIFinder.this.process(image, taggedImage, logger, imageLogRunner, config); return imageLogRunner; } return null; } }))); return imageLogRecords; } @Override public void runInitialize() { } @Override public Status setTaskStatusOnResume(Task task) { if (task.getStatus() != Status.SUCCESS) { return Task.Status.NEW; } List<TaskDispatch> tds = this.workflowRunner.getTaskDispatch().select(where("taskId", task.getId())); while (!tds.isEmpty()) { List<TaskDispatch> newTds = new ArrayList<>(); for (TaskDispatch td : tds) { Task t = this.workflowRunner.getTaskStatus().selectOneOrDie(where("id", td.getParentTaskId())); if (t.getStatus() != Status.SUCCESS) { return Status.NEW; } if (this.workflowRunner.getModuleConfig().selectOne( where("id", t.getModuleId()). and("key", "canImageSlides"). and("value", "yes")) == null) { newTds.addAll(this.workflowRunner.getTaskDispatch().select(where("taskId", t.getId()))); } } tds.clear(); tds.addAll(newTds); } return null; } }
package org.bouncycastle.bcpg; import java.io.*; /** * reader for PGP objects */ public class BCPGInputStream extends InputStream implements PacketTags { InputStream in; boolean next = false; int nextB; public BCPGInputStream( InputStream in) { this.in = in; } public int available() throws IOException { return in.available(); } public int read() throws IOException { if (next) { next = false; return nextB; } else { return in.read(); } } public int read( byte[] buf, int off, int len) throws IOException { if (len == 0) { return 0; } if (!next) { return in.read(buf, off, len); } // We have next byte waiting, so return it if (nextB < 0) { return -1; // EOF } buf[off] = (byte)nextB; // May throw NullPointerException... next = false; // ...so only set this afterwards return 1; } public void readFully( byte[] buf, int off, int len) throws IOException { // make sure we pick up nextB if set. if (len > 0) { int b = this.read(); if (b < 0) { throw new EOFException(); } buf[off] = (byte)b; off++; len } while (len > 0) { int l = in.read(buf, off, len); if (l < 0) { throw new EOFException(); } off += l; len -= l; } } public void readFully( byte[] buf) throws IOException { readFully(buf, 0, buf.length); } /** * returns the nest packet tag in the stream. * * @return the tag number. * * @throws IOException */ public int nextPacketTag() throws IOException { if (!next) { try { nextB = in.read(); } catch (EOFException e) { nextB = -1; } } next = true; if (nextB >= 0) { if ((nextB & 0x40) != 0) // new { return (nextB & 0x3f); } else // old { return ((nextB & 0x3f) >> 2); } } return nextB; } public Packet readPacket() throws IOException { int hdr = this.read(); if (hdr < 0) { return null; } if ((hdr & 0x80) == 0) { throw new IOException("invalid header encountered"); } boolean newPacket = (hdr & 0x40) != 0; int tag = 0; int bodyLen = 0; boolean partial = false; if (newPacket) { tag = hdr & 0x3f; int l = this.read(); if (l < 192) { bodyLen = l; } else if (l <= 223) { int b = in.read(); bodyLen = ((l - 192) << 8) + (b) + 192; } else if (l == 255) { bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; bodyLen = 1 << (l & 0x1f); } } else { int lengthType = hdr & 0x3; tag = (hdr & 0x3f) >> 2; switch (lengthType) { case 0: bodyLen = this.read(); break; case 1: bodyLen = (this.read() << 8) | this.read(); break; case 2: bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read(); break; case 3: partial = true; break; default: throw new IOException("unknown length type encountered"); } } BCPGInputStream objStream; if (bodyLen == 0 && partial) { objStream = this; } else { objStream = new BCPGInputStream(new PartialInputStream(this, partial, bodyLen)); } switch (tag) { case RESERVED: return new InputStreamPacket(objStream); case PUBLIC_KEY_ENC_SESSION: return new PublicKeyEncSessionPacket(objStream); case SIGNATURE: return new SignaturePacket(objStream); case SYMMETRIC_KEY_ENC_SESSION: return new SymmetricKeyEncSessionPacket(objStream); case ONE_PASS_SIGNATURE: return new OnePassSignaturePacket(objStream); case SECRET_KEY: return new SecretKeyPacket(objStream); case PUBLIC_KEY: return new PublicKeyPacket(objStream); case SECRET_SUBKEY: return new SecretSubkeyPacket(objStream); case COMPRESSED_DATA: return new CompressedDataPacket(objStream); case SYMMETRIC_KEY_ENC: return new SymmetricEncDataPacket(objStream); case MARKER: return new MarkerPacket(objStream); case LITERAL_DATA: return new LiteralDataPacket(objStream); case TRUST: return new TrustPacket(objStream); case USER_ID: return new UserIDPacket(objStream); case USER_ATTRIBUTE: return new UserAttributePacket(objStream); case PUBLIC_SUBKEY: return new PublicSubkeyPacket(objStream); case SYM_ENC_INTEGRITY_PRO: return new SymmetricEncIntegrityPacket(objStream); case MOD_DETECTION_CODE: return new ModDetectionCodePacket(objStream); case EXPERIMENTAL_1: case EXPERIMENTAL_2: case EXPERIMENTAL_3: case EXPERIMENTAL_4: return new ExperimentalPacket(tag, objStream); default: throw new IOException("unknown packet type encountered: " + tag); } } public void close() throws IOException { in.close(); } /** * a stream that overlays our input stream, allowing the user to only read a segment of it. */ private static class PartialInputStream extends InputStream { private BCPGInputStream in; private boolean partial; private int dataLength; PartialInputStream( BCPGInputStream in, boolean partial, int dataLength) { this.in = in; this.partial = partial; this.dataLength = dataLength; } public int available() throws IOException { int avail = in.available(); if (avail <= dataLength) { return avail; } else { if (partial && dataLength == 0) { return 1; } return dataLength; } } private int loadDataLength() throws IOException { int l = in.read(); if (l < 0) { return -1; } partial = false; if (l < 192) { dataLength = l; } else if (l <= 223) { dataLength = ((l - 192) << 8) + (in.read()) + 192; } else if (l == 255) { dataLength = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; dataLength = 1 << (l & 0x1f); } return dataLength; } public int read(byte[] buf, int offset, int len) throws IOException { if (dataLength > 0) { int readLen = (dataLength > len) ? len : dataLength; readLen = in.read(buf, offset, readLen); dataLength -= readLen; return readLen; } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(buf, offset, len); } return -1; } public int read() throws IOException { if (dataLength > 0) { dataLength return in.read(); } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(); } return -1; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.panel; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.Chromosome; import org.broad.igv.feature.Locus; import org.broad.igv.feature.genome.Genome; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import java.text.NumberFormat; import java.util.Locale; /** * @author jrobinso */ public class ReferenceFrame { private static Logger log = Logger.getLogger(ReferenceFrame.class); private static NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(Locale.US); private static double minimumScale = Double.MAX_VALUE; String name; int pixelX; private int widthInPixels; /** * The nominal viewport width in pixels. */ public static int binsPerTile = 700; /** * The chromosome currently in view */ private String chrName = "chrAll"; /** * The minimum zoom level for the current screen size + chromosome combination. */ private int minZoom = 0; /** * The current zoom level. Zoom level -1 corresponds to the whole * genome view (chromosome "all") */ private int zoom = minZoom; /** * The maximum zoom level. Set to prevent integer overflow. This is a function * of chromosom length. */ public static int maxZoom = 23; /** * The number of tiles for this zoom level, = 2^zoom */ private int nTiles = 1; /** * The maximum virtual pixel value. */ private double maxPixel; /** * The origin in bp */ private double origin = 0; /** * The location (x axis) locationScale in base pairs / virtual pixel */ private double locationScale; /** * Minimum allowed scale in base pairs / pixel */ private double minScale = 1.0 / 14; private boolean locationScaleValid = false; private Locus initialLocus; public ReferenceFrame(String name) { this.name = name; Genome genome = getGenome(); this.chrName = genome == null ? "" : genome.getHomeChromosome(); } public void setBounds(int x, int w) { this.pixelX = x; if (w != widthInPixels) { widthInPixels = w; computeLocationScale(); } } public int getMidpoint() { return pixelX + widthInPixels / 2; } /** * Compute the maximum zoom level, which is a function of chromosome length. */ public void computeMaxZoom() { Genome genome = getGenome(); // Compute max zoom. Assume window size @ max zoom of ~ 50 bp if (genome != null && chrName != null && genome.getChromosome(chrName) != null) { if (chrName.equals(Globals.CHR_ALL)) { maxZoom = 0; } else { int chrLength = genome.getChromosome(chrName).getLength(); maxZoom = (int) (Math.log(chrLength / 50.0) / Globals.log2) + 1; } if (zoom > maxZoom) { zoomTo(maxZoom); } } // TODO -- fire chromosome changed event rather than this } private void zoomTo(int newZoom) { // All zoom events "release" the frame, enabling pan and zoom zoom = Math.min(maxZoom, newZoom); nTiles = (int) Math.pow(2, Math.max(minZoom, zoom)); maxPixel = getTilesTimesBinsPerTile(); invalidateLocationScale(); // TODO -- do this with events, if (IGV.hasInstance()) { IGV.getInstance().repaintStatusAndZoomSlider(); } } /** * This setter is provided to restore state, it does not do a "zoom" action * * @param z */ public void setZoom(int z) { if (z > 0) this.zoom = z; } public void incrementZoom(int increment) { zoomByAndCenter(increment); } public void zoomAndCenterAdjusted(int newZoom) { double currentCenter = origin + ((widthInPixels / 2) * getScale()); zoomTo(newZoom, currentCenter); } public void zoomByAndCenter(int zoomIncrement) { // Zoom but remain centered about current center double currentCenter = origin + ((widthInPixels / 2) * getScale()); zoomBy(zoomIncrement, currentCenter); } public void zoomBy(final int zoomFactor, final double newCenter) { if (FrameManager.isGeneListMode()) { double f = Math.pow(2.0, zoomFactor); locationScale = Math.max(minScale, locationScale / f); double newOrigin = Math.round(newCenter - ((widthInPixels / 2) * locationScale)); setOrigin(newOrigin); imputeZoom(origin, setEnd); } else { int newZoom = Math.max(0, zoom + zoomFactor); zoomTo(newZoom, newCenter); } } public void zoomTo(final int newZoom, final double newCenter) { if (chrName.equals(Globals.CHR_ALL)) { chrName = getGenome().getHomeChromosome(); } if (chrName.equals(Globals.CHR_ALL)) { // Translate the location to chromosome number jumpToChromosomeForGenomeLocation(newCenter); IGV.getInstance().chromosomeChangeEvent(chrName); } else { if (zoom != newZoom) { zoomTo(newZoom); computeLocationScale(); double newLocationScale = getScale(); // Adjust origin so newCenter is centered double newOrigin = Math.round(newCenter - ((widthInPixels / 2) * newLocationScale)); setOrigin(newOrigin); } } recordHistory(); // This is a hack, this is not a drag event but is a "jump" DragEventManager.getInstance().dragStopped(); } public void recordHistory() { IGV.getInstance().getSession().getHistory().push(getFormattedLocusString(), zoom); } private void jumpToChromosomeForGenomeLocation(double locationMB) { double startMB = 0; for (String chr : getGenome().getChromosomeNames()) { double endMB = startMB + getGenome().getChromosome(chr).getLength() / 1000.0; if ((locationMB > startMB) && (locationMB <= endMB)) { // this.jumpTo(chr, -1, -1); this.setChromosomeName(chr); break; } startMB = endMB; } } public void shiftOriginPixels(double delta) { double shiftBP = delta * getScale(); setOrigin(origin + shiftBP); } public void snapToGrid() { setOrigin(Math.round(origin)); } public void centerOnLocation(String chr, double chrLocation) { if (!chrName.equals(chr)) { chrName = chr; computeMaxZoom(); if (zoom > maxZoom) { zoomTo(maxZoom); } } double windowWidth = (widthInPixels * getScale()) / 2; setOrigin(Math.round(chrLocation - windowWidth)); } public void centerOnLocation(double chrLocation) { double windowWidth = (widthInPixels * getScale()) / 2; setOrigin(Math.round(chrLocation - windowWidth)); recordHistory(); } public boolean windowAtEnd() { double windowLengthBP = widthInPixels * getScale(); return origin + windowLengthBP + 1 > getChromosomeLength(); } /* Keep origin within data range */ /** * Method description * * @param position */ public void setOrigin(double position) { int windowLengthBP = (int) (widthInPixels * getScale()); double newOrigin = origin; if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED)) { newOrigin = Math.max(-1000, Math.min(position, getChromosomeLength() + 1000 - windowLengthBP)); } else { newOrigin = Math.max(0, Math.min(position, getChromosomeLength() - windowLengthBP)); } double delta = newOrigin - origin; origin = newOrigin; // If zoomed in sufficiently track the center position //if (locationScale < 10) { // IGV.getInstance().setStatusBarMessage(chrName + ":" + ((int) getCenter() + 1)); // Repaint IGV.getInstance().repaintDataAndHeaderPanels(); IGV.getInstance().repaintStatusAndZoomSlider(); } public void jumpTo(String chr, int start, int end) { Genome genome = getGenome(); if (chr != null) { if (genome.getChromosome(chr) == null && !chr.contains(Globals.CHR_ALL)) { MessageUtils.showMessage(chr + " is not a valid chromosome."); return; } setChromosomeName(chr); } Chromosome chromosome = genome == null ? null : genome.getChromosome(chr); if (chromosome != null) { end = Math.min(chromosome.getLength(), end); } if (start >= 0) { imputeZoom(start, end); if (widthInPixels > 0) { setLocationScale(((double) (end - start)) / widthInPixels); } origin = start; } if (log.isDebugEnabled()) { log.debug("Data panel width = " + widthInPixels); log.debug("New start = " + (int) origin); log.debug("New end = " + (int) getEnd()); log.debug("New center = " + (int) getCenter()); log.debug("Scale = " + locationScale); } // Repaint IGV.getInstance().repaintDataAndHeaderPanels(); IGV.getInstance().repaintStatusAndZoomSlider(); } private void imputeZoom(double start, double end) { int z = (int) (Math.log(getChromosomeLength() / (end - start)) / Globals.log2) + 1; if (z != this.zoom) { zoom = Math.min(maxZoom, Math.max(minZoom, z)); nTiles = (int) Math.pow(2, zoom); maxPixel = getTilesTimesBinsPerTile(); } } protected Genome getGenome() { return IGV.getInstance().getGenomeManager().getCurrentGenome(); } public double getOrigin() { return origin; } public double getCenter() { return origin + getScale() * widthInPixels / 2; } public double getEnd() { return origin + getScale() * widthInPixels; } public int getZoom() { return zoom; } /** * Return the maximum zoom level * * @return */ public int getMaxZoom() { return maxZoom; } public int getAdjustedZoom() { return zoom - minZoom; } public double getMaxPixel() { return maxPixel; } public void setChrName(String name) { this.setChromosomeName(name); } /** * @param name * @param force * @ deprecated, replace with calls to setChrName(); */ public void setChromosomeName(String name, boolean force) { if ((chrName == null) || !name.equals(chrName) || force) { chrName = name; origin = 0; zoomTo(0); computeMaxZoom(); //dhmay: if there's a RegionNavigatorDialog around, need to update it. //Todo: Properly, there should be a way to register listeners to chromosome changes. if (RegionNavigatorDialog.getActiveInstance() != null) RegionNavigatorDialog.getActiveInstance().updateChromosomeDisplayed(); } } /** * @param name * @ deprecated, replace with calls to setChrName(); */ public void setChromosomeName(String name) { setChromosomeName(name, false); } public String getChrName() { return chrName; } // TODO -- this parameter shouldn't be stored here. Maybe in a specialized // layout manager? /** * Width in pixels */ public int getWidthInPixels() { return widthInPixels; } /** * Return the current locationScale in base pairs / pixel * * @return */ public double getScale() { if ((locationScale == 0) || !locationScaleValid || locationScale < 0) { computeLocationScale(); } return locationScale; } public void invalidateLocationScale() { //Thread.dumpStack(); locationScaleValid = false; } public void computeLocationScale() { Genome genome = getGenome(); if (genome != null) { if (setEnd > 0) { locationScale = (setEnd - origin) / widthInPixels; locationScaleValid = true; imputeZoom(origin, setEnd); } else { computeMinZoom(); double virtualPixelSize = getTilesTimesBinsPerTile(); double nPixel = Math.max(virtualPixelSize, widthInPixels); setLocationScale(((double) getChromosomeLength()) / nPixel); } } } /** * Compute the minimum zoom level for the data panel width. This is defined as the maximum * zoom level for which all data bins will fit in the window without loss of * data, i.e. the maximum zoom level for which nBins < nPixels. The number * of bins is defined as * nBins = 2^z * so minZoom is the value z such that nBins < dataPanelWidth */ private void computeMinZoom() { if (this.chrName.equals(Globals.CHR_ALL)) { minZoom = 0; } else { minZoom = Math.max(0, (int) (Math.log((widthInPixels / binsPerTile)) / Globals.log2)); if (zoom < minZoom) { zoom = minZoom; nTiles = (int) Math.pow(2, zoom); maxPixel = getTilesTimesBinsPerTile(); } } } /** * Return the chromosome position corresponding to the pixel index. The * pixel index is the pixel "position" translated by -origin. * * @param screenPosition * @return */ public double getChromosomePosition(int screenPosition) { return origin + getScale() * screenPosition; } /** * Return the screen position corresponding to the chromosomal position. * * @param chromosomePosition * @return */ public int getScreenPosition(double chromosomePosition) { return (int) ((chromosomePosition - origin) / getScale()); } public Chromosome getChromosome() { Genome genome = getGenome(); if (genome == null) { return null; } return genome.getChromosome(chrName); } public int getChromosomeLength() { Genome genome = getGenome(); if (genome == null) { return 1; } if (chrName.equals("All")) { // TODO -- remove the hardcoded unit divider ("1000") return (int) (genome.getLength() / 1000); // return genome.getLength(); } else { if (getChromosome() == null) { log.error("Null chromosome: " + chrName); if (genome == null || genome.getChromosomes().size() == 0) { return 1; } else { return genome.getChromosomes().iterator().next().getLength(); } } return getChromosome().getLength(); } } public double getTilesTimesBinsPerTile() { return (double) nTiles * (double) binsPerTile; } /** * Get the UCSC style locus string corresponding to the current view. THe UCSC * conventions are followed for coordinates, specifically the internal representation * is "zero" based (first base is numbered 0) but the display representation is * "one" based (first base is numbered 1). Consequently 1 is added to the * computed positions. * * @return */ public String getFormattedLocusString() { if (zoom == 0) { return getChrName(); } else { Range range = getCurrentRange(); return Locus.getFormattedLocusString(range.getChr(), range.getStart(), range.getEnd()); } } public Range getCurrentRange() { int start = 0; int end = widthInPixels; int startLoc = (int) getChromosomePosition(start) + 1; int endLoc = (int) getChromosomePosition(end); Range range = new Range(getChrName(), startLoc, endLoc); return range; } private void setLocationScale(double locationScale) { if (log.isDebugEnabled()) { log.debug("Set location scale: " + locationScale + " origin=" + origin); } this.locationScale = locationScale; locationScaleValid = true; } public void setInterval(Locus locus) { this.initialLocus = locus; setInterval(locus.getChr(), locus.getStart(), locus.getEnd()); } int setEnd = 0; public void setInterval(String chr, int start, int end) { this.chrName = chr; this.origin = start; if (widthInPixels > 0) { locationScale = (end - origin) / widthInPixels; locationScaleValid = true; imputeZoom(origin, end); } else { // Set end temporarily until scale can be calculated this.setEnd = end; } } public void reset() { setInterval(FrameManager.getLocus(name)); IGV.getInstance().repaintDataAndHeaderPanels(); } public String getName() { return name; } public Locus getInitialLocus() { return initialLocus; } public int getMinZoom() { return minZoom; } public static class Range { private String chr; private int start; private int end; public Range(String chr, int start, int end) { this.chr = chr; this.start = start; this.end = end; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return end; } public int getLength() { return end - start; } } }
package org.javarosa.polishforms; import java.util.Enumeration; import org.javarosa.clforms.api.Constants; import org.javarosa.clforms.api.Prompt; import de.enough.polish.ui.ChoiceGroup; import de.enough.polish.ui.Item; import de.enough.polish.ui.StringItem; import de.enough.polish.ui.StyleSheet; import de.enough.polish.ui.TextField; /** * DisplayFrames are a UI component used to interact with Prompts. * * The frame will determine the proper UI component to use for a Prompt, and set return values appropriately. * * @author ctsims * */ public class DisplayFrame { private Prompt thePrompt; private Item theWidget; private StringItem questiontext; private StringItem questionResponse; private Item[] displayedItems; /** * Creates a Display frame for the given prompt * @param thePrompt The prompt to be displayed */ public DisplayFrame(Prompt thePrompt) { this.thePrompt = thePrompt; //#style questiontext questiontext = new StringItem(null,thePrompt.getLongText()); loadWidget(); } /** * Selects the proper Control to use for the given input type of the Prompt */ private void loadWidget() { Enumeration itr; switch(thePrompt.getFormControlType()) { case Constants.INPUT: //#style textBox TextField inputBox = new TextField("","",30,TextField.ANY); theWidget = inputBox; break; case Constants.TEXTAREA: //#style textBox TextField textArea = new TextField("","",15,TextField.ANY); theWidget = textArea; break; case Constants.TEXTBOX: //#style textBox TextField textBox = new TextField("","",50,TextField.ANY); theWidget = textBox; break; case Constants.SELECT1: ChoiceGroup choiceGroup = new ChoiceGroup("", ChoiceGroup.EXCLUSIVE); itr = thePrompt.getSelectMap().keys(); while (itr.hasMoreElements()) { String label = (String) itr.nextElement(); //#style choiceItem choiceGroup.append(label, null); } theWidget = choiceGroup; break; case Constants.SELECT: ChoiceGroup multipleGroup = new ChoiceGroup("", ChoiceGroup.MULTIPLE); itr = thePrompt.getSelectMap().keys(); while (itr.hasMoreElements()) { String label = (String) itr.nextElement(); //#style choiceItem multipleGroup.append(label, null); } theWidget = multipleGroup; break; default: System.out.println("Unhandled Widget type: " + thePrompt.getFormControlType()); break; } } /** * Evaluates a response based on the input type, and sets the Value of the Prompt */ public void evaluateResponse() { switch(thePrompt.getFormControlType()) { case Constants.INPUT: thePrompt.setValue(((StringItem)theWidget).getText()); break; case Constants.TEXTAREA: thePrompt.setValue(((StringItem)theWidget).getText()); break; case Constants.TEXTBOX: thePrompt.setValue(((StringItem)theWidget).getText()); break; case Constants.SELECT1: ChoiceGroup singleWidget = (ChoiceGroup)theWidget; int index = singleWidget.getSelectedIndex(); thePrompt.setSelectedIndex(index); thePrompt.setValue(singleWidget.getItem(index).getText()); break; case Constants.SELECT: ChoiceGroup multiWidget = (ChoiceGroup)theWidget; int numItems = multiWidget.getItems().length; int numSelectedItems = 0; int[] selectedIndicies = new int[numItems]; for(int i = 0 ; i < multiWidget.getItems().length ; i++) { if(multiWidget.isSelected(i)) { selectedIndicies[numSelectedItems] = i; numSelectedItems++; } } int[] questionValue = new int[numSelectedItems]; for(int i = 0 ; i < numSelectedItems ; i++) { questionValue[i] = selectedIndicies[i]; } thePrompt.setValue(questionValue); break; } } /** * Draws the Large Version of the frame onto a Screen * * @param target the Screen to which the Frame will be Added */ public void drawLargeFormOnScreen(ChatScreen target) { //#style questiontext questiontext = new StringItem(null,questiontext.getText()); target.append(questiontext); target.append(theWidget); displayedItems = new Item[] {questiontext,theWidget}; target.focus(theWidget); } /** * Draws the Small (read only) Version of the frame onto a Screen * * @param target the Screen to which the Frame will be Added */ public void drawSmallFormOnScreen(ChatScreen target) { //#style oldprompttext questiontext = new StringItem(null,questiontext.getText()); target.append(questiontext); //#style valueText questionResponse = new StringItem(null,questionValueToString(thePrompt)); target.append(questionResponse); displayedItems = new Item[] {questiontext,questionResponse}; } /** * Removes any of the Frame's Items from a given Screen * * @param target The screen from which the items will be removed */ public void removeFromScreen(ChatScreen target) { for(int i = 0 ; i < displayedItems.length; i++) { target.removeItem(displayedItems[i]); } } private String questionValueToString(Prompt thePrompt) { if(thePrompt.getFormControlType() == Constants.TEXTAREA || thePrompt.getFormControlType() == Constants.TEXTBOX || thePrompt.getFormControlType() == Constants.INPUT) { return thePrompt.getValue().toString(); } else if(thePrompt.getFormControlType() == Constants.SELECT1) { System.out.println(thePrompt.getValue()); return thePrompt.getValue().toString(); } else if(thePrompt.getFormControlType() == Constants.SELECT) { System.out.println(thePrompt.getValue()); String returnString = ""; int[] selectedIndicies = (int[])thePrompt.getValue(); for(int i = 0 ; i < selectedIndicies.length ; i++) { returnString = returnString + thePrompt.getSelectMap().elementAt(selectedIndicies[i]) + ", "; } return returnString.substring(0,returnString.length() - 2); } else { return thePrompt.getValue().toString(); } } /** * Identifies whether a given Item is auto-playable, IE "Select" need not be pressed to set the value for that question. * @param item The item that will be identified for autoplayability * @return True if the item can set its value without being explicitly selected. False otherwise */ public boolean autoPlayItem(Item item) { if(thePrompt.getFormControlType() == Constants.SELECT) { return false; } else { return true; } } }
package org.nschmidt.ldparteditor.data; import java.math.BigDecimal; import java.text.DecimalFormatSymbols; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.MyLanguage; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.opengl.GLMatrixStack; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer20; /** * @author nils * */ public final class GData3 extends GData { public final boolean isTriangle; public final int colourNumber; public final float r; public final float g; public final float b; public final float a; public final float x1; public final float y1; public final float z1; public final float x2; public final float y2; public final float z2; public final float x3; public final float y3; public final float z3; final BigDecimal X1; final BigDecimal Y1; final BigDecimal Z1; final BigDecimal X2; final BigDecimal Y2; final BigDecimal Z2; final BigDecimal X3; final BigDecimal Y3; final BigDecimal Z3; public final float xn; public final float yn; public final float zn; public final GData1 parent; public GData3(final int colourNumber, float r, float g, float b, float a, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, GData1 parent, DatFile datFile, boolean isTriangle) { this.isTriangle = isTriangle; this.colourNumber = colourNumber; this.r = r; this.g = g; this.b = b; this.a = a; this.x1 = x1 * 1000f; this.y1 = y1 * 1000f; this.z1 = z1 * 1000f; this.x2 = x2 * 1000f; this.y2 = y2 * 1000f; this.z2 = z2 * 1000f; this.x3 = x3 * 1000f; this.y3 = y3 * 1000f; this.z3 = z3 * 1000f; this.xn = (y3 - y1) * (z2 - z1) - (z3 - z1) * (y2 - y1); this.yn = (z3 - z1) * (x2 - x1) - (x3 - x1) * (z2 - z1); this.zn = (x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1); this.parent = parent; datFile.getVertexManager().add(this); this.X1 = new BigDecimal(x1); this.Y1 = new BigDecimal(y1); this.Z1 = new BigDecimal(z1); this.X2 = new BigDecimal(x2); this.Y2 = new BigDecimal(y2); this.Z2 = new BigDecimal(z2); this.X3 = new BigDecimal(x3); this.Y3 = new BigDecimal(y3); this.Z3 = new BigDecimal(z3); } public GData3(final int colourNumber, float r, float g, float b, float a, BigDecimal x1, BigDecimal y1, BigDecimal z1, BigDecimal x2, BigDecimal y2, BigDecimal z2, BigDecimal x3, BigDecimal y3, BigDecimal z3, GData1 parent, DatFile datFile, boolean isTriangle) { this.isTriangle = isTriangle; this.colourNumber = colourNumber; this.r = r; this.g = g; this.b = b; this.a = a; final float tx1 = x1.floatValue(); final float ty1 = y1.floatValue(); final float tz1 = z1.floatValue(); final float tx2 = x2.floatValue(); final float ty2 = y2.floatValue(); final float tz2 = z2.floatValue(); final float tx3 = x3.floatValue(); final float ty3 = y3.floatValue(); final float tz3 = z3.floatValue(); this.xn = (ty3 - ty1) * (tz2 - tz1) - (tz3 - tz1) * (ty2 - ty1); this.yn = (tz3 - tz1) * (tx2 - tx1) - (tx3 - tx1) * (tz2 - tz1); this.zn = (tx3 - tx1) * (ty2 - ty1) - (ty3 - ty1) * (tx2 - tx1); this.X1 = x1; this.Y1 = y1; this.Z1 = z1; this.X2 = x2; this.Y2 = y2; this.Z2 = z2; this.X3 = x3; this.Y3 = y3; this.Z3 = z3; this.x1 = X1.floatValue() * 1000f; this.y1 = Y1.floatValue() * 1000f; this.z1 = Z1.floatValue() * 1000f; this.x2 = X2.floatValue() * 1000f; this.y2 = Y2.floatValue() * 1000f; this.z2 = Z2.floatValue() * 1000f; this.x3 = X3.floatValue() * 1000f; this.y3 = Y3.floatValue() * 1000f; this.z3 = Z3.floatValue() * 1000f; this.parent = parent; datFile.getVertexManager().add(this); } public GData3(final int colourNumber, float r, float g, float b, float a, Vertex v1, Vertex v2, Vertex v3, GData1 parent, DatFile datFile, boolean isTriangle) { this.isTriangle = isTriangle; this.colourNumber = colourNumber; this.r = r; this.g = g; this.b = b; this.a = a; this.x1 = v1.x; this.y1 = v1.y; this.z1 = v1.z; this.x2 = v2.x; this.y2 = v2.y; this.z2 = v2.z; this.x3 = v3.x; this.y3 = v3.y; this.z3 = v3.z; this.X1 = v1.X; this.Y1 = v1.Y; this.Z1 = v1.Z; this.X2 = v2.X; this.Y2 = v2.Y; this.Z2 = v2.Z; this.X3 = v3.X; this.Y3 = v3.Y; this.Z3 = v3.Z; this.xn = (y3 - y1) * (z2 - z1) - (z3 - z1) * (y2 - y1); this.yn = (z3 - z1) * (x2 - x1) - (x3 - x1) * (z2 - z1); this.zn = (x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1); this.parent = parent; datFile.getVertexManager().add(this); } /** * FOR CSG, TEXMAP AND Cut, Copy, Paste ONLY! * * @param v1 * @param v2 * @param v3 * @param parent * @param c * @param isTriangle */ public GData3(Vertex v1, Vertex v2, Vertex v3, GData1 parent, GColour c, boolean isTriangle) { this.isTriangle = isTriangle; this.colourNumber = c.getColourNumber(); this.r = c.getR(); this.g = c.getG(); this.b = c.getB(); this.a = c.getA(); this.x1 = v1.x; this.y1 = v1.y; this.z1 = v1.z; this.x2 = v2.x; this.y2 = v2.y; this.z2 = v2.z; this.x3 = v3.x; this.y3 = v3.y; this.z3 = v3.z; this.X1 = v1.X; this.Y1 = v1.Y; this.Z1 = v1.Z; this.X2 = v2.X; this.Y2 = v2.Y; this.Z2 = v2.Z; this.X3 = v3.X; this.Y3 = v3.Y; this.Z3 = v3.Z; this.xn = (y3 - y1) * (z2 - z1) - (z3 - z1) * (y2 - y1); this.yn = (z3 - z1) * (x2 - x1) - (x3 - x1) * (z2 - z1); this.zn = (x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1); this.parent = parent; } public GData3(final int colourNumber, float r, float g, float b, float a, BigDecimal x1, BigDecimal y1, BigDecimal z1, BigDecimal x2, BigDecimal y2, BigDecimal z2, BigDecimal x3, BigDecimal y3, BigDecimal z3, float x12, float y12, float z12, float x22, float y22, float z22, float x32, float y32, float z32, float xn, float yn, float zn, GData1 parent, DatFile datFile, boolean isTriangle) { this.isTriangle = isTriangle; this.colourNumber = colourNumber; this.r = r; this.g = g; this.b = b; this.a = a; this.X1 = x1; this.Y1 = y1; this.Z1 = z1; this.X2 = x2; this.Y2 = y2; this.Z2 = z2; this.X3 = x3; this.Y3 = y3; this.Z3 = z3; this.x1 = x12; this.y1 = y12; this.z1 = z12; this.x2 = x22; this.y2 = y22; this.z2 = z22; this.x3 = x32; this.y3 = y32; this.z3 = z32; this.xn = xn; this.yn = yn; this.zn = zn; this.parent = parent; datFile.getVertexManager().add(this); } public Vector4f getNormal() { Vector4f vn = new Vector4f(xn, yn, zn, 0f); vn.normalise(); vn.setW(1f); return vn; } @Override public void drawGL20(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } GL11.glBegin(GL11.GL_TRIANGLES); if (GData.globalNegativeDeterminant) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } GL11.glEnd(); } @Override public void drawGL20_RandomColours(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } final float r = MathHelper.randomFloat(ID, 0); final float g = MathHelper.randomFloat(ID, 1); final float b = MathHelper.randomFloat(ID, 2); GL11.glBegin(GL11.GL_TRIANGLES); if (GData.globalNegativeDeterminant) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } GL11.glEnd(); } @Override public void drawGL20_BFC(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } GL11.glBegin(GL11.GL_TRIANGLES); switch (GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } else { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } } GL11.glEnd(); } @Override public void drawGL20_BFCuncertified(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; GL11.glBegin(GL11.GL_TRIANGLES); if (GData.globalNegativeDeterminant) { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } GL11.glEnd(); } @Override public void drawGL20_BFC_backOnly(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } GL11.glBegin(GL11.GL_TRIANGLES); switch (GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glColor4f(View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } } GL11.glEnd(); } @Override public void drawGL20_BFC_Colour(Composite3D c3d) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } GL11.glBegin(GL11.GL_TRIANGLES); switch (a < 1f ? BFC.NOCERTIFY : GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); } else { GL11.glColor4f(r, g, b, a); GL11.glNormal3f(xn, yn, zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x3, y3, z3); GL11.glNormal3f(-xn, -yn, -zn); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glVertex3f(x2, y2, z2); } } } GL11.glEnd(); } private void drawBFC_Colour2(Composite3D c3d, float r, float g, float b, float a, int useCubeMap) { if (!visible) return; if (a < 1f && c3d.isDrawingSolidMaterials() || !c3d.isDrawingSolidMaterials() && a == 1f) return; if (!isTriangle) { drawProtractor_GL20(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } switch (a < 1f ? BFC.NOCERTIFY : GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); GL11.glNormal3f(xn, yn, zn); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } } } } @Override public void drawGL20_BFC_Textured(Composite3D c3d) { if (GData.globalDrawObjects) { GColour c = View.getLDConfigColour(View.getLDConfigIndex(r, g, b)); GColourType ct = c.getType(); boolean hasColourType = ct != null; boolean matLight = true; int useCubeMap = 0; if (hasColourType) { switch (ct.type()) { case CHROME: useCubeMap = 1; break; case MATTE_METALLIC: useCubeMap = 2; break; case METAL: useCubeMap = 3; break; case RUBBER: useCubeMap = 2; matLight = false; break; default: break; } } float r = this.r; float g = this.g; float b = this.b; float a = this.a; if (hasColourType && useCubeMap < 1) { a = 0.99f; } final OpenGLRenderer20 ren = (OpenGLRenderer20) c3d.getRenderer(); if (GData.globalTextureStack.isEmpty()) { GL20.glUniform1f(ren.getAlphaSwitchLoc(), c3d.isDrawingSolidMaterials() ? 1f : 0f); // Draw transparent GL20.glUniform1f(ren.getNormalSwitchLoc(), GData.globalNegativeDeterminant ^ GData.globalInvertNext ? 1f : 0f); GL20.glUniform1f(ren.getNoTextureSwitch(), 1f); GL20.glUniform1f(ren.getNoLightSwitch(), c3d.isLightOn() && matLight ? 0f : 1f); GL20.glUniform1f(ren.getCubeMapSwitch(), useCubeMap); switch (GData.accumClip) { case 0: drawBFC_Colour2(c3d, r, g, b, a, useCubeMap); break; default: byte tmp = GData.localWinding; GData.localWinding = BFC.NOCERTIFY; drawBFC_Colour2(c3d, r, g, b, a, useCubeMap); GData.localWinding = tmp; break; } } else { // Draw the textured face if (!visible) return; GTexture tex = GData.globalTextureStack.peek(); tex.bind(c3d.isDrawingSolidMaterials(), GData.globalNegativeDeterminant ^ GData.globalInvertNext, c3d.isLightOn() && matLight, ren, useCubeMap); float[] uv; switch (a < 1f || GData.accumClip > 0 ? BFC.NOCERTIFY : GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); } } else { if (GData.globalInvertNext) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, this); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, this); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, null); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, null); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glEnd(); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, null); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, null); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glEnd(); } else { GL11.glColor4f(r, g, b, a); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, null); tex.calcUVcoords2(x2, y2, z2, parent); tex.calcUVcoords3(x3, y3, z3, parent); uv = tex.getUVcoords(true, null); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, false, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, false, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, false, this, useCubeMap); GL11.glEnd(); GL11.glBegin(GL11.GL_TRIANGLES); tex.calcUVcoords1(x1, y1, z1, parent, null); tex.calcUVcoords2(x3, y3, z3, parent); tex.calcUVcoords3(x2, y2, z2, parent); uv = tex.getUVcoords(true, null); GL11.glTexCoord2f(uv[0], uv[1]); c3d.getVertexManager().setVertexAndNormal(x1, y1, z1, true, this, useCubeMap); GL11.glTexCoord2f(uv[2], uv[3]); c3d.getVertexManager().setVertexAndNormal(x3, y3, z3, true, this, useCubeMap); GL11.glTexCoord2f(uv[4], uv[5]); c3d.getVertexManager().setVertexAndNormal(x2, y2, z2, true, this, useCubeMap); GL11.glEnd(); } } } } if (GData.globalFoundTEXMAPNEXT) { GData.globalFoundTEXMAPStack.pop(); GData.globalTextureStack.pop(); GData.globalFoundTEXMAPStack.push(false); GData.globalFoundTEXMAPNEXT = false; } } @Override public void drawGL20_WhileAddCondlines(Composite3D c3d) { drawGL20_BFC(c3d); } @Override public int type() { return 3; } @Override String getNiceString() { if (text != null) return text; StringBuilder lineBuilder = new StringBuilder(); if (isTriangle) { lineBuilder.append(3); lineBuilder.append(" "); //$NON-NLS-1$ } else { lineBuilder.append("0 !LPE PROTRACTOR "); //$NON-NLS-1$ } if (colourNumber == -1) { lineBuilder.append("0x2"); //$NON-NLS-1$ lineBuilder.append(MathHelper.toHex((int) (255f * r)).toUpperCase()); lineBuilder.append(MathHelper.toHex((int) (255f * g)).toUpperCase()); lineBuilder.append(MathHelper.toHex((int) (255f * b)).toUpperCase()); } else { lineBuilder.append(colourNumber); } lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X3)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y3)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z3)); text = lineBuilder.toString(); return text; } @Override public String inlinedString(byte bfc, GColour colour) { return getNiceString(); } @Override public String transformAndColourReplace(String colour, Matrix matrix) { BigDecimal[] v1; BigDecimal[] v2; BigDecimal[] v3; if (X1 == null) { v1 = matrix.transform(new BigDecimal(x1 / 1000f), new BigDecimal(y1 / 1000f), new BigDecimal(z1 / 1000f)); v2 = matrix.transform(new BigDecimal(x2 / 1000f), new BigDecimal(y2 / 1000f), new BigDecimal(z2 / 1000f)); v3 = matrix.transform(new BigDecimal(x3 / 1000f), new BigDecimal(y3 / 1000f), new BigDecimal(z3 / 1000f)); } else { v1 = matrix.transform(X1, Y1, Z1); v2 = matrix.transform(X2, Y2, Z2); v3 = matrix.transform(X3, Y3, Z3); } StringBuilder lineBuilder = new StringBuilder(); if (isTriangle) { lineBuilder.append(3); lineBuilder.append(" "); //$NON-NLS-1$ } else { lineBuilder.append("0 !LPE PROTRACTOR "); //$NON-NLS-1$ } StringBuilder colourBuilder = new StringBuilder(); if (colourNumber == -1) { colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * r)).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * g)).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * b)).toUpperCase()); } else { colourBuilder.append(colourNumber); } String col = colourBuilder.toString(); if (col.equals(colour)) col = "16"; //$NON-NLS-1$ lineBuilder.append(col); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v1[0])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v1[1])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v1[2])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v2[0])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v2[1])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v2[2])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v3[0])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v3[1])); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(v3[2])); return lineBuilder.toString(); } @Override public void getBFCorientationMap(HashMap<GData, Byte> map) { switch (GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { map.put(this, BFC.CCW); } else { map.put(this, BFC.CW); } } else { if (GData.globalInvertNext) { map.put(this, BFC.CW); } else { map.put(this, BFC.CCW); } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { map.put(this, BFC.CW); } else { map.put(this, BFC.CCW); } } else { if (GData.globalInvertNext) { map.put(this, BFC.CCW); } else { map.put(this, BFC.CW); } } break; case BFC.NOCERTIFY: // map.put(this, BFC.NOCERTIFY); break; } } @Override public void getBFCorientationMapNOCERTIFY(HashMap<GData, Byte> map) { // map.put(this, BFC.NOCERTIFY); } @Override public void getBFCorientationMapNOCLIP(HashMap<GData, Byte> map) { map.put(this, BFC.NOCLIP); } @Override public void getVertexNormalMap(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) { if (state.globalDrawObjects) { Vertex[] verts = vm.getTriangles_NOCLONE().get(this); if (verts == null) { verts = new Vertex[3]; Vector4f v1 = new Vector4f(x1, y1, z1, 1f); Vector4f v2 = new Vector4f(x2, y2, z2, 1f); Vector4f v3 = new Vector4f(x3, y3, z3, 1f); Matrix4f.transform(this.parent.productMatrix, v1, v1); Matrix4f.transform(this.parent.productMatrix, v2, v2); Matrix4f.transform(this.parent.productMatrix, v3, v3); verts[0] = new Vertex(v1.x , v1.y , v1.z, true); verts[1] = new Vertex(v2.x , v2.y , v2.z, true); verts[2] = new Vertex(v3.x , v3.y , v3.z, true); } float xn = (verts[2].y - verts[0].y) * (verts[1].z - verts[0].z) - (verts[2].z - verts[0].z) * (verts[1].y - verts[0].y); float yn = (verts[2].z - verts[0].z) * (verts[1].x - verts[0].x) - (verts[2].x - verts[0].x) * (verts[1].z - verts[0].z); float zn = (verts[2].x - verts[0].x) * (verts[1].y - verts[0].y) - (verts[2].y - verts[0].y) * (verts[1].x - verts[0].x); final float length = (float) Math.sqrt(xn * xn + yn * yn + zn *zn); if (length > 0) { xn = xn / length; yn = yn / length; zn = zn / length; } for (Vertex vertex : verts) { float[] result = new float[3]; switch (state.localWinding) { case BFC.NOCLIP: result[0] = xn; result[1] = yn; result[2] = zn; break; case BFC.CCW: if (state.globalInvertNext) { if (state.globalNegativeDeterminant) { result[0] = -xn; result[1] = -yn; result[2] = -zn; } else { result[0] = xn; result[1] = yn; result[2] = zn; } } else { if (state.globalNegativeDeterminant) { result[0] = -xn; result[1] = -yn; result[2] = -zn; } else { result[0] = xn; result[1] = yn; result[2] = zn; } } break; case BFC.CW: if (state.globalInvertNext) { if (state.globalNegativeDeterminant) { result[0] = -xn; result[1] = -yn; result[2] = -zn; } else { result[0] = xn; result[1] = yn; result[2] = zn; } } else { if (state.globalNegativeDeterminant) { result[0] = -xn; result[1] = -yn; result[2] = -zn; } else { result[0] = xn; result[1] = yn; result[2] = zn; } } break; case BFC.NOCERTIFY: break; } if (state.globalInvertNext) { dataLinkedToNormalCACHE.put(this, new float[]{-result[0], -result[1], -result[2]}); } else { dataLinkedToNormalCACHE.put(this, new float[]{result[0], result[1], result[2]}); } if (!vertexLinkedToNormalCACHE.containsKey(vertex)) { vertexLinkedToNormalCACHE.put(vertex, result); } else { float[] n = vertexLinkedToNormalCACHE.get(vertex); n[0] = n[0] + result[0]; n[1] = n[1] + result[1]; n[2] = n[2] + result[2]; } } } if (state.globalFoundTEXMAPNEXT) { state.globalFoundTEXMAPStack.pop(); state.globalTextureStack.pop(); state.globalFoundTEXMAPStack.push(false); state.globalFoundTEXMAPNEXT = false; } } @Override public void getVertexNormalMapNOCERTIFY(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) {} @Override public void getVertexNormalMapNOCLIP(GDataState state, ThreadsafeTreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, ThreadsafeHashMap<GData, float[]> dataLinkedToNormalCACHE, VM00Base vm) { getVertexNormalMap(state, vertexLinkedToNormalCACHE, dataLinkedToNormalCACHE, vm); } public boolean isCollinear() { Vector3d vertexA = new Vector3d(X1, Y1, Z1); Vector3d vertexB = new Vector3d(X2, Y2, Z2); Vector3d vertexC = new Vector3d(X3, Y3, Z3); Vector3d vertexA2 = new Vector3d(); Vector3d vertexB2 = new Vector3d(); Vector3d.sub(vertexA, vertexC, vertexA2); Vector3d.sub(vertexB, vertexC, vertexB2); return Vector3d.angle(vertexA2, vertexB2) < Threshold.collinear_angle_minimum; } public String colourReplace(String col) { StringBuilder lineBuilder = new StringBuilder(); if (isTriangle) { lineBuilder.append(3); lineBuilder.append(" "); //$NON-NLS-1$ } else { lineBuilder.append("0 !LPE PROTRACTOR "); //$NON-NLS-1$ } lineBuilder.append(col); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z1)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z2)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(X3)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Y3)); lineBuilder.append(" "); //$NON-NLS-1$ lineBuilder.append(bigDecimalToString(Z3)); return lineBuilder.toString(); } public void drawProtractor_GL20(Composite3D c3d, BigDecimal x1c, BigDecimal y1c, BigDecimal z1c, BigDecimal x2c, BigDecimal y2c, BigDecimal z2c, BigDecimal x3c, BigDecimal y3c, BigDecimal z3c) { final java.text.DecimalFormat NUMBER_FORMAT2F = new java.text.DecimalFormat(View.NUMBER_FORMAT2F, new DecimalFormatSymbols(MyLanguage.LOCALE)); final OpenGLRenderer20 renderer = (OpenGLRenderer20) c3d.getRenderer(); final float zoom = 1f / c3d.getZoom(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glLineWidth(View.lineWidthGL[0]); GL11.glColor4f(r, g, b, 1f); GL11.glBegin(GL11.GL_LINES); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x2, y2, z2); GL11.glVertex3f(x1, y1, z1); GL11.glVertex3f(x3, y3, z3); GL11.glEnd(); final Vector4f textOrigin = new Vector4f(x1, y1, z1, 1f); Matrix4f.transform(c3d.getRotation(), textOrigin, textOrigin); Vector3d va = new Vector3d(x1c, y1c, z1c); Vector3d vb = new Vector3d(x2c, y2c, z2c); Vector3d vc = new Vector3d(x3c, y3c, z3c); vb = Vector3d.sub(va, vb); vc = Vector3d.sub(va, vc); double angle = Vector3d.angle(vb, vc); BigDecimal ang = new BigDecimal(angle); String angle_s = NUMBER_FORMAT2F.format(ang) + "°"; //$NON-NLS-1$ float sx1 = x1 + (x2 - x1) * .2f; float sy1 = y1 + (y2 - y1) * .2f; float sz1 = z1 + (z2 - z1) * .2f; float sx2 = x1 + (x3 - x1) * .2f; float sy2 = y1 + (y3 - y1) * .2f; float sz2 = z1 + (z3 - z1) * .2f; float sx1t = x1 + (x2 - x1) * .25f; float sy1t = y1 + (y2 - y1) * .25f; float sz1t = z1 + (z2 - z1) * .25f; float sx2t = x1 + (x3 - x1) * .25f; float sy2t = y1 + (y3 - y1) * .25f; float sz2t = z1 + (z3 - z1) * .25f; float sx1tt = x1 + (x2 - x1) * .24f; float sy1tt = y1 + (y2 - y1) * .24f; float sz1tt = z1 + (z2 - z1) * .24f; float sx2tt = x1 + (x3 - x1) * .24f; float sy2tt = y1 + (y3 - y1) * .24f; float sz2tt = z1 + (z3 - z1) * .24f; float sx3 = sx1t * .5f + sx2t * .5f; float sy3 = sy1t * .5f + sy2t * .5f; float sz3 = sz1t * .5f + sz2t * .5f; float sx3r = sx1tt * .7f + sx2tt * .3f; float sy3r = sy1tt * .7f + sy2tt * .3f; float sz3r = sz1tt * .7f + sz2tt * .3f; float sx3l = sx1tt * .3f + sx2tt * .7f; float sy3l = sy1tt * .3f + sy2tt * .7f; float sz3l = sz1tt * .3f + sz2tt * .7f; GL11.glBegin(GL11.GL_LINES); GL11.glVertex3f(sx1, sy1, sz1); GL11.glVertex3f(sx3r, sy3r, sz3r); GL11.glVertex3f(sx3r, sy3r, sz3r); GL11.glVertex3f(sx3, sy3, sz3); GL11.glVertex3f(sx3, sy3, sz3); GL11.glVertex3f(sx3l, sy3l, sz3l); GL11.glVertex3f(sx3l, sy3l, sz3l); GL11.glVertex3f(sx2, sy2, sz2); GL11.glEnd(); GL11.glPushMatrix(); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glMultMatrixf(renderer.getRotationInverse()); PGData3.beginDrawText(); GL11.glColor4f(r, g, b, 1f); drawNumber(angle_s, textOrigin.x, textOrigin.y, textOrigin.z, zoom); PGData3.endDrawText(); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glPopMatrix(); GL11.glEnable(GL11.GL_LIGHTING); } private void drawNumber(String number, float ox, float oy, float oz, float zoom) { final int length = number.length(); float ox2 = 0f; for (int i = 0; i < length; i++) { Set<PGData3> tris = new HashSet<PGData3>(); final char c = number.charAt(i); switch (c) { case '0': tris = View.D0; break; case '1': tris = View.D1; break; case '2': tris = View.D2; break; case '3': tris = View.D3; break; case '4': tris = View.D4; break; case '5': tris = View.D5; break; case '6': tris = View.D6; break; case '7': tris = View.D7; break; case '8': tris = View.D8; break; case '9': tris = View.D9; break; case '.': tris = View.Dd; break; case ',': tris = View.Dc; break; case '°': tris = View.Dg; break; case '-': tris = View.DM; break; default: break; } for (PGData3 tri : tris) { tri.drawText(ox + ox2, oy, oz + 100000f, zoom); } ox2 = ox2 - .01f * zoom; } } public double getProtractorAngle() { Vector3d va = new Vector3d(X1, Y1, Z1); Vector3d vb = new Vector3d(X2, Y2, Z2); Vector3d vc = new Vector3d(X3, Y3, Z3); vb = Vector3d.sub(va, vb); vc = Vector3d.sub(va, vc); return Vector3d.angle(vb, vc); } public BigDecimal getProtractorLength() { Vector3d va = new Vector3d(X1, Y1, Z1); Vector3d vc = new Vector3d(X3, Y3, Z3); vc = Vector3d.sub(va, vc); return vc.length(); } @Override public void drawGL33(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { if (!visible) return; if (a < 1f ^ drawSolidMaterials) return; if (!isTriangle) { // drawProtractor_GL33(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } final String idStr; int vao; int vbo; { sb.setLength(0); sb.append(ID); sb.append(GDataBFC.globalNegativeDeterminant ^ GDataBFC.globalInvertNext); sb.append(0); // Render mode sb.append(GDataBFC.localWinding); idStr = sb.toString(); } sourceID.remove(idStr); targetID.add(idStr); Integer[] objs = mapGLO.get(idStr); if (objs == null) { vao = -1; } else { vao = objs[0]; vbo = objs[1]; sourceVAO.remove(vao); sourceBUF.remove(vbo); targetVAO.add(vao); targetBUF.add(vbo); } if (vao != -1) { GL30.glBindVertexArray(vao); GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 6); GL30.glBindVertexArray(0); } else { float[] vertices; if (GData.globalNegativeDeterminant) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, r, g, b, a, x2, y2, z2, xn, yn, zn, r, g, b, a, x3, y3, z3, xn, yn, zn, r, g, b, a, x1, y1, z1, -xn, -yn, -zn, r, g, b, a, x3, y3, z3, -xn, -yn, -zn, r, g, b, a, x2, y2, z2, -xn, -yn, -zn, r, g, b, a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, r, g, b, a, x2, y2, z2, -xn, -yn, -zn, r, g, b, a, x3, y3, z3, -xn, -yn, -zn, r, g, b, a, x1, y1, z1, xn, yn, zn, r, g, b, a, x3, y3, z3, xn, yn, zn, r, g, b, a, x2, y2, z2, xn, yn, zn, r, g, b, a, }; } vao = GL30.glGenVertexArrays(); vbo = GL15.glGenBuffers(); targetVAO.add(vao); targetBUF.add(vbo); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); mapGLO.put(idStr, new Integer[]{vao, vbo}); } } @Override public void drawGL33_RandomColours(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { if (!visible) return; if (a < 1f ^ drawSolidMaterials) return; if (!isTriangle) { // drawProtractor_GL33(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } final String idStr; int vao; int vbo; { sb.setLength(0); sb.append(ID); sb.append(GDataBFC.globalNegativeDeterminant ^ GDataBFC.globalInvertNext); sb.append(1); // Render mode sb.append(GDataBFC.localWinding); idStr = sb.toString(); } sourceID.remove(idStr); targetID.add(idStr); Integer[] objs = mapGLO.get(idStr); if (objs == null) { vao = -1; } else { vao = objs[0]; vbo = objs[1]; sourceVAO.remove(vao); sourceBUF.remove(vbo); targetVAO.add(vao); targetBUF.add(vbo); } if (vao != -1) { GL30.glBindVertexArray(vao); GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 6); GL30.glBindVertexArray(0); } else { final float r = MathHelper.randomFloat(ID, 0); final float g = MathHelper.randomFloat(ID, 1); final float b = MathHelper.randomFloat(ID, 2); float[] vertices; if (GData.globalNegativeDeterminant) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, r, g, b, a, x2, y2, z2, xn, yn, zn, r, g, b, a, x3, y3, z3, xn, yn, zn, r, g, b, a, x1, y1, z1, -xn, -yn, -zn, r, g, b, a, x3, y3, z3, -xn, -yn, -zn, r, g, b, a, x2, y2, z2, -xn, -yn, -zn, r, g, b, a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, r, g, b, a, x2, y2, z2, -xn, -yn, -zn, r, g, b, a, x3, y3, z3, -xn, -yn, -zn, r, g, b, a, x1, y1, z1, xn, yn, zn, r, g, b, a, x3, y3, z3, xn, yn, zn, r, g, b, a, x2, y2, z2, xn, yn, zn, r, g, b, a, }; } vao = GL30.glGenVertexArrays(); vbo = GL15.glGenBuffers(); targetVAO.add(vao); targetBUF.add(vbo); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); mapGLO.put(idStr, new Integer[]{vao, vbo}); } } @Override public void drawGL33_BFC(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { if (!visible) return; if (a < 1f ^ drawSolidMaterials) return; if (!isTriangle) { // drawProtractor_GL33(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } final String idStr; int vao; int vbo; { sb.setLength(0); sb.append(ID); sb.append(GDataBFC.globalNegativeDeterminant ^ GDataBFC.globalInvertNext); sb.append(2); // Render mode sb.append(GDataBFC.localWinding); idStr = sb.toString(); } sourceID.remove(idStr); targetID.add(idStr); Integer[] objs = mapGLO.get(idStr); if (objs == null) { vao = -1; } else { vao = objs[0]; vbo = objs[1]; sourceVAO.remove(vao); sourceBUF.remove(vbo); targetVAO.add(vao); targetBUF.add(vbo); } if (vao != -1) { GL30.glBindVertexArray(vao); GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 6); GL30.glBindVertexArray(0); } else { float[] vertices; switch (GData.localWinding) { case BFC.CCW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } } else { if (GData.globalInvertNext) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } } break; case BFC.CW: if (GData.globalNegativeDeterminant) { if (GData.globalInvertNext) { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } } else { if (GData.globalInvertNext) { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_front_Colour_r[0], View.BFC_front_Colour_g[0], View.BFC_front_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_back__Colour_r[0], View.BFC_back__Colour_g[0], View.BFC_back__Colour_b[0], a, }; } } break; case BFC.NOCERTIFY: if (GData.globalNegativeDeterminant) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, }; } break; default: throw new AssertionError("There must be some winding info! GData.localWinding=" + GData.localWinding); //$NON-NLS-1$ } vao = GL30.glGenVertexArrays(); vbo = GL15.glGenBuffers(); targetVAO.add(vao); targetBUF.add(vbo); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); mapGLO.put(idStr, new Integer[]{vao, vbo}); } } @Override public void drawGL33_BFCuncertified(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { if (!visible) return; if (a < 1f ^ drawSolidMaterials) return; if (!isTriangle) { // drawProtractor_GL33(c3d, X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3); return; } final String idStr; int vao; int vbo; { sb.setLength(0); sb.append(ID); sb.append(GDataBFC.globalNegativeDeterminant ^ GDataBFC.globalInvertNext); sb.append(7); // Render mode sb.append(GDataBFC.localWinding); idStr = sb.toString(); } sourceID.remove(idStr); targetID.add(idStr); Integer[] objs = mapGLO.get(idStr); if (objs == null) { vao = -1; } else { vao = objs[0]; vbo = objs[1]; sourceVAO.remove(vao); sourceBUF.remove(vbo); targetVAO.add(vao); targetBUF.add(vbo); } if (vao != -1) { GL30.glBindVertexArray(vao); GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 6); GL30.glBindVertexArray(0); } else { float[] vertices; if (GData.globalNegativeDeterminant) { vertices = new float[]{ x1, y1, z1, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x1, y1, z1, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, }; } else { vertices = new float[]{ x1, y1, z1, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, -xn, -yn, -zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x1, y1, z1, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x3, y3, z3, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, x2, y2, z2, xn, yn, zn, View.BFC_uncertified_Colour_r[0], View.BFC_uncertified_Colour_g[0], View.BFC_uncertified_Colour_b[0], a, }; } vao = GL30.glGenVertexArrays(); vbo = GL15.glGenBuffers(); targetVAO.add(vao); targetBUF.add(vbo); GL30.glBindVertexArray(vao); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); GL20.glEnableVertexAttribArray(0); GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 0); GL20.glEnableVertexAttribArray(1); GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, 3 * 4); GL20.glEnableVertexAttribArray(2); GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT, false, (3 + 3 + 4) * 4, (3 + 3) * 4); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); mapGLO.put(idStr, new Integer[]{vao, vbo}); } } @Override public void drawGL33_BFC_backOnly(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { // TODO Auto-generated method stub } @Override public void drawGL33_BFC_Colour(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { // TODO Auto-generated method stub } @Override public void drawGL33_BFC_Textured(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { // TODO Auto-generated method stub } @Override public void drawGL33_WhileAddCondlines(Composite3D c3d, GLMatrixStack stack, boolean drawSolidMaterials, Set<Integer> sourceVAO, Set<Integer> targetVAO, Set<Integer> sourceBUF, Set<Integer> targetBUF, Set<String> sourceID, Set<String> targetID, Map<String, Integer[]> mapGLO) { drawGL33_BFC(c3d, stack, drawSolidMaterials, sourceVAO, targetVAO, sourceBUF, targetBUF, sourceID, targetID, mapGLO); } }
package org.obd.ws.application; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import org.obd.query.Shard; import org.obd.query.impl.AbstractSQLShard; import org.obd.query.impl.OBDSQLShard; import org.restlet.Application; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.Router; public class OBDApplication extends Application { public OBDApplication(Context context){ super(context); } public void connect() throws SQLException, ClassNotFoundException{ Shard obdsql = new OBDSQLShard(); try{ InputStream fis = this.getClass().getResourceAsStream("connectionInfo.properties"); Properties props = new Properties(); props.load(fis); String dbHost = (String)props.get("dbHost"); String uid = (String)props.get("uid"); String pwd = (String)props.get("pwd"); // String localDbHost = (String)props.get("localDbHost"); // String localUid = (String)props.get("localUid"); // String localPwd = (String)props.get("localPwd"); ((AbstractSQLShard)obdsql).connect(dbHost, uid, pwd); //((AbstractSQLShard)obdsql).connect(localDbHost, // localUid, localPwd); this.getContext().getAttributes().put("shard", obdsql); } catch(Exception e){ e.printStackTrace(); } } public Restlet createRoot() { try{ connect(); } catch(Exception e){ e.printStackTrace(); } final Router router = new Router(this.getContext()); // URL mappings // router.attachDefault(HelloWorldResource.class); router.attach("/term/search", org.obd.ws.resources.AutoCompleteResource.class); router.attach("/term/{termID}", org.obd.ws.resources.TermResource.class); router.attach("/phenotypes/summary/anatomy/{termID}", org.obd.ws.resources.AnatomyResource.class); router.attach("/phenotypes/anatomy/{termID}/taxa/{patoID}", org.obd.ws.resources.TaxaForAnatomyResource.class); router.attach("/phenotypes/anatomy/{termID}/genes/{patoID}", org.obd.ws.resources.GenesForAnatomyResource.class); router.attach("/phenotypes/summary/gene/{termID}", org.obd.ws.resources.GeneResource.class); return router; } }
package org.objectweb.asm.attrs; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.objectweb.asm.ByteVector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; public class StackMapFrame { public Label label; public List locals = new LinkedList(); public List stack = new LinkedList(); public int read( ClassReader cr, int off, char[] buf, int codeOff, Label[] labels) { int n = cr.readUnsignedShort( off); off += 2; if( labels[ n]==null) labels[ n] = new Label(); label = labels[ n]; off = readTypeInfo( cr, off, locals, labels, buf, cr.readUnsignedShort( codeOff+2)); // maxLocals off = readTypeInfo( cr, off, stack, labels, buf, cr.readUnsignedShort( codeOff)); // maxStack return off; } public void write( ClassWriter cw, int maxStack, int maxLocals, ByteVector bv) { bv.putShort( label.getOffset()); writeTypeInfo( bv, cw, locals, maxLocals); writeTypeInfo( bv, cw, stack, maxStack); } public void getLabels( Set labels) { labels.add( label); getTypeInfoLabels( labels, locals); getTypeInfoLabels( labels, stack); } private void getTypeInfoLabels( Set labels, List info) { for( Iterator it = info.iterator(); it.hasNext(); ) { StackMapTypeInfo typeInfo = ( StackMapTypeInfo) it.next(); if( typeInfo.getType()==StackMapTypeInfo.ITEM_Uninitialized) labels.add( typeInfo.getLabel()); } } private int readTypeInfo( ClassReader cr, int off, List info, Label[] labels, char[] buf, int max) { int n = 0; if( max>StackMapAttribute.MAX_SIZE) { n = cr.readInt( off); off += 4; } else { n = cr.readUnsignedShort( off); off += 2; } for( int j = 0; j<n; j++) { int itemType = cr.readUnsignedShort( off++) >> 8; StackMapTypeInfo typeInfo = StackMapTypeInfo.getTypeInfo( itemType); info.add( typeInfo); switch( itemType) { case StackMapTypeInfo.ITEM_Long: case StackMapTypeInfo.ITEM_Double: info.add( StackMapTypeInfo.getTypeInfo( StackMapTypeInfo.ITEM_Top)); break; case StackMapTypeInfo.ITEM_Object: typeInfo.setObject( cr.readClass( off, buf)); off += 2; break; case StackMapTypeInfo.ITEM_Uninitialized: int o = cr.readUnsignedShort( off); off += 2; if( labels[ o]==null) labels[ o] = new Label(); typeInfo.setLabel( labels[ o]); break; } } return off; } private void writeTypeInfo( ByteVector bv, ClassWriter cw, List info, int max) { if( max>StackMapAttribute.MAX_SIZE) bv.putInt( info.size()); else bv.putShort( info.size()); for( int j = 0; j<info.size(); j++) { StackMapTypeInfo typeInfo = ( StackMapTypeInfo) info.get( j); bv = new ByteVector().putByte( typeInfo.getType()); switch( typeInfo.getType()) { case StackMapTypeInfo.ITEM_Long: case StackMapTypeInfo.ITEM_Double: // skip Top in the stack/locals after long/double j++; break; case StackMapTypeInfo.ITEM_Object: bv.putShort( cw.newClass( typeInfo.getObject())); break; case StackMapTypeInfo.ITEM_Uninitialized: bv.putShort( typeInfo.getLabel().getOffset()); break; } } } public void dump( StringBuffer buf, String varName, Map labelNames) { declareLabel( buf, labelNames, label); buf.append( varName).append( ".label = ").append( labelNames.get(label)).append( ";\n"); dumpTypeInfo(buf, varName, labelNames, locals); dumpTypeInfo(buf, varName, labelNames, stack); } private void dumpTypeInfo(StringBuffer buf, String varName, Map labelNames, List infos) { if( infos.size()>0) { buf.append( "{\n"); for( int i = 0; i<infos.size(); i++) { StackMapTypeInfo typeInfo = ( StackMapTypeInfo) infos.get( i); String localName = varName+"Info"+i; int type = typeInfo.getType(); buf.append( "StackMapTypeInfo ").append( localName) .append( " = new StackMapTypeInfo( StackMapTypeInfo.ITEM_") .append( StackMapTypeInfo.ITEM_NAMES[ type]).append(");\n"); switch( type) { case StackMapTypeInfo.ITEM_Object: buf.append( localName).append( ".setObject(").append( typeInfo.getObject()).append(");\n"); break; case StackMapTypeInfo.ITEM_Uninitialized: declareLabel( buf, labelNames, typeInfo.getLabel()); buf.append( localName).append( ".setLabel(").append( labelNames.get( typeInfo.getLabel())).append( ");\n"); break; } buf.append( varName).append( ".add(").append( localName).append( ");\n"); } buf.append( "}\n"); } } public static void declareLabel( StringBuffer buf, Map labelNames, Label l) { String name = (String)labelNames.get(l); if( name==null) { name = "l"+labelNames.size(); labelNames.put( l, name); buf.append("Label ").append(name).append(" = new Label();\n"); } } public String toString() { StringBuffer sb = new StringBuffer( "Frame:L"+System.identityHashCode( label)); sb.append( " locals").append( locals); sb.append( " stack").append( stack); return sb.toString(); } }
package org.olap4j.driver.xmla; import org.olap4j.OlapException; import org.olap4j.impl.*; import org.olap4j.mdx.IdentifierNode; import org.olap4j.metadata.*; import java.util.*; import java.lang.ref.SoftReference; /** * Implementation of {@link Cube} * for XML/A providers. * * @author jhyde * @version $Id$ * @since Dec 4, 2007 */ class XmlaOlap4jCube implements Cube, Named { final XmlaOlap4jSchema olap4jSchema; private final String name; private final String description; final NamedList<XmlaOlap4jDimension> dimensions; final Map<String, XmlaOlap4jDimension> dimensionsByUname = new HashMap<String, XmlaOlap4jDimension>(); private NamedList<XmlaOlap4jHierarchy> hierarchies = null; final Map<String, XmlaOlap4jHierarchy> hierarchiesByUname = new HashMap<String, XmlaOlap4jHierarchy>(); final Map<String, XmlaOlap4jLevel> levelsByUname = new HashMap<String, XmlaOlap4jLevel>(); final List<XmlaOlap4jMeasure> measures = new ArrayList<XmlaOlap4jMeasure>(); private final HashMap<String, XmlaOlap4jMeasure> measuresMap = new HashMap<String, XmlaOlap4jMeasure>(); private final NamedList<XmlaOlap4jNamedSet> namedSets; private final MetadataReader metadataReader; /** * Creates an XmlaOlap4jCube. * * @param olap4jSchema Schema * @param name Name * @param description Description */ XmlaOlap4jCube( XmlaOlap4jSchema olap4jSchema, String name, String description) throws OlapException { assert olap4jSchema != null; assert description != null; assert name != null; this.olap4jSchema = olap4jSchema; this.name = name; this.description = description; this.metadataReader = new CachingMetadataReader( new RawMetadataReader(), measuresMap); final XmlaOlap4jConnection olap4jConnection = olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection; final XmlaOlap4jConnection.Context context = new XmlaOlap4jConnection.Context(this, null, null, null); String[] restrictions = { "CATALOG_NAME", olap4jSchema.olap4jCatalog.getName(), "SCHEMA_NAME", olap4jSchema.getName(), "CUBE_NAME", getName() }; this.dimensions = new DeferredNamedListImpl<XmlaOlap4jDimension>( XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_DIMENSIONS, context, new XmlaOlap4jConnection.DimensionHandler(this), restrictions); // populate measures up front; a measure is needed in every query olap4jConnection.populateList( measures, context, XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_MEASURES, new XmlaOlap4jConnection.MeasureHandler( this.dimensions.get("Measures")), restrictions); for (XmlaOlap4jMeasure measure : measures) { measuresMap.put(measure.getUniqueName(), measure); } // populate named sets namedSets = new DeferredNamedListImpl<XmlaOlap4jNamedSet>( XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_SETS, context, new XmlaOlap4jConnection.NamedSetHandler(), restrictions); } public Schema getSchema() { return olap4jSchema; } public String getName() { return name; } public String getUniqueName() { return "[" + name + "]"; } public String getCaption(Locale locale) { return name; } public String getDescription(Locale locale) { return description; } public NamedList<Dimension> getDimensions() { return Olap4jUtil.cast(dimensions); } public NamedList<Hierarchy> getHierarchies() { // This is a costly operation. It forces the init // of all dimensions and all hierarchies. // We defer it to this point. if (this.hierarchies == null) { this.hierarchies = new NamedListImpl<XmlaOlap4jHierarchy>(); for (XmlaOlap4jDimension dim : this.dimensions) { this.hierarchies.addAll(dim.hierarchies); } } return Olap4jUtil.cast(hierarchies); } public List<Measure> getMeasures() { return Olap4jUtil.cast(measures); } public NamedList<NamedSet> getSets() { return Olap4jUtil.cast(namedSets); } public Collection<Locale> getSupportedLocales() { return Collections.singletonList(Locale.getDefault()); } public Member lookupMember(String... nameParts) throws OlapException { List<IdentifierNode.Segment> segmentList = new ArrayList<IdentifierNode.Segment>(); for (String namePart : nameParts) { segmentList.add(new IdentifierNode.NameSegment(namePart)); } return lookupMember(segmentList); } /** * Finds a member, given its fully qualfieid name. * * @param segmentList List of the segments of the name * @return Member, or null if not found * @throws OlapException on error */ private Member lookupMember( List<IdentifierNode.Segment> segmentList) throws OlapException { StringBuilder buf = new StringBuilder(); for (IdentifierNode.Segment segment : segmentList) { if (buf.length() > 0) { buf.append('.'); } buf.append(segment.toString()); } final String uniqueName = buf.toString(); return getMetadataReader().lookupMemberByUniqueName(uniqueName); } /** * Returns this cube's metadata reader. * * <p>Not part of public olap4j API. * * @return metadata reader */ MetadataReader getMetadataReader() { return metadataReader; } public List<Member> lookupMembers( Set<Member.TreeOp> treeOps, String... nameParts) throws OlapException { StringBuilder buf = new StringBuilder(); for (String namePart : nameParts) { if (buf.length() > 0) { buf.append('.'); } buf.append(new IdentifierNode.NameSegment(namePart)); } final String uniqueName = buf.toString(); final List<XmlaOlap4jMember> list = new ArrayList<XmlaOlap4jMember>(); getMetadataReader().lookupMemberRelatives( treeOps, uniqueName, list); return Olap4jUtil.cast(list); } /** * Abstract implementation of MemberReader that delegates all operations * to an underlying MemberReader. */ private static abstract class DelegatingMetadataReader implements MetadataReader { private final MetadataReader metadataReader; /** * Creates a DelegatingMetadataReader. * * @param metadataReader Underlying metadata reader */ DelegatingMetadataReader(MetadataReader metadataReader) { this.metadataReader = metadataReader; } public XmlaOlap4jMember lookupMemberByUniqueName( String memberUniqueName) throws OlapException { return metadataReader.lookupMemberByUniqueName(memberUniqueName); } public void lookupMembersByUniqueName( List<String> memberUniqueNames, Map<String, XmlaOlap4jMember> memberMap) throws OlapException { metadataReader.lookupMembersByUniqueName( memberUniqueNames, memberMap); } public void lookupMemberRelatives( Set<Member.TreeOp> treeOps, String memberUniqueName, List<XmlaOlap4jMember> list) throws OlapException { metadataReader.lookupMemberRelatives( treeOps, memberUniqueName, list); } public List<XmlaOlap4jMember> getLevelMembers( XmlaOlap4jLevel level) throws OlapException { return metadataReader.getLevelMembers(level); } } /** * Implementation of MemberReader that reads from an underlying member * reader and caches the results. * * <p>Caches are {@link Map}s containing * {@link java.lang.ref.SoftReference}s to cached objects, so can be * cleared when memory is in short supply. */ private static class CachingMetadataReader extends DelegatingMetadataReader { private final Map<String, XmlaOlap4jMeasure> measuresMap; private final Map<String, SoftReference<XmlaOlap4jMember>> memberMap = new HashMap<String, SoftReference<XmlaOlap4jMember>>(); private final Map< XmlaOlap4jLevel, SoftReference<List<XmlaOlap4jMember>>> levelMemberListMap = new HashMap< XmlaOlap4jLevel, SoftReference<List<XmlaOlap4jMember>>>(); /** * Creates a CachingMetadataReader. * * @param metadataReader Underlying metadata reader * @param measuresMap Map of measures by unique name, inherited from the * cube and used read-only by this reader */ CachingMetadataReader( MetadataReader metadataReader, Map<String, XmlaOlap4jMeasure> measuresMap) { super(metadataReader); this.measuresMap = measuresMap; } public XmlaOlap4jMember lookupMemberByUniqueName( String memberUniqueName) throws OlapException { // First, look in measures map. XmlaOlap4jMeasure measure = measuresMap.get(memberUniqueName); if (measure != null) { return measure; } // Next, look in cache. final SoftReference<XmlaOlap4jMember> memberRef = memberMap.get(memberUniqueName); if (memberRef != null) { final XmlaOlap4jMember member = memberRef.get(); if (member != null) { return member; } } final XmlaOlap4jMember member = super.lookupMemberByUniqueName(memberUniqueName); if (member != null && member.getDimension().type != Dimension.Type.MEASURE) { memberMap.put( memberUniqueName, new SoftReference<XmlaOlap4jMember>(member)); } return member; } public void lookupMembersByUniqueName( List<String> memberUniqueNames, Map<String, XmlaOlap4jMember> memberMap) throws OlapException { final ArrayList<String> remainingMemberUniqueNames = new ArrayList<String>(); for (String memberUniqueName : memberUniqueNames) { // First, look in measures map. XmlaOlap4jMeasure measure = measuresMap.get(memberUniqueName); if (measure != null) { memberMap.put(memberUniqueName, measure); continue; } // Next, look in cache. final SoftReference<XmlaOlap4jMember> memberRef = this.memberMap.get(memberUniqueName); final XmlaOlap4jMember member; if (memberRef != null && (member = memberRef.get()) != null) { memberMap.put(memberUniqueName, member); continue; } remainingMemberUniqueNames.add(memberUniqueName); } // If any of the member names were not in the cache, look them up // by delegating. if (!remainingMemberUniqueNames.isEmpty()) { super.lookupMembersByUniqueName( remainingMemberUniqueNames, memberMap); // Add the previously missing members into the cache. for (String memberName : remainingMemberUniqueNames) { XmlaOlap4jMember member = memberMap.get(memberName); if (member != null) { if (!(member instanceof Measure) && member.getDimension().type != Dimension.Type.MEASURE) { this.memberMap.put( memberName, new SoftReference<XmlaOlap4jMember>(member)); } } } } } public List<XmlaOlap4jMember> getLevelMembers( XmlaOlap4jLevel level) throws OlapException { final SoftReference<List<XmlaOlap4jMember>> memberListRef = levelMemberListMap.get(level); if (memberListRef != null) { final List<XmlaOlap4jMember> memberList = memberListRef.get(); if (memberList != null) { return memberList; } } final List<XmlaOlap4jMember> memberList = super.getLevelMembers(level); if (level.olap4jHierarchy.olap4jDimension.type != Dimension.Type.MEASURE) { levelMemberListMap.put( level, new SoftReference<List<XmlaOlap4jMember>>(memberList)); } return memberList; } } /** * Implementation of MetadataReader that reads from the XMLA provider, * without caching. */ private class RawMetadataReader implements MetadataReader { public XmlaOlap4jMember lookupMemberByUniqueName( String memberUniqueName) throws OlapException { NamedList<XmlaOlap4jMember> list = new NamedListImpl<XmlaOlap4jMember>(); lookupMemberRelatives( Olap4jUtil.enumSetOf(Member.TreeOp.SELF), memberUniqueName, list); switch (list.size()) { case 0: return null; case 1: return list.get(0); default: throw new IllegalArgumentException( "more than one member with unique name '" + memberUniqueName + "'"); } } public void lookupMembersByUniqueName( List<String> memberUniqueNames, Map<String, XmlaOlap4jMember> memberMap) throws OlapException { if (olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData .olap4jConnection.getDataSourceInfo() .indexOf("Provider=Mondrian") != -1) //$NON-NLS-1$ { mondrianMembersLookup(memberUniqueNames, memberMap); } else { genericMembersLookup(memberUniqueNames, memberMap); } } /** * Looks up members; optimized for Mondrian servers. * * @param memberUniqueNames A list of the members to lookup * @param memberMap Output map of members keyed by unique name * @throws OlapException Gets thrown for communication errors */ private void mondrianMembersLookup( List<String> memberUniqueNames, Map<String, XmlaOlap4jMember> memberMap) throws OlapException { final XmlaOlap4jConnection.Context context = new XmlaOlap4jConnection.Context( XmlaOlap4jCube.this, null, null, null); final List<XmlaOlap4jMember> memberList = new ArrayList<XmlaOlap4jMember>(); olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection .populateList( memberList, context, XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_MEMBERS, new XmlaOlap4jConnection.MemberHandler(), new Object[] { "CATALOG_NAME", olap4jSchema.olap4jCatalog.getName(), "SCHEMA_NAME", olap4jSchema.getName(), "CUBE_NAME", getName(), "MEMBER_UNIQUE_NAME", memberUniqueNames }); for (XmlaOlap4jMember member : memberList) { if (member != null) { memberMap.put(member.getUniqueName(), member); } } } /** * Looks up members. * * @param memberUniqueNames A list of the members to lookup * @param memberMap Output map of members keyed by unique name * @throws OlapException Gets thrown for communication errors */ private void genericMembersLookup( List<String> memberUniqueNames, Map<String, XmlaOlap4jMember> memberMap) throws OlapException { // Iterates through member names for (String currentMemberName : memberUniqueNames) { // Only lookup if it is not in the map yet if (!memberMap.containsKey(currentMemberName)) { XmlaOlap4jMember member = this.lookupMemberByUniqueName(currentMemberName); // Null members might mean calculated members if (member != null) { memberMap.put(member.getUniqueName(), member); } } } } public void lookupMemberRelatives( Set<Member.TreeOp> treeOps, String memberUniqueName, List<XmlaOlap4jMember> list) throws OlapException { final XmlaOlap4jConnection.Context context = new XmlaOlap4jConnection.Context( XmlaOlap4jCube.this, null, null, null); int treeOpMask = 0; for (Member.TreeOp treeOp : treeOps) { treeOpMask |= treeOp.xmlaOrdinal(); } olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection .populateList( list, context, XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_MEMBERS, new XmlaOlap4jConnection.MemberHandler(), new Object[] { "CATALOG_NAME", olap4jSchema.olap4jCatalog.getName(), "SCHEMA_NAME", olap4jSchema.getName(), "CUBE_NAME", getName(), "MEMBER_UNIQUE_NAME", memberUniqueName, "TREE_OP", String.valueOf(treeOpMask) }); } public List<XmlaOlap4jMember> getLevelMembers( XmlaOlap4jLevel level) throws OlapException { assert level.olap4jHierarchy.olap4jDimension.olap4jCube == XmlaOlap4jCube.this; final XmlaOlap4jConnection.Context context = new XmlaOlap4jConnection.Context(level); List<XmlaOlap4jMember> list = new ArrayList<XmlaOlap4jMember>(); // If this is a level in the [Measures] dimension, we want to // return objects that implement the Measure interface. During // bootstrap, the list will be empty, and we need to return the // regular Member objects which have the extra properties that are // returned by MSCHEMA_MEMBERS but not MDSCHEMA_MEASURES. switch (level.getDimension().getDimensionType()) { case MEASURE: if (!level.olap4jHierarchy.olap4jDimension.olap4jCube.measures .isEmpty()) { return Olap4jUtil.cast( level.olap4jHierarchy.olap4jDimension.olap4jCube .measures); } break; } olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection .populateList( list, context, XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_MEMBERS, new XmlaOlap4jConnection.MemberHandler(), new Object[] { "CATALOG_NAME", olap4jSchema.olap4jCatalog.getName(), "SCHEMA_NAME", olap4jSchema.getName(), "CUBE_NAME", getName(), "DIMENSION_UNIQUE_NAME", level.olap4jHierarchy.olap4jDimension.getUniqueName(), "HIERARCHY_UNIQUE_NAME", level.olap4jHierarchy.getUniqueName(), "LEVEL_UNIQUE_NAME", level.getUniqueName() }); return list; } } } // End XmlaOlap4jCube.java
package org.opencms.loader; import org.opencms.configuration.CmsConfigurationException; import org.opencms.configuration.CmsVfsConfiguration; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.collectors.I_CmsResourceCollector; import org.opencms.file.types.CmsResourceTypeBinary; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.file.types.CmsResourceTypeUnknownFile; import org.opencms.file.types.CmsResourceTypeUnknownFolder; import org.opencms.file.types.I_CmsResourceType; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.module.CmsModule; import org.opencms.module.CmsModuleManager; import org.opencms.relations.CmsRelationType; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.util.CmsResourceTranslator; import org.opencms.util.CmsStringUtil; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; /** * Collects all available resource loaders, resource types and resource collectors at startup and provides * methods to access them during OpenCms runtime.<p> * * @author Alexander Kandzior * * @version $Revision: 1.43 $ * * @since 6.0.0 */ public class CmsResourceManager { /** * Contains the part of the resource manager configuration that can be changed * during runtime by the import / deletion of a module.<p> * * A module can add resource types and extension mappings to resource types.<p> */ static final class CmsResourceManagerConfiguration { /** The mappings of file extensions to resource types. */ protected Map m_extensionMappings; /** A list that contains all initialized resource types. */ protected List m_resourceTypeList; /** A list that contains all initialized resource types, plus configured types for "unknown" resources. */ protected List m_resourceTypeListWithUnknown; /** A map that contains all initialized resource types mapped to their type id. */ private Map m_resourceTypeIdMap; /** A map that contains all initialized resource types mapped to their type name. */ private Map m_resourceTypeNameMap; /** * Creates a new resource manager data storage.<p> */ protected CmsResourceManagerConfiguration() { m_resourceTypeIdMap = new HashMap(128); m_resourceTypeNameMap = new HashMap(128); m_extensionMappings = new HashMap(128); m_resourceTypeList = new ArrayList(32); } /** * Adds a resource type to the list of configured resource types.<p> * * @param type the resource type to add */ protected void addResourceType(I_CmsResourceType type) { // TODO: If we switch to Java 1.5 compatiblity change this to Integer.valueOf(int) for sligthly better performance m_resourceTypeIdMap.put(new Integer(type.getTypeId()), type); m_resourceTypeNameMap.put(type.getTypeName(), type); m_resourceTypeList.add(type); } /** * Freezes the current configuration by making all data structures unmodifiable * that can be accessed form outside this class.<p> * * @param restypeUnknownFolder the configured default resource type for unknown folders * @param restypeUnknownFile the configured default resource type for unknown files */ protected void freeze(I_CmsResourceType restypeUnknownFolder, I_CmsResourceType restypeUnknownFile) { // generate the resource type list with unknown resource types m_resourceTypeListWithUnknown = new ArrayList(m_resourceTypeList.size() + 2); if (restypeUnknownFolder != null) { m_resourceTypeListWithUnknown.add(restypeUnknownFolder); } if (restypeUnknownFile != null) { m_resourceTypeListWithUnknown.add(restypeUnknownFile); } m_resourceTypeListWithUnknown.addAll(m_resourceTypeList); // freeze the current configuration m_resourceTypeListWithUnknown = Collections.unmodifiableList(m_resourceTypeListWithUnknown); m_resourceTypeList = Collections.unmodifiableList(m_resourceTypeList); m_extensionMappings = Collections.unmodifiableMap(m_extensionMappings); } /** * Returns the configured resource type with the matching type id, or <code>null</code> * if a resource type with that id is not configured.<p> * * @param typeId the type id to get the resource type for * * @return the configured resource type with the matching type id, or <code>null</code> */ protected I_CmsResourceType getResourceTypeById(int typeId) { // TODO: If we switch to Java 1.5 compatiblity change this to Integer.valueOf(int) for sligthly better performance return (I_CmsResourceType)m_resourceTypeIdMap.get(new Integer(typeId)); } /** * Returns the configured resource type with the matching type name, or <code>null</code> * if a resource type with that name is not configured.<p> * * @param typeName the type name to get the resource type for * * @return the configured resource type with the matching type name, or <code>null</code> */ protected I_CmsResourceType getResourceTypeByName(String typeName) { return (I_CmsResourceType)m_resourceTypeNameMap.get(typeName); } } /** The MIME type <code>"text/html"</code>. */ public static final String MIMETYPE_HTML = "text/html"; /** The MIME type <code>"text/plain"</code>. */ public static final String MIMETYPE_TEXT = "text/plain"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsResourceManager.class); /** The map for all configured collector names, mapped to their collector class. */ private Map m_collectorNameMappings; /** The list of all currently configured content collector instances. */ private List m_collectors; /** The current resource manager configuration. */ private CmsResourceManagerConfiguration m_configuration; /** The list of all configured MIME types. */ private List m_configuredMimeTypes; /** The list of all configured relation types. */ private List m_configuredRelationTypes; /** Filename translator, used only for the creation of new files. */ private CmsResourceTranslator m_fileTranslator; /** Folder translator, used to translate all accesses to resources. */ private CmsResourceTranslator m_folderTranslator; /** Indicates if the configuration is finalized (frozen). */ private boolean m_frozen; /** Contains all loader extensions to the include process. */ private List m_includeExtensions; /** A list that contains all initialized resource loaders. */ private List m_loaderList; /** All initialized resource loaders, mapped to their id. */ private I_CmsResourceLoader[] m_loaders; /** The OpenCms map of configured MIME types. */ private Map m_mimeTypes; /** A list that contains all resource types added from the XML configuration. */ private List m_resourceTypesFromXml; /** The configured default type for files when the resource type is missing. */ private I_CmsResourceType m_restypeUnknownFile; /** The configured default type for folders when the resource type is missing. */ private I_CmsResourceType m_restypeUnknownFolder; /** * Creates a new instance for the resource manager, * will be called by the VFS configuration manager.<p> */ public CmsResourceManager() { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_STARTING_LOADER_CONFIG_0)); } m_resourceTypesFromXml = new ArrayList(); m_loaders = new I_CmsResourceLoader[16]; m_loaderList = new ArrayList(); m_includeExtensions = new ArrayList(); m_configuredMimeTypes = new ArrayList(); m_configuredRelationTypes = new ArrayList(); } /** * Adds a given content collector class to the type manager.<p> * * @param className the name of the class to add * @param order the order number for this collector * * @return the created content collector instance * * @throws CmsConfigurationException in case the collector could not be properly initialized */ public synchronized I_CmsResourceCollector addContentCollector(String className, String order) throws CmsConfigurationException { Class classClazz; // init class for content collector try { classClazz = Class.forName(className); } catch (ClassNotFoundException e) { LOG.error(Messages.get().getBundle().key(Messages.LOG_CONTENT_COLLECTOR_CLASS_NOT_FOUND_1, className), e); return null; } I_CmsResourceCollector collector; try { collector = (I_CmsResourceCollector)classClazz.newInstance(); } catch (InstantiationException e) { throw new CmsConfigurationException(Messages.get().container( Messages.ERR_INVALID_COLLECTOR_NAME_1, className)); } catch (IllegalAccessException e) { throw new CmsConfigurationException(Messages.get().container( Messages.ERR_INVALID_COLLECTOR_NAME_1, className)); } catch (ClassCastException e) { throw new CmsConfigurationException(Messages.get().container( Messages.ERR_INVALID_COLLECTOR_NAME_1, className)); } // set the configured order for the collector int ord = 0; try { ord = Integer.valueOf(order).intValue(); } catch (NumberFormatException e) { LOG.error(Messages.get().getBundle().key(Messages.LOG_COLLECTOR_BAD_ORDER_NUMBER_1, className), e); } collector.setOrder(ord); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ADD_COLLECTOR_CLASS_2, className, order)); } // extend or init the current list of configured collectors if (m_collectors != null) { m_collectors = new ArrayList(m_collectors); m_collectorNameMappings = new HashMap(m_collectorNameMappings); } else { m_collectors = new ArrayList(); m_collectorNameMappings = new HashMap(); } if (!m_collectors.contains(collector)) { // this is a collector not currently configured m_collectors.add(collector); Iterator i = collector.getCollectorNames().iterator(); while (i.hasNext()) { String name = (String)i.next(); if (m_collectorNameMappings.containsKey(name)) { // this name is already configured, check the order of the collector I_CmsResourceCollector otherCollector = (I_CmsResourceCollector)m_collectorNameMappings.get(name); if (collector.getOrder() > otherCollector.getOrder()) { // new collector has a greater order than the old collector in the Map m_collectorNameMappings.put(name, collector); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_COLLECTOR_REPLACED_1, name)); } } else { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_DUPLICATE_COLLECTOR_SKIPPED_1, name)); } } } else { m_collectorNameMappings.put(name, collector); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_ADD_COLLECTOR_1, name)); } } } } // ensure list is unmodifiable to avoid potential misuse or accidental changes Collections.sort(m_collectors); m_collectors = Collections.unmodifiableList(m_collectors); m_collectorNameMappings = Collections.unmodifiableMap(m_collectorNameMappings); // return the created collector instance return collector; } /** * Adds a new loader to the internal list of loaded loaders.<p> * * @param loader the loader to add * @throws CmsConfigurationException in case the resource manager configuration is already initialized */ public void addLoader(I_CmsResourceLoader loader) throws CmsConfigurationException { // check if new loaders can still be added if (m_frozen) { throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0)); } // add the loader to the internal list of loaders int pos = loader.getLoaderId(); if (pos > m_loaders.length) { I_CmsResourceLoader[] buffer = new I_CmsResourceLoader[pos * 2]; System.arraycopy(m_loaders, 0, buffer, 0, m_loaders.length); m_loaders = buffer; } m_loaders[pos] = loader; if (loader instanceof I_CmsLoaderIncludeExtension) { // this loader requires special processing during the include process m_includeExtensions.add(loader); } m_loaderList.add(loader); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_ADD_LOADER_2, loader.getClass().getName(), new Integer(pos))); } } /** * Adds a new MIME type from the XML configuration to the internal list of MIME types.<p> * * @param extension the MIME type extension * @param type the MIME type description * * @return the created MIME type instance * * @throws CmsConfigurationException in case the resource manager configuration is already initialized */ public CmsMimeType addMimeType(String extension, String type) throws CmsConfigurationException { // check if new mime types can still be added if (m_frozen) { throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0)); } CmsMimeType mimeType = new CmsMimeType(extension, type); m_configuredMimeTypes.add(mimeType); return mimeType; } /** * Adds a new relation type from the XML configuration to the list of user defined relation types.<p> * * @param name the name of the relation type * @param type the type of the relation type, weak or strong * * @return the new created relation type instance * * @throws CmsConfigurationException in case the resource manager configuration is already initialized */ public CmsRelationType addRelationType(String name, String type) throws CmsConfigurationException { // check if new relation types can still be added if (m_frozen) { throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0)); } CmsRelationType relationType = new CmsRelationType(m_configuredRelationTypes.size(), name, type); m_configuredRelationTypes.add(relationType); return relationType; } /** * Adds a new resource type from the XML configuration to the internal list of loaded resource types.<p> * * Resource types can also be added from a module.<p> * * @param resourceType the resource type to add * @throws CmsConfigurationException in case the resource manager configuration is already initialized */ public void addResourceType(I_CmsResourceType resourceType) throws CmsConfigurationException { // check if new resource types can still be added if (m_frozen) { throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0)); } I_CmsResourceType conflictingType = null; if (resourceType.getTypeId() == CmsResourceTypeUnknownFile.RESOURCE_TYPE_ID) { // default unknown file resource type if (m_restypeUnknownFile != null) { // error: already set conflictingType = m_restypeUnknownFile; } else { m_restypeUnknownFile = resourceType; return; } } else if (resourceType.getTypeId() == CmsResourceTypeUnknownFolder.RESOURCE_TYPE_ID) { // default unknown folder resource type if (m_restypeUnknownFolder != null) { // error: already set conflictingType = m_restypeUnknownFolder; } else { m_restypeUnknownFolder = resourceType; return; } } else { // normal resource types int conflictIndex = m_resourceTypesFromXml.indexOf(resourceType); if (conflictIndex >= 0) { conflictingType = (I_CmsResourceType)m_resourceTypesFromXml.get(conflictIndex); } } if (conflictingType != null) { // configuration problem: the resource type (or at least the id or the name) is already configured throw new CmsConfigurationException(Messages.get().container( Messages.ERR_CONFLICTING_RESOURCE_TYPES_4, new Object[] { resourceType.getTypeName(), new Integer(resourceType.getTypeId()), conflictingType.getTypeName(), new Integer(conflictingType.getTypeId())})); } m_resourceTypesFromXml.add(resourceType); } /** * Returns the configured content collector with the given name, or <code>null</code> if * no collector with this name is configured.<p> * * @param collectorName the name of the collector to get * @return the configured content collector with the given name */ public I_CmsResourceCollector getContentCollector(String collectorName) { return (I_CmsResourceCollector)m_collectorNameMappings.get(collectorName); } /** * Returns the default resource type for the given resource name, using the * configured resource type file extensions.<p> * * In case the given name does not map to a configured resource type, * {@link CmsResourceTypePlain} is returned.<p> * * This is only required (and should <i>not</i> be used otherwise) when * creating a new resource automatically during file upload or synchronization. * Only in this case, the file type for the new resource is determined using this method. * Otherwise the resource type is <i>always</i> stored as part of the resource, * and is <i>not</i> related to the file name.<p> * * @param resourcename the resource name to look up the resource type for * * @return the default resource type for the given resource name * * @throws CmsException if something goes wrong */ public I_CmsResourceType getDefaultTypeForName(String resourcename) throws CmsException { String typeName = null; String suffix = null; if (CmsStringUtil.isNotEmpty(resourcename)) { int pos = resourcename.lastIndexOf('.'); if (pos >= 0) { suffix = resourcename.substring(pos); if (CmsStringUtil.isNotEmpty(suffix)) { suffix = suffix.toLowerCase(); typeName = (String)m_configuration.m_extensionMappings.get(suffix); } } } if (typeName == null) { // use default type "plain" typeName = CmsResourceTypePlain.getStaticTypeName(); } if (CmsLog.INIT.isDebugEnabled()) { CmsLog.INIT.debug(Messages.get().getBundle().key(Messages.INIT_GET_RESTYPE_2, typeName, suffix)); } // look up and return the resource type return getResourceType(typeName); } /** * Returns the file extensions (suffixes) mappings to resource types.<p> * * @return a Map with all known file extensions as keys and their resource types as values. */ public Map getExtensionMapping() { return m_configuration.m_extensionMappings; } /** * Returns the file translator.<p> * * @return the file translator */ public CmsResourceTranslator getFileTranslator() { return m_fileTranslator; } /** * Returns the folder translator.<p> * * @return the folder translator */ public CmsResourceTranslator getFolderTranslator() { return m_folderTranslator; } /** * Returns the loader class instance for a given resource.<p> * * @param resource the resource * @return the appropriate loader class instance * @throws CmsLoaderException if something goes wrong */ public I_CmsResourceLoader getLoader(CmsResource resource) throws CmsLoaderException { return getLoader(getResourceType(resource.getTypeId()).getLoaderId()); } /** * Returns the loader class instance for the given loader id.<p> * * @param id the id of the loader to return * @return the loader class instance for the given loader id */ public I_CmsResourceLoader getLoader(int id) { return m_loaders[id]; } /** * Returns the (unmodifyable array) list with all initialized resource loaders.<p> * * @return the (unmodifyable array) list with all initialized resource loaders */ public List getLoaders() { return m_loaderList; } /** * Returns the MIME type for a specified file name.<p> * * If an encoding parameter that is not <code>null</code> is provided, * the returned MIME type is extended with a <code>; charset={encoding}</code> setting.<p> * * If no MIME type for the given filename can be determined, the * default <code>{@link #MIMETYPE_HTML}</code> is used.<p> * * @param filename the file name to check the MIME type for * @param encoding the default encoding (charset) in case of MIME types is of type "text" * * @return the MIME type for a specified file */ public String getMimeType(String filename, String encoding) { return getMimeType(filename, encoding, MIMETYPE_HTML); } /** * Returns the MIME type for a specified file name.<p> * * If an encoding parameter that is not <code>null</code> is provided, * the returned MIME type is extended with a <code>; charset={encoding}</code> setting.<p> * * If no MIME type for the given filename can be determined, the * provided default is used.<p> * * @param filename the file name to check the MIME type for * @param encoding the default encoding (charset) in case of MIME types is of type "text" * @param defaultMimeType the default MIME type to use if no matching type for the filename is found * * @return the MIME type for a specified file */ public String getMimeType(String filename, String encoding, String defaultMimeType) { String mimeType = null; int lastDot = filename.lastIndexOf('.'); // check the MIME type for the file extension if ((lastDot > 0) && (lastDot < (filename.length() - 1))) { mimeType = (String)m_mimeTypes.get(filename.substring(lastDot).toLowerCase(Locale.ENGLISH)); } if (mimeType == null) { mimeType = defaultMimeType; if (mimeType == null) { // no default MIME type was provided return null; } } StringBuffer result = new StringBuffer(mimeType); if ((encoding != null) && mimeType.startsWith("text") && (mimeType.indexOf("charset") == -1)) { result.append("; charset="); result.append(encoding); } return result.toString(); } /** * Returns an unmodifiable List of the configured {@link CmsMimeType} objects.<p> * * @return an unmodifiable List of the configured {@link CmsMimeType} objects */ public List getMimeTypes() { return m_configuredMimeTypes; } /** * Returns an (unmodifiable) list of class names of all currently registered content collectors * ({@link I_CmsResourceCollector} objects).<p> * * @return an (unmodifiable) list of class names of all currently registered content collectors * ({@link I_CmsResourceCollector} objects) */ public List getRegisteredContentCollectors() { return m_collectors; } /** * Returns an unmodifiable List of the configured {@link CmsRelationType} objects.<p> * * @return an unmodifiable List of the configured {@link CmsRelationType} objects */ public List getRelationTypes() { return m_configuredRelationTypes; } /** * Convenience method to get the initialized resource type * instance for the given resource, including unknown resource types.<p> * * @param resource the resource to get the type for * * @return the initialized resource type instance for the given resource * @throws CmsLoaderException * * @see org.opencms.loader.CmsResourceManager#getResourceType(int) * * @throws CmsLoaderException if no resource type is available for the given resource */ public I_CmsResourceType getResourceType(CmsResource resource) throws CmsLoaderException { try { return getResourceType(resource.getTypeId()); } catch (CmsLoaderException e) { if (resource.isFolder()) { if (m_restypeUnknownFolder != null) { return m_restypeUnknownFolder; } // if no unknown folder configured, take the default folder type return getResourceType(CmsResourceTypeFolder.getStaticTypeId()); } if (m_restypeUnknownFile != null) { return m_restypeUnknownFile; } // if no unknown folder configured, take the default folder type return getResourceType(CmsResourceTypeBinary.getStaticTypeId()); } } /** * Returns the initialized resource type instance for the given id.<p> * * @param typeId the id of the resource type to get * * @return the initialized resource type instance for the given id * * @throws CmsLoaderException if no resource type is available for the given id */ public I_CmsResourceType getResourceType(int typeId) throws CmsLoaderException { I_CmsResourceType result = m_configuration.getResourceTypeById(typeId); if (result == null) { throw new CmsLoaderException(Messages.get().container( Messages.ERR_UNKNOWN_RESTYPE_ID_REQ_1, new Integer(typeId))); } return result; } /** * Returns the initialized resource type instance for the given resource type name.<p> * * @param typeName the name of the resource type to get * * @return the initialized resource type instance for the given name * * @throws CmsLoaderException if no resource type is available for the given name */ public I_CmsResourceType getResourceType(String typeName) throws CmsLoaderException { I_CmsResourceType result = m_configuration.getResourceTypeByName(typeName); if (result != null) { return result; } throw new CmsLoaderException(Messages.get().container(Messages.ERR_UNKNOWN_RESTYPE_NAME_REQ_1, typeName)); } /** * Returns the (unmodifiable) list with all initialized resource types.<p> * * @return the (unmodifiable) list with all initialized resource types */ public List getResourceTypes() { return m_configuration.m_resourceTypeList; } /** * Returns the (unmodifiable) list with all initialized resource types including unknown types.<p> * * @return the (unmodifiable) list with all initialized resource types including unknown types */ public List getResourceTypesWithUnknown() { return m_configuration.m_resourceTypeListWithUnknown; } /** * The configured default type for files when the resource type is missing.<p> * * @return the configured default type for files */ public I_CmsResourceType getResTypeUnknownFile() { return m_restypeUnknownFile; } /** * The configured default type for folders when the resource type is missing.<p> * * @return The configured default type for folders */ public I_CmsResourceType getResTypeUnknownFolder() { return m_restypeUnknownFolder; } /** * Returns a template loader facade for the given file.<p> * @param cms the current OpenCms user context * @param resource the requested file * @param templateProperty the property to read for the template * * @return a resource loader facade for the given file * @throws CmsException if something goes wrong */ public CmsTemplateLoaderFacade getTemplateLoaderFacade(CmsObject cms, CmsResource resource, String templateProperty) throws CmsException { String templateProp = cms.readPropertyObject(resource, templateProperty, true).getValue(); if (templateProp == null) { // no template property defined, this is a must for facade loaders throw new CmsLoaderException(Messages.get().container( Messages.ERR_NONDEF_PROP_2, templateProperty, cms.getSitePath(resource))); } CmsResource template = cms.readFile(templateProp, CmsResourceFilter.IGNORE_EXPIRATION); return new CmsTemplateLoaderFacade(getLoader(template), resource, template); } /** * Checks if an initialized resource type instance equal to the given resource type is available.<p> * * @param type the resource type to check * @return <code>true</code> if such a resource type has been configured, <code>false</code> otherwise * * @see #getResourceType(String) * @see #getResourceType(int) */ public boolean hasResourceType(I_CmsResourceType type) { return hasResourceType(type.getTypeId()); } /** * Checks if an initialized resource type instance for the given resource type is is available.<p> * * @param typeId the id of the resource type to check * @return <code>true</code> if such a resource type has been configured, <code>false</code> otherwise * * @see #getResourceType(int) */ public boolean hasResourceType(int typeId) { return m_configuration.getResourceTypeById(typeId) != null; } /** * Checks if an initialized resource type instance for the given resource type name is available.<p> * * @param typeName the name of the resource type to check * @return <code>true</code> if such a resource type has been configured, <code>false</code> otherwise * * @see #getResourceType(String) */ public boolean hasResourceType(String typeName) { return m_configuration.getResourceTypeByName(typeName) != null; } /** * @see org.opencms.configuration.I_CmsConfigurationParameterHandler#initConfiguration() * * @throws CmsConfigurationException in case of duplicate resource types in the configuration */ public void initConfiguration() throws CmsConfigurationException { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LOADER_CONFIG_FINISHED_0)); } m_resourceTypesFromXml = Collections.unmodifiableList(m_resourceTypesFromXml); m_loaderList = Collections.unmodifiableList(m_loaderList); Collections.sort(m_configuredMimeTypes); m_configuredMimeTypes = Collections.unmodifiableList(m_configuredMimeTypes); m_configuredRelationTypes = Collections.unmodifiableList(m_configuredRelationTypes); // initialize the resource types initResourceTypes(); // initialize the MIME types initMimeTypes(); } public synchronized void initialize(CmsObject cms) throws CmsRoleViolationException, CmsConfigurationException { if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_1_CORE_OBJECT) { // some simple test cases don't require this check OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); } // initialize the resource types initResourceTypes(); // call initialize method on all resource types Iterator i = m_configuration.m_resourceTypeList.iterator(); while (i.hasNext()) { I_CmsResourceType type = (I_CmsResourceType)i.next(); type.initialize(cms); } if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LOADER_CONFIG_FINISHED_0)); } } /** * Loads the requested resource and writes the contents to the response stream.<p> * * @param req the current HTTP request * @param res the current HTTP response * @param cms the current OpenCms user context * @param resource the requested resource * @throws ServletException if something goes wrong * @throws IOException if something goes wrong * @throws CmsException if something goes wrong */ public void loadResource(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, CmsException { res.setContentType(getMimeType(resource.getName(), cms.getRequestContext().getEncoding())); I_CmsResourceLoader loader = getLoader(resource); loader.load(cms, resource, req, res); } /** * Extension method for handling special, loader depended actions during the include process.<p> * * Note: If you have multiple loaders configured that require include extensions, * all loaders are called in the order they are configured in.<p> * * @param target the target for the include, might be <code>null</code> * @param element the element to select form the target might be <code>null</code> * @param editable the flag to indicate if the target is is enabled for direct edit * @param paramMap a map of parameters for the include, can be modified, might be <code>null</code> * @param req the current request * @param res the current response * @throws CmsException in case something goes wrong * @return the modified target URI */ public String resolveIncludeExtensions( String target, String element, boolean editable, Map paramMap, ServletRequest req, ServletResponse res) throws CmsException { if (m_includeExtensions == null) { return target; } String result = target; for (int i = 0; i < m_includeExtensions.size(); i++) { // offer the element to every include extension I_CmsLoaderIncludeExtension loader = (I_CmsLoaderIncludeExtension)m_includeExtensions.get(i); result = loader.includeExtension(target, element, editable, paramMap, req, res); } return result; } /** * Sets the folder and the file translator.<p> * * @param folderTranslator the folder translator to set * @param fileTranslator the file translator to set */ public void setTranslators(CmsResourceTranslator folderTranslator, CmsResourceTranslator fileTranslator) { m_folderTranslator = folderTranslator; m_fileTranslator = fileTranslator; } /** * Shuts down this resource manage instance.<p> * * @throws Exception in case of errors during shutdown */ public synchronized void shutDown() throws Exception { Iterator it = m_loaderList.iterator(); while (it.hasNext()) { // destroy all resource loaders I_CmsResourceLoader loader = (I_CmsResourceLoader)it.next(); loader.destroy(); } m_loaderList = null; m_loaders = null; m_collectorNameMappings = null; m_includeExtensions = null; m_mimeTypes = null; m_configuredMimeTypes = null; m_configuredRelationTypes = null; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SHUTDOWN_1, this.getClass().getName())); } } /** * Initialize the MIME types.<p> * * MIME types are configured in the OpenCms <code>opencms-vfs.xml</code> configuration file.<p> * * For legacy reasons, the MIME types are also read from a file <code>"mimetypes.properties"</code> * that must be located in the default <code>"classes"</code> folder of the web application.<p> */ private void initMimeTypes() { // legacy MIME type initialization: try to read properties file Properties mimeTypes = new Properties(); try { // first try: read MIME types from default package mimeTypes.load(getClass().getClassLoader().getResourceAsStream("mimetypes.properties")); } catch (Throwable t) { try { // second try: read MIME types from loader package (legacy reasons, there are no types by default) mimeTypes.load(getClass().getClassLoader().getResourceAsStream( "org/opencms/loader/mimetypes.properties")); } catch (Throwable t2) { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key( Messages.LOG_READ_MIMETYPES_FAILED_2, "mimetypes.properties", "org/opencms/loader/mimetypes.properties")); } } } // initialize the Map with all available MIME types List combinedMimeTypes = new ArrayList(mimeTypes.size() + m_configuredMimeTypes.size()); // first add all MIME types from the configuration combinedMimeTypes.addAll(m_configuredMimeTypes); // now add the MIME types from the properties Iterator i = mimeTypes.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); CmsMimeType mimeType = new CmsMimeType((String)entry.getKey(), (String)entry.getValue(), false); if (!combinedMimeTypes.contains(mimeType)) { // make sure no MIME types from the XML configuration are overwritten combinedMimeTypes.add(mimeType); } } // create a lookup Map for the MIME types m_mimeTypes = new HashMap(mimeTypes.size()); Iterator j = combinedMimeTypes.iterator(); while (j.hasNext()) { CmsMimeType mimeType = (CmsMimeType)j.next(); m_mimeTypes.put(mimeType.getExtension(), mimeType.getType()); } if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_NUM_MIMETYPES_1, new Integer(m_mimeTypes.size()))); } } /** * Adds a new resource type to the internal list of loaded resource types and initializes * options for the resource type.<p> * * @param resourceType the resource type to add * @param configuration the resource configuration */ private synchronized void initResourceType( I_CmsResourceType resourceType, CmsResourceManagerConfiguration configuration) { // add the loader to the internal list of loaders configuration.addResourceType(resourceType); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_ADD_RESTYPE_3, resourceType.getTypeName(), new Integer(resourceType.getTypeId()), resourceType.getClass().getName())); } // add the mappings List mappings = resourceType.getConfiguredMappings(); Iterator i = mappings.iterator(); while (i.hasNext()) { String mapping = (String)i.next(); // only add this mapping if a mapping with this file extension does not // exist already if (!configuration.m_extensionMappings.containsKey(mapping)) { configuration.m_extensionMappings.put(mapping, resourceType.getTypeName()); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_MAP_RESTYPE_2, mapping, resourceType.getTypeName())); } } } } /** * Initializes member variables required for storing the resource types.<p> * * @throws CmsConfigurationException in case of duplicate resource types in the configuration */ private synchronized void initResourceTypes() throws CmsConfigurationException { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_STARTING_LOADER_CONFIG_0)); } CmsResourceManagerConfiguration newConfiguration = new CmsResourceManagerConfiguration(); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_ADD_RESTYPE_FROM_FILE_2, new Integer(m_resourceTypesFromXml.size()), CmsVfsConfiguration.DEFAULT_XML_FILE_NAME)); } // build a new resource type list from the resource types of the XML configuration Iterator i; i = m_resourceTypesFromXml.iterator(); while (i.hasNext()) { I_CmsResourceType resourceType = (I_CmsResourceType)i.next(); initResourceType(resourceType, newConfiguration); } // add all resource types declared in the modules CmsModuleManager moduleManager = OpenCms.getModuleManager(); if (moduleManager != null) { i = moduleManager.getModuleNames().iterator(); while (i.hasNext()) { CmsModule module = moduleManager.getModule((String)i.next()); if ((module != null) && (module.getResourceTypes().size() > 0)) { // module contains resource types if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_ADD_NUM_RESTYPES_FROM_MOD_2, new Integer(module.getResourceTypes().size()), module.getName())); } Iterator j = module.getResourceTypes().iterator(); while (j.hasNext()) { I_CmsResourceType resourceType = (I_CmsResourceType)j.next(); I_CmsResourceType conflictingType = null; if (resourceType.getTypeId() == CmsResourceTypeUnknownFile.RESOURCE_TYPE_ID) { // default unknown file resource type if (m_restypeUnknownFile != null) { // error: already set conflictingType = m_restypeUnknownFile; } else { m_restypeUnknownFile = resourceType; continue; } } else if (resourceType.getTypeId() == CmsResourceTypeUnknownFolder.RESOURCE_TYPE_ID) { // default unknown folder resource type if (m_restypeUnknownFolder != null) { // error: already set conflictingType = m_restypeUnknownFolder; } else { m_restypeUnknownFile = resourceType; continue; } } else { // normal resource types conflictingType = newConfiguration.getResourceTypeById(resourceType.getTypeId()); } if (conflictingType != null) { throw new CmsConfigurationException(Messages.get().container( Messages.ERR_CONFLICTING_MODULE_RESOURCE_TYPES_5, new Object[] { resourceType.getTypeName(), new Integer(resourceType.getTypeId()), module.getName(), conflictingType.getTypeName(), new Integer(conflictingType.getTypeId())})); } initResourceType(resourceType, newConfiguration); } } } } // freeze the current configuration newConfiguration.freeze(m_restypeUnknownFile, m_restypeUnknownFile); m_configuration = newConfiguration; m_frozen = true; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_RESOURCE_TYPE_INITIALIZED_0)); } } }
package com.telefonica.iot.cygnus.sinks; import com.telefonica.iot.cygnus.backends.cartodb.CartoDBBackendImpl; import com.telefonica.iot.cygnus.containers.NotifyContextRequest; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.CommonUtils; import com.telefonica.iot.cygnus.utils.NGSIConstants; import com.telefonica.iot.cygnus.utils.NGSIUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import org.apache.flume.Context; /** * * @author frb */ public class NGSICartoDBSink extends NGSISink { private static final CygnusLogger LOGGER = new CygnusLogger(NGSICartoDBSink.class); private String host; private String port; private boolean ssl; private String apiKey; private boolean flipCoordinates; private boolean enableRaw; private boolean enableDistance; private String schema; private CartoDBBackendImpl backend; /** * Constructor. */ public NGSICartoDBSink() { super(); } // NGSICartoDBSink /** * Gets the CartoDB backend. It is protected since it is only used by the tests. * @return The CartoDB backend */ protected CartoDBBackendImpl getBackend() { return backend; } // getBackend @Override public void configure(Context context) { // Read NGSISink general configuration super.configure(context); // impose enable ower case, since PostgreSQL only accepts lower case enableLowercase = true; // Read NGSICartoDB specific configuration String endpoint = context.getString("endpoint"); if (endpoint == null) { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (endpoint=null) -- Must not be empty"); return; } else { LOGGER.debug("[" + this.getName() + "] Reading configuration (endpoint=" + endpoint + ")"); } // else int index; if (endpoint.startsWith("http: port = "80"; ssl = false; index = 7; } else if (endpoint.startsWith("https: port = "443"; ssl = true; index = 8; } else { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (endpoint=" + endpoint + ") " + "-- The URI must use the http or https schemes"); return; } // if else String hostPort = endpoint.substring(index); String[] split = hostPort.split(":"); if (split.length == 2) { host = split[0]; port = split[1]; } else { host = split[0]; } // if else apiKey = context.getString("api_key"); String[] split2 = host.split("\\."); schema = split2[0]; if (apiKey == null) { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (apiKey=null) -- Must not be empty"); return; } else { LOGGER.debug("[" + this.getName() + "] Reading configuration (apiKey=" + apiKey + ")"); } // if else String flipCoordinatesStr = context.getString("flip_coordinates", "false"); if (flipCoordinatesStr.equals("true") || flipCoordinatesStr.equals("false")) { flipCoordinates = flipCoordinatesStr.equals("true"); LOGGER.debug("[" + this.getName() + "] Reading configuration (flip_coordinates=" + flipCoordinatesStr + ")"); } else { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (flip_coordinates=" + flipCoordinatesStr + ") -- Must be 'true' or 'false'"); } // if else String enableRawStr = context.getString("enable_raw", "true"); if (enableRawStr.equals("true") || enableRawStr.equals("false")) { enableRaw = enableRawStr.equals("true"); LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_raw=" + enableRawStr + ")"); } else { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (enable_raw=" + enableRawStr + ") -- Must be 'true' or 'false'"); } // if else String enableDistanceStr = context.getString("enable_distance", "false"); if (enableDistanceStr.equals("true") || enableDistanceStr.equals("false")) { enableDistance = enableDistanceStr.equals("true"); LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_distance=" + enableDistanceStr + ")"); } else { invalidConfiguration = true; LOGGER.error("[" + this.getName() + "] Invalid configuration (enable_distance=" + enableDistanceStr + ") -- Must be 'true' or 'false'"); } // if else } // configure @Override public void start() { try { // create the persistence backend backend = new CartoDBBackendImpl(host, port, ssl, apiKey); LOGGER.debug("[" + this.getName() + "] CartoDB persistence backend created"); } catch (Exception e) { LOGGER.error("Error while creating the CartoDB persistence backend. Details: " + e.getMessage()); } // try catch super.start(); } // start @Override void persistBatch(NGSIBatch batch) throws Exception { if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // iterate on the destinations, for each one a single create / append will be performed for (String destination : batch.getDestinations()) { LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // get the sub-batch for this destination ArrayList<NGSIEvent> subBatch = batch.getEvents(destination); CartoDBAggregator aggregator = null; if (enableRaw) { // get an aggregator for this destination and initialize it aggregator = new CartoDBAggregator(); aggregator.initialize(subBatch.get(0)); } for (NGSIEvent cygnusEvent : subBatch) { if (enableRaw && aggregator != null) { aggregator.aggregate(cygnusEvent); } if (enableDistance) { persistDistanceAnalysis(cygnusEvent); } } // for if (enableRaw) { // persist the aggregation persistAggregation(aggregator); } batch.setPersisted(destination); } // for } // persistBatch /** * Convenience class for aggregating data. */ protected class CartoDBAggregator { private LinkedHashMap<String, ArrayList<String>> aggregation; private String service; private String servicePath; private String entity; private String attribute; private String dbName; private String tableName; public String getDbName() { return dbName; } // getDbName public String getTableName() { return tableName; } // getTableName /** * Gets PostgreSQL-like rows from the aggregation. * @return */ public String getRows() { String rows = ""; int numEvents = aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).size(); for (int i = 0; i < numEvents; i++) { if (i == 0) { rows += "("; } else { rows += ",("; } // if else boolean first = true; Iterator it = aggregation.keySet().iterator(); while (it.hasNext()) { ArrayList<String> values = (ArrayList<String>) aggregation.get((String) it.next()); String value = values.get(i); if (!value.startsWith("ST_SetSRID(ST_MakePoint(")) { value = "'" + value + "'"; } if (first) { rows += value; first = false; } else { rows += "," + value; } // if else } // while rows += ")"; } // for return rows; } // getRows /** * Gets PostgreSLQ-like fields from the aggregation. * @return */ public String getFields() { String fields = "("; boolean first = true; Iterator it = aggregation.keySet().iterator(); while (it.hasNext()) { if (first) { fields += (String) it.next(); first = false; } else { fields += "," + (String) it.next(); } // if else } // while fields += ")"; return fields.toLowerCase(); } // getFields /** * Initializes an aggregation. * @param event * @throws Exception */ public void initialize(NGSIEvent event) throws Exception { service = event.getService(); servicePath = event.getServicePath(); entity = event.getEntity(); attribute = event.getAttribute(); //dbName = buildDbName(service); tableName = buildTableName(servicePath, entity, attribute); // aggregation initialization aggregation = new LinkedHashMap<String, ArrayList<String>>(); aggregation.put(NGSIConstants.RECV_TIME, new ArrayList<String>()); aggregation.put(NGSIConstants.FIWARE_SERVICE_PATH, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_ID, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_TYPE, new ArrayList<String>()); aggregation.put(NGSIConstants.THE_GEOM, new ArrayList<String>()); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = event.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); if (!NGSIUtils.getLocation(attrValue, attrType, attrMetadata, flipCoordinates).startsWith( "ST_SetSRID(ST_MakePoint(")) { aggregation.put(attrName, new ArrayList<String>()); aggregation.put(attrName + "_md", new ArrayList<String>()); } } // for } // initialize /** * Aggregates a given Cygnus event. * @param cygnusEvent * @throws Exception */ public void aggregate(NGSIEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = CommonUtils.getHumanReadable(recvTimeTs, true); // get the event body NotifyContextRequest.ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } aggregation.get(NGSIConstants.RECV_TIME).add(recvTime); aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).add(servicePath); aggregation.get(NGSIConstants.ENTITY_ID).add(entityId); aggregation.get(NGSIConstants.ENTITY_TYPE).add(entityType); for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); String location = NGSIUtils.getLocation(attrValue, attrType, attrMetadata, flipCoordinates); if (location.startsWith("ST_SetSRID(ST_MakePoint(")) { aggregation.get(NGSIConstants.THE_GEOM).add(location); } else { aggregation.get(attrName).add(attrValue); aggregation.get(attrName + "_md").add(attrMetadata); } // if else } // for } // aggregate } // CartoDBAggregator private void persistAggregation(CartoDBAggregator aggregator) throws Exception { //String dbName = aggregator.getDbName(); // enable_lowercase is unncessary, PostgreSQL is case insensitive String tableName = aggregator.getTableName(); // enable_lowercase is unncessary, PostgreSQL is case insensitive String withs = ""; String fields = aggregator.getFields(); String rows = aggregator.getRows(); LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema + "), Table (" + tableName + "), Data (" + rows + ")"); backend.insert(tableName, withs, fields, rows); } // persistAggregation /* private String buildDbName(String service) throws Exception { String name = NGSIUtils.encodePostgreSQL(service, false); if (name.length() > NGSIConstants.POSTGRESQL_MAX_ID_LEN) { throw new CygnusBadConfiguration("Building database name '" + name + "' and its length is greater than " + NGSIConstants.POSTGRESQL_MAX_ID_LEN); } // if return name; } // buildDbName */ /** * Builds a table name for CartoDB given a service path, an entity and an attribute. * @param servicePath * @param entity * @param attribute * @return The table name for CartoDB * @throws Exception */ protected String buildTableName(String servicePath, String entity, String attribute) throws Exception { String name; switch(dataModel) { case DMBYSERVICEPATH: if (servicePath.equals("/")) { throw new CygnusBadConfiguration("Default service path '/' cannot be used with " + "dm-by-service-path data model"); } name = NGSIUtils.encodePostgreSQL(servicePath, true); break; case DMBYENTITY: String truncatedServicePath = NGSIUtils.encodePostgreSQL(servicePath, true); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encodePostgreSQL(entity, false); break; case DMBYATTRIBUTE: truncatedServicePath = NGSIUtils.encodePostgreSQL(servicePath, true); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encodePostgreSQL(entity, false) + '_' + NGSIUtils.encodePostgreSQL(attribute, false); break; default: throw new CygnusBadConfiguration("Unknown data model '" + dataModel.toString() + "'. Please, use DMBYSERVICEPATH, DMBYENTITY or DMBYATTRIBUTE"); } // switch if (name.length() > NGSIConstants.POSTGRESQL_MAX_ID_LEN) { throw new CygnusBadConfiguration("Building table name '" + name + "' and its length is greater than " + NGSIConstants.POSTGRESQL_MAX_ID_LEN); } return name; } // buildTableName private void persistDistanceAnalysis(NGSIEvent event) throws Exception { // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = event.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } for (ContextAttribute contextAttribute : contextAttributes) { long recvTimeMs = event.getRecvTimeTs(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); String location = NGSIUtils.getLocation(attrValue, attrType, attrMetadata, flipCoordinates); String tableName = schema + "." + buildTableName(event.getServicePath(), event.getEntity(), event.getAttribute()) + "_distance"; if (location.startsWith("ST_SetSRID(ST_MakePoint(")) { // Create the table... the cost of checking if it exists and creating it is higher than directly // attempting to create it. If existing, nothing will be re-created try { String typedFields = "(recvTimeMs bigint, fiwareServicePath text, entityId text, entityType text, " + "stageDistance float, stageTime float, stageSpeed float, sumDistance float, " + "sumTime float, sumSpeed float, sum2Distance float, sum2Time float, sum2Speed float, " + "maxDistance float, minDistance float, maxTime float, minTime float, maxSpeed float, " + "minSpeed float, numSamples bigint)"; backend.createTable(schema, tableName, typedFields); } catch (Exception e) { String withs = ""; String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance," + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time," + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)"; String rows = "(" + recvTimeMs + ",'" + event.getServicePath() + "','" + event.getEntity() + "','" + event.getEntity() + "'," + location + ",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1)"; LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema + "), Table (" + tableName + "), Data (" + rows + ")"); backend.insert(tableName, withs, fields, rows); continue; } // try catch String withs = "" + "WITH geom AS (" + " SELECT " + location + " AS point" + "), calcs AS (" + " SELECT" + " cartodb_id," + " ST_Distance(the_geom::geography, geom.point::geography) AS stage_distance," + " (" + recvTimeMs + " - recvTimeMs) AS stage_time" + " FROM " + tableName + ", geom" + " ORDER BY cartodb_id DESC" + " LIMIT 1" + "), speed AS (" + " SELECT" + " (calcs.stage_distance / NULLIF(calcs.stage_time, 0)) AS stage_speed" + " FROM calcs" + "), inserts AS (" + " SELECT" + " (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum_dist," + " (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum_time," + " (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum_speed," + " (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) " + " * (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum2_dist," + " (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) " + " * (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum2_time," + " (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) " + " * (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum2_speed," + " t1.max_distance," + " t1.min_distance," + " t1.max_time," + " t1.min_time," + " t1.max_speed," + " t1.min_speed," + " t2.num_samples" + " FROM" + " (" + " SELECT" + " GREATEST(calcs.stage_distance, maxDistance) AS max_distance," + " LEAST(calcs.stage_distance, minDistance) AS min_distance," + " GREATEST(calcs.stage_time, maxTime) AS max_time," + " LEAST(calcs.stage_time, minTime) AS min_time," + " GREATEST(speed.stage_speed, maxSpeed) AS max_speed," + " LEAST(speed.stage_speed, minSpeed) AS min_speed," + " sumDistance," + " sumTime," + " sumSpeed" + " FROM " + tableName + ", speed, calcs" + " ORDER BY " + tableName + ".cartodb_id DESC" + " LIMIT 1" + " ) AS t1," + " (" + " SELECT (-1 * ((-1 * COUNT(*)) - 1)) AS num_samples" + " FROM " + tableName + " ) AS t2," + " speed," + " calcs" + ")"; String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance," + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time," + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)"; String rows = "(" + recvTimeMs + ",'" + event.getServicePath() + "','" + event.getEntity() + "','" + event.getEntity() + "'," + "(SELECT point FROM geom),(SELECT stage_distance FROM calcs)," + "(SELECT stage_time FROM calcs),(SELECT stage_speed FROM speed)," + "(SELECT sum_dist FROM inserts),(SELECT sum_time FROM inserts)," + "(SELECT sum_speed FROM inserts),(SELECT sum2_dist FROM inserts)," + "(SELECT sum2_time FROM inserts),(SELECT sum2_speed FROM inserts)," + "(SELECT max_distance FROM inserts),(SELECT min_distance FROM inserts)," + "(SELECT max_time FROM inserts),(SELECT min_time FROM inserts)," + "(SELECT max_speed FROM inserts),(SELECT min_speed FROM inserts)," + "(SELECT num_samples FROM inserts))"; LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema + "), Table (" + tableName + "), Data (" + rows + ")"); backend.insert(tableName, withs, fields, rows); } } // for } // persistDistanceAnalysis } // NGSICartoDBSink
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc.team4546.robot2; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.Preferences; import edu.wpi.first.wpilibj.Timer; import org.usfirst.frc.team4546.robot2.commands.*; import org.usfirst.frc.team4546.robot2.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; SendableChooser autoChooser; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static Drivetrain drivetrain; public static Lift lift; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static Claw claw; public static Gyro gyro; public static PowerDistributionPanel pdp; public static double speed; public static Timer timer; public static double rampIncrement; public Preferences prefs; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS drivetrain = new Drivetrain(); lift = new Lift(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS gyro = RobotMap.gyro; claw = new Claw(); pdp = RobotMap.pdp; speed = 1; timer = new Timer(); // OI must be constructed after subsystems. If the OI creates Commands //(which it very likely will), subsystems are not guaranteed to be // constructed yet. Thus, their requires() statements may grab null // pointers. Bad news. Don't move it. oi = new OI(); pdp.clearStickyFaults(); gyro.initGyro(); autoChooser = new SendableChooser(); autoChooser.addDefault("Straight Auto, No Ramp", new StraightAutoNoRamp()); autoChooser.addObject("Straight Auto With Ramp", new StraightAutoWithRamp()); autoChooser.addObject("Stacking Auto", new StackingAuto()); autoChooser.addObject("Sideways Auto Left", new SidewaysAutoLeft()); autoChooser.addObject("Sideways Auto Right", new SidewaysAutoRight()); autoChooser.addObject("Sideway Auto Left With Ramp", new SidewaysAutoLeftRamp()); autoChooser.addObject("Sideways Auto Right With Ramp", new SidewaysAutoRightRamp()); SmartDashboard.putData("Auto Chooser", autoChooser); } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ claw.open(); } public void disabledPeriodic() { Scheduler.getInstance().run(); } public void autonomousInit() { // schedule the autonomous command (example) autonomousCommand = (Command) autoChooser.getSelected(); if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); rampIncrement = .05; } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); SmartDashboard.putNumber("Speed %", Robot.speed*100); SmartDashboard.putBoolean("Claw Status", Robot.claw.isClosed()); SmartDashboard.putBoolean("Lift Fully Up", Robot.lift.isFullyUp()); SmartDashboard.putBoolean("Lift Fully Down", Robot.lift.isFullyDown()); SmartDashboard.putData(drivetrain); SmartDashboard.putData(lift); SmartDashboard.putData(claw); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package org.barbon.mangaget; import android.app.Activity; import android.app.Instrumentation; import android.content.Context; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.test.ActivityInstrumentationTestCase2; import android.support.v4.app.FragmentManager; import android.view.KeyEvent; import org.barbon.mangaget.data.DB; import org.barbon.mangaget.fragments.ChapterList; import org.barbon.mangaget.fragments.MangaList; import org.barbon.mangaget.tests.Utils; // TODO add tests for Main activity and fragments, // MangaSearch activity and Download service public class MainTest extends ActivityInstrumentationTestCase2<Main> { private MangaList mangaList; private ChapterList chapterList; private Main activity; private FragmentManager manager; private void refreshMembers() { activity = (Main) getActivity(); manager = activity.getSupportFragmentManager(); mangaList = (MangaList) manager.findFragmentById(R.id.manga_list); chapterList = (ChapterList) manager.findFragmentById(R.id.chapter_list); } private void selectListAndMoveToTop() throws Exception { activity.runOnUiThread( new Runnable() { public void run() { mangaList.getListView().requestFocus(); } }); sendKeys(KeyEvent.KEYCODE_DPAD_UP); sendKeys(KeyEvent.KEYCODE_DPAD_UP); sendKeys(KeyEvent.KEYCODE_DPAD_UP); Thread.sleep(500); } private void selectCurrent() throws Exception { sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); getInstrumentation().waitForIdleSync(); Thread.sleep(1000); // blech } private void moveDown() { sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); } private Activity reloadActivity() { IntentFilter filter = null; Instrumentation instr = getInstrumentation(); Instrumentation.ActivityMonitor monitor = instr.addMonitor(filter, null, false); int orientation = activity.getResources().getConfiguration().orientation; int req_orientation; switch (orientation) { case Configuration.ORIENTATION_PORTRAIT: req_orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Configuration.ORIENTATION_LANDSCAPE: req_orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; default: throw new RuntimeException("Unknown orientation " + orientation); } activity.setRequestedOrientation(req_orientation); // wait for activity to reload Activity activity = monitor.waitForActivity(); instr.waitForIdleSync(); return activity; } public MainTest() { super("org.barbon.mangaget", Main.class); } @Override protected void setUp() throws Exception { super.setUp(); Utils.setupTestEnvironment(this); Utils.setupTestDatabase(this); setActivityInitialTouchMode(false); refreshMembers(); } public void testPreconditions() { assertEquals(2, mangaList.getListView().getCount()); assertEquals(0, chapterList.getListView().getCount()); } public void testMangaSelection() throws Throwable { selectListAndMoveToTop(); // select first item selectCurrent(); assertEquals(1, chapterList.getListView().getCount()); // select second item moveDown(); selectCurrent(); assertEquals(2, chapterList.getListView().getCount()); } public void testRestart() throws Throwable { selectListAndMoveToTop(); // select second item moveDown(); selectCurrent(); // sanity check assertEquals(2, chapterList.getListView().getCount()); // force reload setActivity(reloadActivity()); refreshMembers(); // check the activity restored correctly assertEquals(2, chapterList.getListView().getCount()); } public void testMangaRefresh() throws Throwable { selectListAndMoveToTop(); DB db = DB.getInstance(null); Context targetContext = getInstrumentation().getTargetContext(); // select first item selectCurrent(); // sanity check assertEquals(1, chapterList.getListView().getCount()); // update manga Download.startMangaUpdate(targetContext, Utils.firstDummyManga); // wait until refresh completes for (;;) { Cursor cursor = db.getChapterList(Utils.firstDummyManga); int count = cursor.getCount(); cursor.close(); if (count != 1) break; Thread.sleep(500); } Thread.sleep(2000); // blech // check chapter list has been refreshed assertEquals(29, chapterList.getListView().getCount()); } public void testRemoveManga() throws Exception { Instrumentation instr = getInstrumentation(); selectListAndMoveToTop(); moveDown(); selectCurrent(); // sanity check assertEquals(2, mangaList.getListView().getCount()); assertTrue(instr.invokeContextMenuAction(activity, R.id.delete, 0)); DB db = DB.getInstance(null); // wait until refresh completes for (;;) { Cursor cursor = db.getMangaList(); int count = cursor.getCount(); cursor.close(); if (count == 1) break; Thread.sleep(500); } Thread.sleep(2000); // blech // check chapter list has been refreshed assertEquals(1, mangaList.getListView().getCount()); } }
package de.peeeq.wurstio.languageserver; import com.google.common.base.Charsets; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.io.Files; import de.peeeq.wurstio.ModelChangedException; import de.peeeq.wurstio.WurstCompilerJassImpl; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.*; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import de.peeeq.wurstscript.gui.WurstGuiLogger; import de.peeeq.wurstscript.parser.WPos; import de.peeeq.wurstscript.utils.LineOffsets; import de.peeeq.wurstscript.utils.Utils; import org.eclipse.jdt.annotation.Nullable; import java.io.*; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; /** * keeps a version of the model which is always the most recent one */ public class ModelManagerImpl implements ModelManager { private volatile @Nullable WurstModel model; private File projectPath; private boolean needsFullBuild = true; // dependency folders (folders mentioned in wurst.dependencies) private final Set<String> dependencies = Sets.newLinkedHashSet(); // private WurstGui gui = new WurstGuiLogger(); private List<Consumer<CompilationResult>> onCompilationResultListeners = new ArrayList<>(); // compile errors for each file private Map<String, List<CompileError>> parseErrors = new LinkedHashMap<>(); // hashcode for each compilation unit content as string private Map<String, Integer> fileHashcodes = new HashMap<>(); public ModelManagerImpl(String projectPath) { this(new File(projectPath)); } public ModelManagerImpl(File projectPath) { this.projectPath = projectPath; } private WurstModel newModel(CompilationUnit cu, WurstGui gui) { try { CompilationUnit commonJ = compileFromJar(gui, "common.j"); CompilationUnit blizzardJ = compileFromJar(gui, "blizzard.j"); return Ast.WurstModel(blizzardJ, commonJ, cu); } catch (IOException e) { WLogger.severe(e); return Ast.WurstModel(cu); } } @Override public boolean removeCompilationUnit(String resource) { parseErrors.remove(resource); WurstModel model2 = model; if (model2 == null) { return false; } ListIterator<CompilationUnit> it = model2.listIterator(); while (it.hasNext()) { CompilationUnit cu = it.next(); if (cu.getFile().equals(resource)) { it.remove(); return true; } } return false; } @Override public void clean() { fileHashcodes.clear(); parseErrors.clear(); model = null; dependencies.clear(); needsFullBuild = true; WLogger.info("Clean done."); } /** * does a full build, reading whole directory * * @throws IOException */ public void buildProject() { try { WurstGui gui = new WurstGuiLogger(); readDependencies(gui); if (!projectPath.exists()) { throw new RuntimeException("Folder " + projectPath + " does not exist!"); } File wurstFolder = new File(projectPath, "wurst"); if (!wurstFolder.exists()) { System.err.println("No wurst folder found, using complete directory instead."); wurstFolder = projectPath; } processWurstFiles(wurstFolder); resolveImports(gui); doTypeCheck(gui, true); // TODO report errors needsFullBuild = false; // Map<String, List<CompileError>> groupedByFile = // gui.getErrorsAndWarnings().stream().collect(Collectors.groupingBy(err // -> err.getSource().getFile())); // for (Entry<String, List<CompileError>> err : // groupedByFile.entrySet()) { // CompilationResult r = CompilationResult.create(err.getKey(), // err.getValue()); // onCompilationResultListeners.forEach(c -> c.accept(r)); } catch (IOException e) { WLogger.severe(e); throw new ModelManagerException(e); } } private void processWurstFiles(File dir) throws IOException { for (File f : dir.listFiles()) { if (f.isDirectory()) { processWurstFiles(f); } else if (f.getName().endsWith(".wurst") || f.getName().endsWith(".jurst") || f.getName().endsWith(".j")) { processWurstFile(f); } } } private void processWurstFile(File f) throws IOException { System.out.println("processing file " + f); replaceCompilationUnit(f); } private void readDependencies(WurstGui gui) throws IOException { dependencies.clear(); File depFile = new File(projectPath, "wurst.dependencies"); if (!depFile.exists()) { WLogger.info("no dependency file found."); return; } try (BufferedReader reader = new BufferedReader(new FileReader(depFile))) { LineOffsets lineOffsets = new LineOffsets(); int offset = 0; int lineNr = 0; while (true) { String line = reader.readLine(); lineNr++; lineOffsets.set(lineNr, offset); if (line == null) break; int endOffset = offset + line.length(); addDependency(gui, depFile, line, lineOffsets, offset, endOffset); offset = endOffset; } } } private String getProjectRelativePath(File f) { Path normalizedProjectPath = projectPath.getAbsoluteFile().toPath().normalize(); Path normalizedFilePath = f.getAbsoluteFile().toPath().normalize(); try { normalizedFilePath = normalizedProjectPath.relativize(normalizedFilePath); } catch (IllegalArgumentException e) { // this can happen if project path and file path are on different drives // we just ignore the error in this case and keep using the absolute path } return normalizedFilePath.toString(); } private void addDependency(WurstGui gui, File depfile, String fileName, LineOffsets lineOffsets, int offset, int endOffset) { WLogger.info("Adding dependency: " + fileName); File f = new File(fileName); WPos pos = new WPos(getProjectRelativePath(depfile), lineOffsets, offset, endOffset); if (!f.exists()) { gui.sendError(new CompileError(pos, "Path '" + fileName + "' could not be found.")); return; } else if (!f.isDirectory()) { gui.sendError(new CompileError(pos, "Path '" + fileName + "' is not a folder.")); return; } dependencies.add(fileName); } private List<CompilationUnit> getCompilationUnits(List<String> fileNames) { WurstModel model2 = model; if (model2 == null) { return Collections.emptyList(); } return model2.stream().filter(cu -> fileNames.contains(cu.getFile())).collect(Collectors.toList()); } private List<String> getfileNames(List<CompilationUnit> compilationUnits) { return compilationUnits.stream().map(CompilationUnit::getFile).collect(Collectors.toList()); } /** * clear the attributes for all compilation units that import something from * 'toCheck' and for 'toCheck' * * @return a list of all the CUs which have been cleared */ private List<CompilationUnit> clearAttributes(List<CompilationUnit> toCheck) { WurstModel model2 = model; if (model2 == null) { return Collections.emptyList(); } List<CompilationUnit> cleared = new ArrayList<>(toCheck); model2.clearAttributesLocal(); Set<String> packageNames = Sets.newHashSet(); for (CompilationUnit cu : toCheck) { cu.clearAttributes(); for (WPackage p : cu.getPackages()) { packageNames.add(p.getName()); } } for (CompilationUnit cu : model2) { if (imports(cu, packageNames, false)) { cu.clearAttributes(); cleared.add(cu); } } return cleared; } /** * check whether cu imports something from 'toCheck' */ private boolean imports(CompilationUnit cu, Set<String> packageNames, boolean importPublic) { for (WPackage p : cu.getPackages()) { if (imports(p, packageNames, false, Sets.<WPackage>newHashSet())) { return true; } } return false; } /** * check whether p imports something from 'toCheck' */ private boolean imports(WPackage p, Set<String> packageNames, boolean importPublic, HashSet<WPackage> visited) { if (visited.contains(p)) { return false; } visited.add(p); for (WImport imp : p.getImports()) { if ((!importPublic || imp.getIsPublic()) && packageNames.contains(imp.getPackagename())) { return true; } else { WPackage importedPackage = imp.attrImportedPackage(); if (imp.getIsPublic() && importedPackage != null) { if (imports(importedPackage, packageNames, true, visited)) { return true; } } } } return false; } private void doTypeCheck(WurstGui gui, boolean addErrorMarkers) { WurstCompilerJassImpl comp = getCompiler(gui); long time = System.currentTimeMillis(); if (gui.getErrorCount() > 0) { if (addErrorMarkers) { reportErrorsForProject("build project, doTypecheck, early", gui); } WLogger.info("finished typechecking* in " + (System.currentTimeMillis() - time) + "ms"); return; } @Nullable WurstModel model2 = model; if (model2 == null) { return; } try { model2.clearAttributes(); comp.addImportedLibs(model2); comp.checkProg(model2); } catch (CompileError e) { gui.sendError(e); } WLogger.info("finished typechecking in " + (System.currentTimeMillis() - time) + "ms"); if (addErrorMarkers) { reportErrorsForProject("build project, doTypecheck, end", gui); } } private void reportErrorsForProject(String extra, WurstGui gui) { Multimap<String, CompileError> typeErrors = ArrayListMultimap.create(); for (CompileError e : gui.getErrorsAndWarnings()) { typeErrors.put(e.getSource().getFile(), e); } for (String file : parseErrors.keySet()) { List<CompileError> errors = new ArrayList<>(parseErrors.getOrDefault(file, Collections.emptyList())); errors.addAll(typeErrors.get(file)); reportErrors(extra, file, errors); } } private void reportErrorsForFiles(String extra, List<String> filenames, WurstGui gui) { Multimap<String, CompileError> typeErrors = ArrayListMultimap.create(); for (CompileError e : gui.getErrorsAndWarnings()) { typeErrors.put(e.getSource().getFile(), e); } for (String file : filenames) { List<CompileError> errors = new ArrayList<>(parseErrors.getOrDefault(file, Collections.emptyList())); errors.addAll(typeErrors.get(file)); reportErrors(extra, file, errors); } } private void reportErrors(String extra, String filename, List<CompileError> errors) { CompilationResult cr = CompilationResult.create(extra, filename, errors); for (Consumer<CompilationResult> consumer : onCompilationResultListeners) { consumer.accept(cr); } } private WurstCompilerJassImpl getCompiler(WurstGui gui) { RunArgs runArgs = RunArgs.defaults(); runArgs.addLibs(dependencies); WurstCompilerJassImpl comp = new WurstCompilerJassImpl(gui, null, runArgs); comp.setHasCommonJ(true); return comp; } private void updateModel(CompilationUnit cu, WurstGui gui) { System.out.println("update model with " + cu.getFile()); parseErrors.put(cu.getFile(), new ArrayList<>(gui.getErrorsAndWarnings())); WurstModel model2 = model; if (model2 == null) { model = model2 = newModel(cu, gui); } else { ListIterator<CompilationUnit> it = model2.listIterator(); boolean updated = false; while (it.hasNext()) { CompilationUnit c = it.next(); if (c.getFile().equals(cu.getFile())) { // replace old compilationunit with new one: it.set(cu); updated = true; break; } } if (!updated) { model2.add(cu); } } //doTypeCheckPartial(gui, false, ImmutableList.of(cu.getFile())); } private CompilationUnit compileFromJar(WurstGui gui, String filename) throws IOException { InputStream source = this.getClass().getResourceAsStream("/" + filename); File sourceFile; if (source == null) { System.err.println("could not find " + filename + " in jar"); sourceFile = new File("./resources/" + filename); } else { sourceFile = File.createTempFile("wurst", filename); java.nio.file.Files.copy(source, sourceFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } WurstCompilerJassImpl comp = new WurstCompilerJassImpl(gui, null, RunArgs.defaults()); try (InputStreamReader reader = new FileReader(sourceFile)) { CompilationUnit cu = comp.parse(sourceFile.getAbsolutePath(), reader); cu.setFile(getProjectRelativePath(sourceFile)); return cu; } } private void resolveImports(WurstGui gui) { WurstCompilerJassImpl comp = getCompiler(gui); try { WurstModel m = model; if (m == null) { return; } comp.addImportedLibs(m); } catch (CompileError e) { gui.sendError(e); } } @Override public void replaceCompilationUnit(String filename) { try { File f = getFile(filename); replaceCompilationUnit(f); } catch (IOException e) { WLogger.severe(e); throw new ModelManagerException(e); } } /** * get a file object, where relative files are resolved with respect to * the project root */ private File getFile(String filename) { File f = new File(filename); if (f.isAbsolute()) { return f; } return new File(projectPath, filename); } private void replaceCompilationUnit(File f) throws IOException { if (!f.exists()) { removeCompilationUnit(getProjectRelativePath(f)); return; } WLogger.info("replaceCompilationUnit 1 " + f); String filename = getProjectRelativePath(f); WLogger.info("replaceCompilationUnit 2 " + f); String contents = Files.toString(f, Charsets.UTF_8); replaceCompilationUnit(filename, contents, true); WLogger.info("replaceCompilationUnit 3 " + f); } @Override public void syncCompilationUnit(String filename) { WLogger.info("syncCompilationUnit " + filename); try { File f = getFile(filename); syncCompilationUnit(f); } catch (IOException e) { WLogger.severe(e); throw new ModelManagerException(e); } } @Override public void syncCompilationUnitContent(String filename, String contents) { WLogger.info("sync contents for " + filename); filename = normalizeFilename(filename); replaceCompilationUnit(filename, contents, true); WurstGui gui = new WurstGuiLogger(); doTypeCheckPartial(gui, true, ImmutableList.of(filename)); } @Override public CompilationUnit replaceCompilationUnitContent(String filename, String contents, boolean reportErrors) { filename = normalizeFilename(filename); return replaceCompilationUnit(filename, contents, reportErrors); } private String normalizeFilename(String filename) { File f = getFile(filename); filename = getProjectRelativePath(f); return filename; } private void syncCompilationUnit(File f) throws IOException { WLogger.info("syncCompilationUnit File " + f); replaceCompilationUnit(f); WLogger.info("replaced file " + f); WurstGui gui = new WurstGuiLogger(); doTypeCheckPartial(gui, true, ImmutableList.of(getProjectRelativePath(f))); } private CompilationUnit replaceCompilationUnit(String filename, String contents, boolean reportErrors) { if (fileHashcodes.containsKey(filename)) { int oldHash = fileHashcodes.get(filename); WLogger.info("oldHash = " + oldHash + " == " + contents.hashCode()); if (oldHash == contents.hashCode()) { // no change WLogger.info("CU " + filename + " was unchanged."); return getCompilationUnit(filename); } } WLogger.info("replace CU " + filename); WurstGui gui = new WurstGuiLogger(); WurstCompilerJassImpl c = getCompiler(gui); CompilationUnit cu = c.parse(filename, new StringReader(contents)); cu.setFile(filename); updateModel(cu, gui); fileHashcodes.put(filename, contents.hashCode()); if (reportErrors) { System.out.println("found " + gui.getErrorCount() + " errors in file " + filename); reportErrors("sync cu " + filename, filename, gui.getErrorsAndWarnings()); } return cu; } @Override public CompilationUnit getCompilationUnit(String filename) { filename = normalizeFilename(filename); List<CompilationUnit> matches = getCompilationUnits(Collections.singletonList(filename)); if (matches.isEmpty()) { WLogger.info("compilation unit not found: " + filename); WLogger.info("available: " + model.stream().map(cu -> cu.getFile()).collect(Collectors.joining(", "))); return null; } return matches.get(0); } @Override public WurstModel getModel() { return model; } @Override public boolean hasErrors() { // TODO add type errors as well return parseErrors.values().stream().anyMatch(l -> !l.isEmpty()); } @Override public void updateCompilationUnit(String filename, String contents, boolean reportErrors) { replaceCompilationUnit(normalizeFilename(filename), contents, reportErrors); } @Override public void onCompilationResult(Consumer<CompilationResult> f) { onCompilationResultListeners.add(f); } public static void main(String[] args) throws IOException { // WurstGui gui = new WurstGuiCliImpl(); // WurstCompilerJassImpl c = new WurstCompilerJassImpl(gui, null, new // RunArgs(Arrays.asList())); // CompilationUnit cu = c.parse("RegionData.wurst", new // FileReader("/home/peter/work/EBR/wurst/region/RegionData.wurst")); // for (CompileError err : gui.getErrorsAndWarnings()) { // System.out.println(err); // System.out.println(ExternCompileError.convert(err)); ModelManagerImpl m = new ModelManagerImpl("/home/peter/work/EBR"); m.onCompilationResult(cr -> { for (ExternCompileError err : cr.getErrors()) { System.err.println(cr.getFilename()); System.err.println(" " + err); } }); m.buildProject(); } private void doTypeCheckPartial(WurstGui gui, boolean addErrorMarkers, List<String> toCheckFilenames) { WLogger.info("do typecheck partial of " + toCheckFilenames); WurstCompilerJassImpl comp = getCompiler(gui); List<CompilationUnit> toCheck = getCompilationUnits(toCheckFilenames); WurstModel model2 = model; if (model2 == null) { return; } toCheck = new ArrayList<>(addPackageDependencies(toCheck, model2)); List<CompilationUnit> clearedCUs = Collections.emptyList(); try { clearedCUs = clearAttributes(toCheck); comp.addImportedLibs(model2); comp.checkProg(model2, toCheck); } catch (ModelChangedException e) { // model changed, early return return; } catch (CompileError e) { gui.sendError(e); } if (addErrorMarkers) { List<String> fileNames = getfileNames(clearedCUs); reportErrorsForFiles("partial ", fileNames, gui); } } private Set<CompilationUnit> addPackageDependencies(List<CompilationUnit> toCheck, WurstModel model) { Set<CompilationUnit> result = new TreeSet<>(Comparator.comparing(CompilationUnit::getFile)); result.addAll(toCheck); Collection<String> providedPackages = result.stream() .flatMap(cu -> cu.getPackages().stream()) .map(p -> p.getName()) .collect(Collectors.toSet()); addImportingPackages(providedPackages, model, result); return result; } private void addImportingPackages(Collection<String> providedPackages, WurstModel model2, Set<CompilationUnit> result) { nextCu: for (CompilationUnit compilationUnit : model2) { if (result.contains(compilationUnit)) { continue; } for (WPackage p : compilationUnit.getPackages()) { for (WImport imp : p.getImports()) { String importedPackage = imp.getPackagenameId().getName(); if (providedPackages.contains(importedPackage)) { result.add(compilationUnit); if (imp.getIsPublic()) { // recursive call terminates, because it is only called for packages not yet in result addImportingPackages(Collections.singletonList(p.getName()), model2, result); } continue nextCu; } } } } } @Override public synchronized Set<File> getDependencyWurstFiles() { Set<File> result = Sets.newHashSet(); for (String dep : dependencies) { addDependencyWurstFiles(result, new File(dep)); } return result; } private void addDependencyWurstFiles(Set<File> result, File file) { if (file.isDirectory()) { for (File child : file.listFiles()) { addDependencyWurstFiles(result, child); } } else if (Utils.isWurstFile(file)) { result.add(file); } } }
package org.deegree.rendering.r2d; import static java.lang.Math.abs; import static org.deegree.commons.utils.math.MathUtils.round; import static org.slf4j.LoggerFactory.getLogger; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.LinkedList; import org.deegree.commons.utils.Pair; import org.deegree.commons.utils.log.LoggingNotes; import org.deegree.coverage.raster.AbstractRaster; import org.deegree.coverage.raster.SimpleRaster; import org.deegree.coverage.raster.data.RasterData; import org.deegree.coverage.raster.data.RasterDataFactory; import org.deegree.coverage.raster.data.info.BandType; import org.deegree.coverage.raster.data.info.DataType; import org.deegree.coverage.raster.geom.RasterGeoReference; import org.deegree.coverage.raster.utils.RasterFactory; import org.deegree.geometry.Envelope; import org.deegree.geometry.Geometry; import org.deegree.rendering.r2d.styling.RasterChannelSelection; import org.deegree.rendering.r2d.styling.RasterStyling; import org.deegree.rendering.r2d.styling.Styling; import org.deegree.rendering.r2d.styling.RasterChannelSelection.ChannelSelectionMode; import org.deegree.rendering.r2d.styling.RasterStyling.ContrastEnhancement; import org.deegree.rendering.r2d.utils.Raster2Feature; import org.deegree.rendering.r2d.utils.RasterDataUtility; import org.slf4j.Logger; @LoggingNotes(debug = "logs which raster style is used for rendering", trace = "logs details about the raster rendering process", warn = "logs when null rasters are rendered") public class Java2DRasterRenderer implements RasterRenderer { private static final Logger LOG = getLogger( Java2DRasterRenderer.class ); private Graphics2D graphics; private AffineTransform worldToScreen = new AffineTransform(); private int width; private int height; private Envelope envelope; private double resx, resy; /** * @param graphics * @param width * @param height * @param bbox */ public Java2DRasterRenderer( Graphics2D graphics, int width, int height, Envelope bbox ) { this.graphics = graphics; this.width = width; this.height = height; this.envelope = bbox; if ( bbox != null ) { double scalex = width / bbox.getSpan0(); double scaley = height / bbox.getSpan1(); resx = abs( 1 / scalex ); resy = abs( 1 / scaley ); // we have to flip horizontally, so invert y scale and add the screen height worldToScreen.translate( -bbox.getMin().get0() * scalex, bbox.getMin().get1() * scaley + height ); worldToScreen.scale( scalex, -scaley ); LOG.debug( "For coordinate transformations, scaling by x = {} and y = {}", scalex, -scaley ); LOG.trace( "Final transformation was {}", worldToScreen ); } else { LOG.warn( "No envelope given, proceeding with a scale of 1." ); } } /** * @param graphics */ public Java2DRasterRenderer( Graphics2D graphics ) { this.graphics = graphics; } public void render( RasterStyling styling, AbstractRaster raster ) { LOG.debug( "Rendering raster with style '{}'.", styling ); BufferedImage img = null; if ( raster == null ) { LOG.warn( "Trying to render null raster." ); return; } if ( styling == null ) { LOG.debug( "Raster style is null, rendering without style" ); render( raster ); return; } if ( styling.channelSelection != null ) { // Compute channel selection indexes on current raster styling.channelSelection.evaluate( raster.getRasterDataInfo().bandInfo ); } // TODO maybe reorder this a bit if ( styling.shaded != null ) { raster = performHillShading( raster, styling ); } if ( styling.channelSelection != null ) { raster = evaluateChannelSelections( styling.channelSelection, raster ); } if ( styling.contrastEnhancement != null ) { raster = performContrastEnhancement( raster, styling.contrastEnhancement ); } if ( styling.opacity != 1 ) { LOG.trace( "Using opacity: {}", styling.opacity ); graphics.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, (float) styling.opacity ) ); } if ( styling.categorize != null || styling.interpolate != null ) { LOG.trace( "Creating raster ColorMap..." ); if ( styling.categorize != null ) { img = styling.categorize.evaluateRaster( raster, styling ); } else if ( styling.interpolate != null ) { img = styling.interpolate.evaluateRaster( raster, styling ); } } LOG.trace( "Rendering raster..." ); if ( img != null ) { render( img, raster.getEnvelope() ); } else { render( raster ); } LOG.trace( "Done rendering raster." ); // TODO cleanup outline stuff if ( styling.imageOutline != null ) { LOG.trace( "Rendering image outline..." ); Geometry geom = Raster2Feature.createPolygonGeometry( raster ); Java2DRenderer vectorRenderer = new Java2DRenderer( graphics ); @SuppressWarnings("unchecked") Pair<Styling, LinkedList<Geometry>> pair = (Pair) styling.imageOutline.evaluate( null, null ); Styling ls = pair.first; vectorRenderer.render( ls, geom ); LOG.trace( "Done rendering image outline." ); } } /** * Performs contrast enhancement on all bands of a raster and returns the modified raster. * * @param raster * initial raster * @param contrastEnhancement * @return the enhanced raster */ private AbstractRaster performContrastEnhancement( AbstractRaster raster, ContrastEnhancement contrastEnhancement ) { if ( contrastEnhancement == null ) return raster; LOG.trace( "Enhancing contrast for overall raster..." ); RasterData data = raster.getAsSimpleRaster().getRasterData(), newData = data; RasterDataUtility rasutil = new RasterDataUtility( raster ); rasutil.setContrastEnhancement( contrastEnhancement ); rasutil.precomputeContrastEnhancements( -1, contrastEnhancement ); for ( int band = 0; band < data.getBands(); band++ ) newData = setEnhancedChannelData( newData, rasutil, band, band, contrastEnhancement ); AbstractRaster newRaster = new SimpleRaster( newData, raster.getEnvelope(), raster.getRasterReference() ); return newRaster; } /** * Create a new raster according to the specified channel selections (after performing needed contrast * enhancements). * * @param channels * @param raster */ private AbstractRaster evaluateChannelSelections( RasterChannelSelection channels, AbstractRaster raster ) { if ( channels.getMode() == ChannelSelectionMode.NONE ) return raster; LOG.trace( "Evaluating channel selections ..." ); SimpleRaster simpleRaster = raster.getAsSimpleRaster(); RasterData data = simpleRaster.getRasterData(); int cols = data.getColumns(), rows = data.getRows(); int[] idx = channels.evaluate( simpleRaster.getBandTypes() ); int redIndex = idx[0], greenIndex = idx[1]; int blueIndex = idx[2], grayIndex = idx[3]; RasterDataUtility rasutil = new RasterDataUtility( raster, channels ); RasterData newData = simpleRaster.getRasterData(); BandType[] bandTypes = null; if ( channels.getMode() == ChannelSelectionMode.RGB && data.getBands() > 1 ) { bandTypes = new BandType[] { BandType.RED, BandType.GREEN, BandType.BLUE }; newData = RasterDataFactory.createRasterData( cols, rows, bandTypes, DataType.BYTE, data.getDataInfo().interleaveType, false ); rasutil.precomputeContrastEnhancements( redIndex, channels.channelContrastEnhancements.get( "red" ) ); newData = setEnhancedChannelData( newData, rasutil, redIndex, 0, channels.channelContrastEnhancements.get( "red" ) ); rasutil.precomputeContrastEnhancements( greenIndex, channels.channelContrastEnhancements.get( "green" ) ); newData = setEnhancedChannelData( newData, rasutil, greenIndex, 1, channels.channelContrastEnhancements.get( "green" ) ); rasutil.precomputeContrastEnhancements( blueIndex, channels.channelContrastEnhancements.get( "blue" ) ); newData = setEnhancedChannelData( newData, rasutil, blueIndex, 2, channels.channelContrastEnhancements.get( "blue" ) ); } if ( channels.getMode() == ChannelSelectionMode.GRAY ) { bandTypes = new BandType[] { BandType.BAND_0 }; newData = RasterDataFactory.createRasterData( cols, rows, bandTypes, DataType.BYTE, data.getDataInfo().interleaveType, false ); newData = setEnhancedChannelData( newData, rasutil, grayIndex, 0, channels.channelContrastEnhancements.get( "gray" ) ); } AbstractRaster newRaster = new SimpleRaster( newData, raster.getEnvelope(), raster.getRasterReference() ); return newRaster; } /** * Perform contrast enhancement on one channel and copy the result to a RasterData object. * * @param newData * RasterData output container * @param rasutil * channel data source * @param inIndex * input channel index * @param outIndex * output channel index * @param enhancement * ContrastEnhancement to perform * @return modified RasterData container */ private RasterData setEnhancedChannelData( RasterData newData, RasterDataUtility rasutil, int inIndex, int outIndex, ContrastEnhancement enhancement ) { int i = 0, j = 0, val = 0, cols = newData.getColumns(), rows = newData.getRows(); rasutil.setContrastEnhancement( enhancement ); if ( enhancement != null ) { LOG.trace( "Using gamma {} for channel '{}'...", enhancement.gamma, inIndex ); } for ( i = 0; i < cols; i++ ) for ( j = 0; j < rows; j++ ) { val = (int) rasutil.getEnhanced( i, j, inIndex ); newData.setByteSample( i, j, outIndex, int2byte( val ) ); } return newData; } private static final byte int2byte( final int val ) { return ( val < 128 ? (byte) val : (byte) ( val + 2 * Byte.MIN_VALUE ) ); } public AbstractRaster performHillShading( AbstractRaster raster, RasterStyling style ) { LOG.debug( "Performing Hill-Shading '{}'.", style.shaded ); int cols = raster.getColumns(), rows = raster.getRows(); RasterDataUtility data = new RasterDataUtility( raster, style.channelSelection ); RasterData shadeData = RasterDataFactory.createRasterData( cols - 2, rows - 2, DataType.BYTE, false ); RasterGeoReference ref = raster.getRasterReference(); double resx = cols * ref.getResolutionX() / ( cols - 2 ); double resy = rows * ref.getResolutionY() / ( rows - 2 ); ref = new RasterGeoReference( ref.getOriginLocation(), resx, resy, ref.getOrigin()[0], ref.getOrigin()[1] ); SimpleRaster hillShade = new SimpleRaster( shadeData, raster.getEnvelope(), ref ); final double zenith_rad = Math.toRadians( 90 - style.shaded.alt ); final double azimuth_rad = Math.toRadians( 90 - style.shaded.azimuthAngle ); final double sinZenith = Math.sin( zenith_rad ); final double cosZenith = Math.cos( zenith_rad ); double slope_rad; double aspect_rad = 0; byte shade = 0; double dx, dy; float m[][] = new float[3][3]; for ( int row = 1; row < rows - 1; row++ ) { for ( int col = 1; col < cols - 1; col++ ) { m[0][0] = data.get( col - 1, row - 1 ); m[0][1] = data.get( col, row - 1 ); m[0][2] = data.get( col + 1, row - 1 ); m[1][0] = data.get( col - 1, row ); m[1][1] = data.get( col, row ); m[1][2] = data.get( col + 1, row ); m[2][0] = data.get( col - 1, row + 1 ); m[2][1] = data.get( col, row + 1 ); m[2][2] = data.get( col + 1, row + 1 ); dx = ( ( m[0][2] + 2 * m[1][2] + m[2][2] ) - ( m[0][0] + 2 * m[1][0] + m[2][0] ) ) / 8; dy = ( ( m[2][0] + 2 * m[2][1] + m[2][2] ) - ( m[0][0] + 2 * m[0][1] + m[0][2] ) ) / 8; slope_rad = Math.atan( style.shaded.reliefFactor * Math.sqrt( dx * dx + dy * dy ) ); if ( dx != 0 ) { aspect_rad = Math.atan2( dy, -dx ); if ( aspect_rad < 0 ) aspect_rad += Math.PI * 2; } if ( dx == 0 ) { if ( dy > 0 ) aspect_rad = Math.PI / 2; else if ( dy < 0 ) aspect_rad = 2 * Math.PI - Math.PI / 2; else aspect_rad = 0; } long val = Math.round( 255.0 * ( ( cosZenith * Math.cos( slope_rad ) ) + ( sinZenith * Math.sin( slope_rad ) * Math.cos( azimuth_rad - aspect_rad ) ) ) ); if ( val < 0 ) val = 0; shade = (byte) val; shadeData.setByteSample( col - 1, row - 1, 0, shade ); } } return hillShade; } private void render( final AbstractRaster raster ) { render( RasterFactory.imageFromRaster( raster ), raster.getEnvelope() ); } private void render( final BufferedImage img, final Envelope box ) { if ( envelope != null && box != null ) { int minx = 0, miny = 0, maxx = width, maxy = height; minx = round( ( box.getMin().get0() - envelope.getMin().get0() ) / resx ); miny = round( ( box.getMin().get1() - envelope.getMin().get1() ) / resy ); maxx = width - round( ( envelope.getMax().get0() - box.getMax().get0() ) / resx ); maxy = height - round( ( envelope.getMax().get1() - box.getMax().get1() ) / resy ); graphics.drawImage( img, minx, miny, maxx - minx, maxy - miny, null ); } else { graphics.drawImage( img, worldToScreen, null ); } } }
//$HeadURL: svn+ssh://lbuesching@svn.wald.intevation.de/deegree/base/trunk/resources/eclipse/files_template.xml $ package org.deegree.client.generic; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.deegree.services.controller.OGCFrontController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ManagedBean @SessionScoped public class LogBean implements Serializable { private static final Logger LOG = LoggerFactory.getLogger( LogBean.class ); // location of password file (relative to workspace root) private static final String PASSWORD_FILE = "manager/password.txt"; private static final long serialVersionUID = -4865071415988778817L; private String password; private boolean loggedIn = false; public boolean isLoggedIn() { return loggedIn; } public Object logIn() { String correctPw = null; File pwFile = null; try { File workspace = OGCFrontController.getServiceWorkspace().getLocation(); pwFile = new File( workspace, PASSWORD_FILE ); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream( pwFile ) ) ); try { String line; while ( ( line = in.readLine() ) != null ) { if ( !line.startsWith( " correctPw = line.trim(); break; } } } finally { in.close(); } } catch ( IOException e ) { LOG.warn( "Error reading password from file '{}': {}", pwFile, e.getMessage() ); } if ( password != null && password.equals( correctPw ) ) { loggedIn = true; return "success"; } else { return "failed"; } } public Object logOut() { loggedIn = false; return "/console"; } public void setPassword( String password ) { this.password = password; } public String getPassword() { return password; } }
package com.liulishuo.magicprogress.demo.activity; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AccelerateInterpolator; import com.liulishuo.magicprogress.demo.R; import com.liulishuo.magicprogress.demo.widget.AnimTextView; import com.liulishuo.magicprogresswidget.MagicProgressBar; import com.liulishuo.magicprogresswidget.MagicProgressCircle; import java.util.Random; import cn.dreamtobe.percentsmoothhandler.ISmoothTarget; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); assignViews(); anim(); } private boolean isAnimActive; private final Random random = new Random(); private void anim() { final int ceil = 26; final int progress = random.nextInt(ceil); AnimatorSet set = new AnimatorSet(); set.playTogether( ObjectAnimator.ofFloat(demoMpc, "percent", 0, progress / 100f), ObjectAnimator.ofInt(demoTv, "progress", 0, progress), ObjectAnimator.ofFloat(demo1Mpb, "percent", 0, random.nextInt(ceil) / 100f), ObjectAnimator.ofFloat(demo2Mpb, "percent", 0, random.nextInt(ceil) / 100f), ObjectAnimator.ofFloat(demo3Mpb, "percent", 0, random.nextInt(ceil) / 100f), ObjectAnimator.ofFloat(demo4Mpb, "percent", 0, random.nextInt(ceil) / 100f) ); set.setDuration(600); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { isAnimActive = true; } @Override public void onAnimationEnd(Animator animation) { isAnimActive = false; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); set.setInterpolator(new AccelerateInterpolator()); set.start(); } public void onReRandomPercent(final View view) { if (isAnimActive) { return; } anim(); } public void onClickIncreaseSmoothly(final View view) { if (isAnimActive) { return; } float mpcPercent = getIncreasedPercent(demoMpc); demoMpc.setSmoothPercent(mpcPercent); demoTv.setSmoothPercent(mpcPercent); demo1Mpb.setSmoothPercent(getIncreasedPercent(demo1Mpb)); demo2Mpb.setSmoothPercent(getIncreasedPercent(demo2Mpb)); demo3Mpb.setSmoothPercent(getIncreasedPercent(demo3Mpb)); demo4Mpb.setSmoothPercent(getIncreasedPercent(demo4Mpb)); } private float getIncreasedPercent(ISmoothTarget target) { float increasedPercent = target.getPercent() + 0.1f; return Math.min(1, increasedPercent); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_github: openGitHub(); return true; default: return super.onOptionsItemSelected(item); } } private void openGitHub() { Uri uri = Uri.parse(getString(R.string.app_github_url)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } private MagicProgressCircle demoMpc; private AnimTextView demoTv; private MagicProgressBar demo1Mpb; private MagicProgressBar demo2Mpb; private MagicProgressBar demo3Mpb; private MagicProgressBar demo4Mpb; private void assignViews() { demoMpc = (MagicProgressCircle) findViewById(R.id.demo_mpc); demoTv = (AnimTextView) findViewById(R.id.demo_tv); demo1Mpb = (MagicProgressBar) findViewById(R.id.demo_1_mpb); demo2Mpb = (MagicProgressBar) findViewById(R.id.demo_2_mpb); demo3Mpb = (MagicProgressBar) findViewById(R.id.demo_3_mpb); demo4Mpb = (MagicProgressBar) findViewById(R.id.demo_4_mpb); } }
package org.arquillian.cube.impl.await; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.arquillian.cube.spi.Cube; public class SleepingAwaitStrategy implements AwaitStrategy { private static final Logger log = Logger.getLogger(SleepingAwaitStrategy.class.getName()); public static final String TAG = "sleeping"; private static final int DEFAULT_SLEEP_TIME = 500; private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.MILLISECONDS; private static final String SLEEPING_TIME = "sleepTime"; private int sleepTime = DEFAULT_SLEEP_TIME; private TimeUnit timeUnit = DEFAULT_TIME_UNIT; public SleepingAwaitStrategy(Cube cube, Map<String, Object> params) { if (params.containsKey(SLEEPING_TIME)) { configureSleepingTime(params); } } private void configureSleepingTime(Map<String, Object> params) { Object sleepTime = params.get(SLEEPING_TIME); if(sleepTime instanceof Integer) { this.sleepTime = (Integer) sleepTime; } else { String sleepTimeWithUnit = ((String) sleepTime).trim(); if(sleepTimeWithUnit.endsWith("ms")) { this.timeUnit = TimeUnit.MILLISECONDS; } else { if(sleepTimeWithUnit.endsWith("s")) { this.timeUnit = TimeUnit.SECONDS; this.sleepTime = Integer.parseInt(sleepTimeWithUnit.substring(0, sleepTimeWithUnit.indexOf('s')).trim()); } else { this.timeUnit = TimeUnit.MILLISECONDS; this.sleepTime = Integer.parseInt(sleepTimeWithUnit.substring(0, sleepTimeWithUnit.indexOf("ms")).trim()); } } } } public int getSleepTime() { return sleepTime; } public TimeUnit getTimeUnit() { return timeUnit; } @Override public boolean await() { try { timeUnit.sleep(sleepTime); } catch (final InterruptedException e) { log.log(Level.WARNING, e.getMessage()); } return true; } }
package com.yahoo.documentapi.local; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentPut; import com.yahoo.document.fieldset.FieldSet; import com.yahoo.document.fieldset.FieldSetRepo; import com.yahoo.document.select.DocumentSelector; import com.yahoo.document.select.Result; import com.yahoo.document.select.parser.ParseException; import com.yahoo.documentapi.AckToken; import com.yahoo.documentapi.ProgressToken; import com.yahoo.documentapi.VisitorControlHandler; import com.yahoo.documentapi.VisitorDataHandler; import com.yahoo.documentapi.VisitorDataQueue; import com.yahoo.documentapi.VisitorParameters; import com.yahoo.documentapi.VisitorResponse; import com.yahoo.documentapi.VisitorSession; import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage; import com.yahoo.messagebus.Trace; import com.yahoo.yolean.Exceptions; import java.util.Comparator; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Phaser; import java.util.concurrent.atomic.AtomicReference; /** * Local visitor session that copies and iterates through all items in the local document access. * Each document must be ack'ed for the session to be done visiting, unless the destinatino is remote. * Only document puts are sent by this session, and this is done from a separate thread. * * @author jonmv */ public class LocalVisitorSession implements VisitorSession { private enum State { RUNNING, FAILURE, ABORTED, SUCCESS } private final VisitorDataHandler data; private final VisitorControlHandler control; private final Map<DocumentId, Document> outstanding; private final DocumentSelector selector; private final FieldSet fieldSet; private final AtomicReference<State> state; private final AtomicReference<Phaser> phaser; private final ProgressToken token; public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException { this.selector = new DocumentSelector(parameters.getDocumentSelection()); this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet()); this.token = parameters.getResumeToken(); if (parameters.getRemoteDataHandler() == null) { this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler(); this.data.reset(); this.data.setSession(this); } else { if (parameters.getLocalDataHandler() != null) throw new IllegalArgumentException("Cannot have both a remote and a local data handler"); this.data = null; } this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler(); this.control.reset(); this.control.setSession(this); this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString)); this.outstanding.putAll(access.documents); this.state = new AtomicReference<>(State.RUNNING); this.phaser = access.phaser; start(); } void start() { Phaser synchronizer = phaser.get(); if (synchronizer != null) synchronizer.register(); new Thread(() -> { try { // Iterate through all documents and pass on to data handler outstanding.forEach((id, document) -> { if (state.get() != State.RUNNING) return; try { if (selector.accepts(new DocumentPut(document)) != Result.TRUE) return; } catch (RuntimeException e) { return; } Document copy = new Document(document.getDataType(), document.getId()); new FieldSetRepo().copyFields(document, copy, fieldSet); if (synchronizer != null) synchronizer.arriveAndAwaitAdvance(); if (data != null) data.onMessage(new PutDocumentMessage(new DocumentPut(copy)), new AckToken(id)); else outstanding.remove(id); if (synchronizer != null) synchronizer.arriveAndAwaitAdvance(); }); // Transition to a terminal state when done state.updateAndGet(current -> { switch (current) { case RUNNING: control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success"); return State.SUCCESS; case ABORTED: control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user"); return State.ABORTED; default: control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");; return State.FAILURE; } }); } // Transition to failure terminal state on error catch (Exception e) { state.set(State.FAILURE); outstanding.clear(); control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e)); } finally { if (synchronizer != null) synchronizer.awaitAdvance(synchronizer.arriveAndDeregister()); if (data != null) data.onDone(); } }).start(); } @Override public boolean isDone() { return outstanding.isEmpty() // All documents ack'ed && control.isDone(); // Control handler has been notified } /** Returns the token set in the parameters used to create this. */ @Override public ProgressToken getProgress() { return token; } @Override public Trace getTrace() { throw new UnsupportedOperationException("Traces are not supported"); } @Override public boolean waitUntilDone(long timeoutMs) throws InterruptedException { return control.waitUntilDone(timeoutMs); } @Override public void ack(AckToken token) { outstanding.remove((DocumentId) token.ackObject); } @Override public void abort() { state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current); outstanding.clear(); } @Override public VisitorResponse getNext() { return data.getNext(); } @Override public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException { return data.getNext(timeoutMilliseconds); } @Override public void destroy() { abort(); } }
package org.dspace.curate; import java.util.Date; import java.text.DateFormat; import java.util.Locale; import java.text.SimpleDateFormat; import java.text.ParseException; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.dspace.authorize.AuthorizeException; import org.dspace.content.DSpaceObject; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.core.Context; import org.dspace.core.Constants; import org.dspace.workflow.WorkflowItem; import org.datadryad.api.DryadDataPackage; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.apache.log4j.Logger; /** * PlosItemsReviewMonth reports on items from PLOS publications that have been in the review workflow * longer than one month. * * The task succeeds if it was able to calculate the correct result. * * Input: a collection (any collection) * Output: a CSV indicating simple information about the PLOS data packages * that have been in review longer than one month * * @author Debra Fagan/Ryan Scherle */ @Distributive public class ItemsInReviewPlosMonth extends AbstractCurationTask { private static Logger log = Logger.getLogger(FileSimpleStats.class); private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); Context context; // Database objects static final String DB_MANUSCRIPT_TABLE = "manuscript"; static final String DB_COLUMN_ID = "manuscript_id"; static final String DB_COLUMN_ORGANIZATION_ID = "organization_id"; static final String DB_COLUMN_MSID = "msid"; static final String DB_COLUMN_VERSION = "version"; // active is stored as String because DatabaseManager doesn't support Boolean static final String DB_COLUMN_ACTIVE = "active"; static final String DB_COLUMN_JSON_DATA = "json_data"; static final String DB_ACTIVE_TRUE = String.valueOf(true); static final String DB_ACTIVE_FALSE = String.valueOf(false); @Override public void init(Curator curator, String taskId) throws IOException { super.init(curator, taskId); try { context = new Context(); } catch (SQLException e) { log.fatal("Cannot initialize database connection", e); } } /** returns data from the manuscript table based on the given Manuscript ID and organization code */ // private static Manuscript getManuscriptByIdAndOrg(Context myContext, String msid, String organizationCode) throws SQLException, IOException { private static String getManuscriptData(Context myContext, String msid, String organizationCode) throws SQLException, IOException { // Integer organizationId = getOrganizationInternalId(myContext, organizationCode); String query = "SELECT * FROM MANUSCRIPT WHERE msid = ? and active = ?"; TableRow row = DatabaseManager.querySingleTable(myContext, DB_MANUSCRIPT_TABLE, query, msid, DB_ACTIVE_TRUE); // Manuscript manuscript = manuscriptFromTableRow(row); // return manuscript; if(row != null) { String json_data = row.getStringColumn(DB_COLUMN_JSON_DATA); return json_data; } else { return null; } // return row; } /** returns the number of days between today's date and anotherDateMS, which is passed in */ public static int numDaysSince(long anotherDateMS) { Date todayDate = new Date(); long todayDateMS = todayDate.getTime(); long timeBetweenDatesMS = todayDateMS - anotherDateMS; long timeInReview = timeBetweenDatesMS / (24 * 60 * 60 * 1000); int numDaysInReview = (int) timeInReview; return numDaysInReview; } /** Perform **/ @Override public int perform(DSpaceObject dso) throws IOException { try { if (dso.getType() == Constants.COLLECTION) { report("itemID, publicationName, lastModificationDate"); // Iterate over the workflow "collection", calling this perform method on each item. // This bypasses the normal functionality of the curation task system, since items in // workflow don't yet belong to a real collection. WorkflowItem[] wfis = WorkflowItem.findAll(context); for(int i = 0; i < wfis.length; i++) { perform(wfis[i].getItem()); } } else if (dso.getType() == Constants.ITEM) { // determine whether this item is in the review workflow // workflow stage is stored in taskowner table DryadDataPackage dataPackage = new DryadDataPackage((Item)dso); log.debug("processing " + dataPackage.getItem().getID()); WorkflowItem wfi = dataPackage.getWorkflowItem(context); if(wfi != null) { log.debug(" -- is in workflow"); int workflowID = wfi.getID(); TableRow tr = DatabaseManager.querySingleTable(context,"taskowner", "SELECT * FROM taskowner WHERE workflow_item_id= ?", workflowID); if(tr != null && tr.getStringColumn("step_id").equals("reviewStep")) { log.debug(" -- is in review"); // report on the item int itemID = dataPackage.getItem().getID(); // RYAN, Where is getPublicationName method located??? Setter is in: - *DF* // /dspace/modules/api/src/main/java/org/datadryad/api/DryadDataPackage.java - *DF* String publicationName = dataPackage.getPublicationName(); Date lastModificationDate = dataPackage.getItem().getLastModified(); // Select and write to file PLOS items that have been in review 30 days or more - *DF* int NUMBEROFDAYS = 0; String PUBNAME = "plos"; String DRYADDOI = "doi:10.5061"; boolean notificationReceived = false; int numDaysInReview = numDaysSince(lastModificationDate.getTime()); report("Before processing: " + "Item ID: " + itemID + ", " + "Pub Name: " + publicationName + ", " + "Last Mod: " + lastModificationDate); if ( (publicationName.toLowerCase().contains(PUBNAME)) && (numDaysInReview >= NUMBEROFDAYS) ) { // report whether we have a plos notification for the item // 1. search for the data package DOI in the manuscript table, json_data field. // It should appear in the dataReviewURL of the json, but may appear in the dataAvailabilityStatement // 2. select json_data from manuscript where json_data like '%resource/doi:10.5061/dryad.p5hd0%'; //boolean notificationReceived = dataPackage.getPublicationName(); String doi = manuscript.dryadDataDOI; // get DOI and manuscript number - *DF* String packageDOI = dataPackage.getIdentifier(); String packageManuscriptNumber = dataPackage.getManuscriptNumber(); report("DOI: " + packageDOI); report("Manuscript #: " + packageManuscriptNumber); // Get manuscript from the Manuscript table based on manuscript number // Check to see if string contains "doi:10.5061" // If string contains "doi:10.5061" then print to xml file. String plosManuscriptData = getManuscriptData(context, packageManuscriptNumber, PUBNAME); // String dataDOI = plosManuscript.dryadDataDOI; report("ManuscriptData #: " + plosManuscriptData); if (plosManuscriptData != null) { // If string contains "doi:10.5061" then print to xml file if ( plosManuscriptData.toLowerCase().contains(DRYADDOI)) { report(itemID + ", " + publicationName + ", " + lastModificationDate); } } } } } // clean up the DSpace cache so we don't use excessive memory ((Item)dso).decache(); } } catch (SQLException e) { log.fatal("Problem with database access", e); } catch (AuthorizeException e) { log.fatal("Problem with authorization", e); } return Curator.CURATE_SUCCESS; } }
package com.voxeo.rayo.client; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.media.mscontrol.join.Joinable; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rayo.core.AcceptCommand; import com.rayo.core.AnswerCommand; import com.rayo.core.CallCommand; import com.rayo.core.CallRef; import com.rayo.core.CallRejectReason; import com.rayo.core.DialCommand; import com.rayo.core.DtmfCommand; import com.rayo.core.HangupCommand; import com.rayo.core.JoinCommand; import com.rayo.core.JoinDestinationType; import com.rayo.core.OfferEvent; import com.rayo.core.RedirectCommand; import com.rayo.core.RejectCommand; import com.rayo.core.UnjoinCommand; import com.rayo.core.verb.Ask; import com.rayo.core.verb.Choices; import com.rayo.core.verb.HoldCommand; import com.rayo.core.verb.Input; import com.rayo.core.verb.InputMode; import com.rayo.core.verb.MuteCommand; import com.rayo.core.verb.Output; import com.rayo.core.verb.Record; import com.rayo.core.verb.RecordPauseCommand; import com.rayo.core.verb.RecordResumeCommand; import com.rayo.core.verb.Say; import com.rayo.core.verb.SeekCommand; import com.rayo.core.verb.SpeedDownCommand; import com.rayo.core.verb.SpeedUpCommand; import com.rayo.core.verb.Ssml; import com.rayo.core.verb.StopCommand; import com.rayo.core.verb.Transfer; import com.rayo.core.verb.UnholdCommand; import com.rayo.core.verb.UnmuteCommand; import com.rayo.core.verb.VerbRef; import com.rayo.core.verb.VolumeDownCommand; import com.rayo.core.verb.VolumeUpCommand; import com.voxeo.moho.Participant.JoinType; import com.voxeo.rayo.client.auth.AuthenticationListener; import com.voxeo.rayo.client.exception.DialTimeoutException; import com.voxeo.rayo.client.filter.XmppObjectFilter; import com.voxeo.rayo.client.listener.RayoMessageListener; import com.voxeo.rayo.client.listener.StanzaListener; import com.voxeo.rayo.client.registry.Call; import com.voxeo.rayo.client.registry.CallsRegistry; import com.voxeo.rayo.client.verb.ClientPauseCommand; import com.voxeo.rayo.client.verb.ClientResumeCommand; import com.voxeo.rayo.client.xmpp.extensions.Extension; import com.voxeo.rayo.client.xmpp.stanza.IQ; import com.voxeo.rayo.client.xmpp.stanza.Ping; import com.voxeo.rayo.client.xmpp.stanza.Presence; import com.voxeo.rayo.client.xmpp.stanza.Presence.Show; import com.voxeo.rayo.client.xmpp.stanza.Presence.Type; import com.voxeo.rayo.client.xmpp.stanza.Stanza; /** * This class servers as a client to the Rayo XMPP platform. * * @author martin * */ public class RayoClient { private Logger logger = LoggerFactory.getLogger(RayoClient.class); protected final XmppConnection connection; public static final String DEFAULT_RESOURCE = "voxeo"; private CallsRegistry callRegistry = new CallsRegistry(); private String rayoServer; private ReentrantReadWriteLock connectionLock = new ReentrantReadWriteLock(); private Timer pingTimer = null; /** * Creates a new client object. This object will be used to interact with an Rayo server. * * @param server Rayo Server that this client will be connecting to */ public RayoClient(String xmppServer, String rayoServer) { this(xmppServer, null, rayoServer); } /** * Creates a new client object that will use the specified port number. * This object will be used to interact with an Rayo server. * * @param server Server that this client will be connecting to * @param port Port number that the server is listening at */ public RayoClient(String xmppServer, Integer port, String rayoServer) { connection = new SimpleXmppConnection(xmppServer, port); this.rayoServer = rayoServer; } /** * Creates a Rayo Client using the given XMPP connection * * @param connection XMPP connection that will be used * @param rayoServer Rayo Sever to connect this Rayo client to */ public RayoClient(XmppConnection connection, String rayoServer) { this.connection = connection; this.rayoServer = rayoServer; } /** * Connects and authenticates into the Rayo Server. By default it will use the resource 'voxeo'. * * @param username Rayo username * @param password Rayo password * * @throws XmppException If the client is not able to connect or authenticate into the Rayo Server */ public void connect(String username, String password) throws XmppException { connect(username, password, DEFAULT_RESOURCE); } /** * Connects and authenticates into the Rayo Server. By default it will use the resource 'voxeo'. * * @param username Rayo username * @param password Rayo password * @param resource Resource that will be used in this communication * * @throws XmppException If the client is not able to connect or authenticate into the Rayo Server */ public void connect(String username, String password, String resource) throws XmppException { connect(username, password, resource, 5); } /** * Connects and authenticates into the Rayo Server. By default it will use the resource 'voxeo'. * * @param username Rayo username * @param password Rayo password * @param resource Resource that will be used in this communication * * @throws XmppException If the client is not able to connect or authenticate into the Rayo Server */ public void connect(String username, String password, String resource, int timeout) throws XmppException { Lock lock = connectionLock.writeLock(); lock.lock(); if (connection.isConnected()) { try { disconnect(); } catch (Exception e) { e.printStackTrace(); } } try { logger.info("Connecting Rayo client XMPP Connection"); if (!connection.isConnected()) { connection.connect(timeout); connection.login(username, password, resource, timeout); connection.addStanzaListener(new RayoMessageListener("offer") { @Override @SuppressWarnings("rawtypes") public void messageReceived(Object object) { //TODO: Stanza should have methods to fetch the JID node name, domain, etc. Stanza stanza = (Stanza)object; int at = stanza.getFrom().indexOf('@'); String callId = stanza.getFrom().substring(0, at); String domain = stanza.getFrom().substring(at+1); if (domain.contains(":")) { domain = domain.substring(0, domain.indexOf(':')); } Call call = new Call(callId, domain); callRegistry.registerCall(callId, call); } }); connection.addStanzaListener(new RayoMessageListener("end") { @Override @SuppressWarnings("rawtypes") public void messageReceived(Object object) { //TODO: Stanza should have methods to fetch the JID node name, domain, etc. Stanza stanza = (Stanza)object; int at = stanza.getFrom().indexOf('@'); String callId = stanza.getFrom().substring(0, at); callRegistry.unregisterCal(callId); } }); broadcastAvailability(); TimerTask pingTask = new TimerTask() { @Override public void run() { ping(); } }; pingTimer = new Timer(); pingTimer.schedule(pingTask, 5000, 30000); connection.addStanzaListener(new RayoMessageListener("ping") { @Override public void messageReceived(Object object) { IQ iq = (IQ)object; if (!iq.isError()) { // pong try { sendIQ(iq.result()); } catch (XmppException e) { e.printStackTrace(); } } } }); } else { logger.error("Trying to connect while the old XMPP connection is active. Please, disconnect first"); } logger.info("Rayo client is now connected"); } catch (XmppException xe) { logger.error("Error while trying to opean an XMPP connection"); xe.printStackTrace(); throw xe; } catch (Exception e) { logger.error("Error while trying to opean an XMPP connection"); e.printStackTrace(); throw new XmppException(e.getMessage()); } finally { lock.unlock(); } } public void setAvailable(boolean status) throws XmppException { if (status == true) { broadcastAvailability(); } else { broadcastUnavailability(); } } public void setStatus(Show status) throws XmppException { Presence presence = new Presence() .setId(UUID.randomUUID().toString()) .setFrom(connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource()) .setTo(rayoServer) .setShow(status); connection.send(presence); } private void broadcastAvailability() throws XmppException { Presence presence = new Presence() .setId(UUID.randomUUID().toString()) .setShow(Show.chat); connection.send(presence); presence = new Presence() .setId(UUID.randomUUID().toString()) .setFrom(connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource()) .setTo(rayoServer) .setShow(Show.chat); connection.send(presence); } private void broadcastUnavailability() throws XmppException { Presence presence = new Presence() .setId(UUID.randomUUID().toString()) .setFrom(connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource()) .setTo(rayoServer) .setType(Type.unavailable); connection.send(presence); presence = new Presence() .setId(UUID.randomUUID().toString()) .setType(Type.unavailable); connection.send(presence); } public void unavailable(String mixerName) throws XmppException { Presence presence = new Presence() .setId(UUID.randomUUID().toString()) .setFrom(connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource()) .setTo(mixerName + "@" +rayoServer) .setType(Type.unavailable); connection.send(presence); } public void available(String mixerName) throws XmppException { Presence presence = new Presence() .setId(UUID.randomUUID().toString()) .setFrom(connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource()) .setTo(mixerName + "@" + rayoServer) .setShow(Show.chat); connection.send(presence); } /** * Adds a callback class to listen for events on all the incoming stanzas. * * @param listener Stanza Callback. */ public void addStanzaListener(StanzaListener listener) { Lock lock = connectionLock.readLock(); lock.lock(); try { connection.addStanzaListener(listener); } finally { lock.unlock(); } } /** * Removes a stanza listener * * @param listener Stanza Callback to be removed */ public void removeStanzaListener(StanzaListener listener) { Lock lock = connectionLock.readLock(); lock.lock(); try { connection.removeStanzaListener(listener); } finally { lock.unlock(); } } /** * Adds a callback class to listen for authentication events. * * @param listener Callback. */ public void addAuthenticationListener(AuthenticationListener listener) { Lock lock = connectionLock.readLock(); lock.lock(); try { connection.addAuthenticationListener(listener); } finally { lock.unlock(); } } /** * Adds an XMPP filter * * @param filter Filter object to be added */ public void addFilter(XmppObjectFilter filter) { Lock lock = connectionLock.readLock(); lock.lock(); try { connection.addFilter(filter); } finally { lock.unlock(); } } /** * Removes an XMPP filter * * @param filter Filter object to be removed */ public void removeFilter(XmppObjectFilter filter) { Lock lock = connectionLock.readLock(); lock.lock(); try { connection.removeFilter(filter); } finally { lock.unlock(); } } /** * Disconnects this client connection from the Rayo server * */ public void disconnect() throws XmppException { Lock lock = connectionLock.writeLock(); lock.lock(); try { logger.info("Disconnecting Rayo client XMPP Connection"); if (connection.isConnected()) { broadcastUnavailability(); connection.disconnect(); } } finally { logger.info("Rayo Client XMPP Connection has been disconnected"); lock.unlock(); if (pingTimer != null) { pingTimer.cancel(); pingTimer = null; } } } /** * <p>Waits for an Offer Event. Shortcut method to wait for an incoming call.</p> * * @return OfferEvent Offer event that has been received * * @throws XmppException If there is any problem waiting for offer event */ public OfferEvent waitForOffer() throws XmppException { return waitForOffer(null); } /** * <p>Waits for an Offer Event. Shortcut method to wait for an incoming call.</p> * * @timeout Timeout * @return OfferEvent Offer event that has been received * * @throws XmppException If there is any problem waiting for offer event */ public OfferEvent waitForOffer(Integer timeout) throws XmppException { final StringBuilder callId = new StringBuilder(); RayoMessageListener tempListener = new RayoMessageListener("offer") { @Override @SuppressWarnings("rawtypes") public void messageReceived(Object object) { Stanza stanza = (Stanza)object; callId.append(stanza.getFrom().substring(0, stanza.getFrom().indexOf('@'))); } }; addStanzaListener(tempListener); try { OfferEvent stanza = waitFor("offer", OfferEvent.class, timeout); OfferEvent offer = new OfferEvent(callId.toString()); offer.setTo(stanza.getTo()); offer.setFrom(stanza.getFrom()); offer.setHeaders(stanza.getHeaders()); return offer; } finally { removeStanzaListener(tempListener); } } /** * <p>Waits for an Rayo message. This is a blocking call and therefore should be used carefully. * When invoked, the invoking thread will block until it receives the specified Rayo * message.</p> * * @param rayoMessage Rayo message that the invoking thread will be waiting for * * @return Object The first Rayo messaging received that matches the specified message name * * @throws XmppException If there is any problem waiting for the message */ public Object waitFor(String rayoMessage) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { Extension extension = (Extension)connection.waitForExtension(rayoMessage); return extension.getObject(); } finally { lock.unlock(); } } /** * <p>Waits for an Rayo message. This is a blocking call and therefore should be used carefully. * When invoked, the invoking thread will block until it receives the specified Rayo * message.</p> * * @param rayoMessage Rayo message that the invoking thread will be waiting for * @param clazz Class to cast the returning object to * * @return T The first Rayo messaging received that matches the specified message name * * @throws XmppException If there is any problem waiting for the message */ @SuppressWarnings("unchecked") public <T> T waitFor(String rayoMessage, Class<T> clazz) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { Extension extension = (Extension)connection.waitForExtension(rayoMessage); return (T)extension.getObject(); } finally { lock.unlock(); } } /** * <p>Waits for an Rayo message. This is a blocking call but uses a timeout to specify * the amount of time that the connection will wait until the specified message is received. * If no message is received during the specified timeout then a <code>null</code> object * will be returned.</p> * * @param rayoMessage Rayo message that the invoking thread will be waiting for * @param timeout Timeout that will be used when waiting for an incoming Rayo message * * @return Object The first Rayo messaging received that matches the specified message name * or <code>null</code> if no message is received during the specified timeout * * @throws XmppException If there is any problem waiting for the message */ public Object waitFor(String extensionName, int timeout) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { Extension extension = (Extension)connection.waitForExtension(extensionName, timeout); return extension.getObject(); } finally { lock.unlock(); } } /** * <p>Waits for an Rayo message. This is a blocking call but uses a timeout to specify * the amount of time that the connection will wait until the specified message is received. * If no message is received during the specified timeout then a <code>null</code> object * will be returned.</p> * * @param rayoMessage Rayo message that the invoking thread will be waiting for * @param clazz Class to cast the returning object to * @param timeout Timeout that will be used when waiting for an incoming Rayo message * * @return Object The first Rayo messaging received that matches the specified message name * or <code>null</code> if no message is received during the specified timeout * * @throws XmppException If there is any problem waiting for the message */ @SuppressWarnings("unchecked") public <T> T waitFor(String extensionName, Class<T> clazz, Integer timeout) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { Extension extension = (Extension)connection.waitForExtension(extensionName, timeout); return (T)extension.getObject(); } finally { lock.unlock(); } } /** * Answers the call with the id specified as a parameter. * * @param callId Id of the call that will be answered * * @return IQ Resulting IQ * * @throws XmppException If there is any issue while answering the call */ public IQ answer(String callId) throws XmppException { return answer(callId, new AnswerCommand()); } /** * Answers the call with the id specified as a parameter. * * @param callId Id of the call that will be answered * @param command Answer command * * @return IQ Resulting IQ * * @throws XmppException If there is any issue while answering the call */ public IQ answer(String callId, AnswerCommand command) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(command)); return sendIQ(iq); } /** * Accepts the call with the id specified as a parameter. * * @param callId Id of the call that will be accepted * @return IQ Resulting IQ * @throws XmppException If there is any issue while accepting the call */ public IQ accept(String callId) throws XmppException { return accept(callId, new AcceptCommand()); } /** * Accepts the call with the id specified as a parameter. * * @param callId Id of the call that will be accepted * @param command Accept command * @return IQ Resulting IQ * @throws XmppException If there is any issue while accepting the call */ public IQ accept(String callId, AcceptCommand command) throws XmppException { return command(command, callId); } /** * Rejects the latest call that this connection has received from the Rayo server * * @param callId Id of the call * @return IQ Resulting IQ * * @throws XmppException If there is any issue while rejecting the call */ public IQ reject(String callId) throws XmppException { return reject(CallRejectReason.DECLINE, callId); } /** * Rejects a call id * * @param reject Reject command * @param callId Id of the call * @return IQ Resulting IQ * * @throws XmppException If there is any issue while rejecting the call */ public IQ reject(String callId, RejectCommand reject) throws XmppException { return command(reject, callId); } /** * Rejects the call with the id specified as a parameter. * * @param callId Id of the call that will be accepted * @return IQ Resulting IQ * * @throws XmppException If there is any issue while rejecting the call */ public IQ reject(CallRejectReason reason, String callId) throws XmppException { RejectCommand reject = new RejectCommand(callId, reason); return command(reject, callId); } public VerbRef outputSsml(String ssml, String callId) throws XmppException { return internalOutput(new Ssml(ssml), callId); } public VerbRef output(URI uri, String callId) throws XmppException { return internalOutput(new Ssml(String.format("<audio src=\"%s\"/>",uri.toString())), callId); } public VerbRef output(String text, String callId) throws XmppException { return internalOutput(new Ssml(text), callId); } /** * Sends a 'Say' command including some SSML text * * @param ssml SSML text * @param callId Id of the call to which the say command will be sent * * @return VerbRef VerbRef instance that allows to handle the say stream * * @throws XmppException If there is any issues while sending the say command */ public VerbRef saySsml(String ssml, String callId) throws XmppException { return internalSay(new Ssml(ssml), callId); } /** * Sends a 'Say' command to Rayo that will play the specified audio file * * @param audio URI to the audio file * @param callId Id of the call * * @return VerbRef VerbRef instance that allows to handle the say stream * * @throws XmppException If there is any issues while sending the say command * @throws URISyntaxException If the specified audio file is not a valid URI */ public VerbRef sayAudio(String audio, String callId) throws XmppException, URISyntaxException { return say(new URI(audio), callId); } /** * Sends a 'Say' command to Rayo that will play the specified audio file * * @param uri URI to an audio resource that will be played * @param callId Id of the call to which the say command will be sent * @return VerbRef VerbRef instance that allows to handle the say stream * * @throws XmppException If there is any issues while sending the say command */ public VerbRef say(URI uri, String callId) throws XmppException { return internalSay(new Ssml(String.format("<audio src=\"%s\"/>",uri.toString())), callId); } /** * Instructs Rayo to say the specified text on the call with the specified id * * @param text Text that we want to say * @param callId Id of the call to which the say command will be sent * @return VerbRef VerbRef instance that allows to handle the say stream * * @throws XmppException If there is any issues while sending the say command */ public VerbRef say(String text, String callId) throws XmppException { return internalSay(new Ssml(text), callId); } /** * Transfers a specific call to another destination * * @param to URI where the call will be transfered * @param callId Id of the call we want to transfer * @return IQ Resulting IQ * @throws XmppException If there is any issue while transfering the call */ public IQ transfer(URI to, String callId) throws XmppException { List<URI> list = new ArrayList<URI>(); list.add(to); return transfer(null, list, callId); } /** * Transfers a specific call to another destination * * @param to URI where the call will be transfered * @param callId Id of the call we want to transfer * @return IQ Resulting IQ * @throws XmppException If there is any issue while transfering the call * @throws URISyntaxException If an invalid URI is passed as a parameter */ public IQ transfer(String to, String callId) throws XmppException, URISyntaxException { return transfer(new URI(to), callId); } public IQ transfer(List<URI> to, String callId) throws XmppException { return transfer(null, to, callId); } /** * Transfers a call to another phone speaking some text before doing the transfer. * * @param text Text that will be prompted to the user * @param to URI of the call destination * @param callId Id of the call that we want to transfer * @return IQ Resulting IQ * @throws XmppException If there is any issue while transfering the call */ public IQ transfer(String text, List<URI> to, String callId) throws XmppException { Transfer transfer = new Transfer(); transfer.setTimeout(new Duration(20000)); transfer.setTerminator(' if (text != null) { Ssml ssml = new Ssml(text); transfer.setRingbackTone(ssml); } transfer.setTo(to); return transfer(transfer, callId); } /** * Transfers a call to another phone with the specified settings * * @param transfer Model object with all the transfer settings * @param callId Id of the call that we want to transfer * @return IQ Resulting IQ * * @throws XmppException If there is any issue while transfering the call */ public IQ transfer(Transfer transfer,String callId) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(transfer)); return sendIQ(iq); } public IQ hold(String callId) throws XmppException { HoldCommand hold = new HoldCommand(); return command(hold,callId); } public IQ unhold(String callId) throws XmppException { UnholdCommand unhold = new UnholdCommand(); return command(unhold,callId); } public IQ mute(String callId) throws XmppException { MuteCommand mute = new MuteCommand(); return command(mute,callId); } public IQ unmute(String callId) throws XmppException { UnmuteCommand unmute = new UnmuteCommand(); return command(unmute,callId); } /** * Calls a specific destination * * @param to URI to dial * * @throws XmppException If there is any issue while dialing */ public CallRef dial(URI to) throws XmppException { return dial(null, null, to); } /** * Sends a dial message to the specified Rayo/Gateway node * to dial a destination from the specified URI * * @param to URI that we want to dial * * @throws XmppException If there is any issue while transfering the call */ public CallRef dial(String destination, URI to) throws XmppException { return dial(destination, null, to); } /** * Sends a dial message to the connected node * to dial a destination from the specified URI * * @param from URI that is dialing * @param to URI that we want to dial * * @throws XmppException If there is any issue while transfering the call */ public CallRef dial(URI from, URI to) throws XmppException { return dial(null, from, to); } /** * Sends a dial message to a specific rayo node or gateway * to dial a destination from the specified URI * * @param String Rayo/Gateway node * @param from URI that is dialing * @param to URI that we want to dial * * @throws XmppException If there is any issue while transfering the call */ public CallRef dial(String destination, URI from, URI to) throws XmppException { DialCommand dial = new DialCommand(); dial.setTo(to); if (from == null) { try { from = new URI(String.format("sip:%s:5060",InetAddress.getLocalHost().getHostAddress())); } catch (Exception e) { e.printStackTrace(); } } dial.setFrom(from); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(rayoServer) .setChild(Extension.create(dial)); CallRef ref = getCallRef(sendAndGetRef(null, iq)); if (ref == null) { throw new DialTimeoutException(); } // dials return a call id on refs, so different than other components //ref.setCallId(ref.getVerbId()); return ref; } private IQ sendAndGetRef(String callId, IQ iq) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { IQ result = ((IQ)connection.sendAndWait(iq)); if (result != null) { if (result.hasChild("error")) { throw new XmppException(result.getError()); } return result; } else { return null; } } finally { lock.unlock(); } } private CallRef getCallRef(IQ iq) { return (CallRef)iq.getExtension().getObject(); } private VerbRef getVerbRef(IQ iq) { CallRef callRef = (CallRef)iq.getExtension().getObject(); return new VerbRef(iq.getFromJid().getNode(), callRef.getCallId()); } /** * Instructs Rayo to ask a question with the specified choices on the call with the given id * * @param text Text that will be prompted * @param choicesText Choices * @param callId Id of the call in which the question will be asked * @return IQ Resulting IQ * @throws XmppException If there is any issue while asking the question */ public IQ ask(String text, String choicesText, String callId) throws XmppException { Ask ask = new Ask(); Ssml ssml = new Ssml(text); ask.setPrompt(ssml); List<Choices> list = new ArrayList<Choices>(); Choices choices = new Choices(); choices.setContent(choicesText); choices.setContentType("application/grammar+voxeo"); list.add(choices); ask.setChoices(list); ask.setTerminator(' ask.setMode(InputMode.DTMF); ask.setTimeout(new Duration(650000)); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(ask)); return sendIQ(iq); } public VerbRef input(String simpleGrammar, String callId) throws XmppException { Input input = new Input(); List<Choices> choices = new ArrayList<Choices>(); Choices choice = new Choices(); choice.setContent(simpleGrammar); choice.setContentType("application/grammar+voxeo"); choices.add(choice); input.setGrammars(choices); return input(input, callId); } public VerbRef input(Input input, String callId) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(input)); return getVerbRef(sendAndGetRef(callId, iq)); } private VerbRef internalSay(Ssml item, String callId) throws XmppException { Say say = new Say(); say.setPrompt(item); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(say)); return getVerbRef(sendAndGetRef(callId, iq)); } private VerbRef internalOutput(Ssml item, String callId) throws XmppException { Output output = new Output(); output.setPrompt(item); return output(output, callId); } public VerbRef output(Output output, String callId) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(output)); return getVerbRef(sendAndGetRef(callId, iq)); } /** * Pauses a verb component * * @param ref Verb component that we want to pause * @return IQ Resulting IQ */ public IQ pause(VerbRef ref) throws XmppException { ClientPauseCommand pause = new ClientPauseCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(pause)); return sendIQ(iq); } /** * Resumes a verb component * * @param ref Verb component that we want to resume * @return IQ Resulting IQ */ public IQ resume(VerbRef ref) throws XmppException { ClientResumeCommand resume = new ClientResumeCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(resume)); return sendIQ(iq); } /** * Speeds up * * @param ref Verb component that we want to speed up * @return IQ Resulting IQ */ public IQ speedUp(VerbRef ref) throws XmppException { SpeedUpCommand speedup = new SpeedUpCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(speedup)); return sendIQ(iq); } /** * Speeds down * * @param ref Verb component that we want to speed up * @return IQ Resulting IQ */ public IQ speedDown(VerbRef ref) throws XmppException { SpeedDownCommand speedDown = new SpeedDownCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(speedDown)); return sendIQ(iq); } /** * Turn volume up * * @param ref Verb component that we want to turn volume up * @return IQ Resulting IQ */ public IQ volumeUp(VerbRef ref) throws XmppException { VolumeUpCommand volumeUp = new VolumeUpCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(volumeUp)); return sendIQ(iq); } /** * Turn volume down * * @param ref Verb component that we want to turn volume down * @return IQ Resulting IQ */ public IQ volumeDown(VerbRef ref) throws XmppException { VolumeDownCommand volumeDown = new VolumeDownCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(volumeDown)); return sendIQ(iq); } /** * Pauses a records component * * @param ref Verb component that we want to pause */ public IQ pauseRecord(VerbRef ref) throws XmppException { RecordPauseCommand pause = new RecordPauseCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(pause)); return sendIQ(iq); } /** * Resumes a record component * * @param ref Verb component that we want to resume */ public IQ resumeRecord(VerbRef ref) throws XmppException { RecordResumeCommand resume = new RecordResumeCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(resume)); return sendIQ(iq); } /** * Performs a seek operation on the given verb * * @param ref Verb component that we want to resume * @param command Seek command to execute */ public IQ seek(VerbRef ref, SeekCommand command) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(command)); return sendIQ(iq); } /** * Stops a verb component * * @param ref Verb component that we want to stop */ public IQ stop(VerbRef ref) throws XmppException { StopCommand stop = new StopCommand(); IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(ref.getCallId(),ref.getVerbId())) .setChild(Extension.create(stop)); return sendIQ(iq); } public VerbRef record(String callId) throws XmppException { return record(new Record(), callId); } public VerbRef record(Record record, String callId) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(record)); return getVerbRef(sendAndGetRef(callId, iq)); } /** * Hangs up the specified call id * * @param callId Id of the call to be hung up * @return IQ Resulting IQ */ public IQ hangup(String callId) throws XmppException { return hangup(callId, new HangupCommand(null)); } /** * Hangs up the specified call id * * @param command Hangup command * @return IQ Resulting IQ */ public IQ hangup(String callId, HangupCommand command) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(command)); return sendIQ(iq); } public IQ unjoin(String from, JoinDestinationType type, String callId) throws XmppException { UnjoinCommand unjoin = new UnjoinCommand(); unjoin.setFrom(from); unjoin.setType(type); return command(unjoin,callId); } public IQ join(String to, String media, String direction, JoinDestinationType type, String callId) throws XmppException { JoinCommand join = new JoinCommand(); join.setTo(to); if (direction != null) { join.setDirection(Joinable.Direction.valueOf(direction.toUpperCase())); } else { join.setDirection(null); } if (media != null) { join.setMedia(JoinType.valueOf(media.toUpperCase())); } else { join.setMedia(null); } join.setType(type); return command(join,callId); } public IQ join(JoinCommand join, String callId) throws XmppException { return command(join,callId); } public IQ dtmf(String tones, String callId) throws XmppException { DtmfCommand dtmf = new DtmfCommand(tones); return command(dtmf, callId); } public IQ command(CallCommand command, String callId) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(buildTo(callId)) .setChild(Extension.create(command)); return sendIQ(iq); } public CallRef dial(DialCommand command) throws XmppException { IQ iq = new IQ(IQ.Type.set) .setFrom(buildFrom()) .setTo(rayoServer) .setChild(Extension.create(command)); CallRef ref = getCallRef(sendAndGetRef(null, iq)); if (ref == null) { throw new DialTimeoutException(); } // dials return a call id on refs, so different than other components //ref.setCallId(ref.getVerbId()); return ref; } /** * Redirects an existing call to the given URI * * @param uri URI for redirecting the call to * @param callId Id of the call to redirect */ public IQ redirect(URI uri, String callId) throws XmppException { RedirectCommand redirect = new RedirectCommand(); redirect.setTo(uri); return redirect(redirect, callId); } /** * Redirects an existing call * * @param command Redirect command * @param callId Id of the call to redirect * @return IQ Resulting IQ */ public IQ redirect(RedirectCommand command, String callId) throws XmppException { return command(command, callId); } protected IQ sendIQ(IQ iq) throws XmppException { Lock lock = connectionLock.readLock(); lock.lock(); try { return (IQ)connection.sendAndWait(iq); } finally { lock.unlock(); } } private String buildFrom() { return connection.getUsername() + "@" + connection.getServiceName() + "/" + connection.getResource(); } private String buildTo(String callId) { return buildTo(callId, null); } private String buildTo(String callId, String resourceId) { String to = callId + "@" + rayoServer; if (resourceId != null) { to = to + "/" + resourceId; } return to; } public XmppConnection getXmppConnection() { return connection; } private void ping() { Lock lock = connectionLock.readLock(); lock.lock(); try { if (connection.isConnected()) { IQ ping = new IQ(IQ.Type.get) .setFrom(buildFrom()) .setTo(rayoServer) .setChild(new Ping()); try { connection.send(ping); } catch (XmppException e) { e.printStackTrace(); } } } finally { lock.unlock(); } } }
package de.fosd.jdime.common; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import org.apache.log4j.Logger; import AST.ASTNode; import AST.BytecodeParser; import AST.CompilationUnit; import AST.ConstructorDecl; import AST.FieldDecl; import AST.FieldDeclaration; import AST.ImportDecl; import AST.InterfaceDecl; import AST.JavaParser; import AST.MethodDecl; import AST.Program; import de.fosd.jdime.common.operations.ConflictOperation; import de.fosd.jdime.common.operations.MergeOperation; import de.fosd.jdime.matcher.Color; import de.fosd.jdime.matcher.Matching; import de.fosd.jdime.strategy.ASTNodeStrategy; import de.fosd.jdime.strategy.MergeStrategy; /** * @author Olaf Lessenich * */ public class ASTNodeArtifact extends Artifact<ASTNodeArtifact> { /** * Logger. */ private static final Logger LOG = Logger.getLogger(ASTNodeArtifact.class); /** * Initializes parser. * * @param p * program */ private static void initParser(final Program p) { p.initJavaParser(new JavaParser() { @Override public CompilationUnit parse(final java.io.InputStream is, final String fileName) throws java.io.IOException, beaver.Parser.Exception { return new parser.JavaParser().parse(is, fileName); } }); } /** * Initializes a program. * * @return program */ private static Program initProgram() { Program program = new Program(); program.state().reset(); program.initBytecodeReader(new BytecodeParser()); initParser(program); return program; } /** * Encapsulated ASTNode. */ private ASTNode<?> astnode = null; /** * Constructor class. */ public ASTNodeArtifact() { } /** * @param astnode * astnode */ public ASTNodeArtifact(final ASTNode<?> astnode) { assert (astnode != null); this.astnode = astnode; } /** * Constructs an ASTNodeArtifact from a FileArtifact. * * @param artifact * file artifact */ public ASTNodeArtifact(final FileArtifact artifact) { assert (artifact != null); setRevision(artifact.getRevision()); ASTNode<?> astnode = null; if (artifact.isEmptyDummy()) { astnode = new ASTNode<>(); setEmptyDummy(true); } else { Program p = initProgram(); p.addSourceFile(artifact.getPath()); astnode = p; } assert (astnode != null); this.astnode = astnode; renumber(1, this); } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#addChild(de.fosd.jdime.common.Artifact) */ @Override public final ASTNodeArtifact addChild(final ASTNodeArtifact child) throws IOException { if (child.isConflict()) { child.setParent(this); children.add(child); return child; } ASTNodeArtifact myChild; try { myChild = new ASTNodeArtifact((ASTNode<?>) child.astnode.clone()); myChild.deleteChildren(); myChild.setRevision(child.getRevision()); myChild.setParent(this); myChild.astnode.setParent(astnode); myChild.setRevision(child.getRevision()); myChild.setNumber(child.getNumber()); myChild.cloneMatches(child); if (children == null) { initializeChildren(); } children.add(myChild); // astnode.flushCaches(); if (LOG.isTraceEnabled()) { LOG.trace("Added child " + myChild.getId() + " to parent node " + getId()); } return myChild; } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new NotYetImplementedException(); } } @Override public final int compareTo(final ASTNodeArtifact o) { if (hasUniqueLabels()) { return astnode.dumpString().compareTo(o.astnode.dumpString()); } else { throw new RuntimeException("This artifact is not comparable."); } } /* * (non-Javadoc) * * @see * de.fosd.jdime.common.Artifact#copyArtifact(de.fosd.jdime.common.Artifact) */ @Override public final void copyArtifact(final ASTNodeArtifact destination) throws IOException { ASTNodeArtifact copy = destination.addChild(this); if (!isConflict() && hasChildren()) { for (ASTNodeArtifact child : getChildren()) { child.copyArtifact(copy); } } } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createArtifact(boolean) */ @Override public final void createArtifact(final boolean isLeaf) throws IOException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#createEmptyDummy() */ @Override public final ASTNodeArtifact createEmptyDummy() throws FileNotFoundException { ASTNodeArtifact dummy = new ASTNodeArtifact(); dummy.astnode = new ASTNode<>(); dummy.setEmptyDummy(true); dummy.setRevision(getRevision()); return dummy; } public final void deleteChildren() { while (hasChildren()) { ASTNodeArtifact child = getChild(0); child.astnode = null; child = null; children.remove(0); } } /** * Returns the AST in dot-format. * * @param includeNumbers * include node number in label if true * @return AST in dot-format. */ public final String dumpGraphvizTree(final boolean includeNumbers) { assert (astnode != null); StringBuffer sb = new StringBuffer(); sb.append(getNumber() + "[label=\""); // node label if (includeNumbers) { sb.append("(" + getNumber() + ") "); } sb.append(astnode.dumpString()); sb.append("\""); if (hasMatches()) { sb.append(", fillcolor = green, style = filled"); } sb.append("];"); sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpGraphvizTree(includeNumbers)); // edge sb.append(getNumber() + "->" + child.getNumber() + ";" + System.lineSeparator()); } return sb.toString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#dumpTree(java.lang.String) */ @Override protected final String dumpTree(final String indent) { assert (astnode != null); StringBuffer sb = new StringBuffer(); // node itself Matching<ASTNodeArtifact> m = null; // color if (!isConflict() && hasMatches()) { Set<Revision> matchingRevisions = matches.keySet(); // print color code String color = ""; for (Revision rev : matchingRevisions) { m = getMatching(rev); color = m.getColor().toShell(); } sb.append(color); } if (isConflict()) { sb.append(Color.RED.toShell()); sb.append(indent + "(" + getId() + ") "); sb.append(this); sb.append(System.lineSeparator()); sb.append(Color.RED.toShell()); sb.append("<<<<<<< "); sb.append(System.lineSeparator()); // children if (left != null) { sb.append(left.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append("======= "); sb.append(System.lineSeparator()); // children if (right != null) { sb.append(right.dumpTree(indent)); } sb.append(Color.RED.toShell()); sb.append(">>>>>>> "); sb.append(System.lineSeparator()); } else { sb.append(indent + "(" + getId() + ") "); sb.append(this); if (hasMatches()) { assert (m != null); sb.append(" <=> (" + m.getMatchingArtifact(this).getId() + ")"); sb.append(Color.DEFAULT.toShell()); } sb.append(System.lineSeparator()); // children for (ASTNodeArtifact child : getChildren()) { sb.append(child.dumpTree(indent + " ")); } } return sb.toString(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ // @Override // public final boolean equals(final Object obj) { // assert (astnode != null); // assert (obj != null); // assert (obj instanceof ASTNodeArtifact); // return astnode.dumpString().equals( // ((ASTNodeArtifact) obj).astnode.dumpString()); /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#exists() */ @Override public final boolean exists() { return astnode != null; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#getId() */ @Override public final String getId() { return getRevision() + ":" + getNumber(); } @Override public final String getStatsKey(final MergeContext context) { return "nodes"; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#hashCode() */ @Override public final int hashCode() { return astnode.dumpString().hashCode(); } @Override public final boolean hasUniqueLabels() { if (astnode instanceof ImportDecl) { return true; } return false; } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#initializeChildren() */ @Override public final void initializeChildren() { assert (astnode != null); ArtifactList<ASTNodeArtifact> children = new ArtifactList<ASTNodeArtifact>(); for (int i = 0; i < astnode.getNumChildNoTransform(); i++) { ASTNodeArtifact child = new ASTNodeArtifact(astnode.getChild(i)); child.setParent(this); child.setRevision(getRevision()); children.add(child); } setChildren(children); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isEmpty() */ @Override public final boolean isEmpty() { return !hasChildren(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#isLeaf() */ @Override public final boolean isLeaf() { // TODO Auto-generated method stub return false; } /** * Returns whether declaration order is significant for this node. * * @return whether declaration order is significant for this node */ public final boolean isOrdered() { if (astnode instanceof CompilationUnit || astnode instanceof ConstructorDecl || astnode instanceof MethodDecl || astnode instanceof InterfaceDecl || astnode instanceof FieldDecl || astnode instanceof FieldDeclaration || astnode instanceof ImportDecl) { return false; } return true; } /** * Returns whether a node matches another node. * * @param other * node to compare with. * @return true if the node matches another node. */ public final boolean matches(final ASTNodeArtifact other) { assert (astnode != null); assert (other != null); assert (other.astnode != null); if (astnode instanceof ImportDecl && other.astnode instanceof ImportDecl) { return astnode.toString().equals(other.astnode.toString()); } return astnode.dumpString().equals(other.astnode.dumpString()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#merge(de.fosd.jdime.common.operations. * MergeOperation, de.fosd.jdime.common.MergeContext) */ @Override public final void merge(final MergeOperation<ASTNodeArtifact> operation, final MergeContext context) throws IOException, InterruptedException { assert (operation != null); assert (context != null); MergeStrategy<ASTNodeArtifact> strategy = new ASTNodeStrategy(); if (LOG.isDebugEnabled()) { LOG.debug("Using strategy: " + strategy.toString()); } MergeTriple<ASTNodeArtifact> triple = operation.getMergeTriple(); assert (triple != null); ASTNodeArtifact left, right, target; left = triple.getLeft(); right = triple.getRight(); target = operation.getTarget(); boolean safeMerge = true; try { if (!isRoot() && target.astnode.getClass().newInstance() .getNumChildNoTransform() > 0) { // this language element has a fixed number of children // we need to be careful with this one boolean leftChanges = left.hasChanges(false); boolean rightChanges = right.hasChanges(false); if (leftChanges || rightChanges) { if (LOG.isTraceEnabled()) { LOG.trace("target " + target.getId() + " expects a fixed amount of children."); LOG.trace("changes in " + left.getId() + ": " + leftChanges); LOG.trace("changes in " + right.getId() + ": " + rightChanges); LOG.trace("We will report a conflict instead of performing the merge"); } safeMerge = false; // to be safe, we will report a conflict instead of merging ASTNodeArtifact targetParent = target.getParent(); targetParent.removeChild(target); ConflictOperation conflictOp = new ConflictOperation<>( left, left, right, targetParent); conflictOp.apply(context); } } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } if (safeMerge) { strategy.merge(operation, context); } if (!context.isQuiet() && context.hasOutput()) { System.out.println(context.getStdIn()); } } public final void removeChild(ASTNodeArtifact child) { if (LOG.isTraceEnabled()) { LOG.trace("[" + getId() + "] removing child " + child.getId()); LOG.trace("children before removal: " + getChildren()); } Iterator<ASTNodeArtifact> it = children.iterator(); ASTNodeArtifact elem; while (it.hasNext()) { elem = it.next(); if (elem == child) { it.remove(); } } if (LOG.isTraceEnabled()) { LOG.trace("children after removal: " + getChildren()); } } /** * Pretty-prints the AST to source code. * * @return Pretty-printed AST (source code) */ public final String prettyPrint() { assert (astnode != null); rebuildAST(); astnode.flushCaches(); if (LOG.isDebugEnabled()) { System.out.println(dumpTree()); } return astnode.prettyPrint(); } /** * Rebuild the encapsulated ASTNode tree top down. This should be only * called at the root node */ public final void rebuildAST() { if (isConflict()) { astnode.isConflict = true; astnode.jdimeId = getId(); if (left != null) { left.rebuildAST(); astnode.left = left.astnode; } if (right != null) { right.rebuildAST(); astnode.right= right.astnode; } } ASTNode<?>[] newchildren = new ASTNode[getNumChildren()]; for (int i = 0; i < getNumChildren(); i++) { ASTNodeArtifact child = getChild(i); newchildren[i] = child.astnode; newchildren[i].setParent(astnode); child.rebuildAST(); } astnode.jdimeChanges = hasChanges(); astnode.jdimeId = getId(); astnode.setChildren(newchildren); if (LOG.isTraceEnabled()) { if (getNumChildren() != astnode.getNumChildNoTransform()) { LOG.trace("ASTNodeArtifact has " + getNumChildren() + " children: {" + getChildren() + "}"); StringBuilder sb = new StringBuilder(); sb.append("astnode has " + astnode.getNumChildNoTransform() + " children: {"); ASTNode[] astnodechildren = new ASTNode[astnode.getNumChild()]; for (int i = 0; i < astnode.getNumChild(); i++) { astnodechildren[i] = astnode.getChild(i); } sb.append(Arrays.toString(astnodechildren)); sb.append("}"); LOG.trace(sb); } } assert (isConflict() || getNumChildren() == astnode .getNumChildNoTransform()); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#toString() */ @Override public final String toString() { assert (astnode != null); return astnode.dumpString(); } /* * (non-Javadoc) * * @see de.fosd.jdime.common.Artifact#write(java.lang.String) */ @Override public final void write(final String str) throws IOException { // TODO Auto-generated method stub } /** * @param artifact * artifact to create program from * @return ASTNodeArtifact */ public static ASTNodeArtifact createProgram(final ASTNodeArtifact artifact) { assert (artifact.astnode != null); assert (artifact.astnode instanceof Program); Program program = (Program) artifact.astnode.copy(); // Iterator<CompilationUnit> it = program.compilationUnitIterator(); // while (it.hasNext()) { // CompilationUnit cu = it.next(); // for (int i = 0; i < cu.getNumChild(); i++) { // cu.getImportDeclList().removeChildren(); // cu.getTypeDeclList().removeChildren(); ASTNodeArtifact p = new ASTNodeArtifact(program); p.deleteChildren(); return p; } @Override public final ASTNodeArtifact createConflictDummy( final ASTNodeArtifact type, final ASTNodeArtifact left, final ASTNodeArtifact right) throws FileNotFoundException { ASTNodeArtifact conflict; conflict = new ASTNodeArtifact(type.astnode.fullCopy()); conflict.setConflict(left, right); return conflict; } }
package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import de.geeksfactory.opacclient.ISBNTools; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.searchfields.CheckboxSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import de.geeksfactory.opacclient.storage.MetaDataSource; /** * @author Johan von Forstner, 16.09.2013 * */ public class Pica extends BaseApi implements OpacApi { protected String opac_url = ""; protected String https_url = ""; protected JSONObject data; protected MetaDataSource metadata; protected boolean initialised = false; protected Library library; protected int resultcount = 10; protected String reusehtml; protected Integer searchSet; protected String db; protected String pwEncoded; CookieStore cookieStore = new BasicCookieStore(); protected String lor_reservations; protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); static { defaulttypes.put("book", MediaType.BOOK); defaulttypes.put("article", MediaType.BOOK); defaulttypes.put("binary", MediaType.EBOOK); defaulttypes.put("periodical", MediaType.MAGAZINE); defaulttypes.put("onlineper", MediaType.EBOOK); defaulttypes.put("letter", MediaType.UNKNOWN); defaulttypes.put("handwriting", MediaType.UNKNOWN); defaulttypes.put("map", MediaType.MAP); defaulttypes.put("picture", MediaType.ART); defaulttypes.put("audiovisual", MediaType.MOVIE); defaulttypes.put("score", MediaType.SCORE_MUSIC); defaulttypes.put("sound", MediaType.CD_MUSIC); defaulttypes.put("software", MediaType.CD_SOFTWARE); defaulttypes.put("microfilm", MediaType.UNKNOWN); defaulttypes.put("empty", MediaType.UNKNOWN); } @Override public void start() throws IOException, NotReachableException { // String html = httpGet(opac_url // + "/DB=" + db + "/SET=1/TTL=1/ADVANCED_SEARCHFILTER", // getDefaultEncoding(), false, cookieStore); // Document doc = Jsoup.parse(html); // updateSearchSetValue(doc); try { metadata.open(); } catch (Exception e) { throw new RuntimeException(e); } if (!metadata.hasMeta(library.getIdent())) { metadata.close(); // extract_meta(doc); } else { metadata.close(); } } @Override public void init(MetaDataSource metadata, Library lib) { super.init(metadata, lib); this.metadata = metadata; this.library = lib; this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); this.db = data.getString("db"); if (!library.getData().isNull("accountSupported")) { if (data.has("httpsbaseurl")) { this.https_url = data.getString("httpsbaseurl"); } else { this.https_url = this.opac_url; } } } catch (JSONException e) { throw new RuntimeException(e); } } protected int addParameters(SearchQuery query, List<NameValuePair> params, int index) throws JSONException { if (query.getValue().equals("") || query.getValue().equals("false")) return index; if (query.getSearchField() instanceof TextSearchField) { if (query.getSearchField().getData().getBoolean("ADI")) { params.add(new BasicNameValuePair(query.getKey(), query.getValue())); } else { if (index == 0) { params.add(new BasicNameValuePair("ACT" + index, "SRCH")); } else { params.add(new BasicNameValuePair("ACT" + index, "*")); } params.add(new BasicNameValuePair("IKT" + index, query.getKey())); params.add(new BasicNameValuePair("TRM" + index, query.getValue())); return index + 1; } } else if (query.getSearchField() instanceof CheckboxSearchField) { boolean checked = Boolean.valueOf(query.getValue()); if (checked) { params.add(new BasicNameValuePair(query.getKey(), "Y")); } } else if (query.getSearchField() instanceof DropdownSearchField) { params.add(new BasicNameValuePair(query.getKey(), query.getValue())); } return index; } @Override public SearchRequestResult search(List<SearchQuery> query) throws IOException, NotReachableException, OpacErrorException, JSONException { List<NameValuePair> params = new ArrayList<NameValuePair>(); int index = 0; start(); params.add(new BasicNameValuePair("ACT", "SRCHM")); params.add(new BasicNameValuePair("MATCFILTER", "Y")); params.add(new BasicNameValuePair("MATCSET", "Y")); params.add(new BasicNameValuePair("NOSCAN", "Y")); params.add(new BasicNameValuePair("PARSE_MNEMONICS", "N")); params.add(new BasicNameValuePair("PARSE_OPWORDS", "N")); params.add(new BasicNameValuePair("PARSE_OLDSETS", "N")); for (SearchQuery singleQuery:query) { index = addParameters(singleQuery, params, index); } if (index == 0) { throw new OpacErrorException( "Es wurden keine Suchkriterien eingegeben."); } if (index > 4) { throw new OpacErrorException( "Diese Bibliothek unterstützt nur bis zu vier benutzte Suchkriterien."); } String html = httpGet(opac_url + "/DB=" + db + "/SET=1/TTL=1/CMD?" + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding(), false, cookieStore); return parse_search(html, 1); } protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException { Document doc = Jsoup.parse(html); updateSearchSetValue(doc); if (doc.select(".error").size() > 0) { if (doc.select(".error").text().trim() .equals("Es wurde nichts gefunden.")) { // nothing found return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1); } else { // error throw new OpacErrorException(doc.select(".error").first() .text().trim()); } } reusehtml = html; int results_total = -1; String resultnumstr = doc.select(".pages").first().text(); Pattern p = Pattern.compile("[0-9]+$"); Matcher m = p.matcher(resultnumstr); if (m.find()) { resultnumstr = m.group(); } if (resultnumstr.contains("(")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*\\(([0-9]+)\\).*", "$1")); } else if (resultnumstr.contains(": ")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*: ([0-9]+)$", "$1")); } else { results_total = Integer.parseInt(resultnumstr); } List<SearchResult> results = new ArrayList<SearchResult>(); if (results_total == 1) { // Only one result try { DetailledItem singleResult = parse_result(html); SearchResult sr = new SearchResult(); sr.setType(getMediaTypeInSingleResult(html)); sr.setInnerhtml("<b>" + singleResult.getTitle() + "</b><br>" + singleResult.getDetails().get(0).getContent()); results.add(sr); } catch (IOException e) { e.printStackTrace(); } } Elements table = doc .select("table[summary=hitlist] tbody tr[valign=top]"); // identifier = null; Elements links = doc.select("table[summary=hitlist] a"); boolean haslink = false; for (int i = 0; i < links.size(); i++) { Element node = links.get(i); if (node.hasAttr("href") & node.attr("href").contains("SHW?") && !haslink) { haslink = true; try { List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI( node.attr("href")), getDefaultEncoding()); for (NameValuePair nv : anyurl) { if (nv.getName().equals("identifier")) { // identifier = nv.getValue(); break; } } } catch (Exception e) { e.printStackTrace(); } } } for (int i = 0; i < table.size(); i++) { Element tr = table.get(i); SearchResult sr = new SearchResult(); if (tr.select("td.hit img").size() > 0) { String[] fparts = tr.select("td img").get(0).attr("src") .split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { sr.setType(MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname))); } catch (JSONException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } catch (IllegalArgumentException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } else { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } Element middlething = tr.child(2); List<Node> children = middlething.childNodes(); int childrennum = children.size(); List<String[]> strings = new ArrayList<String[]>(); for (int ch = 0; ch < childrennum; ch++) { Node node = children.get(ch); if (node instanceof TextNode) { String text = ((TextNode) node).text().trim(); if (text.length() > 3) strings.add(new String[] { "text", "", text }); } else if (node instanceof Element) { List<Node> subchildren = node.childNodes(); for (int j = 0; j < subchildren.size(); j++) { Node subnode = subchildren.get(j); if (subnode instanceof TextNode) { String text = ((TextNode) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), "text", text, ((Element) node).className(), ((Element) node).attr("style") }); } else if (subnode instanceof Element) { String text = ((Element) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), ((Element) subnode).tag().getName(), text, ((Element) node).className(), ((Element) node).attr("style") }); } } } } StringBuilder description = new StringBuilder(); int k = 0; for (String[] part : strings) { if (part[0] == "a" && k == 0) { description.append("<b>" + part[2] + "</b>"); } else if (k < 3) { description.append("<br />" + part[2]); } k++; } sr.setInnerhtml(description.toString()); sr.setNr(10 * (page - 1) + i); sr.setId(null); results.add(sr); } resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException, OpacErrorException { if (!initialised) start(); String html = httpGet(opac_url + "/DB=" + db + "/SET=" + searchSet + "/TTL=1/NXT?FRST=" + (((page - 1) * resultcount) + 1), getDefaultEncoding(), false, cookieStore); return parse_search(html, page); } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, NotReachableException { return null; } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (id == null && reusehtml != null) { return parse_result(reusehtml); } String html = httpGet(id, getDefaultEncoding()); return parse_result(html); } @Override public DetailledItem getResult(int position) throws IOException { String html = httpGet(opac_url + "/DB=" + db + "/SET=" + searchSet + "/TTL=1/SHW?FRST=" + (position + 1), getDefaultEncoding(), false, cookieStore); return parse_result(html); } protected DetailledItem parse_result(String html) throws IOException { Document doc = Jsoup.parse(html); doc.setBaseUri(opac_url); DetailledItem result = new DetailledItem(); if (doc.select("img[src*=permalink], img[src*=zitierlink]").size() > 0) { String id = opac_url + doc.select("img[src*=permalink], img[src*=zitierlink]") .get(0).parent().absUrl("href"); result.setId(id); } else { for (Element a : doc.select("a")) { if (a.attr("href").contains("PPN=")) { Map<String, String> hrefq = getQueryParamsFirst(a .absUrl("href")); String ppn = hrefq.get("PPN"); try { result.setId(opac_url + "/DB=" + data.getString("db") + "/PPNSET?PPN=" + ppn); } catch (JSONException e1) { e1.printStackTrace(); } break; } } } // GET COVER if (doc.select("td.preslabel:contains(ISBN) + td.presvalue").size() > 0) { Element isbnElement = doc.select( "td.preslabel:contains(ISBN) + td.presvalue").first(); String isbn = ""; for (Node child : isbnElement.childNodes()) { if (child instanceof TextNode) { isbn = ((TextNode) child).text().trim(); break; } } result.setCover(ISBNTools.getAmazonCoverURL(isbn, true)); } // GET TITLE AND SUBTITLE String titleAndSubtitle = ""; if (doc.select("td.preslabel:contains(Titel) + td.presvalue").size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Titel) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail("Titelzusatz", subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else if (doc.select("td.preslabel:contains(Aufsatz) + td.presvalue") .size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Aufsatz) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail("Titelzusatz", subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else if (doc.select( "td.preslabel:contains(Zeitschrift) + td.presvalue").size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Zeitschrift) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail("Titelzusatz", subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else { result.setTitle(""); } // GET OTHER INFORMATION Map<String, String> e = new HashMap<String, String>(); String location = ""; // reservation info will be stored as JSON, because it can get // complicated JSONArray reservationInfo = new JSONArray(); for (Element element : doc.select("td.preslabel + td.presvalue")) { Element titleElem = element.firstElementSibling(); String detail = element.text().trim(); String title = titleElem.text().trim().replace("\u00a0", ""); if (element.select("hr").size() == 0) { // no separator if (title.indexOf(":") != -1) { title = title.substring(0, title.indexOf(":")); // remove // colon } if (title.contains("Standort") || title.contains("Vorhanden in")) { location += detail; } else if (title.contains("Sonderstandort")) { location += " - " + detail; } else if (title.contains("Fachnummer")) { e.put(DetailledItem.KEY_COPY_LOCATION, detail); } else if (title.contains("Signatur")) { e.put(DetailledItem.KEY_COPY_SHELFMARK, detail); } else if (title.contains("Anmerkung")) { location += " (" + detail + ")"; } else if (title.contains("Status") || title.contains("Ausleihinfo")) { detail = detail.replace("Bestellen", "") .replace("verfuegbar", "verfügbar") .replace("Verfuegbar", "verfügbar") .replace("Vormerken", "") .replace("Liste der Exemplare", "").trim(); e.put(DetailledItem.KEY_COPY_STATUS, detail); // Get reservation info if (element.select( "a:contains(Vormerken), a:contains(Exemplare)") .size() > 0) { Element a = element.select( "a:contains(Vormerken), a:contains(Exemplare)") .first(); boolean multipleCopies = a.text().contains("Exemplare"); JSONObject reservation = new JSONObject(); try { reservation.put("multi", multipleCopies); reservation.put("link", opac_url + a.attr("href")); reservation.put("desc", location); reservationInfo.put(reservation); } catch (JSONException e1) { e1.printStackTrace(); } result.setReservable(true); } } else if (!title.equals("Titel")) { result.addDetail(new Detail(title, detail)); } } else if (e.size() > 0) { e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); location = ""; e = new HashMap<String, String>(); } } e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); result.setReservation_info(reservationInfo.toString()); ; return result; } @Override public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection) throws IOException { try { if (selection == null || !selection.startsWith("{")) { JSONArray json = new JSONArray(item.getReservation_info()); int selectedPos; if (selection != null) { selectedPos = Integer.parseInt(selection); } else if (json.length() == 1) { selectedPos = 0; } else { // a location must be selected ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_BRANCH); Map<String, String> selections = new HashMap<String, String>(); for (int i = 0; i < json.length(); i++) { selections.put(String.valueOf(i), json.getJSONObject(i) .getString("desc")); } res.setSelection(selections); return res; } if (json.getJSONObject(selectedPos).getBoolean("multi")) { // A copy must be selected String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); Elements trs = doc1 .select("table[summary=list of volumes header] tr:has(input[type=radio])"); if (trs.size() > 0) { Map<String, String> selections = new HashMap<String, String>(); for (Element tr : trs) { JSONObject values = new JSONObject(); for (Element input : doc1 .select("input[type=hidden]")) { values.put(input.attr("name"), input.attr("value")); } values.put(tr.select("input").attr("name"), tr .select("input").attr("value")); selections.put(values.toString(), tr.text()); } ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_USER); res.setMessage("Welches Exemplar soll reserviert/bestellt werden? (verfügbare Exemplare werden bestellt)"); res.setSelection(selections); return res; } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage("Es ist kein Exemplar reservierbar."); return res; } } else { String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Element input : doc1.select("input[type=hidden]")) { params.add(new BasicNameValuePair(input.attr("name"), input.attr("value"))); } params.add(new BasicNameValuePair("BOR_U", account .getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, false); } } else { // A copy has been selected JSONObject values = new JSONObject(selection); List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator<String> keys = values.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = values.getString(key); params.add(new BasicNameValuePair(key, value)); } params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, true); } } catch (JSONException e) { e.printStackTrace(); ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage("interner Fehler"); return res; } } public ReservationResult reservation_result(List<NameValuePair> params, boolean multi) throws IOException { String html2 = httpPost(https_url + "/loan/LNG=DU/DB=" + db + "/SET=" + searchSet + "/TTL=1/" + (multi ? "REQCONT" : "RESCONT"), new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc2 = Jsoup.parse(html2); if (doc2.select(".alert").text().contains("ist fuer Sie vorgemerkt")) { return new ReservationResult(MultiStepResult.Status.OK); } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(doc2.select(".cnt .alert").text()); return res; } } @Override public ProlongResult prolong(String media, Account account, int useraction, String Selection) throws IOException { if (pwEncoded == null) try { account(account); } catch (JSONException e1) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e1) { return new ProlongResult(MultiStepResult.Status.ERROR, e1.getMessage()); } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_RENEWLOAN")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text") .text() .contains( "Die Leihfrist Ihrer ausgeliehenen Publikationen ist ") || doc.select("td.regular-text").text() .contains("Ihre ausgeliehenen Publikationen sind verl")) { return new ProlongResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt").text().contains("identify")) { try { account(account); return prolong(media, account, useraction, Selection); } catch (JSONException e) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e) { return new ProlongResult(MultiStepResult.Status.ERROR, e.getMessage()); } } else { ProlongResult res = new ProlongResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_CANCELRES")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); if (lor_reservations != null) params.add(new BasicNameValuePair("LOR_RESERVATIONS", lor_reservations)); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/SET=" + searchSet + "/TTL=1/USERINFO", new UrlEncodedFormEntity( params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text").text() .contains("Ihre Vormerkungen sind ")) { return new CancelResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt .alert").text() .contains("identify yourself")) { try { account(account); return cancel(media, account, useraction, selection); } catch (JSONException e) { throw new OpacErrorException("Interner Fehler"); } } else { CancelResult res = new CancelResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_DATA")); params.add(new BasicNameValuePair("HOST_NAME", "")); params.add(new BasicNameValuePair("HOST_PORT", "")); params.add(new BasicNameValuePair("HOST_SCRIPT", "")); params.add(new BasicNameValuePair("LOGIN", "KNOWNUSER")); params.add(new BasicNameValuePair("STATUS", "HML_OK")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account.getPassword())); String html = httpPost(https_url + "/loan/DB=" + db + "/LNG=DU/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select(".cnt .alert, .cnt .error").size() > 0) { throw new OpacErrorException(doc.select(".cnt .alert, .cnt .error") .text()); } if (doc.select("input[name=BOR_PW_ENC]").size() > 0) { pwEncoded = URLEncoder.encode(doc.select("input[name=BOR_PW_ENC]") .attr("value"), "UTF-8"); } else { // TODO: do something here to help fix bug #229 } html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOL&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); doc = Jsoup.parse(html); html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOR&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); Document doc2 = Jsoup.parse(html); AccountData res = new AccountData(account.getId()); List<Map<String, String>> medien = new ArrayList<Map<String, String>>(); List<Map<String, String>> reserved = new ArrayList<Map<String, String>>(); if (doc.select("table[summary^=list]").size() > 0) { parse_medialist(medien, doc, 1, account.getName()); } if (doc2.select("table[summary^=list]").size() > 0) { parse_reslist(reserved, doc2, 1); } res.setLent(medien); res.setReservations(reserved); if (medien == null || reserved == null) { throw new OpacErrorException( "Unbekannter Fehler. Bitte prüfen Sie, ob ihre Kontodaten korrekt sind."); // Log.d("OPACCLIENT", html); } return res; } protected void parse_medialist(List<Map<String, String>> medien, Document doc, int offset, String accountName) throws ClientProtocolException, IOException { Elements copytrs = doc.select("table[summary^=list] tr[valign=top]"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); String prolongCount = ""; try { String html = httpGet(https_url + "/nr_renewals.php?U=" + accountName + "&DB=" + db + "&VBAR=" + tr.child(1).select("input").attr("value"), getDefaultEncoding()); prolongCount = Jsoup.parse(html).text(); } catch (IOException e) { } String reminderCount = tr.child(13).text().trim(); if (reminderCount.indexOf(" Mahn") >= 0 && reminderCount.indexOf("(") >= 0 && reminderCount.indexOf("(") < reminderCount .indexOf(" Mahn")) reminderCount = reminderCount.substring( reminderCount.indexOf("(") + 1, reminderCount.indexOf(" Mahn")); else reminderCount = ""; Map<String, String> e = new HashMap<String, String>(); if (tr.child(4).text().trim().length() < 5 && tr.child(5).text().trim().length() > 4) { e.put(AccountData.KEY_LENT_TITLE, tr.child(5).text().trim()); } else { e.put(AccountData.KEY_LENT_TITLE, tr.child(4).text().trim()); } String status = ""; if (!reminderCount.equals("0") && !reminderCount.equals("")) { status += reminderCount + " Mahnungen, "; } status += prolongCount + "x verl."; // + tr.child(25).text().trim() // + " Vormerkungen"); e.put(AccountData.KEY_LENT_STATUS, status); e.put(AccountData.KEY_LENT_DEADLINE, tr.child(21).text().trim()); try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String .valueOf(sdf .parse(e.get(AccountData.KEY_LENT_DEADLINE)) .getTime())); } catch (ParseException e1) { e1.printStackTrace(); } e.put(AccountData.KEY_LENT_LINK, tr.child(1).select("input").attr("value")); medien.add(e); } assert (medien.size() == trs - 1); } protected void parse_reslist(List<Map<String, String>> medien, Document doc, int offset) throws ClientProtocolException, IOException { if (doc.select("input[name=LOR_RESERVATIONS]").size() > 0) { lor_reservations = doc.select("input[name=LOR_RESERVATIONS]").attr( "value"); } Elements copytrs = doc.select("table[summary^=list] tr[valign=top]"); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); Map<String, String> e = new HashMap<String, String>(); e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(5).text().trim()); e.put(AccountData.KEY_RESERVATION_READY, tr.child(17).text().trim()); e.put(AccountData.KEY_RESERVATION_CANCEL, tr.child(1).select("input").attr("value")); medien.add(e); } assert (medien.size() == trs - 1); } @Override public List<SearchField> getSearchFields() throws ClientProtocolException, IOException, JSONException { String html = httpGet(opac_url + "/ADVANCED_SEARCHFILTER", getDefaultEncoding()); Document doc = Jsoup.parse(html); List<SearchField> fields = new ArrayList<SearchField>(); Elements options = doc.select("select[name=IKT0] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setDisplayName(option.text()); field.setId(option.attr("value")); field.setHint(""); field.setData(new JSONObject("{\"ADI\": false}")); Pattern pattern = Pattern.compile("\\[[A-Z]+\\]"); Matcher matcher = pattern.matcher(field.getDisplayName()); if (matcher.find()) { field.getData().put("meaning", matcher.group()); field.setDisplayName(matcher.replaceFirst("").trim()); } fields.add(field); } Elements sort = doc.select("select[name=SRT]"); if (sort.size() > 0) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(sort.first().parent().parent() .select(".longval").first().text()); field.setId("SRT"); List<Map<String, String>> sortOptions = new ArrayList<Map<String, String>>(); for (Element option : sort.select("option")) { Map<String, String> sortOption = new HashMap<String, String>(); sortOption.put("key", option.attr("value")); sortOption.put("value", option.text()); sortOptions.add(sortOption); } field.setDropdownValues(sortOptions); fields.add(field); } for (Element input : doc.select("input[type=text][name^=ADI]")) { TextSearchField field = new TextSearchField(); field.setDisplayName(input.parent().parent().select(".longkey").text()); field.setId(input.attr("name")); field.setHint(input.parent().select("span").text()); field.setData(new JSONObject("{\"ADI\": true}")); fields.add(field); } for (Element dropdown : doc.select("select[name^=ADI]")) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(dropdown.parent().parent() .select(".longkey").text()); field.setId(dropdown.attr("name")); List<Map<String, String>> dropdownOptions = new ArrayList<Map<String, String>>(); for (Element option : dropdown.select("option")) { Map<String, String> dropdownOption = new HashMap<String, String>(); dropdownOption.put("key", option.attr("value")); dropdownOption.put("value", option.text()); dropdownOptions.add(dropdownOption); } field.setDropdownValues(dropdownOptions); fields.add(field); } Elements fuzzy = doc.select("input[name=FUZZY]"); if (fuzzy.size() > 0) { CheckboxSearchField field = new CheckboxSearchField(); field.setDisplayName(fuzzy.first().parent().parent() .select(".longkey").first().text()); field.setId("FUZZY"); fields.add(field); } return fields; } @Override public boolean isAccountSupported(Library library) { if (!library.getData().isNull("accountSupported")) { try { return library.getData().getBoolean("accountSupported"); } catch (JSONException e) { e.printStackTrace(); } } return false; } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { return id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT; } public void updateSearchSetValue(Document doc) { String url = doc.select("base").first().attr("href"); Integer setPosition = url.indexOf("SET=") + 4; String searchSetString = url.substring(setPosition, url.indexOf("/", setPosition)); searchSet = Integer.parseInt(searchSetString); } public MediaType getMediaTypeInSingleResult(String html) { Document doc = Jsoup.parse(html); MediaType mediatype = MediaType.UNKNOWN; if (doc.select("table[summary=presentation switch] img").size() > 0) { String[] fparts = doc .select("table[summary=presentation switch] img").get(0) .attr("src").split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { mediatype = MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname)); } catch (JSONException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } catch (IllegalArgumentException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } } else { mediatype = defaulttypes.get(fname.toLowerCase(Locale.GERMAN) .replace(".jpg", "").replace(".gif", "") .replace(".png", "")); } } return mediatype; } @Override protected String getDefaultEncoding() { try { if (data.has("charset")) return data.getString("charset"); } catch (JSONException e) { e.printStackTrace(); } return "UTF-8"; } }