answer
stringlengths
17
10.2M
package com.github.rnewson.couchdb.lucene; import static java.lang.Math.max; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.net.SocketException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.Map.Entry; import java.util.concurrent.CountDownLatch; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.configuration.HierarchicalINIConfiguration; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.log4j.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.IndexReader.FieldOption; import org.apache.lucene.index.IndexWriter.MaxFieldLength; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.mozilla.javascript.ClassShutter; import org.mozilla.javascript.Context; import com.github.rnewson.couchdb.lucene.couchdb.CouchDocument; import com.github.rnewson.couchdb.lucene.couchdb.Database; import com.github.rnewson.couchdb.lucene.couchdb.DesignDocument; import com.github.rnewson.couchdb.lucene.couchdb.View; import com.github.rnewson.couchdb.lucene.util.Constants; import com.github.rnewson.couchdb.lucene.util.ServletUtils; import com.github.rnewson.couchdb.lucene.util.StopWatch; import com.github.rnewson.couchdb.lucene.util.Utils; public final class DatabaseIndexer implements Runnable, ResponseHandler<Void> { private class IndexState { private final DocumentConverter converter; private boolean readerDirty; private boolean writerDirty; private String etag; private final QueryParser parser; private long pending_seq; private IndexReader reader; private final IndexWriter writer; private final Database database; public IndexState(final DocumentConverter converter, final IndexWriter writer, final QueryParser parser, final Database database) { this.converter = converter; this.writer = writer; this.parser = parser; this.database = database; } public synchronized IndexReader borrowReader(final boolean staleOk) throws IOException { blockForLatest(staleOk); if (reader == null) { etag = newEtag(); } if (reader != null) { reader.decRef(); } reader = writer.getReader(); if (readerDirty) { etag = newEtag(); readerDirty = false; } reader.incRef(); return reader; } public IndexSearcher borrowSearcher(final boolean staleOk) throws IOException { return new IndexSearcher(borrowReader(staleOk)); } public void returnReader(final IndexReader reader) throws IOException { reader.decRef(); } public void returnSearcher(final IndexSearcher searcher) throws IOException { returnReader(searcher.getIndexReader()); } private synchronized void close() throws IOException { if (reader != null) reader.close(); if (writer != null) writer.rollback(); } private synchronized String getEtag() { return etag; } private String newEtag() { return Long.toHexString(now()); } private synchronized boolean notModified(final HttpServletRequest req) { return etag != null && etag.equals(req.getHeader("If-None-Match")); } private void blockForLatest(final boolean staleOk) throws IOException { if (staleOk) { return; } final long latest = database.getInfo().getUpdateSequence(); synchronized (this) { while (pending_seq < latest) { try { wait(getSearchTimeout()); } catch (final InterruptedException e) { throw new IOException("Search timed out."); } } } } private synchronized void setPendingSequence(final long newSequence) { pending_seq = newSequence; notifyAll(); } @Override public String toString() { return writer.getDirectory().toString(); } } private final class RestrictiveClassShutter implements ClassShutter { public boolean visibleToScripts(final String fullClassName) { return false; } } private static final JSONObject JSON_SUCCESS = JSONObject .fromObject("{\"ok\":true}"); public static File uuidDir(final File root, final UUID uuid) { return new File(root, uuid.toString()); } public static File viewDir(final File root, final UUID uuid, final String digest, final boolean mkdirs) throws IOException { final File uuidDir = uuidDir(root, uuid); final File viewDir = new File(uuidDir, digest); if (mkdirs) { viewDir.mkdirs(); } return viewDir; } private static long now() { return System.nanoTime(); } private final HttpClient client; private boolean closed; private Context context; private final Database database; private long ddoc_seq; private long lastCommit; private final CountDownLatch latch = new CountDownLatch(1); private final Logger logger; private final Map<String, View> paths = new HashMap<String, View>(); private HttpUriRequest req; private final File root; private long since; private final Map<View, IndexState> states = Collections .synchronizedMap(new HashMap<View, IndexState>()); private UUID uuid; private final HierarchicalINIConfiguration ini; public DatabaseIndexer(final HttpClient client, final File root, final Database database, final HierarchicalINIConfiguration ini) throws IOException { this.client = client; this.root = root; this.database = database; this.ini = ini; this.logger = Logger.getLogger(DatabaseIndexer.class.getName() + "." + database.getInfo().getName()); } public void admin(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final IndexState state = getState(req, resp); if (state == null) return; final String command = new PathParts(req).getCommand(); if ("_expunge".equals(command)) { logger.info("Expunging deletes from " + state); state.writer.expungeDeletes(false); ServletUtils.setResponseContentTypeAndEncoding(req, resp); resp.setStatus(202); ServletUtils.writeJSON(resp, JSON_SUCCESS); return; } if ("_optimize".equals(command)) { logger.info("Optimizing " + state); state.writer.optimize(false); ServletUtils.setResponseContentTypeAndEncoding(req, resp); resp.setStatus(202); ServletUtils.writeJSON(resp, JSON_SUCCESS); return; } } public void awaitInitialization() { try { latch.await(); } catch (final InterruptedException e) { // Ignore. } } public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { final HttpEntity entity = response.getEntity(); final BufferedReader reader = new BufferedReader(new InputStreamReader( entity.getContent(), "UTF-8")); String line; loop: while ((line = reader.readLine()) != null) { maybeCommit(); // Heartbeat. if (line.length() == 0) { logger.trace("heartbeat"); continue loop; } final JSONObject json = JSONObject.fromObject(line); if (json.has("error")) { logger.warn("Indexing stopping due to error: " + json); break loop; } if (json.has("last_seq")) { logger.warn("End of changes detected."); break loop; } final long seq = json.getLong("seq"); final String id = json.getString("id"); CouchDocument doc; if (json.has("doc")) { doc = new CouchDocument(json.getJSONObject("doc")); } else { // include_docs=true doesn't work prior to 0.11. try { doc = database.getDocument(id); } catch (final HttpResponseException e) { switch (e.getStatusCode()) { case HttpStatus.SC_NOT_FOUND: doc = CouchDocument.deletedDocument(id); break; default: logger.warn("Failed to fetch " + id); break loop; } } } if (id.startsWith("_design") && seq > ddoc_seq) { logger.info("Exiting due to design document change."); break loop; } if (doc.isDeleted()) { for (final IndexState state : states.values()) { state.writer.deleteDocuments(new Term("_id", id)); state.setPendingSequence(seq); state.readerDirty = true; } } else { for (final Entry<View, IndexState> entry : states.entrySet()) { final View view = entry.getKey(); final IndexState state = entry.getValue(); final Document[] docs; try { docs = state.converter.convert(doc, view .getDefaultSettings(), database); } catch (final Exception e) { logger.warn(id + " caused " + e.getMessage()); continue loop; } state.writer.deleteDocuments(new Term("_id", id)); for (final Document d : docs) { state.writer.addDocument(d, view.getAnalyzer()); state.writerDirty = true; } state.setPendingSequence(seq); state.readerDirty = true; } } } req.abort(); return null; } public void info(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final IndexState state = getState(req, resp); if (state == null) return; final IndexReader reader = state.borrowReader(isStaleOk(req)); try { final JSONObject result = new JSONObject(); result.put("current", reader.isCurrent()); result.put("disk_size", Utils.directorySize(reader.directory())); result.put("doc_count", reader.numDocs()); result.put("doc_del_count", reader.numDeletedDocs()); final JSONArray fields = new JSONArray(); for (final Object field : reader.getFieldNames(FieldOption.INDEXED)) { if (((String) field).startsWith("_")) { continue; } fields.add(field); } result.put("fields", fields); result.put("last_modified", Long.toString(IndexReader .lastModified(reader.directory()))); result.put("optimized", reader.isOptimized()); result.put("ref_count", reader.getRefCount()); final JSONObject info = new JSONObject(); info.put("code", 200); info.put("json", result); ServletUtils.setResponseContentTypeAndEncoding(req, resp); final Writer writer = resp.getWriter(); try { writer.write(result.toString()); } finally { writer.close(); } } finally { state.returnReader(reader); } } public void run() { if (closed) { throw new IllegalStateException("closed!"); } try { init(); } catch (final IOException e) { logger.warn("Exiting after init() raised I/O exception.", e); return; } try { try { req = database.getChangesRequest(since); logger.info("Indexing from update_seq " + since); client.execute(req, this); } finally { close(); } } catch (final SocketException e) { // Ignored because req.abort() does this. } catch (final IOException e) { logger.warn("Exiting due to I/O exception.", e); } } public void search(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final IndexState state = getState(req, resp); if (state == null) return; final IndexSearcher searcher = state.borrowSearcher(isStaleOk(req)); final String etag = state.getEtag(); final JSONArray result = new JSONArray(); try { if (state.notModified(req)) { resp.setStatus(304); return; } for (final String queryString : req.getParameterValues("q")) { final Query q = state.parser.parse(queryString); final JSONObject queryRow = new JSONObject(); queryRow.put("q", q.toString()); if (getBooleanParameter(req, "debug")) { queryRow.put("plan", QueryPlan.toPlan(q)); } queryRow.put("etag", etag); if (getBooleanParameter(req, "rewrite")) { final Query rewritten_q = q.rewrite(searcher .getIndexReader()); queryRow.put("rewritten_q", rewritten_q.toString()); final JSONObject freqs = new JSONObject(); final Set<Term> terms = new HashSet<Term>(); rewritten_q.extractTerms(terms); for (final Object term : terms) { final int freq = searcher.docFreq((Term) term); freqs.put(term, freq); } queryRow.put("freqs", freqs); } else { // Perform the search. final TopDocs td; final StopWatch stopWatch = new StopWatch(); final boolean include_docs = getBooleanParameter(req, "include_docs"); final int limit = getIntParameter(req, "limit", 25); final Sort sort = CustomQueryParser.toSort(req .getParameter("sort")); final int skip = getIntParameter(req, "skip", 0); if (sort == null) { td = searcher.search(q, null, skip + limit); } else { td = searcher.search(q, null, skip + limit, sort); } stopWatch.lap("search"); // Fetch matches (if any). final int max = Math.max(0, Math.min(td.totalHits - skip, limit)); final JSONArray rows = new JSONArray(); final String[] fetch_ids = new String[max]; for (int i = skip; i < skip + max; i++) { final Document doc = searcher.doc(td.scoreDocs[i].doc); final JSONObject row = new JSONObject(); final JSONObject fields = new JSONObject(); // Include stored fields. for (final Object f : doc.getFields()) { final Field fld = (Field) f; if (!fld.isStored()) { continue; } final String name = fld.name(); final String value = fld.stringValue(); if (value != null) { if ("_id".equals(name)) { row.put("id", value); } else { if (!fields.has(name)) { fields.put(name, value); } else { final Object obj = fields.get(name); if (obj instanceof String) { final JSONArray arr = new JSONArray(); arr.add(obj); arr.add(value); fields.put(name, arr); } else { assert obj instanceof JSONArray; ((JSONArray) obj).add(value); } } } } } if (!Float.isNaN(td.scoreDocs[i].score)) { row.put("score", td.scoreDocs[i].score); }// Include sort order (if any). if (td instanceof TopFieldDocs) { final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i]; row.put("sort_order", fd.fields); } // Fetch document (if requested). if (include_docs) { fetch_ids[i - skip] = doc.get("_id"); } if (fields.size() > 0) { row.put("fields", fields); } rows.add(row); } // Fetch documents (if requested). if (include_docs && fetch_ids.length > 0) { database.getDocuments(fetch_ids); final List<CouchDocument> fetched_docs = database .getDocuments(fetch_ids); for (int j = 0; j < max; j++) { rows.getJSONObject(j).put("doc", fetched_docs.get(j).asJson()); } } stopWatch.lap("fetch"); queryRow.put("skip", skip); queryRow.put("limit", limit); queryRow.put("total_rows", td.totalHits); queryRow.put("search_duration", stopWatch .getElapsed("search")); queryRow.put("fetch_duration", stopWatch .getElapsed("fetch")); // Include sort info (if requested). if (td instanceof TopFieldDocs) { queryRow.put("sort_order", CustomQueryParser .toString(((TopFieldDocs) td).fields)); } queryRow.put("rows", rows); } result.add(queryRow); } } catch (final ParseException e) { ServletUtils.sendJSONError(req, resp, 400, "Bad query syntax: " + e.getMessage()); return; } finally { state.returnSearcher(searcher); } resp.setHeader("ETag", etag); resp.setHeader("Cache-Control", "must-revalidate"); ServletUtils.setResponseContentTypeAndEncoding(req, resp); final JSON json = result.size() > 1 ? result : result.getJSONObject(0); final String callback = req.getParameter("callback"); final String body; if (callback != null) { body = String.format("%s(%s)", callback, json); } else { body = json.toString(getBooleanParameter(req, "debug") ? 2 : 0); } final Writer writer = resp.getWriter(); try { writer.write(body); } finally { writer.close(); } } private void close() throws IOException { this.closed = true; for (final IndexState state : states.values()) { state.close(); } states.clear(); Context.exit(); } private void commitAll() throws IOException { for (final Entry<View, IndexState> entry : states.entrySet()) { final View view = entry.getKey(); final IndexState state = entry.getValue(); if (state.pending_seq > getUpdateSequence(state.writer)) { final Map<String, String> userData = new HashMap<String, String>(); userData.put("last_seq", Long.toString(state.pending_seq)); if (!state.writerDirty) { logger .warn("Forcing additional document as nothing else was indexed since last commit."); state.writer.updateDocument(forceTerm(), forceDocument()); } state.writer.commit(userData); state.writerDirty = false; logger.info(view + " now at update_seq " + state.pending_seq); } } lastCommit = now(); } private Document forceDocument() { final Document result = new Document(); result.add(new Field("_cl", uuid.toString(), Store.NO, Index.NOT_ANALYZED_NO_NORMS)); return result; } private Term forceTerm() { return new Term("_cl", uuid.toString()); } private boolean getBooleanParameter(final HttpServletRequest req, final String parameterName) { return Boolean.parseBoolean(req.getParameter(parameterName)); } private int getIntParameter(final HttpServletRequest req, final String parameterName, final int defaultValue) { final String result = req.getParameter(parameterName); return result != null ? Integer.parseInt(result) : defaultValue; } private IndexState getState(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final View view = paths.get(toPath(req)); if (view == null) { ServletUtils.sendJSONError(req, resp, 400, "no_such_view"); return null; } final IndexState result = states.get(view); if (result == null) { ServletUtils.sendJSONError(req, resp, 400, "no_such_state"); } return result; } private long getUpdateSequence(final Directory dir) throws IOException { if (!IndexReader.indexExists(dir)) { return 0L; } return getUpdateSequence(IndexReader.getCommitUserData(dir)); } private long getUpdateSequence(final IndexWriter writer) throws IOException { return getUpdateSequence(writer.getDirectory()); } private long getUpdateSequence(final Map<String, String> userData) { if (userData != null && userData.containsKey("last_seq")) { return Long.parseLong(userData.get("last_seq")); } return 0L; } private void init() throws IOException { this.uuid = database.getOrCreateUuid(); this.context = Context.enter(); context.setClassShutter(new RestrictiveClassShutter()); context.setOptimizationLevel(9); this.ddoc_seq = database.getInfo().getUpdateSequence(); this.since = 0; for (final DesignDocument ddoc : database.getAllDesignDocuments()) { for (final Entry<String, View> entry : ddoc.getAllViews() .entrySet()) { final String name = entry.getKey(); final View view = entry.getValue(); paths.put(toPath(ddoc.getId(), name), view); if (!states.containsKey(view)) { final Directory dir = FSDirectory.open(viewDir(view, true)); final long seq = getUpdateSequence(dir); if (since == 0) { since = seq; } if (seq != -1L) { since = Math.min(since, seq); } logger.debug(dir + " bumped since to " + since); final DocumentConverter converter = new DocumentConverter( context, view); final IndexWriter writer = newWriter(dir); final QueryParser parser = new CustomQueryParser( Constants.VERSION, Constants.DEFAULT_FIELD, view .getAnalyzer()); final IndexState state = new IndexState(converter, writer, parser, database); state.setPendingSequence(seq); states.put(view, state); } } } logger.debug("paths: " + paths); this.lastCommit = now(); latch.countDown(); } private boolean isStaleOk(final HttpServletRequest req) { return "ok".equals(req.getParameter("stale")); } private void maybeCommit() throws IOException { if (now() - lastCommit >= getCommitInterval()) { commitAll(); } } private IndexWriter newWriter(final Directory dir) throws IOException { final IndexWriter result = new IndexWriter(dir, Constants.ANALYZER, MaxFieldLength.UNLIMITED); result.setMergeFactor(ini.getInt("lucene.mergeFactor", 10)); result.setUseCompoundFile(ini.getBoolean("lucene.useCompoundFile", false)); result.setRAMBufferSizeMB(ini.getDouble("lucene.ramBufferSizeMB", IndexWriter.DEFAULT_RAM_BUFFER_SIZE_MB)); return result; } private File viewDir(final View view, final boolean mkdirs) throws IOException { return viewDir(root, uuid, view.getDigest(), mkdirs); } private long getSearchTimeout() { return ini.getLong("lucene.timeout", 5000); } private long getCommitInterval() { final long commitSeconds = max(1L, ini .getLong("lucene.commitEvery", 15)); return SECONDS.toNanos(commitSeconds); } private String toPath(final HttpServletRequest req) { final PathParts parts = new PathParts(req); return toPath(parts.getDesignDocumentName(), parts.getViewName()); } private String toPath(final String ddoc, final String view) { return ddoc + "/" + view; } }
package com.github.tomitakussaari.mysqlcluscon; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.sql.SQLException; import java.util.*; import java.util.stream.Collectors; class URLHelpers { static String constructMysqlConnectUrl(String host, String jdbcUrl, Map<String, List<String>> queryParameters) { final String protocol = "jdbc:mysql"; final URL originalUrl = createURL(jdbcUrl); final String port = originalUrl.getPort() != -1 ? ":"+originalUrl.getPort() : ""; final String database = originalUrl.getPath(); return protocol+"://"+host+port+database+toQueryParametersString(queryParameters); } static String toQueryParametersString(Map<String, List<String>> queryParameters) { if(queryParameters.isEmpty()) { return ""; } return "?"+queryParameters.entrySet() .stream() .map(entry -> entry.getValue().stream().map(value -> entry.getKey()+"="+value).collect(Collectors.joining("&"))) .collect(Collectors.joining("&")); } static List<String> getHosts(String jdbcUrl) { URL url = createURL(jdbcUrl); return Arrays.asList(url.getHost().split(",")); } static String getProtocol(String jdbcUrl) { return jdbcUrl.substring(0, jdbcUrl.indexOf(": } static URL createURL(String jdbcUrl) { try { //hackiness warning: //Java URL by default supports only certain protocols, so protocol is "changed" here to make URL work. //we could implement our own URLStreamHandler, but that would then be much more code... return new URL(jdbcUrl.replace(MysclusconDriver.galeraClusterConnectorName, "http") .replace(MysclusconDriver.mysqlReadClusterConnectorName, "http")); } catch (MalformedURLException e) { throw new RuntimeException(e); } } static String getParameter(Map<String, List<String>> queryParameters, String parameter, String defaultValue) { return queryParameters.getOrDefault(parameter, new ArrayList<>()).stream().findFirst().orElse(defaultValue); } static Map<String, List<String>> getQueryParameters(String url) throws SQLException { final Map<String, List<String>> queryParameters = new LinkedHashMap<>(); final int startOfQueryParams = url.indexOf("?"); if(startOfQueryParams < 0) { return queryParameters; } return parseQueryParameters(url, queryParameters, startOfQueryParams+1); } private static Map<String, List<String>> parseQueryParameters(String url, Map<String, List<String>> queryParameters, int startOfQueryParams) throws SQLException { final String[] pairs = url.substring(startOfQueryParams).split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? decode(pair.substring(0, idx)) : pair; List<String> values = queryParameters.computeIfAbsent(key, (k) -> new LinkedList<>()); final String value = idx > 0 && pair.length() > idx + 1 ? decode(pair.substring(idx + 1)) : null; values.add(value); } return queryParameters; } private static String decode(String substring) throws SQLException { try { return URLDecoder.decode(substring, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new SQLException("Unable to decode url using UTF-8: "+substring, e); } } }
package com.metaweb.gridworks.importers; import com.metaweb.gridworks.expr.ExpressionUtils; import com.metaweb.gridworks.model.Cell; import com.metaweb.gridworks.model.Row; public class ImporterUtilities { static public Object parseCellValue(String text) { if (text.length() > 0) { if (text.length() > 1 && text.startsWith("\"") && text.endsWith("\"")) { return text.substring(1, text.length() - 1); } try { return Long.parseLong(text); } catch (NumberFormatException e) { } try { return Double.parseDouble(text); } catch (NumberFormatException e) { } } return text; } static public boolean parseCSVIntoRow(Row row, String line) { boolean hasData = false; int start = 0; while (start < line.length()) { String text = null; if (line.charAt(start) == '"') { int next = line.indexOf('"', start + 1); if (next < 0) { text = line.substring(start); start = line.length(); } else { text = line.substring(start, next + 1); start = next + 2; } } else { int next = line.indexOf(',', start); if (next < 0) { text = line.substring(start); start = line.length(); } else { text = line.substring(start, next); start = next + 1; } } Object value = parseCellValue(text); if (ExpressionUtils.isBlank(value)) { row.cells.add(null); } else { row.cells.add(new Cell(value, null)); hasData = true; } } return hasData; } static public boolean parseTSVIntoRow(Row row, String line) { boolean hasData = false; String[] cells = line.split("\t"); for (int c = 0; c < cells.length; c++) { String text = cells[c]; Object value = parseCellValue(text); if (ExpressionUtils.isBlank(value)) { row.cells.add(null); } else { row.cells.add(new Cell(value, null)); hasData = true; } } return hasData; } }
package com.nhn.pinpoint.profiler.util; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * @author emeroad */ public final class RuntimeMXBeanUtils { private static final RuntimeMXBean RUNTIME_MBEAN = ManagementFactory.getRuntimeMXBean(); private static long START_TIME = 0; private static int PID = 0; private static final Random RANDOM = new Random(); private RuntimeMXBeanUtils() { } public static int getPid() { if (PID == 0) { PID = getPid0(); } return PID; } private static int getPid0() { final String name = RUNTIME_MBEAN.getName(); final int pidIndex = name.indexOf('@'); if (pidIndex == -1) { getLogger().log(Level.WARNING, "invalid pid name:" + name); return getNegativeRandomValue(); } String strPid = name.substring(0, pidIndex); try { return Integer.parseInt(strPid); } catch (NumberFormatException e) { return getNegativeRandomValue(); } } private static int getNegativeRandomValue() { final int abs = Math.abs(RANDOM.nextInt()); if (abs == Integer.MIN_VALUE) { return -1; } return abs; } public static long getVmStartTime() { if (START_TIME == 0) { START_TIME = getVmStartTime0(); } return START_TIME; } private static long getVmStartTime0() { try { return RUNTIME_MBEAN.getStartTime(); } catch (UnsupportedOperationException e) { final Logger logger = getLogger(); logger.log(Level.WARNING, "RuntimeMXBean.getStartTime() unsupported. Caused:" + e.getMessage(), e); return System.currentTimeMillis(); } } private static Logger getLogger() { return Logger.getLogger(RuntimeMXBeanUtils.class.getName()); } }
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Connection.Response; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.jsoup.Connection.Method; import com.rarchives.ripme.ripper.AbstractHTMLRipper; import com.rarchives.ripme.ui.RipStatusMessage.STATUS; import com.rarchives.ripme.utils.Http; /** * * @author losipher */ public class EroShareRipper extends AbstractHTMLRipper { public EroShareRipper (URL url) throws IOException { super(url); } @Override public String getDomain() { return "eroshare.com"; } @Override public String getHost() { return "eroshare"; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url); } @Override public boolean canRip(URL url) { Pattern p = Pattern.compile("^https?://spacescience.tech/([a-zA-Z0-9\\-_]+)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return true; } Pattern pa = Pattern.compile("^https?://spacescience.tech/u/([a-zA-Z0-9\\-_]+)/?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return true; } return false; } public boolean is_profile(URL url) { Pattern pa = Pattern.compile("^https?://spacescience.tech/u/([a-zA-Z0-9\\-_]+)/?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return true; } return false; } @Override public Document getNextPage(Document doc) throws IOException { // Find next page String nextUrl = ""; Element elem = doc.select("li.next > a").first(); if (elem == null) { throw new IOException("No more pages"); } nextUrl = elem.attr("href"); if (nextUrl == "") { throw new IOException("No more pages"); } return Http.url("spacescience.tech" + nextUrl).get(); } @Override public String getAlbumTitle(URL url) throws MalformedURLException { if (is_profile(url) == false) { try { // Attempt to use album title as GID Element titleElement = getFirstPage().select("meta[property=og:title]").first(); String title = titleElement.attr("content"); title = title.substring(title.lastIndexOf('/') + 1); return getHost() + "_" + getGID(url) + "_" + title.trim(); } catch (IOException e) { // Fall back to default album naming convention logger.info("Unable to find title at " + url); } return super.getAlbumTitle(url); } return url.toExternalForm().split("/u/")[1]; } @Override public List<String> getURLsFromPage(Document doc) { List<String> URLs = new ArrayList<String>(); //Pictures Elements imgs = doc.getElementsByTag("img"); for (Element img : imgs) { if (img.hasClass("album-image")) { String imageURL = img.attr("src"); imageURL = "https:" + imageURL; URLs.add(imageURL); } } //Videos Elements vids = doc.getElementsByTag("video"); for (Element vid : vids) { if (vid.hasClass("album-video")) { Elements source = vid.getElementsByTag("source"); String videoURL = source.first().attr("src"); URLs.add("https:" + videoURL); } } // Profile videos Elements links = doc.select("div.item-container > a.item"); for (Element link : links) { Document video_page; try { video_page = Http.url("spacescience.tech" + link.attr("href")).get(); } catch (IOException e) { logger.warn("Failed to log link in Jsoup"); video_page = null; e.printStackTrace(); } Elements profile_vids = video_page.getElementsByTag("video"); for (Element vid : profile_vids) { if (vid.hasClass("album-video")) { Elements source = vid.getElementsByTag("source"); String videoURL = source.first().attr("src"); URLs.add("https:" + videoURL); } } } return URLs; } @Override public Document getFirstPage() throws IOException { Response resp = Http.url(this.url) .ignoreContentType() .response(); Document doc = resp.parse(); return doc; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://spacescience.tech/([a-zA-Z0-9\\-_]+)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } Pattern pa = Pattern.compile("^https?://spacescience.tech/u/([a-zA-Z0-9\\-_]+)/?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return m.group(1) + "_profile"; } throw new MalformedURLException("eroshare album not found in " + url + ", expected https://eroshare.com/album or spacescience.tech/album"); } public static List<URL> getURLs(URL url) throws IOException{ Response resp = Http.url(url) .ignoreContentType() .response(); Document doc = resp.parse(); List<URL> URLs = new ArrayList<URL>(); //Pictures Elements imgs = doc.getElementsByTag("img"); for (Element img : imgs) { if (img.hasClass("album-image")) { String imageURL = img.attr("src"); imageURL = "https:" + imageURL; URLs.add(new URL(imageURL)); } } //Videos Elements vids = doc.getElementsByTag("video"); for (Element vid : vids) { if (vid.hasClass("album-video")) { Elements source = vid.getElementsByTag("source"); String videoURL = source.first().attr("src"); URLs.add(new URL("https:" + videoURL)); } } return URLs; } }
package com.redhat.victims.cli.commands; import com.redhat.victims.VictimsException; import com.redhat.victims.cli.Environment; import com.redhat.victims.cli.results.CommandResult; import com.redhat.victims.database.VictimsDB; import com.redhat.victims.database.VictimsDBInterface; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * * @author gm */ public class PomScannerCommand implements Command { public static final String COMMAND_NAME = "scan-pom"; private Usage help; private List<String> arguments; public PomScannerCommand(){ help = new Usage(getName(), "Scan dependencies in a pom.xml file"); help.addExample("pom.xml"); } @Override public final String getName() { return COMMAND_NAME; } private void scanPomFile(File pomFile, CommandResult result){ MavenXpp3Reader pomReader = new MavenXpp3Reader(); try { VictimsDBInterface db = Environment.getInstance().getDatabase(); Model model = pomReader.read(new FileReader(pomFile)); List<Dependency> dependencies = model.getDependencies(); DependencyManagement dependencyManagement = model.getDependencyManagement(); if (dependencyManagement != null){ if (dependencies == null){ dependencies = new ArrayList<Dependency>(); } dependencies.addAll(dependencyManagement.getDependencies()); } for (Dependency dep : dependencies){ HashMap<String, String> gav = new HashMap(); String groupId = dep.getGroupId(); String artifactId = dep.getArtifactId(); String version = dep.getVersion(); String info = String.format("%s: %s, %s, %s", pomFile.getCanonicalPath(), groupId, artifactId, version); gav.put("groupId", groupId); gav.put("artifactId", artifactId); gav.put("version", version); HashSet<String> cves = db.getVulnerabilities(gav); if (! cves.isEmpty()){ result.addOutput(info); result.addOutput(" VULNERABLE! "); for (String cve : cves){ result.addOutput(cve); result.addOutput(" "); } result.addOutput(String.format("%n")); } else { result.addVerboseOutput(info); result.addVerboseOutput(" ok "); } } } catch (IOException e){ result.setResultCode(CommandResult.RESULT_ERROR); result.addOutput(String.format("error: %s", e.getMessage())); } catch (XmlPullParserException e) { result.setResultCode(CommandResult.RESULT_ERROR); result.addOutput(String.format("error: malformed POM file '%s'", pomFile.getAbsolutePath())); } catch (VictimsException e){ result.setResultCode(CommandResult.RESULT_ERROR); result.addOutput(String.format("error: %s", e.getMessage())); } } @Override public CommandResult execute(List<String> args) { CommandResult result = new CommandResult(); result.setResultCode(CommandResult.RESULT_SUCCESS); for (String arg : args){ File pomFile = new File(arg); result.addVerboseOutput("scanning - "); result.addVerboseOutput(arg); result.addVerboseOutput(String.format("%n")); if (! pomFile.exists()){ result.addOutput(String.format("no such file: %s%n", arg)); } else { scanPomFile(pomFile, result); } } return result; } @Override public String usage() { return help.toString(); } @Override public void setArguments(List<String> args) { this.arguments = args; } @Override public CommandResult call() throws Exception { return execute(this.arguments); } @Override public Command newInstance(){ return new PomScannerCommand(); } }
package com.remonsinnema.awe.worktype; import org.json.simple.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(path = "/work-types") public class WorkTypesController { private static final String NL = System.getProperty("line.separator"); private static final String START_ROW = "<tr><td>"; private static final String START_CELL = "</td><td>"; private static final String END_ROW = "</td></tr>"; private WorkTypesService service; @Autowired void setService(WorkTypesService service) { this.service = service; } @RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE) public String getWorkTypes() { StringBuilder result = new StringBuilder(512); result.append("<table>").append(NL).append(START_ROW).append(labelFor("type", "Type")) .append(START_CELL).append("<select id='type' onchange='typeChanged()'>"); for (String type : service.getTypes()) { result.append("<option value='").append(type).append("'>").append(type).append("</option>"); } result.append("</select>").append(END_ROW).append(NL).append(START_ROW).append(labelFor("category", "Category")) .append(START_CELL).append("<select id='category' onchange='categoryChanged()'></select>").append(END_ROW) .append(NL).append(START_ROW).append(labelFor("subcategory", "Sub-category")) .append(START_CELL).append("<select id='subcategory'></select>").append(END_ROW) .append(NL).append("</table>").append(NL); return result.toString(); } private String labelFor(String id, String label) { String key = label.substring(0, 1); return String.format("<label for='%s' accesskey='%s'><u>%s</u>%s:</label>", id, key, key, label.substring(1)); } @RequestMapping(path = "/{type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String getCategoriesFor(@PathVariable("type") String type) { return toJsonArrayAsString(service.getCategoriesFor(type)); } @SuppressWarnings("unchecked") private String toJsonArrayAsString(Iterable<String> items) { JSONArray result = new JSONArray(); items.forEach(result::add); return result.toJSONString(); } @RequestMapping(path = "/{type}/{category}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String getSubcategoriesFor(@PathVariable("type") String type, @PathVariable("category") String category) { return toJsonArrayAsString(service.getSubcategoriesFor(type, category)); } }
package com.salesforce.storm.spout.sideline; import com.google.common.base.Strings; import com.salesforce.storm.spout.sideline.config.SidelineSpoutConfig; import com.salesforce.storm.spout.sideline.filter.FilterChainStep; import com.salesforce.storm.spout.sideline.filter.NegatingFilterChainStep; import com.salesforce.storm.spout.sideline.kafka.VirtualSidelineSpout; import com.salesforce.storm.spout.sideline.kafka.consumerState.ConsumerState; import com.salesforce.storm.spout.sideline.kafka.failedMsgRetryManagers.NoRetryFailedMsgRetryManager; import com.salesforce.storm.spout.sideline.metrics.MetricsRecorder; import com.salesforce.storm.spout.sideline.persistence.PersistenceManager; import com.salesforce.storm.spout.sideline.trigger.SidelineIdentifier; import com.salesforce.storm.spout.sideline.trigger.StartRequest; import com.salesforce.storm.spout.sideline.trigger.StartingTrigger; import com.salesforce.storm.spout.sideline.trigger.StopRequest; import com.salesforce.storm.spout.sideline.trigger.StoppingTrigger; import org.apache.kafka.common.TopicPartition; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; /** * Skeleton implementation for now. */ public class SidelineSpout extends BaseRichSpout { // Logging private static final Logger logger = LoggerFactory.getLogger(SidelineSpout.class); // Storm Topology Items private Map topologyConfig; private SpoutOutputCollector outputCollector; private TopologyContext topologyContext; private transient ConcurrentLinkedDeque<KafkaMessage> queue; private VirtualSidelineSpout fireHoseSpout; private SpoutCoordinator coordinator; private StartingTrigger startingTrigger; private StoppingTrigger stoppingTrigger; /** * Manages creating implementation instances. */ private FactoryManager factoryManager; /** * Stores state about starting/stopping sideline requests. */ private PersistenceManager persistenceManager; /** * For collecting metrics. */ private transient MetricsRecorder metricsRecorder; /** * Determines which output stream to emit tuples out. * Gets set during open(). */ private String outputStreamId = null; /** * Constructor to create our SidelineSpout. * @TODO this method arguments may change to an actual SidelineSpoutConfig object instead of a generic map? * * @param topologyConfig - Our configuration. */ public SidelineSpout(Map topologyConfig) { // Save off config. this.topologyConfig = topologyConfig; // Create our factory manager, which must be serializable. factoryManager = new FactoryManager(this.topologyConfig); } /** * Set a starting trigger on the spout for starting a sideline request * @param startingTrigger An impplementation of a starting trigger */ public void setStartingTrigger(StartingTrigger startingTrigger) { this.startingTrigger = startingTrigger; } /** * Set a trigger on the spout for stopping a sideline request * @param stoppingTrigger An implementation of a stopping trigger */ public void setStoppingTrigger(StoppingTrigger stoppingTrigger) { this.stoppingTrigger = stoppingTrigger; } /** * Starts a sideline request * @param startRequest A representation of the request that is being started */ public void startSidelining(StartRequest startRequest) { logger.info("Received START sideline request"); final SidelineIdentifier id = new SidelineIdentifier(); // Store the offset that this request was made at, when the sideline stops we will begin processing at // this offset final ConsumerState startingState = fireHoseSpout.getCurrentState(); // TODO - Talk to slemon about this. // These are the committed offsets, meaning we have successfully processed them // So we want to start at the next message in each partition for (TopicPartition topicPartition: startingState.getTopicPartitions()) { // Increment by 1? This seems like a hack. startingState.setOffset(topicPartition, startingState.getOffsetForTopicAndPartition(topicPartition) + 1); } // Store in request manager persistenceManager.persistSidelineRequestState(id, startingState); // Add our new filter steps fireHoseSpout.getFilterChain().addSteps(id, startRequest.steps); // Call back to the trigger after starting // TODO: Revisit this, specifically the payload startingTrigger.start(id); // Update start count metric metricsRecorder.count(getClass(), "start-sideline", 1L); } /** * Stops a sideline request. * @param stopRequest A representation of the request that is being stopped */ public void stopSidelining(StopRequest stopRequest) { if (!fireHoseSpout.getFilterChain().hasSteps(stopRequest.id)) { logger.error("Received STOP sideline request, but I don't actually have any filter chain steps for it!"); return; } logger.info("Received STOP sideline request"); List<FilterChainStep> negatedSteps = new ArrayList<>(); List<FilterChainStep> steps = fireHoseSpout.getFilterChain().removeSteps(stopRequest.id); for (FilterChainStep step : steps) { negatedSteps.add(new NegatingFilterChainStep(step)); } // This is the state that the VirtualSidelineSpout should start with final ConsumerState startingState = persistenceManager.retrieveSidelineRequestState(stopRequest.id); // This is the state that the VirtualSidelineSpout should end with final ConsumerState endingState = fireHoseSpout.getCurrentState(); logger.info("Starting VirtualSidelineSpout with starting state {}", startingState); logger.info("Starting VirtualSidelineSpout with Ending state {}", endingState); final VirtualSidelineSpout spout = new VirtualSidelineSpout( topologyConfig, topologyContext, factoryManager.createNewDeserializerInstance(), new NoRetryFailedMsgRetryManager(), // Starting offset of the sideline request startingState, // When the sideline request ends endingState ); spout.setConsumerId(fireHoseSpout.getConsumerId() + "_" + stopRequest.id.toString()); spout.getFilterChain().addSteps(stopRequest.id, negatedSteps); coordinator.addSidelineSpout(spout); // Callback to teh trigger after stopping // TODO: Revisit this, specifically the payload stoppingTrigger.stop(); // Update stop count metric metricsRecorder.count(getClass(), "stop-sideline", 1L); } @Override public void open(Map toplogyConfig, TopologyContext context, SpoutOutputCollector collector) { // Save references. this.topologyConfig = Collections.unmodifiableMap(toplogyConfig); this.topologyContext = context; this.outputCollector = collector; // Initialize Metrics Collection this.metricsRecorder = factoryManager.createNewMetricsRecorder(); metricsRecorder.open(this.topologyConfig, this.topologyContext); // Setup our concurrent queue. this.queue = new ConcurrentLinkedDeque<>(); this.startingTrigger.setSidelineSpout(this); this.stoppingTrigger.setSidelineSpout(this); // Grab our ConsumerId prefix from the config final String cfgConsumerIdPrefix = (String) getTopologyConfigItem(SidelineSpoutConfig.CONSUMER_ID_PREFIX); if (Strings.isNullOrEmpty(cfgConsumerIdPrefix)) { throw new IllegalStateException("Missing required configuration: " + SidelineSpoutConfig.CONSUMER_ID_PREFIX); } // Create and open() persistence manager passing appropriate configuration. persistenceManager = factoryManager.createNewPersistenceManagerInstance(); persistenceManager.open(getTopologyConfig()); // Create the main spout for the topic, we'll dub it the 'firehose' fireHoseSpout = new VirtualSidelineSpout(getTopologyConfig(), getTopologyContext(), factoryManager.createNewDeserializerInstance(), factoryManager.createNewFailedMsgRetryManagerInstance()); fireHoseSpout.setConsumerId(cfgConsumerIdPrefix + "firehose"); // Setting up thread to call nextTuple // Fire up thread/instance/class that watches for any sideline consumers that should be running // This thread/class will then spawn any additional VirtualSidelineSpout instances that should be running // This thread could also maybe manage when it should kill off finished VirtualSideLineSpout instanes? // Fire up thread that manages which tuples should get emitted next // This thing cycles thru the firehose instance, and any sideline consumer instances // and fills up a buffer of what messages should go out next // Maybe this instance is a wrapper/container around all of the VirtualSideLineSpout instances? coordinator = new SpoutCoordinator( // Our main firehose spout instance. fireHoseSpout, // Our metrics recorder. metricsRecorder ); if (startingTrigger != null) { startingTrigger.open(toplogyConfig); } if (stoppingTrigger != null) { stoppingTrigger.open(toplogyConfig); } // TODO: Look for any existing sideline requests that haven't finished and add them to the // coordinator coordinator.open((KafkaMessage message) -> { queue.add(message); }); } @Override public void nextTuple() { // Talk to thread that manages what tuples should be emitted next to get the next tuple // Ensure that the tuple's Id identifies which spout instance it came from // so we can trace the tuple id back to the spout later. // Emit tuple. if (!queue.isEmpty()) { final KafkaMessage kafkaMessage = queue.removeFirst(); // Debug logging logger.info("Emitting MsgId[{}] - {}", kafkaMessage.getTupleMessageId(), kafkaMessage.getValues()); // Dump to output collector. outputCollector.emit(getOutputStreamId(), kafkaMessage.getValues(), kafkaMessage.getTupleMessageId()); // Update emit count metric for SidelineSpout metricsRecorder.count(getClass(), "emit", 1L); // Update emit count metric for VirtualSidelineSpout this tuple originated from metricsRecorder.count(VirtualSidelineSpout.class, kafkaMessage.getTupleMessageId().getSrcConsumerId() + ".emit", 1); } } /** * Declare the output fields. * @param declarer The output field declarer */ @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // I'm unsure where declareOutputFields() gets called in the spout lifecycle, it may get called // prior to open, in which case we need to shuffle some logic around. // Handles both explicitly defined and default stream definitions. declarer.declareStream(getOutputStreamId(), factoryManager.createNewDeserializerInstance().getOutputFields()); } @Override public void close() { logger.info("Stopping the coordinator and closing all spouts"); if (coordinator != null) { coordinator.close(); coordinator = null; } if (startingTrigger != null) { startingTrigger.close(); } if (stoppingTrigger != null) { stoppingTrigger.close(); } } @Override public void activate() { logger.info("Activating spout"); } @Override public void deactivate() { logger.info("Deactivate spout"); } @Override public void ack(Object id) { // Cast to appropriate object type final TupleMessageId tupleMessageId = (TupleMessageId) id; // Ack the tuple coordinator.ack(tupleMessageId); // Update ack count metric metricsRecorder.count(getClass(), "ack", 1L); // Update ack count metric for VirtualSidelineSpout this tuple originated from metricsRecorder.count(VirtualSidelineSpout.class, tupleMessageId.getSrcConsumerId() + ".ack", 1); } @Override public void fail(Object id) { // Cast to appropriate object type final TupleMessageId tupleMessageId = (TupleMessageId) id; // Fail the tuple coordinator.fail(tupleMessageId); // Update fail count metric metricsRecorder.count(getClass(), "fail", 1L); // Update ack count metric for VirtualSidelineSpout this tuple originated from metricsRecorder.count(VirtualSidelineSpout.class, tupleMessageId.getSrcConsumerId() + ".fail", 1); } public Map getTopologyConfig() { return topologyConfig; } public Object getTopologyConfigItem(final String key) { return getTopologyConfig().get(key); } public TopologyContext getTopologyContext() { return topologyContext; } /** * @return - returns the stream that tuples will be emitted out. */ protected String getOutputStreamId() { if (outputStreamId == null) { if (topologyConfig == null) { throw new IllegalStateException("Missing required configuration! SidelineSpoutConfig not defined!"); } outputStreamId = (String) getTopologyConfigItem(SidelineSpoutConfig.OUTPUT_STREAM_ID); if (Strings.isNullOrEmpty(outputStreamId)) { outputStreamId = Utils.DEFAULT_STREAM_ID; } } return outputStreamId; } }
package com.tn.dw.integration; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; public abstract class ConfigDecryptingApplication<T extends ConfigDecryptingConfiguration> extends Application<T> { @Override public void initialize(Bootstrap<T> bootstrap) { super.initialize(bootstrap); bootstrap.addBundle(new DecryptionConfiguredBundle<>(ConfigDecryptingConfiguration::getKeyEncryptionClient)); } }
package com.xtremelabs.robolectric.shadows; import android.app.Activity; import android.app.Application; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.xtremelabs.robolectric.Robolectric; import com.xtremelabs.robolectric.internal.Implementation; import com.xtremelabs.robolectric.internal.Implements; import com.xtremelabs.robolectric.internal.RealObject; import com.xtremelabs.robolectric.tester.android.view.TestWindow; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.xtremelabs.robolectric.Robolectric.shadowOf; @SuppressWarnings({"UnusedDeclaration"}) @Implements(Activity.class) public class ShadowActivity extends ShadowContextWrapper { @RealObject private Activity realActivity; private Intent intent; View contentView; private int resultCode; private Intent resultIntent; private Activity parent; private boolean finishWasCalled; private TestWindow window; private boolean hasOverriddenTransition; private List<IntentForResult> startedActivitiesForResults = new ArrayList<IntentForResult>(); private Map<Intent, Integer> intentRequestCodeMap = new HashMap<Intent, Integer>(); private int requestedOrientation = -1; @Implementation public final Application getApplication() { return Robolectric.application; } @Override @Implementation public final Application getApplicationContext() { return getApplication(); } @Implementation public void setIntent(Intent intent) { this.intent = intent; } @Implementation public Intent getIntent() { return intent; } /** * Sets the {@code contentView} for this {@code Activity} by invoking the * {@link android.view.LayoutInflater} * * @param layoutResID ID of the layout to inflate * @see #getContentView() */ @Implementation public void setContentView(int layoutResID) { contentView = getLayoutInflater().inflate(layoutResID, null); realActivity.onContentChanged(); } @Implementation public void setContentView(View view) { contentView = view; realActivity.onContentChanged(); } @Implementation public final void setResult(int resultCode) { this.resultCode = resultCode; } @Implementation public final void setResult(int resultCode, Intent data) { this.resultCode = resultCode; this.resultIntent = data; } @Implementation public LayoutInflater getLayoutInflater() { return LayoutInflater.from(realActivity); } @Implementation public MenuInflater getMenuInflater() { return new MenuInflater(realActivity); } /** * Checks to ensure that the{@code contentView} has been set * * @param id ID of the view to find * @return the view * @throws RuntimeException if the {@code contentView} has not been called first */ @Implementation public View findViewById(int id) { if (contentView != null) { return contentView.findViewById(id); } else { System.out.println("WARNING: you probably should have called setContentView() first"); return null; } } @Implementation public final Activity getParent() { return parent; } @Implementation public void onBackPressed() { finish(); } @Implementation public void finish() { finishWasCalled = true; } /** * @return whether {@link #finish()} was called */ @Implementation public boolean isFinishing() { return finishWasCalled; } /** * Constructs a new Window (a {@link com.xtremelabs.robolectric.tester.android.view.TestWindow}) if no window has previously been * set. * * @return the window associated with this Activity */ @Implementation public Window getWindow() { if (window == null) { window = new TestWindow(realActivity); } return window; } @Implementation public void runOnUiThread(Runnable action) { Robolectric.getUiThreadScheduler().post(action); } /** * Checks to see if {@code BroadcastListener}s are still registered. * * @throws RuntimeException if any listeners are still registered * @see #assertNoBroadcastListenersRegistered() */ @Implementation public void onDestroy() { assertNoBroadcastListenersRegistered(); } @Implementation public WindowManager getWindowManager() { return (WindowManager) Robolectric.application.getSystemService(Context.WINDOW_SERVICE); } @Implementation public void setRequestedOrientation(int requestedOrientation) { this.requestedOrientation = requestedOrientation; } @Implementation public int getRequestedOrientation() { return requestedOrientation; } /** * Checks the {@code ApplicationContext} to see if {@code BroadcastListener}s are still registered. * * @throws RuntimeException if any listeners are still registered * @see ShadowApplication#assertNoBroadcastListenersRegistered(android.content.Context, String) */ public void assertNoBroadcastListenersRegistered() { shadowOf(getApplicationContext()).assertNoBroadcastListenersRegistered(realActivity, "Activity"); } /** * Non-Android accessor. * * @return the {@code contentView} set by one of the {@code setContentView()} methods */ public View getContentView() { return contentView; } /** * Non-Android accessor. * * @return the {@code resultCode} set by one of the {@code setResult()} methods */ public int getResultCode() { return resultCode; } /** * Non-Android accessor. * * @return the {@code Intent} set by {@link #setResult(int, android.content.Intent)} */ public Intent getResultIntent() { return resultIntent; } /** * Non-Android accessor consumes and returns the next {@code Intent} on the * started activities for results stack. * * @return the next started {@code Intent} for an activity, wrapped in * an {@link ShadowActivity.IntentForResult} object */ public IntentForResult getNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.remove(0); } } /** * Non-Android accessor returns the most recent {@code Intent} started by * {@link #startActivityForResult(android.content.Intent, int)} without * consuming it. * * @return the most recently started {@code Intent}, wrapped in * an {@link ShadowActivity.IntentForResult} object */ public IntentForResult peekNextStartedActivityForResult() { if (startedActivitiesForResults.isEmpty()) { return null; } else { return startedActivitiesForResults.get(0); } } /** * Container object to hold an Intent, together with the requestCode used * in a call to {@code Activity#startActivityForResult(Intent, int)} */ public class IntentForResult { public Intent intent; public int requestCode; public IntentForResult(Intent intent, int requestCode) { this.intent = intent; this.requestCode = requestCode; } } @Implementation public void startActivityForResult(Intent intent, int requestCode) { intentRequestCodeMap.put(intent, requestCode); startedActivitiesForResults.add(new IntentForResult(intent, requestCode)); getApplicationContext().startActivity(intent); } public void receiveResult(Intent requestIntent, int resultCode, Intent resultIntent) { Integer requestCode = intentRequestCodeMap.get(requestIntent); if (requestCode == null) { throw new RuntimeException("No intent matches " + requestIntent + " among " + intentRequestCodeMap.keySet()); } try { Method method = Activity.class.getDeclaredMethod("onActivityResult", Integer.TYPE, Integer.TYPE, Intent.class); method.setAccessible(true); method.invoke(realActivity, requestCode, resultCode, resultIntent); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } @Implementation public final void showDialog(int id) { showDialog(id, null); } @Implementation public final boolean showDialog(int id, Bundle args) { Dialog dialog = null; try { Method method = Activity.class.getDeclaredMethod("onCreateDialog", Integer.TYPE); method.setAccessible(true); dialog = (Dialog) method.invoke(realActivity, id); method = Activity.class.getDeclaredMethod("onPrepareDialog", Integer.TYPE, Dialog.class, Bundle.class); method.setAccessible(true); method.invoke(realActivity, id, dialog, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } dialog.show(); return true; } public boolean hasOverriddenTransition() { return hasOverriddenTransition; } @Implementation public void overridePendingTransition(int enterAnim, int exitAnim) { hasOverriddenTransition = true; } }
package de.cinovo.cloudconductor.agent.jobs; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import de.cinovo.cloudconductor.agent.AgentState; import de.cinovo.cloudconductor.agent.helper.JWTHelper; import de.cinovo.cloudconductor.agent.helper.ServerCom; import de.cinovo.cloudconductor.agent.tasks.SchedulerService; import de.cinovo.cloudconductor.api.lib.exceptions.CloudConductorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.util.concurrent.TimeUnit; public class RefreshJWTJob implements AgentJob { /** * the job name, used by the scheduler */ public static final String JOB_NAME = "REFRESH_JWT_JOB"; private static final Logger LOGGER = LoggerFactory.getLogger(RefreshJWTJob.class); private final long defaultPeriod = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES); @Override public void run() { RefreshJWTJob.LOGGER.debug("Start RefreshJWTJob"); long period = this.defaultPeriod; AgentState.info().setJWT(null); try { String newJWT = ServerCom.getJWT(); if(newJWT != null) { JWTClaimsSet claimsSet = SignedJWT.parse(newJWT).getJWTClaimsSet(); AgentState.info().setJWT(newJWT); period = JWTHelper.calcNextRefreshInMillis(claimsSet); RefreshJWTJob.LOGGER.debug("Authentication successful!"); } else { RefreshJWTJob.LOGGER.error("Authentication failed: Missing JWT!"); throw new CloudConductorException("Missing JWT!"); } } catch(CloudConductorException e) { RefreshJWTJob.LOGGER.error("Error refreshing JWT: ", e); } catch(ParseException e) { RefreshJWTJob.LOGGER.error("Error parsing new JWT: ", e); } finally { SchedulerService.instance.executeOnce(new RefreshJWTJob(), period, TimeUnit.MILLISECONDS); if(period == this.defaultPeriod) { RefreshJWTJob.LOGGER.warn("Scheduled next refresh of JWT in default period time! Something is wrong. "); } RefreshJWTJob.LOGGER.debug("Scheduled next refresh of JWT in " + period + " ms"); RefreshJWTJob.LOGGER.debug("Finished RefreshJWTJob"); } } @Override public String getJobIdentifier() { return RefreshJWTJob.JOB_NAME; } @Override public boolean isDefaultStart() { return false; } @Override public long defaultStartTimer() { return 30; } @Override public TimeUnit defaultStartTimerUnit() { return TimeUnit.MINUTES; } }
package de.hwrberlin.it2014.sweproject.cbr; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import de.hwrberlin.it2014.sweproject.database.DatabaseConnection; import de.hwrberlin.it2014.sweproject.synonym.LawTester; import de.hwrberlin.it2014.sweproject.synonym.ThesaurusLoader; /** * Klasse fr hnlichkeitsanalyse * * @author Tobias Glaeser * @since 11.02.2016 09:43:34 */ public class ScoreProcessor<T extends Scoreable> { /** * ignore timestamp flag */ public static final long IGNORE_TIMESTAMP = -1; private HashMap<T, Double> scoreCache = new HashMap<>(); private final double weights[]; private final double[] sortWeights; /** * @author Tobias Glaeser * @since 11.02.2016 09:45:21 * @param weights Gewichte fr Scoring: * [0] : keyword (normal) * [1] : keyword (jura) * [2] : Weight pro Tag Unterschied * * @param sortWeights Gewichte fr Sortierung * [0] : -score * [1] : pagerank value */ public ScoreProcessor(double weights[], double sortWeights[]){ this.weights = weights; this.sortWeights = sortWeights; } /** * Constructor mit Default Weight * * @author Tobias Glaeser * @since 11.02.2016 09:46:36 */ public ScoreProcessor(){ this(new double[]{10, 20, 2, 0}, new double[]{1, 0.2d}); } /** * Distanz von keywords zu einem Fall * * @author Tobias Glaeser * @since 08.02.2016 11:22:09 * @param s entry to check * @param queryKeywords query keywords with synonyms * @param timestamp Zeitangabe im query (in ms) * @return distance value */ public double getDistance(T s, ArrayList<String> filteredKeywords, long timestamp){ double dist = 0d; // check keyword for(String keyword : filteredKeywords) { ArrayList<String> synynoms = expandSynonyms(keyword); boolean found = false; boolean isJura = LawTester.testIfWordIsLawTerm(keyword); check: for(String sy : synynoms) { if(s.getKeywordsAsList().contains(sy.toLowerCase())) { found = true; break check; } } if(!found) { dist += isJura ? weights[1] : weights[0]; } } // check timestamp if(timestamp != IGNORE_TIMESTAMP) { dist += (Math.abs(timestamp - s.getTimestamp()) / (1000 * 60 * 60 * 24)) * weights[2]; } return dist; } /** * Findet die besten Matches * * @author Tobias Glaeser * @since 08.02.2016 11:33:09 * @param queryKeywords Raw query keywords (ungefiltert) * @param number Anzahl der Flle die max. zurckgegeben werden sollen * @param timestamp Zeitangabe im query (in ms) * @param lawsector Rechtsbereich (prefilter exclude only) * @return liste mit hnlichen Fllen (absteigende hnlichkeit) * @throws SQLException db error */ public ArrayList<T> getBestMatches(ArrayList<String> queryKeywords, int number, long timestamp, String lawsector) throws SQLException{ ArrayList<String> filteredKeywords = filterKeywords(queryKeywords); ArrayList<String> allKeywords = expandSynonyms(filteredKeywords); String query = QueryBuilder.buildQuery(allKeywords, lawsector); DatabaseConnection con = new DatabaseConnection(); con.connectToMysql(); ArrayList<T> prefilter = (ArrayList<T>) con.convertResultSetToJudgementList(con.executeQuery(query)); // cast is safe as Judgement implement scoreable final HashMap<T, Double> scores = new HashMap<>(); for(T s : prefilter) { scores.put(s, getDistance(s, filteredKeywords, timestamp)); } scoreCache.putAll(scores); // sort ArrayList<T> ordered = new ArrayList<>(prefilter); Collections.sort(ordered, new Comparator<T>(){ @Override public int compare(T o1, T o2){ double d1 = scores.get(o1); double d2 = scores.get(o2); double v1 = -(d1 * sortWeights[0]) + o1.getPageRank() * sortWeights[1]; double v2 = -(d2 * sortWeights[0]) + o2.getPageRank() * sortWeights[1]; if(v1 < v2) { return -1; } else if(v1 > v2) { return 1; } else return 0; } }); for(int i = 0; i < ordered.size() - number; i++) { ordered.remove(ordered.size() - 1); } return ordered; } /** * gibt gecachten score wert zurck * achtung: vorher muss getBestMatches() ausgefhrt worden sein. * * @author Tobias Glaeser * @param t case/judgement * @return hnlichkeitswert der fr diesen fall berechnet wurde */ public double getCachedScore(T t){ return scoreCache.get(t); } /** * Entfernt alle Keywords aus der Liste, die Synonym eines anderen sind * * @author Tobias Glaeser * @since 08.02.2016 11:48:20 * @param queryKeywords raw user query keywords * @return Gefilterte Keyword Liste */ private ArrayList<String> filterKeywords(ArrayList<String> queryKeywords){ ArrayList<String> filtered = new ArrayList<>(); filtered.add(queryKeywords.get(0)); for(int i = 1; i < queryKeywords.size(); i++) { String word = queryKeywords.get(i); ArrayList<String> preSublist = new ArrayList<>(); for(int a = 0; a < i; a++) { preSublist.add(queryKeywords.get(a)); } if(!expandSynonyms(filtered).contains(word.toLowerCase())) { filtered.add(word); } } return filtered; } /** * Erweitert ein Keyword um Synonyme * * @author Tobias Glaeser * @since 08.02.2016 11:30:17 * @param keyword Keyword * @return keyword Liste mit input keyword und synonymen */ public ArrayList<String> expandSynonyms(String keyword){ ArrayList<String> words = new ArrayList<>(); words.add(keyword); return expandSynonyms(words); } /** * Erweitert Keyword Liste um Synonyme * * @author Tobias Glaeser * @since 08.02.2016 11:30:17 * @param keywords raw keyword list * @return keyword liste mit input keywords und synonymen */ public ArrayList<String> expandSynonyms(ArrayList<String> keywords){ ArrayList<String> allKeywords = new ArrayList<>(keywords); for(String keyword : keywords) { ArrayList<String> synonyms = ThesaurusLoader.getSynonyms(keyword.toLowerCase()); for(String word : synonyms) { if(!allKeywords.contains(word.toLowerCase())) { allKeywords.add(word.toLowerCase()); } } } return allKeywords; } }
package de.omnikryptec.libapi.opengl.buffer; import java.nio.IntBuffer; import org.lwjgl.opengl.GL15; import de.omnikryptec.libapi.exposed.render.IndexBuffer; public class GLIndexBuffer extends GLBuffer implements IndexBuffer { public GLIndexBuffer() { super(GL15.GL_ELEMENT_ARRAY_BUFFER); } @Override public void storeData(final IntBuffer data, final boolean dynamic) { bindBuffer(); GL15.glBufferData(bufferType(), data, dynamic ? GL15.GL_DYNAMIC_DRAW : GL15.GL_STATIC_DRAW); } }
package de.slikey.effectlib.effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.MathUtils; import de.slikey.effectlib.util.ParticleEffect; import de.slikey.effectlib.util.RandomUtils; import de.slikey.effectlib.util.VectorUtils; import org.bukkit.Location; import org.bukkit.util.Vector; import java.util.Random; public class CylinderLocationEffect extends LocationEffect { /** * Particle of the cube */ public ParticleEffect particle = ParticleEffect.FLAME; /** * Radius of cylinder */ public float radius = 1; /** * Height of Cylinder */ public float height = 3; /** * Turns the cube by this angle each iteration around the x-axis */ public double angularVelocityX = Math.PI / 200; /** * Turns the cube by this angle each iteration around the y-axis */ public double angularVelocityY = Math.PI / 170; /** * Turns the cube by this angle each iteration around the z-axis */ public double angularVelocityZ = Math.PI / 155; /** * Rotation of the cylinder */ public double rotationX, rotationY, rotationZ; /** * Particles in each row */ public int particles = 100; /** * True if rotation is enable */ public boolean enableRotation = true; /** * Toggles the cylinder to be solid */ public boolean solid = false; /** * Current step. Works as counter */ protected int step = 0; /** * Ratio of sides to entire surface */ protected float sideRatio = 0; public CylinderLocationEffect(EffectManager effectManager, Location location) { super(effectManager, location); type = EffectType.REPEATING; period = 2; iterations = 200; } @Override public void onRun() { if (sideRatio == 0) calculateSideRatio(); Random r = RandomUtils.random; double xRotation = rotationX, yRotation = rotationY, zRotation = rotationZ; if (enableRotation) { xRotation += step * angularVelocityX; yRotation += step * angularVelocityY; zRotation += step * angularVelocityZ; } for (int i = 0; i < particles; i++) { float multi = (solid) ? r.nextFloat() : 1; Vector v = RandomUtils.getRandomCircleVector().multiply(radius); if (r.nextFloat() <= sideRatio) { // SIDE PARTICLE v.multiply(multi); v.setY((r.nextFloat() * 2 - 1) * (height / 2)); } else { // GROUND PARTICLE v.multiply(r.nextFloat()); if (r.nextFloat() < 0.5) { // TOP v.setY(multi * (height / 2)); } else { // BOTTOM v.setY(-multi * (height / 2)); } } if (enableRotation) VectorUtils.rotateVector(v, xRotation, yRotation, zRotation); particle.display(location.add(v), visibleRange); location.subtract(v); } particle.display(location, visibleRange); step++; } protected void calculateSideRatio() { float grounds, side; grounds = MathUtils.PI * MathUtils.PI * radius * 2; side = 2 * MathUtils.PI * radius * height; sideRatio = side / (side + grounds); } }
package edu.harvard.iq.dataverse.export.ddi; import com.google.gson.Gson; import edu.harvard.iq.dataverse.DatasetFieldConstant; import edu.harvard.iq.dataverse.api.dto.DatasetDTO; import edu.harvard.iq.dataverse.api.dto.DatasetVersionDTO; import edu.harvard.iq.dataverse.api.dto.FieldDTO; import edu.harvard.iq.dataverse.api.dto.FileDTO; import edu.harvard.iq.dataverse.api.dto.MetadataBlockDTO; import edu.harvard.iq.dataverse.util.json.JsonUtil; import edu.harvard.iq.dataverse.util.xml.XmlPrinter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.json.JsonObject; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class DdiExportUtil { private static final Logger logger = Logger.getLogger(DdiExportUtil.class.getCanonicalName()); public static String datasetDtoAsJson2ddi(String datasetDtoAsJson) { logger.fine(JsonUtil.prettyPrint(datasetDtoAsJson)); Gson gson = new Gson(); DatasetDTO datasetDto = gson.fromJson(datasetDtoAsJson, DatasetDTO.class); try { return dto2ddi(datasetDto); } catch (XMLStreamException ex) { Logger.getLogger(DdiExportUtil.class.getName()).log(Level.SEVERE, null, ex); return null; } } public static OutputStream datasetJson2ddi(JsonObject datasetDtoAsJson) { logger.fine(JsonUtil.prettyPrint(datasetDtoAsJson.toString())); Gson gson = new Gson(); DatasetDTO datasetDto = gson.fromJson(datasetDtoAsJson.toString(), DatasetDTO.class); try { return dtoddi(datasetDto); } catch (XMLStreamException ex) { Logger.getLogger(DdiExportUtil.class.getName()).log(Level.SEVERE, null, ex); return null; } } private static OutputStream dtoddi(DatasetDTO datasetDto) throws XMLStreamException { OutputStream outputStream = new ByteArrayOutputStream(); XMLStreamWriter xmlw = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream); xmlw.writeStartElement("codeBook"); xmlw.writeDefaultNamespace("http: writeAttribute(xmlw, "version", "2.0"); createStdyDscr(xmlw, datasetDto); createdataDscr(xmlw, datasetDto.getDatasetVersion().getFiles()); xmlw.writeEndElement(); // codeBook xmlw.flush(); return outputStream; } private static String dto2ddi(DatasetDTO datasetDto) throws XMLStreamException { OutputStream outputStream = dtoddi(datasetDto); String xml = outputStream.toString(); return XmlPrinter.prettyPrintXml(xml); } private static void createStdyDscr(XMLStreamWriter xmlw, DatasetDTO datasetDto) throws XMLStreamException { DatasetVersionDTO version = datasetDto.getDatasetVersion(); String persistentAgency = datasetDto.getProtocol(); String persistentAuthority = datasetDto.getAuthority(); String persistentId = datasetDto.getIdentifier(); String citation = datasetDto.getDatasetVersion().getCitation(); xmlw.writeStartElement("stdyDscr"); xmlw.writeStartElement("citation"); xmlw.writeStartElement("titlStmt"); writeFullElement(xmlw, "titl", dto2Primitive(version, DatasetFieldConstant.title)); xmlw.writeStartElement("IDNo"); writeAttribute(xmlw, "agency", persistentAgency); xmlw.writeCharacters(persistentAuthority + "/" + persistentId); xmlw.writeEndElement(); // IDNo writeFullElement(xmlw, "subTitl", dto2Primitive(version, DatasetFieldConstant.subTitle)); writeFullElement(xmlw, "altTitl", dto2Primitive(version, DatasetFieldConstant.alternativeTitle)); xmlw.writeEndElement(); // titlStmt writeAuthorsElement(xmlw, version); writeProducersElement(xmlw, version); xmlw.writeStartElement("biblCit"); xmlw.writeCharacters(citation); xmlw.writeEndElement(); // biblCit xmlw.writeEndElement(); // citation //End Citation Block //Start Study Info Block // Study Info xmlw.writeStartElement("stdyInfo"); writeSubjectElement(xmlw, version); //Subject and Keywords writeAbstractElement(xmlw, version); // Description writeFullElement(xmlw, "notes", dto2Primitive(version, DatasetFieldConstant.notesText)); writeSummaryDescriptionElement(xmlw, version); writeRelPublElement(xmlw, version); writeFullElement(xmlw, "prodDate", dto2Primitive(version, DatasetFieldConstant.productionDate)); writeFullElement(xmlw, "prodPlac", dto2Primitive(version, DatasetFieldConstant.productionPlace)); writeGrantElement(xmlw, version); xmlw.writeEndElement(); // stdyInfo // End Info Block xmlw.writeEndElement(); // stdyDscr } private static void writeSummaryDescriptionElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { xmlw.writeStartElement("sumDscr"); for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { Integer per = 0; Integer coll = 0; for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.timePeriodCovered.equals(fieldDTO.getTypeName())) { String dateValStart = ""; String dateValEnd = ""; for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { per++; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.timePeriodCoveredStart.equals(next.getTypeName())) { dateValStart = next.getSinglePrimitive(); } if (DatasetFieldConstant.timePeriodCoveredEnd.equals(next.getTypeName())) { dateValEnd = next.getSinglePrimitive(); } } if (!dateValStart.isEmpty()) { writeDateElement(xmlw, "timePrd", "P"+ per.toString(), "start", dateValStart ); } if (!dateValEnd.isEmpty()) { writeDateElement(xmlw, "timePrd", "P"+ per.toString(), "end", dateValEnd ); } } } if (DatasetFieldConstant.dateOfCollection.equals(fieldDTO.getTypeName())) { String dateValStart = ""; String dateValEnd = ""; for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { coll++; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.dateOfCollectionStart.equals(next.getTypeName())) { dateValStart = next.getSinglePrimitive(); } if (DatasetFieldConstant.dateOfCollectionEnd.equals(next.getTypeName())) { dateValEnd = next.getSinglePrimitive(); } } if (!dateValStart.isEmpty()) { writeDateElement(xmlw, "collDate", "P"+ coll.toString(), "start", dateValStart ); } if (!dateValEnd.isEmpty()) { writeDateElement(xmlw, "collDate", "P"+ coll.toString(), "end", dateValEnd ); } } } if (DatasetFieldConstant.kindOfData.equals(fieldDTO.getTypeName())) { writeMultipleElement(xmlw, "dataKind", fieldDTO); } } } if("geospatial".equals(key)){ for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.geographicCoverage.equals(fieldDTO.getTypeName())) { for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.country.equals(next.getTypeName())) { writeFullElement(xmlw, "nation", next.getSinglePrimitive()); } if (DatasetFieldConstant.city.equals(next.getTypeName())) { writeFullElement(xmlw, "georgCover", next.getSinglePrimitive()); } if (DatasetFieldConstant.state.equals(next.getTypeName())) { writeFullElement(xmlw, "georgCover", next.getSinglePrimitive()); } if (DatasetFieldConstant.otherGeographicCoverage.equals(next.getTypeName())) { writeFullElement(xmlw, "georgCover", next.getSinglePrimitive()); } } } } } } if("socialscience".equals(key)){ for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.universe.equals(fieldDTO.getTypeName())) { writeMultipleElement(xmlw, "universe", fieldDTO); } if (DatasetFieldConstant.unitOfAnalysis.equals(fieldDTO.getTypeName())) { writeMultipleElement(xmlw, "anlyUnit", fieldDTO); } } } } xmlw.writeEndElement(); //sumDscr } private static void writeMultipleElement(XMLStreamWriter xmlw, String element, FieldDTO fieldDTO) throws XMLStreamException { for (String value : fieldDTO.getMultiplePrimitive()) { writeFullElement(xmlw, element, value); } } private static void writeDateElement(XMLStreamWriter xmlw, String element, String cycle, String event, String dateIn) throws XMLStreamException { xmlw.writeStartElement(element); writeAttribute(xmlw, "cycle", cycle); writeAttribute(xmlw, "event", event); writeAttribute(xmlw, "date", dateIn); xmlw.writeCharacters(dateIn); xmlw.writeEndElement(); } private static void writeSubjectElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException{ //Key Words and Topic Classification xmlw.writeStartElement("subject"); for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.subject.equals(fieldDTO.getTypeName())){ for ( String subject : fieldDTO.getMultipleVocab()){ xmlw.writeStartElement("keyword"); xmlw.writeCharacters(subject); xmlw.writeEndElement(); //Keyword } } if (DatasetFieldConstant.keyword.equals(fieldDTO.getTypeName())) { for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { String keywordValue = ""; String keywordVocab = ""; String keywordURI = ""; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.keywordValue.equals(next.getTypeName())) { keywordValue = next.getSinglePrimitive(); } if (DatasetFieldConstant.keywordVocab.equals(next.getTypeName())) { keywordVocab = next.getSinglePrimitive(); } if (DatasetFieldConstant.keywordVocabURI.equals(next.getTypeName())) { keywordURI = next.getSinglePrimitive(); } } if (!keywordValue.isEmpty()){ xmlw.writeStartElement("keyword"); if(!keywordVocab.isEmpty()){ writeAttribute(xmlw,"vocab",keywordVocab); } if(!keywordURI.isEmpty()){ writeAttribute(xmlw,"URI",keywordURI); } xmlw.writeCharacters(keywordValue); xmlw.writeEndElement(); //Keyword } } } if (DatasetFieldConstant.topicClassification.equals(fieldDTO.getTypeName())) { for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { String topicClassificationValue = ""; String topicClassificationVocab = ""; String topicClassificationURI = ""; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.topicClassValue.equals(next.getTypeName())) { topicClassificationValue = next.getSinglePrimitive(); } if (DatasetFieldConstant.topicClassVocab.equals(next.getTypeName())) { topicClassificationVocab = next.getSinglePrimitive(); } if (DatasetFieldConstant.topicClassVocabURI.equals(next.getTypeName())) { topicClassificationURI = next.getSinglePrimitive(); } } if (!topicClassificationValue.isEmpty()){ xmlw.writeStartElement("topcClas"); if(!topicClassificationVocab.isEmpty()){ writeAttribute(xmlw,"vocab",topicClassificationVocab); } if(!topicClassificationURI.isEmpty()){ writeAttribute(xmlw,"URI",topicClassificationURI); } xmlw.writeCharacters(topicClassificationValue); xmlw.writeEndElement(); //topcClas } } } } } } xmlw.writeEndElement(); // subject } private static void writeAuthorsElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { xmlw.writeStartElement("rspStmt"); for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.author.equals(fieldDTO.getTypeName())) { String authorName = ""; String authorAffiliation = ""; for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.authorName.equals(next.getTypeName())) { authorName = next.getSinglePrimitive(); } if (DatasetFieldConstant.authorAffiliation.equals(next.getTypeName())) { authorAffiliation = next.getSinglePrimitive(); } } if (!authorName.isEmpty()){ xmlw.writeStartElement("AuthEnty"); if(!authorAffiliation.isEmpty()){ writeAttribute(xmlw,"affiliation",authorAffiliation); } xmlw.writeCharacters(authorName); xmlw.writeEndElement(); //AuthEnty } } } } } } xmlw.writeEndElement(); //rspStmt } private static void writeProducersElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.producer.equals(fieldDTO.getTypeName())) { xmlw.writeStartElement("rspStmt"); for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { String producerName = ""; String producerAffiliation = ""; String producerAbbreviation = ""; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.producerName.equals(next.getTypeName())) { producerName = next.getSinglePrimitive(); } if (DatasetFieldConstant.producerAffiliation.equals(next.getTypeName())) { producerAffiliation = next.getSinglePrimitive(); } if (DatasetFieldConstant.producerAffiliation.equals(next.getTypeName())) { producerAffiliation = next.getSinglePrimitive(); } } if (!producerName.isEmpty()) { xmlw.writeStartElement("producer"); if (!producerAffiliation.isEmpty()) { writeAttribute(xmlw, "affiliation", producerAffiliation); } if (!producerAbbreviation.isEmpty()) { writeAttribute(xmlw, "abbr", producerAbbreviation); } xmlw.writeCharacters(producerName); xmlw.writeEndElement(); //AuthEnty } } xmlw.writeEndElement(); //rspStmt } } } } } private static void writeRelPublElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.publication.equals(fieldDTO.getTypeName())) { for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { String pubString = ""; String citation = ""; String IDType = ""; String IDNo = ""; String url = ""; for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.publicationCitation.equals(next.getTypeName())) { citation = next.getSinglePrimitive(); } if (DatasetFieldConstant.publicationIDType.equals(next.getTypeName())) { IDType = next.getSinglePrimitive(); } if (DatasetFieldConstant.publicationIDNumber.equals(next.getTypeName())) { IDNo = next.getSinglePrimitive(); } if (DatasetFieldConstant.publicationURL.equals(next.getTypeName())) { url = next.getSinglePrimitive(); } } pubString = appendCommaSeparatedValue(citation, IDType); pubString = appendCommaSeparatedValue(pubString, IDNo); pubString = appendCommaSeparatedValue(pubString, url); if (!pubString.isEmpty()){ xmlw.writeStartElement("relPubl"); xmlw.writeCharacters(pubString); xmlw.writeEndElement(); //relPubl } } } } } } } private static String appendCommaSeparatedValue(String inVal, String next) { if (!next.isEmpty()) { if (!inVal.isEmpty()) { return inVal + ", " + next; } else { return next; } } return inVal; } private static void writeAbstractElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.description.equals(fieldDTO.getTypeName())) { String descriptionText = ""; String descriptionDate = ""; for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.descriptionText.equals(next.getTypeName())) { descriptionText = next.getSinglePrimitive(); } if (DatasetFieldConstant.descriptionDate.equals(next.getTypeName())) { descriptionDate = next.getSinglePrimitive(); } } if (!descriptionText.isEmpty()){ xmlw.writeStartElement("abstract"); if(!descriptionDate.isEmpty()){ writeAttribute(xmlw,"date",descriptionDate); } xmlw.writeCharacters(descriptionText); xmlw.writeEndElement(); //abstract } } } } } } } private static void writeGrantElement(XMLStreamWriter xmlw, DatasetVersionDTO datasetVersionDTO) throws XMLStreamException { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (DatasetFieldConstant.grantNumber.equals(fieldDTO.getTypeName())) { String grantNumber = ""; String grantAgency = ""; for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (DatasetFieldConstant.grantNumberValue.equals(next.getTypeName())) { grantNumber = next.getSinglePrimitive(); } if (DatasetFieldConstant.grantNumberAgency.equals(next.getTypeName())) { grantAgency = next.getSinglePrimitive(); } } if (!grantNumber.isEmpty()){ xmlw.writeStartElement("grantNo"); if(!grantAgency.isEmpty()){ writeAttribute(xmlw,"agency",grantAgency); } xmlw.writeCharacters(grantNumber); xmlw.writeEndElement(); //grantno } } } } } } } /** * @todo Create a full dataDscr and otherMat sections of the DDI. This stub * adapted from the minimal DDIExportServiceBean example. */ private static void createdataDscr(XMLStreamWriter xmlw, List<FileDTO> fileDtos) throws XMLStreamException { if (fileDtos.isEmpty()) { return; } xmlw.writeStartElement("dataDscr"); xmlw.writeEndElement(); // dataDscr for (FileDTO fileDTo : fileDtos) { xmlw.writeStartElement("otherMat"); writeAttribute(xmlw, "ID", "f" + fileDTo.getDatafile().getId()); writeAttribute(xmlw, "level", "datafile"); xmlw.writeStartElement("labl"); xmlw.writeCharacters(fileDTo.getDatafile().getName()); xmlw.writeEndElement(); // labl writeFileDescription(xmlw, fileDTo); xmlw.writeEndElement(); // otherMat } } private static void writeFileDescription(XMLStreamWriter xmlw, FileDTO fileDTo) throws XMLStreamException { xmlw.writeStartElement("txt"); String description = fileDTo.getDatafile().getDescription(); if (description != null) { xmlw.writeCharacters(description); } xmlw.writeEndElement(); // txt } private static String dto2Primitive(DatasetVersionDTO datasetVersionDTO, String datasetFieldTypeName) { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); // if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (datasetFieldTypeName.equals(fieldDTO.getTypeName())) { return fieldDTO.getSinglePrimitive(); } } } return null; } private static String dto2ChildVal(DatasetVersionDTO datasetVersionDTO, String parentDatasetFieldTypeName, String childDatasetFieldTypeName) { for (Map.Entry<String, MetadataBlockDTO> entry : datasetVersionDTO.getMetadataBlocks().entrySet()) { String key = entry.getKey(); MetadataBlockDTO value = entry.getValue(); // if ("citation".equals(key)) { for (FieldDTO fieldDTO : value.getFields()) { if (parentDatasetFieldTypeName.equals(fieldDTO.getTypeName())) { for (HashSet<FieldDTO> foo : fieldDTO.getMultipleCompound()) { for (Iterator<FieldDTO> iterator = foo.iterator(); iterator.hasNext();) { FieldDTO next = iterator.next(); if (childDatasetFieldTypeName.equals(next.getTypeName())) { return next.getSinglePrimitive(); } } } } } } return null; } private static void writeFullElement (XMLStreamWriter xmlw, String name, String value) throws XMLStreamException { //For the simplest Elements we can if (!StringUtilisEmpty(value)) { xmlw.writeStartElement(name); xmlw.writeCharacters(value); xmlw.writeEndElement(); // labl } } private static void writeAttribute(XMLStreamWriter xmlw, String name, String value) throws XMLStreamException { if (!StringUtilisEmpty(value)) { xmlw.writeAttribute(name, value); } } private static boolean StringUtilisEmpty(String str) { if (str == null || str.trim().equals("")) { return true; } return false; } private static void saveJsonToDisk(String datasetVersionAsJson) throws IOException { Files.write(Paths.get("/tmp/out.json"), datasetVersionAsJson.getBytes()); } }
package ganymedes01.etfuturum.client.skins; import java.awt.image.BufferedImage; import java.io.File; import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type; import com.mojang.authlib.minecraft.MinecraftSessionService; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import ganymedes01.etfuturum.api.client.ISkinDownloadCallback; import ganymedes01.etfuturum.lib.Reference; import net.minecraft.client.renderer.IImageBuffer; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.SkinManager; import net.minecraft.util.ResourceLocation; /** * Stolen from 1.8 and modified to work with 1.7.10 */ @SideOnly(Side.CLIENT) public class NewSkinManager extends SkinManager { private final TextureManager textureManager; private final File skinFolder; public NewSkinManager(SkinManager oldManager, TextureManager textureManager, File skinFolder, MinecraftSessionService sessionService) { super(textureManager, skinFolder, sessionService); this.textureManager = textureManager; this.skinFolder = skinFolder; } @Override public ResourceLocation func_152789_a(final MinecraftProfileTexture texture, final Type type, final SkinManager.SkinAvailableCallback callBack) { if (type != Type.SKIN) return super.func_152789_a(texture, type, callBack); final boolean isSpecialCallBack = callBack instanceof ISkinDownloadCallback; final ResourceLocation resLocationOld = new ResourceLocation("skins/" + texture.getHash()); final ResourceLocation resLocation = new ResourceLocation(Reference.MOD_ID, resLocationOld.getResourcePath()); ITextureObject itextureobject = textureManager.getTexture(resLocation); if (itextureobject != null) { if (callBack != null) callBack.func_152121_a(type, resLocation); } else { File file1 = new File(skinFolder, texture.getHash().substring(0, 2)); File file2 = new File(file1, texture.getHash()); final NewImageBufferDownload imgDownload = new NewImageBufferDownload(); ITextureObject imgData = new NewThreadDownloadImageData(file2, texture.getUrl(), field_152793_a, imgDownload, resLocationOld, new IImageBuffer() { @Override public BufferedImage parseUserSkin(BufferedImage buffImg) { if (buffImg != null) PlayerModelManager.analyseTexture(buffImg, resLocation); return imgDownload.parseUserSkin(buffImg); } @Override public void func_152634_a() { imgDownload.func_152634_a(); if (callBack != null) callBack.func_152121_a(type, isSpecialCallBack ? resLocation : resLocationOld); } }); textureManager.loadTexture(resLocation, imgData); textureManager.loadTexture(resLocationOld, imgData); // Avoid thrown exception if the image is requested before the download is done } return isSpecialCallBack ? resLocation : resLocationOld; } }
package info.tritusk.insanepatcher; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import java.util.Iterator; public class PatcherCustomStuffFood implements IClassTransformer { @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (transformedName.equals("cubex2.cs2.item.ItemCSFood")) { ClassReader reader = new ClassReader(basicClass); ClassNode node = new ClassNode(); reader.accept(node, 0); node.interfaces.add("squeek/applecore/api/food/IEdible"); MethodNode onFoodEaten = node.methods.stream().filter(m -> m.name.equals("func_77654_b") || m.name.equals("onEaten")).findFirst().orElseThrow(Error::new); final boolean runtime = onFoodEaten.name.equals("func_77654_b"); Iterator<AbstractInsnNode> itr = onFoodEaten.instructions.iterator(); while (itr.hasNext()) { AbstractInsnNode insn = itr.next(); itr.remove(); if (insn.getOpcode() == Opcodes.INVOKEVIRTUAL && ((MethodInsnNode)insn).owner.equals("net/minecraft/util/FoodStats")) { break; } } InsnList insnListToAppend = new InsnList(); insnListToAppend.add(new InsnNode(Opcodes.ICONST_1)); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 1)); insnListToAppend.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/item/ItemStack", runtime ? "field_77994_a" : "stackSize", "I")); insnListToAppend.add(new InsnNode(Opcodes.ISUB)); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 3)); insnListToAppend.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/entity/player/EntityPlayer", runtime ? "func_71024_bL" : "getFoodStats", "()Lnet/minecraft/util/FoodStats;", false)); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 1)); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 3)); insnListToAppend.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "info/tritusk/insanepatcher/FoodUtil", "getFoodValues", "(Lnet/minecraft/item/ItemStack;Lnet/minecraft/entity/player/EntityPlayer;)Lsqueek/applecore/api/food/FoodValues;", false)); insnListToAppend.add(new VarInsnNode(Opcodes.ASTORE, 4)); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 4)); insnListToAppend.add(new FieldInsnNode(Opcodes.GETFIELD, "squeek/applecore/api/food/FoodValues", "hunger", "I")); insnListToAppend.add(new VarInsnNode(Opcodes.ALOAD, 4)); insnListToAppend.add(new FieldInsnNode(Opcodes.GETFIELD, "squeek/applecore/api/food/FoodValues", "saturationModifier", "F")); insnListToAppend.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/util/FoodStats", runtime ? "func_75122_a" : "addStats", "(IF)V", false)); onFoodEaten.instructions.insertBefore(onFoodEaten.instructions.getFirst(), insnListToAppend); MethodVisitor getFoodValues = node.visitMethod(Opcodes.ACC_PUBLIC, "getFoodValues", "(Lnet/minecraft/item/ItemStack;)Lsqueek/applecore/api/food/FoodValues;", null, null); getFoodValues.visitVarInsn(Opcodes.ALOAD, 1); getFoodValues.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/minecraft/item/ItemStack", runtime ? "func_77960_j" : "getItemDamage", "()I", false); getFoodValues.visitVarInsn(Opcodes.ISTORE, 4); getFoodValues.visitTypeInsn(Opcodes.NEW, "squeek/applecore/api/food/FoodValues"); getFoodValues.visitInsn(Opcodes.DUP); getFoodValues.visitVarInsn(Opcodes.ALOAD, 0); getFoodValues.visitFieldInsn(Opcodes.GETFIELD, "cubex2/cs2/item/ItemCSFood", "attributes", "Lcubex2/cs2/item/attributes/ItemFoodAttributes;"); getFoodValues.visitFieldInsn(Opcodes.GETFIELD, "cubex2/cs2/item/attributes/ItemFoodAttributes", "hunger", "[I"); getFoodValues.visitVarInsn(Opcodes.ILOAD, 4); getFoodValues.visitInsn(Opcodes.IALOAD); getFoodValues.visitVarInsn(Opcodes.ALOAD, 0); getFoodValues.visitFieldInsn(Opcodes.GETFIELD, "cubex2/cs2/item/ItemCSFood", "attributes", "Lcubex2/cs2/item/attributes/ItemFoodAttributes;"); getFoodValues.visitFieldInsn(Opcodes.GETFIELD, "cubex2/cs2/item/attributes/ItemFoodAttributes", "saturation", "[F"); getFoodValues.visitVarInsn(Opcodes.ILOAD, 4); getFoodValues.visitInsn(Opcodes.FALOAD); getFoodValues.visitMethodInsn(Opcodes.INVOKESPECIAL, "squeek/applecore/api/food/FoodValues", "<init>", "(IF)V", false); getFoodValues.visitInsn(Opcodes.ARETURN); getFoodValues.visitEnd(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); node.accept(writer); return writer.toByteArray(); } return basicClass; } }
package me.otisdiver.otisprojectile.targeting; import java.util.List; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Projectile; import me.otisdiver.otisprojectile.OtisProjectile; import me.otisdiver.otisprojectile.Utils; public class EggTargeter extends Targeter { private static int searchRange = 20; // Entity the egg has "locked on" to. private Entity target; private boolean lastUpdateFailed = false; public EggTargeter(OtisProjectile main, Projectile projectile) { super(main, projectile); } private boolean identifyTarget() { // Get a list of all entities within the search range. List<Entity> nearbyEntities = Utils.getNearbyEntitiesList(projectile, searchRange); // Remove from the list any entities that aren't hostile mobs. for(Entity e : nearbyEntities) { if (!Utils.isEntityHostile(e)) nearbyEntities.remove(e); if (projectile.getShooter().equals(e)) nearbyEntities.remove(e); } // Find the nearest entity. If it exists, update the target and report success. Entity entity = Utils.getNearestEntityInList(projectile.getLocation(), nearbyEntities); if (entity != null) { target = entity; return true; } else { return false; } } @Override public void updateTarget() { if (isProjectileGone()) { cancelTargetingTask(); return; } // If there's no target, try to find one. If that fails, stop. if (target == null || target.isDead()) { if (!identifyTarget()) return; } Location projectileLocation = projectile.getLocation(); Location targetLocation = target.getLocation(); // Continue chasing the target if it's still within the search range. if (Utils.calculateDistance(projectileLocation, targetLocation) < searchRange) { projectile.setVelocity(Utils.getLocationsVectorDifference(projectileLocation, targetLocation)); lastUpdateFailed = false; } // If the attempt fails, and the last attempt also failed, give up (will find new target on next tick). else if (lastUpdateFailed) { target = null; lastUpdateFailed = false; } // If the attempt fails, but the last one didn't, mark that this one did. else { lastUpdateFailed = true; } } }
package mil.dds.anet.search.sqlite; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import jersey.repackaged.com.google.common.base.Joiner; import org.skife.jdbi.v2.Handle; import mil.dds.anet.beans.Location; import mil.dds.anet.beans.lists.AbstractAnetBeanList.LocationList; import mil.dds.anet.beans.search.LocationSearchQuery; import mil.dds.anet.database.mappers.LocationMapper; import mil.dds.anet.search.ILocationSearcher; import mil.dds.anet.utils.DaoUtils; import mil.dds.anet.utils.Utils; public class SqliteLocationSearcher implements ILocationSearcher { @Override public LocationList runSearch(LocationSearchQuery query, Handle dbHandle) { final List<String> whereClauses = new LinkedList<String>(); final Map<String,Object> sqlArgs = new HashMap<String,Object>(); final StringBuilder sql = new StringBuilder("/* SqliteLocationSearch */ SELECT * FROM locations"); final String text = query.getText(); final boolean doFullTextSearch = (text != null && !text.trim().isEmpty()); if (doFullTextSearch) { whereClauses.add("name LIKE '%' || :text || '%'"); sqlArgs.put("text", Utils.getSqliteFullTextQuery(text)); } if (query.getStatus() != null) { whereClauses.add("status = :status"); sqlArgs.put("status", DaoUtils.getEnumId(query.getStatus())); } final LocationList result = new LocationList(); result.setPageNum(query.getPageNum()); result.setPageSize(query.getPageSize()); if (whereClauses.isEmpty()) { return result; } sql.append(" WHERE "); sql.append(Joiner.on(" AND ").join(whereClauses)); sql.append(" LIMIT :limit OFFSET :offset"); final List<Location> list = dbHandle.createQuery(sql.toString()) .bindFromMap(sqlArgs) .bind("offset", query.getPageSize() * query.getPageNum()) .bind("limit", query.getPageSize()) .map(new LocationMapper()) .list(); result.setList(list); result.setTotalCount(result.getList().size()); // Sqlite cannot do true total counts, so this is a crutch. return result; } }
package net.atomcode.bearing.location; import android.content.Context; import android.location.Location; /** * Gets the users current location using the best available service */ public class CurrentLocationTask extends LocationTask { public CurrentLocationTask(Context context) { super(context); } /** * Begin the lookup task using the set configuration. * Returns the task for cancellation if required. */ @SuppressWarnings("unused") public CurrentLocationTask start() { super.start(); locationProvider.requestSingleLocationUpdate(request, new LocationListener() { @Override public void onUpdate(Location location) { if (running) { // Cancel current task running = false; if (listener != null) { listener.onUpdate(location); } } } @Override public void onFailure() { listener.onFailure(); } @Override public void onTimeout() { listener.onTimeout(); } }); return this; } }
package net.contargo.iris.connection.dto; import net.contargo.iris.route.RoutePartData; import java.math.BigDecimal; /** * Dto for {@link RoutePartData}. * * @author Sandra Thieme - thieme@synyx.de */ public class RoutePartDataDto { private BigDecimal airlineDistance; private BigDecimal distance; private BigDecimal dieselDistance; private BigDecimal bargeDieselDistance; private BigDecimal railDieselDistance; private BigDecimal electricDistance; private BigDecimal tollDistance; private BigDecimal duration; private BigDecimal co2; public RoutePartDataDto() { // needed for Spring MVC instantiation of Controller parameter } public RoutePartDataDto(RoutePartData data) { if (data != null) { this.airlineDistance = data.getAirLineDistance(); this.distance = data.getDistance(); this.dieselDistance = data.getDieselDistance(); this.bargeDieselDistance = data.getBargeDieselDistance(); this.railDieselDistance = data.getRailDieselDistance(); this.electricDistance = data.getElectricDistance(); this.tollDistance = data.getTollDistance(); this.duration = data.getDuration(); this.co2 = data.getCo2(); } } public RoutePartData toRoutePartData() { RoutePartData routePartData = new RoutePartData(); routePartData.setAirLineDistance(airlineDistance); routePartData.setDistance(distance); routePartData.setDieselDistance(dieselDistance); routePartData.setBargeDieselDistance(bargeDieselDistance); routePartData.setRailDieselDistance(railDieselDistance); routePartData.setElectricDistance(electricDistance); routePartData.setTollDistance(tollDistance); routePartData.setDuration(duration); routePartData.setCo2(co2); return routePartData; } public BigDecimal getAirlineDistance() { return airlineDistance; } public BigDecimal getDistance() { return distance; } public BigDecimal getDieselDistance() { return dieselDistance; } public BigDecimal getBargeDieselDistance() { return bargeDieselDistance; } public BigDecimal getRailDieselDistance() { return railDieselDistance; } public BigDecimal getElectricDistance() { return electricDistance; } public BigDecimal getTollDistance() { return tollDistance; } public BigDecimal getDuration() { return duration; } public BigDecimal getCo2() { return co2; } }
package net.sf.taverna.t2.activities.biomoby; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.biomoby.shared.MobyException; import org.biomoby.shared.Utils; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * * @author Eddie Kawas * */ @SuppressWarnings("unchecked") public class XMLUtilities { // private variables // machine independent new line character public final static String newline = System.getProperty("line.separator"); // class variable to keep persistant queryIDs private static int queryCount = 0; // the moby namespaces public final static Namespace MOBY_NS = Namespace.getNamespace("moby", "http: /** * * @param message * the structurally valid BioMoby message as a String * @return true if the message contains multiple invocations, false * otherwise. * @throws MobyException * if the message is null */ public static boolean isMultipleInvocationMessage(String message) throws MobyException { if (message == null) throw new MobyException( newline + "null 'xml' found where it was not expected in isMultipleInvocationMessage(String message)."); Element documentElement = getDOMDocument(message).getRootElement(); return isMultipleInvocationMessage(documentElement); } /** * * @param message * the structurally valid BioMoby message as an Element * @return true if the message contains multiple invocations, false * otherwise. * @throws MobyException * if the message is null */ public static boolean isMultipleInvocationMessage(Element message) throws MobyException { if (message == null) throw new MobyException( newline + "null 'xml' found where it was not expected in isMultipleInvocationMessage(Element message)."); Element e = (Element) message.clone(); List list = new ArrayList(); listChildren(e, "mobyData", list); if (list != null) if (list.size() > 1) return true; return false; } /** * * @param element * the element to extract the list of simples from. This method * assumes that you are passing in a single invokation and that * you wish to extract the Simples not contained in any * collections. This method also maintains any past queryIDs. * @return an array of elements that are fully 'wrapped' simples. * @throws MobyException * if the Element isnt structurally valid in terms of Moby * message structure */ public static Element[] getListOfSimples(Element element) throws MobyException { Element temp = (Element) element.clone(); Element e = (Element) element.clone(); String queryID = ""; if (isMultipleInvocationMessage(element)) return new Element[] {}; Element serviceNotes = getServiceNotes(e); // if the current elements name isnt MOBY, see if its direct child is if (!e.getName().equals("MOBY")) { if (e.getChild("MOBY") != null) temp = e.getChild("MOBY"); else if (e.getChild("MOBY", MOBY_NS) != null) temp = e.getChild("MOBY", MOBY_NS); else throw new MobyException(newline + "Expected 'MOBY' as the local name for the element " + newline + "and instead received '" + e.getName() + "' (getListOfSimples(Element element)."); } // parse the mobyContent node if (temp.getChild("mobyContent") != null) temp = temp.getChild("mobyContent"); else if (temp.getChild("mobyContent", MOBY_NS) != null) temp = temp.getChild("mobyContent", MOBY_NS); else throw new MobyException( newline + "Expected 'mobyContent' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getListOfSimples(Element element)."); // parse the mobyData node if (temp.getChild("mobyData") != null) { temp = temp.getChild("mobyData"); } else if (temp.getChild("mobyData", MOBY_NS) != null) { temp = temp.getChild("mobyData", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyData' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getListOfSimples(Element element)."); } // temp == mobyData now we need to get the queryID and save it if (temp.getAttribute("queryID") != null) { queryID = temp.getAttribute("queryID").getValue(); } else if (temp.getAttribute("queryID", MOBY_NS) != null) { queryID = temp.getAttribute("queryID", MOBY_NS).getValue(); } else { // create a new one -> shouldnt happen very often queryID = "a" + queryCount++; } // now we iterate through all of the direct children called Simple, wrap // them individually and set the queryID = queryID List list = temp.getChildren("Simple", MOBY_NS); if (list.isEmpty()) { list = temp.getChildren("Simple"); if (list.isEmpty()) { return new Element[] {}; } } // non empty list Element[] elements = new Element[list.size()]; int index = 0; for (Iterator it = list.iterator(); it.hasNext();) { Element next = (Element) it.next(); elements[index++] = createMobyDataElementWrapper(next, queryID, serviceNotes); } return elements; } /** * * @param message * the String of xml to extract the list of simples from. This * method assumes that you are passing in a single invokation and * that you wish to extract the Simples not contained in any * collections. This method also maintains any past queryIDs. * @return an array of Strings that represent fully 'wrapped' simples. * @throws MobyException * if the String doesnt contain a structurally valid Moby * message structure or if an unexpected error occurs */ public static String[] getListOfSimples(String message) throws MobyException { Element element = getDOMDocument(message).getRootElement(); Element[] elements = getListOfSimples(element); String[] strings = new String[elements.length]; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int count = 0; count < elements.length; count++) { try { strings[count] = outputter.outputString(elements[count]); } catch (Exception e) { throw new MobyException(newline + "Unexpected error occured while creating String[]:" + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param message * the String to extract the list of collections from and assumes * that you are passing in a single invocation message. * @return an array of Strings representing all of the fully 'wrapped' * collections in the message. * @throws MobyException * if the the element contains an invalid BioMOBY message */ public static String[] getListOfCollections(String message) throws MobyException { Element element = getDOMDocument(message).getRootElement(); Element[] elements = getListOfCollections(element); String[] strings = new String[elements.length]; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int count = 0; count < elements.length; count++) { try { strings[count] = outputter.outputString(elements[count]); } catch (Exception e) { throw new MobyException(newline + "Unexpected error occured while creating String[]:" + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param element * the element to extract the list of collections from and * assumes that you are passing in a single invocation message. * @return an array of Elements representing all of the fully 'wrapped' * collections in the message * @throws MobyException * if the element contains an invalid BioMOBY message */ public static Element[] getListOfCollections(Element element) throws MobyException { Element temp = (Element) element.clone(); Element e = (Element) element.clone(); String queryID = ""; if (isMultipleInvocationMessage(e)) return new Element[] {}; Element serviceNotes = getServiceNotes(e); // if the current elements name isnt MOBY, see if its direct child is if (!e.getName().equals("MOBY")) { if (e.getChild("MOBY") != null) temp = e.getChild("MOBY"); else if (e.getChild("MOBY", MOBY_NS) != null) temp = e.getChild("MOBY", MOBY_NS); else throw new MobyException(newline + "Expected 'MOBY' as the local name for the element " + newline + "and instead received '" + e.getName() + "' (getListOfCollections(Element element)."); } // parse the mobyContent node if (temp.getChild("mobyContent") != null) temp = temp.getChild("mobyContent"); else if (temp.getChild("mobyContent", MOBY_NS) != null) temp = temp.getChild("mobyContent", MOBY_NS); else throw new MobyException( newline + "Expected 'mobyContent' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getListOfCollections(Element element)."); // parse the mobyData node if (temp.getChild("mobyData") != null) { temp = temp.getChild("mobyData"); } else if (temp.getChild("mobyData", MOBY_NS) != null) { temp = temp.getChild("mobyData", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyData' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getListOfCollections(Element element)."); } // temp == mobyData now we need to get the queryID and save it if (temp.getAttribute("queryID") != null) { queryID = temp.getAttribute("queryID").getValue(); } else if (temp.getAttribute("queryID", MOBY_NS) != null) { queryID = temp.getAttribute("queryID", MOBY_NS).getValue(); } else { // create a new one -> shouldnt happen very often queryID = "a" + queryCount++; } // now we iterate through all of the direct children called Simple, wrap // them individually and set the queryID = queryID List list = temp.getChildren("Collection", MOBY_NS); if (list.isEmpty()) { list = temp.getChildren("Collection"); if (list.isEmpty()) { return new Element[] {}; } } // non empty list Element[] elements = new Element[list.size()]; int index = 0; for (Iterator it = list.iterator(); it.hasNext();) { Element next = (Element) it.next(); elements[index++] = createMobyDataElementWrapper(next, queryID, serviceNotes); } return elements; } /** * This method assumes a single invocation was passed to it * <p> * * @param name * the article name of the simple that you are looking for * @param xml * the xml that you want to query * @return a String object that represent the simple found. * @throws MobyException * if no simple was found given the article name and/or data * type or if the xml was not valid moby xml or if an unexpected * error occurs. */ public static String getSimple(String name, String xml) throws MobyException { Element element = getDOMDocument(xml).getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); Element simples = getSimple(name, element); if (simples != null) { try { return outputter.outputString(simples); } catch (Exception e) { throw new MobyException(newline + "Unexpected error occured while creating String[]:" + newline + Utils.format(e.getLocalizedMessage(), 3)); } } throw new MobyException(newline + "The simple named '" + name + "' was not found in the xml:" + newline + xml + newline); } /** * This method assumes a single invocation was passed to it * <p> * * @param name * the article name of the simple that you are looking for * @param element * the Element that you want to query * @return an Element that represents the simple found. * @throws MobyException * if no simple was found given the article name and/or data * type or if the xml was not valid moby xml or if an unexpected * error occurs. */ public static Element getSimple(String name, Element element) throws MobyException { Element el = (Element) element.clone(); Element[] elements = getListOfSimples(el); // try matching based on type(less impt) and/or article name (more impt) for (int i = 0; i < elements.length; i++) { // PRE: elements[i] is a fully wrapped element Element e = elements[i]; if (e.getChild("mobyContent") != null) { e = e.getChild("mobyContent"); } else if (e.getChild("mobyContent", MOBY_NS) != null) { e = e.getChild("mobyContent", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyContent' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getSimple(String name, " + "Element element)."); } if (e.getChild("mobyData") != null) { e = e.getChild("mobyData"); } else if (e.getChild("mobyData", MOBY_NS) != null) { e = e.getChild("mobyData", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyData' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getSimple(String name," + " Element element)."); } if (e.getChild("Simple") != null) { e = e.getChild("Simple"); } else if (e.getChild("Simple", MOBY_NS) != null) { e = e.getChild("Simple", MOBY_NS); } else { throw new MobyException( newline + "Expected 'Simple' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getSimple(String name," + " Element element)."); } // e == Simple -> check its name as long as name != "" if (!name.equals("")) if (e.getAttributeValue("articleName") != null) { String value = e.getAttributeValue("articleName"); if (value.equals(name)) { return e; } } else if (e.getAttributeValue("articleName", MOBY_NS) != null) { String value = e.getAttributeValue("articleName", MOBY_NS); if (value.equals(name)) { return e; } } } throw new MobyException(newline + "The simple named '" + name + "' was not found in the xml:" + newline + (new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false))).outputString(element) + newline); } /** * * @param xml * a string of xml containing a single invocation message to * extract the queryID from * @return the queryID contained in the xml or a generated one if one doesnt * exist * @throws MobyException * if the String of xml is invalid or if the message is a * multiple invocation message */ public static String getQueryID(String xml) throws MobyException { return getQueryID(getDOMDocument(xml).getRootElement()); } /** * * @param xml * a single invocation message to extract the queryID from * @return the queryID contained in the xml or a generated one if one doesnt * exist * @throws if * the message is a multiple invocation message */ public static String getQueryID(Element xml) throws MobyException { Element temp = (Element) xml.clone(); Element e = (Element) xml.clone(); if (isMultipleInvocationMessage(e)) throw new MobyException( "Unable to retrieve the queryID from the BioMOBY message because a message with greater than one IDs exists."); if (!e.getName().equals("MOBY")) { if (e.getChild("MOBY") != null) temp = e.getChild("MOBY"); else if (e.getChild("MOBY", MOBY_NS) != null) temp = e.getChild("MOBY", MOBY_NS); } // parse the mobyContent node if (temp.getChild("mobyContent") != null) temp = temp.getChild("mobyContent"); else if (temp.getChild("mobyContent", MOBY_NS) != null) temp = temp.getChild("mobyContent", MOBY_NS); // parse the mobyData node if (temp.getChild("mobyData") != null) { temp = temp.getChild("mobyData"); } else if (temp.getChild("mobyData", MOBY_NS) != null) { temp = temp.getChild("mobyData", MOBY_NS); } // temp == mobyData now we need to get the queryID and save it if (temp.getAttribute("queryID") != null) { return temp.getAttribute("queryID").getValue(); } else if (temp.getAttribute("queryID", MOBY_NS) != null) { return temp.getAttribute("queryID", MOBY_NS).getValue(); } else { // create a new one -> shouldnt happen very often return "a" + queryCount++; } } /** * * @param xml * a string of xml containing a single invocation message to * extract the queryID from * @return the element passed in to the method with the queryID set if the * message was valid. * @throws MobyException * if the String of xml is syntatically invalid or if the * message is a multiple invocation message */ public static String setQueryID(String xml, String id) throws MobyException { return new XMLOutputter(Format.getPrettyFormat().setOmitDeclaration( false)).outputString(setQueryID(getDOMDocument(xml) .getRootElement(), id)); } /** * * @param xml * a single invocation message to extract the queryID from * @return the element passed in to the method with the queryID set if the * message was valid. * @throws MobyException * if the message is a multiple invocation message */ public static Element setQueryID(Element xml, String id) throws MobyException { Element e = (Element) xml.clone(); Element temp = e; if (isMultipleInvocationMessage(e)) throw new MobyException( "Unable to set the queryID, because there are more than one queryID to set!"); if (!e.getName().equals("MOBY")) { if (e.getChild("MOBY") != null) temp = e.getChild("MOBY"); else if (e.getChild("MOBY", MOBY_NS) != null) temp = e.getChild("MOBY", MOBY_NS); } // parse the mobyContent node if (temp.getChild("mobyContent") != null) temp = temp.getChild("mobyContent"); else if (temp.getChild("mobyContent", MOBY_NS) != null) temp = temp.getChild("mobyContent", MOBY_NS); // parse the mobyData node if (temp.getChild("mobyData") != null) { temp = temp.getChild("mobyData"); } else if (temp.getChild("mobyData", MOBY_NS) != null) { temp = temp.getChild("mobyData", MOBY_NS); } temp.removeAttribute("queryID"); temp.removeAttribute("queryID", MOBY_NS); temp.setAttribute("queryID", (id == null || id == "" ? "a" + queryCount++ : id), MOBY_NS); return e; } /** * * @param name * the articlename of the simple that you wish to extract * @param xml * the xml message * @return the wrapped simple if it exists * @throws MobyException * if the message is a multiple invocation message or if the xml * is syntatically invalid. */ public static String getWrappedSimple(String name, String xml) throws MobyException { Element element = getWrappedSimple(name, getDOMDocument(xml) .getRootElement()); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return outputter.outputString(element); } /** * * @param name * the articlename of the simple that you wish to extract * @param xml * the xml message * @return the wrapped simple if it exists * @throws MobyException * if the message is a multiple invocation message. */ public static Element getWrappedSimple(String name, Element element) throws MobyException { Element e = (Element) element.clone(); String queryID = getQueryID(e); Element serviceNotes = getServiceNotes(e); Element simple = getSimple(name, e); return createMobyDataElementWrapper(simple, queryID, serviceNotes); } /** * * @param name * the name of the collection to extract * @param element * the element to extract the collection from * @return the collection if found * @throws MobyException * if the message is invalid */ public static Element getCollection(String name, Element element) throws MobyException { Element el = (Element) element.clone(); Element[] elements = getListOfCollections(el); for (int i = 0; i < elements.length; i++) { // PRE: elements[i] is a fully wrapped element Element e = elements[i]; if (e.getChild("mobyContent") != null) { e = e.getChild("mobyContent"); } else if (e.getChild("mobyContent", MOBY_NS) != null) { e = e.getChild("mobyContent", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyContent' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getCollection(String name, " + "Element element)."); } if (e.getChild("mobyData") != null) { e = e.getChild("mobyData"); } else if (e.getChild("mobyData", MOBY_NS) != null) { e = e.getChild("mobyData", MOBY_NS); } else { throw new MobyException( newline + "Expected 'mobyData' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getCollection(String name," + " Element element)."); } if (e.getChild("Collection") != null) { e = e.getChild("Collection"); } else if (e.getChild("Collection", MOBY_NS) != null) { e = e.getChild("Collection", MOBY_NS); } else { // TODO should i throw exception or continue? throw new MobyException( newline + "Expected 'Collection' as the local name for the next child element but it " + newline + "wasn't there. I even tried a qualified name (getCollection(String name," + " Element element)."); } // e == collection -> check its name if (e.getAttributeValue("articleName") != null) { String value = e.getAttributeValue("articleName"); if (value.equals(name)) { return e; } } else if (e.getAttributeValue("articleName", MOBY_NS) != null) { String value = e.getAttributeValue("articleName", MOBY_NS); if (value.equals(name)) { return e; } } if (elements.length == 1) { if (e.getAttributeValue("articleName") != null) { String value = e.getAttributeValue("articleName"); if (value.equals("")) { // rename it to make it compatible with moby e.setAttribute("articleName", name, MOBY_NS); return e; } } else if (e.getAttributeValue("articleName", MOBY_NS) != null) { String value = e.getAttributeValue("articleName", MOBY_NS); if (value.equals("")) { // rename it to make it compatible with moby e.setAttribute("articleName", name, MOBY_NS); return e; } } } // name didnt match, so too bad ;-) } throw new MobyException( newline + "The Collection named '" + name + "' was not found in the xml:" + newline + (new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false))) .outputString(element) + newline + "Note: A collection of that may exist, but may be contained in a multiple invocation message."); } /** * * @param name * @param xml * @return * @throws MobyException */ public static String getCollection(String name, String xml) throws MobyException { Element element = getDOMDocument(xml).getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); Element collection = getCollection(name, element); if (collection != null) return outputter.outputString(collection); return null; } /** * * @param name * @param element * @return * @throws MobyException */ public static Element getWrappedCollection(String name, Element element) throws MobyException { Element e = (Element) element.clone(); String queryID = getQueryID(e); Element collection = getCollection(name, e); Element serviceNotes = getServiceNotes(e); return createMobyDataElementWrapper(collection, queryID, serviceNotes); } /** * * @param name * @param xml * @return * @throws MobyException */ public static String getWrappedCollection(String name, String xml) throws MobyException { Element element = getWrappedCollection(name, getDOMDocument(xml) .getRootElement()); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return outputter.outputString(element); } /** * * @param name * the name of the collection to extract the simples from. * @param xml * the XML to extract from * @return an array of String objects that represent the simples * @throws MobyException */ public static String[] getSimplesFromCollection(String name, String xml) throws MobyException { Element[] elements = getSimplesFromCollection(name, getDOMDocument(xml) .getRootElement()); String[] strings = new String[elements.length]; XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int i = 0; i < elements.length; i++) { try { strings[i] = output.outputString(elements[i]); } catch (Exception e) { throw new MobyException(newline + "Unknown error occured while creating String[]." + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param name * the name of the collection to extract the simples from. * @param element * the Element to extract from * @return an array of Elements objects that represent the simples * @throws MobyException */ public static Element[] getSimplesFromCollection(String name, Element element) throws MobyException { Element e = (Element) element.clone(); // exception thrown if not found Element collection = getCollection(name, e); List list = collection.getChildren("Simple"); if (list.isEmpty()) list = collection.getChildren("Simple", MOBY_NS); if (list.isEmpty()) return new Element[] {}; Vector vector = new Vector(); for (Iterator it = list.iterator(); it.hasNext();) { Object o = it.next(); if (o instanceof Element) { ((Element) o).setAttribute("articleName", name, MOBY_NS); if (((Element) o).getChildren().size() > 0) vector.add(o); } } Element[] elements = new Element[vector.size()]; vector.copyInto(elements); return elements; } /** * * @param name * the name of the simples that you would like to extract. The * name can be collection name as well. This method extracts * simples from all invocation messages. * @param xml * the xml to extract the simples from * @return a String[] of Simples that you are looking for, taken from * collections with your search name as well as simple elements with * the search name * @throws MobyException * if there is a problem with the BioMOBY message */ public static String[] getAllSimplesByArticleName(String name, String xml) throws MobyException { Element[] elements = getAllSimplesByArticleName(name, getDOMDocument( xml).getRootElement()); String[] strings = new String[elements.length]; XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int i = 0; i < elements.length; i++) { try { strings[i] = output.outputString(elements[i]); } catch (Exception e) { throw new MobyException(newline + "Unknown error occured while creating String[]." + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param name * the name of the simples that you would like to extract. The * name can be collection name as well. This method extracts * simples from all invocation messages. * @param element * the xml to extract the simples from * @return a String[] of Simples that you are looking for, taken from * collections with your search name as well as simple elements with * the search name * @throws MobyException * if there is a problem with the BioMOBY message */ public static Element[] getAllSimplesByArticleName(String name, Element element) throws MobyException { Element e = (Element) element.clone(); Element[] invocations = getSingleInvokationsFromMultipleInvokations(e); Vector vector = new Vector(); for (int i = 0; i < invocations.length; i++) { Element collection = null; try { collection = getCollection(name, invocations[i]); } catch (MobyException me) { } if (collection != null) { List list = collection.getChildren("Simple"); if (list.isEmpty()) list = collection.getChildren("Simple", MOBY_NS); if (list.isEmpty()) return new Element[] {}; for (Iterator it = list.iterator(); it.hasNext();) { Object o = it.next(); if (o instanceof Element) { ((Element) o) .setAttribute("articleName", name, MOBY_NS); } vector.add(o); } } collection = null; Element[] potentialSimples = getListOfSimples(invocations[i]); for (int j = 0; j < potentialSimples.length; j++) { Element mobyData = extractMobyData(potentialSimples[j]); Element simple = mobyData.getChild("Simple"); if (simple == null) simple = mobyData.getChild("Simple", MOBY_NS); if (simple != null) { if (simple.getAttribute("articleName") != null) { if (simple.getAttribute("articleName").getValue() .equals(name)) vector.add(simple); } else if (simple.getAttribute("articleName", MOBY_NS) != null) { if (simple.getAttribute("articleName", MOBY_NS) .getValue().equals(name)) vector.add(simple); } } } } Element[] elements = new Element[vector.size()]; vector.copyInto(elements); return elements; } /** * * @param xml * the XML to extract from * @return an array of String objects that represent the simples * @throws MobyException */ public static String[] getSimplesFromCollection(String xml) throws MobyException { Element[] elements = getSimplesFromCollection(getDOMDocument(xml) .getRootElement()); String[] strings = new String[elements.length]; XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int i = 0; i < elements.length; i++) { try { strings[i] = output.outputString(elements[i]); } catch (Exception e) { throw new MobyException(newline + "Unknown error occured while creating String[]." + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param name * the name of the collection to extract the simples from. * @param element * the Element to extract from * @return an array of Elements objects that represent the 'unwrapped' * simples * @throws MobyException */ public static Element[] getSimplesFromCollection(Element element) throws MobyException { Element e = (Element) element.clone(); Element mobyData = extractMobyData(e); Element collection = mobyData.getChild("Collection"); if (collection == null) collection = mobyData.getChild("Collection", MOBY_NS); List list = collection.getChildren("Simple"); if (list.isEmpty()) list = collection.getChildren("Simple", MOBY_NS); if (list.isEmpty()) return new Element[] {}; Vector vector = new Vector(); for (Iterator it = list.iterator(); it.hasNext();) { vector.add(it.next()); } Element[] elements = new Element[vector.size()]; vector.copyInto(elements); return elements; } /** * * @param name * the name of the collection to extract the simples from. * @param xml * the XML to extract from * @return an array of String objects that represent the simples, with the * name of the collection * @throws MobyException * if the collection doesnt exist or the xml is invalid */ public static String[] getWrappedSimplesFromCollection(String name, String xml) throws MobyException { Element[] elements = getWrappedSimplesFromCollection(name, getDOMDocument(xml).getRootElement()); String[] strings = new String[elements.length]; XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int i = 0; i < elements.length; i++) { try { strings[i] = output.outputString(elements[i]); } catch (Exception e) { throw new MobyException(newline + "Unknown error occured while creating String[]." + newline + Utils.format(e.getLocalizedMessage(), 3)); } } return strings; } /** * * @param name * the name of the collection to extract the simples from. * @param element * the Element to extract from * @return an array of Elements objects that represent the simples, with the * name of the collection * @throws MobyException * MobyException if the collection doesnt exist or the xml is * invalid */ public static Element[] getWrappedSimplesFromCollection(String name, Element element) throws MobyException { Element el = (Element) element.clone(); String queryID = getQueryID(el); Element collection = getCollection(name, el); Element serviceNotes = getServiceNotes(el); List list = collection.getChildren("Simple"); if (list.isEmpty()) list = collection.getChildren("Simple", MOBY_NS); if (list.isEmpty()) return new Element[] {}; Vector vector = new Vector(); for (Iterator it = list.iterator(); it.hasNext();) { Element e = (Element) it.next(); e.setAttribute("articleName", name, MOBY_NS); e = createMobyDataElementWrapper(e, queryID + "_split" + queryCount++, serviceNotes); vector.add(e); } Element[] elements = new Element[vector.size()]; vector.copyInto(elements); return elements; } /** * * @param xml * the message to extract the invocation messages from * @return an array of String objects each representing a distinct BioMOBY * invocation message. * @throws MobyException * if the moby message is invalid or if the xml is syntatically * invalid. */ public static String[] getSingleInvokationsFromMultipleInvokations( String xml) throws MobyException { Element[] elements = getSingleInvokationsFromMultipleInvokations(getDOMDocument( xml).getRootElement()); String[] strings = new String[elements.length]; XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); for (int i = 0; i < elements.length; i++) { strings[i] = output.outputString(new Document(elements[i])); } return strings; } /** * * @param element * the message to extract the invocation messages from * @return an array of Element objects each representing a distinct * invocation message. * @throws MobyException * if the moby message is invalid. */ public static Element[] getSingleInvokationsFromMultipleInvokations( Element element) throws MobyException { Element e = (Element) element.clone(); Element serviceNotes = getServiceNotes(e); if (e.getChild("MOBY") != null) { e = e.getChild("MOBY"); } else if (e.getChild("MOBY", MOBY_NS) != null) { e = e.getChild("MOBY", MOBY_NS); } if (e.getChild("mobyContent") != null) { e = e.getChild("mobyContent"); } else if (e.getChild("mobyContent", MOBY_NS) != null) { e = e.getChild("mobyContent", MOBY_NS); } else { throw new MobyException( newline + "Expected a child element called 'mobyContent' and did not receive it in:" + newline + new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)).outputString(e)); } List invocations = e.getChildren("mobyData"); if (invocations.isEmpty()) invocations = e.getChildren("mobyData", MOBY_NS); Element[] elements = new Element[] {}; ArrayList theData = new ArrayList(); for (Iterator it = invocations.iterator(); it.hasNext();) { Element MOBY = new Element("MOBY", MOBY_NS); Element mobyContent = new Element("mobyContent", MOBY_NS); if (serviceNotes != null) mobyContent.addContent(serviceNotes.detach()); Element mobyData = new Element("mobyData", MOBY_NS); Element next = (Element) it.next(); String queryID = next.getAttributeValue("queryID", MOBY_NS); if (queryID == null) queryID = next.getAttributeValue("queryID"); mobyData.setAttribute("queryID", (queryID == null ? "a"+queryCount++ : queryID), MOBY_NS); mobyData.addContent(next.cloneContent()); MOBY.addContent(mobyContent); mobyContent.addContent(mobyData); if (next.getChildren().size() > 0) theData.add(MOBY); } elements = new Element[theData.size()]; elements = (Element[]) theData.toArray(elements); return elements; } /** * * @param document * the string to create a DOM document from * @return a Document object that represents the string of XML. * @throws MobyException * if the xml is invalid syntatically. */ public static Document getDOMDocument(String document) throws MobyException { if (document == null) throw new MobyException(newline + "null found where an XML document was expected."); SAXBuilder builder = new SAXBuilder(); // Create the document Document doc = null; try { doc = builder.build(new StringReader(document)); } catch (JDOMException e) { throw new MobyException(newline + "Error parsing XML:->" + newline + document + newline + Utils.format(e.getLocalizedMessage(), 3) + "."); } catch (IOException e) { throw new MobyException(newline + "Error parsing XML:->" + newline + Utils.format(e.getLocalizedMessage(), 3) + "."); } catch (Exception e) { throw new MobyException(newline + "Error parsing XML:->" + newline + Utils.format(e.getLocalizedMessage(), 3) + "."); } return doc; } /** * * @param elements * the fully wrapped moby simples and/or collections to wrap an * input message around * @param queryID * the queryID for this input * @return a fully wrapped message with an appropriate queryID and elements * added to it * @throws MobyException * if an element is invalid or if the XML is syntatically * invalid. */ public static String createServiceInput(String[] elements, String queryID) throws MobyException { Element[] element = new Element[elements.length]; for (int i = 0; i < elements.length; i++) { element[i] = getDOMDocument(elements[i]).getRootElement(); } XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return output.outputString(createServiceInput(element, queryID)); } /** * * @param elements * the fully wrapped moby simples and/or collections to wrap an * input message around * @param queryID * the queryID for this input * @return a fully wrapped message with an appropriate queryID and elements * added to it * @throws MobyException * if an element is invalid. */ public static Element createServiceInput(Element[] elements, String queryID) throws MobyException { // create the main elements Element MOBY = new Element("MOBY", MOBY_NS); Element mobyContent = new Element("mobyContent", MOBY_NS); Element mobyData = new Element("mobyData", MOBY_NS); mobyData.setAttribute("queryID", (queryID == null ? "" : queryID), MOBY_NS); // add the content MOBY.addContent(mobyContent); mobyContent.addContent(mobyData); // iterate through elements adding the content of mobyData for (int i = 0; i < elements.length; i++) { Element e = (Element) elements[i].clone(); e = extractMobyData(e); mobyData.addContent(e.cloneContent()); } return MOBY; } /** * @param element * the element that contains the moby message that you would like * to extract the mobyData block from (assumes single invocation, * but returns the first mobyData block in a multiple invocation * message). * @return the mobyData element block. * @throws MobyException * if the moby message is invalid */ public static Element extractMobyData(Element element) throws MobyException { Element e = (Element) element.clone(); if (e.getChild("MOBY") != null) { e = e.getChild("MOBY"); } else if (e.getChild("MOBY", MOBY_NS) != null) { e = e.getChild("MOBY", MOBY_NS); } if (e.getChild("mobyContent") != null) { e = e.getChild("mobyContent"); } else if (e.getChild("mobyContent", MOBY_NS) != null) { e = e.getChild("mobyContent", MOBY_NS); } else { throw new MobyException( newline + "Expected the child element 'mobyContent' and did not receive it in:" + newline + new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)).outputString(e)); } if (e.getChild("mobyData") != null) { e = e.getChild("mobyData"); } else if (e.getChild("mobyData", MOBY_NS) != null) { e = e.getChild("mobyData", MOBY_NS); } else { throw new MobyException( newline + "Expected the child element 'mobyData' and did not receive it in:" + newline + new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)).outputString(e)); } return e; } /** * * @param newName * the new name for this fully wrapped BioMOBY collection * @param element * the fully wrapped BioMOBY collection * @return @return an element 'Collection' representing the renamed collection * @throws MobyException * if the message is invalid */ public static Element renameCollection(String newName, Element element) throws MobyException { Element e = (Element) element.clone(); Element mobyData = extractMobyData(e); Element coll = mobyData.getChild("Collection"); if (coll == null) coll = mobyData.getChild("Collection", MOBY_NS); if (coll == null) return e; coll.removeAttribute("articleName"); coll.removeAttribute("articleName", MOBY_NS); coll.setAttribute("articleName", newName, MOBY_NS); return coll; } /** * * @param newName * the new name for this fully wrapped BioMOBY collection * @param xml * the fully wrapped BioMOBY collection * @return an element 'Collection' representing the renamed collection * @throws MobyException * if the BioMOBY message is invalid or the xml is syntatically * invalid. */ public static String renameCollection(String newName, String xml) throws MobyException { return new XMLOutputter(Format.getPrettyFormat().setOmitDeclaration( false)).outputString(renameCollection(newName, getDOMDocument( xml).getRootElement())); } /** * * @param oldName * @param newName * @param type * @param xml * @return * @throws MobyException */ public static String renameSimple(String newName, String type, String xml) throws MobyException { return new XMLOutputter(Format.getPrettyFormat().setOmitDeclaration( false)).outputString(renameSimple(newName, type, getDOMDocument(xml).getRootElement())); } /** * * @param oldName * @param newName * @param type * @param element * @return * @throws MobyException */ public static Element renameSimple(String newName, String type, Element element) throws MobyException { Element e = (Element) element.clone(); Element mobyData = extractMobyData(e); String queryID = getQueryID(e); Element serviceNotes = getServiceNotes(e); Element simple = mobyData.getChild("Simple"); if (simple == null) simple = mobyData.getChild("Simple", MOBY_NS); if (simple == null) { return e; } simple.removeAttribute("articleName"); simple.removeAttribute("articleName", MOBY_NS); simple.setAttribute("articleName", newName, MOBY_NS); return createMobyDataElementWrapper(simple, queryID, serviceNotes); } /** * * @return * @throws MobyException */ public static Document createDomDocument() throws MobyException { Document d = new Document(); d.setBaseURI(MOBY_NS.getURI()); return d; } /** * * @param element * @param queryID * @param serviceNotes * @return * @throws MobyException */ public static Element createMobyDataElementWrapper(Element element, String queryID, Element serviceNotes) throws MobyException { Element e = (Element) element.clone(); Element MOBY = new Element("MOBY", MOBY_NS); Element mobyContent = new Element("mobyContent", MOBY_NS); Element mobyData = new Element("mobyData", MOBY_NS); mobyData.setAttribute("queryID", queryID, MOBY_NS); MOBY.addContent(mobyContent); mobyContent.addContent(mobyData); // add the serviceNotes if they exist if (serviceNotes != null) mobyContent.addContent(serviceNotes.detach()); if (e != null) { if (e.getName().equals("Simple")) { Element simple = new Element("Simple", MOBY_NS); simple.setAttribute("articleName", (e .getAttributeValue("articleName") == null ? e .getAttributeValue("articleName", MOBY_NS, "") : e .getAttributeValue("articleName", "")), MOBY_NS); simple.addContent(e.cloneContent()); if (simple.getChildren().size() > 0) mobyData.addContent(simple.detach()); } else if (e.getName().equals("Collection")) { Element collection = new Element("Collection", MOBY_NS); collection.setAttribute("articleName", (e .getAttributeValue("articleName") == null ? e .getAttributeValue("articleName", MOBY_NS, "") : e .getAttributeValue("articleName", "")), MOBY_NS); collection.addContent(e.cloneContent()); if (collection.getChildren().size() > 0) mobyData.addContent(collection.detach()); } } return MOBY; } public static Element createMobyDataWrapper(String queryID, Element serviceNotes) throws MobyException { Element e = null; if (serviceNotes != null) e = (Element) serviceNotes.clone(); Element MOBY = new Element("MOBY", MOBY_NS); Element mobyContent = new Element("mobyContent", MOBY_NS); if (e != null) mobyContent.addContent(e.detach()); Element mobyData = new Element("mobyData", MOBY_NS); mobyData.setAttribute("queryID", queryID, MOBY_NS); MOBY.addContent(mobyContent); mobyContent.addContent(mobyData); return MOBY; } /** * * @param xml * @return * @throws MobyException */ public static String createMobyDataElementWrapper(String xml) throws MobyException { return createMobyDataElementWrapper(xml, "a" + queryCount++); } /** * * @param element * @return * @throws MobyException */ public static Element createMobyDataElementWrapper(Element element) throws MobyException { Element serviceNotes = getServiceNotes((Element) element.clone()); return createMobyDataElementWrapper(element, "a" + queryCount++, serviceNotes); } /** * * @param xml * @param queryID * @return * @throws MobyException */ public static String createMobyDataElementWrapper(String xml, String queryID) throws MobyException { if (xml == null) return null; Element serviceNotes = getServiceNotes(getDOMDocument(xml) .getRootElement()); Element element = createMobyDataElementWrapper(getDOMDocument(xml) .getRootElement(), queryID, serviceNotes); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return (element == null ? null : outputter.outputString(element)); } public static String createMobyDataElementWrapper(String xml, String queryID, Element serviceNotes) throws MobyException { if (xml == null) return null; Element element = createMobyDataElementWrapper(getDOMDocument(xml) .getRootElement(), queryID, serviceNotes); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return (element == null ? null : outputter.outputString(element)); } /** * * @param elements * @return * @throws MobyException */ public static Element createMultipleInvokations(Element[] elements) throws MobyException { Element MOBY = new Element("MOBY", MOBY_NS); Element mobyContent = new Element("mobyContent", MOBY_NS); Element serviceNotes = null; for (int i = 0; i < elements.length; i++) { if (serviceNotes == null) { serviceNotes = getServiceNotes((Element) elements[i].clone()); if (serviceNotes != null) mobyContent.addContent(serviceNotes.detach()); } Element mobyData = new Element("mobyData", MOBY_NS); Element md = extractMobyData((Element) elements[i].clone()); String queryID = getQueryID((Element) elements[i].clone()); mobyData.setAttribute("queryID", queryID, MOBY_NS); mobyData.addContent(md.cloneContent()); mobyContent.addContent(mobyData); } MOBY.addContent(mobyContent); return MOBY; } /** * * @param xmls * @return * @throws MobyException */ public static String createMultipleInvokations(String[] xmls) throws MobyException { Element[] elements = new Element[xmls.length]; for (int i = 0; i < elements.length; i++) { elements[i] = getDOMDocument(xmls[i]).getRootElement(); } XMLOutputter output = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return output.outputString(createMultipleInvokations(elements)); } /** * * @param xml * a string of xml * @return true if the xml contains a full moby message (assumes single * invocation, but will return the first mobyData block from a * multiple invocation message). */ public static boolean isWrapped(Element element) { try { extractMobyData((Element) element.clone()); return true; } catch (MobyException e) { return false; } } /** * * @param xml * a string of xml * @return true if the xml contains a full moby message (assumes single * invocation, but will return the first mobyData block from a * multiple invocation message). * @throws MobyException * if the xml is syntatically invalid */ public static boolean isWrapped(String xml) throws MobyException { Element element = getDOMDocument(xml).getRootElement(); return isWrapped(element); } /** * * @param element * an Element containing a single invocation * @return true if the element contains a moby collection, false otherwise. * @throws MobyException * if xml is invalid */ public static boolean isCollection(Element element) throws MobyException { try { return getListOfCollections((Element) element.clone()).length > 0; } catch (MobyException e) { return false; } } /** * * @param xml * a string of xml containing a single invocation * @return true if the xml contains a moby collection, false otherwise. * @throws MobyException * if xml is invalid */ public static boolean isCollection(String xml) throws MobyException { Element element = getDOMDocument(xml).getRootElement(); return isCollection(element); } /** * * @param xml * a string of xml to check for emptiness * @return true if the element is empty, false otherwise. */ public static boolean isEmpty(String xml) { try { return isEmpty(getDOMDocument(xml).getRootElement()); } catch (MobyException e) { return true; } } /** * * @param xml * an element to check for emptiness * @return true if the element is empty, false otherwise. */ public static boolean isEmpty(Element xml) { try { Element e = extractMobyData((Element) xml.clone()); if (e.getChild("Collection") != null) return false; if (e.getChild("Collection", MOBY_NS) != null) return false; if (e.getChild("Simple") != null) return false; if (e.getChild("Simple", MOBY_NS) != null) return false; } catch (MobyException e) { } return true; } /** * * @param theList * a list of Elements that represent collections (wrapped in a * MobyData tag * @param name * the name to set for the collection * @return a list containing a single wrapped collection Element that contains all * of the simples in the collections in theList * @throws MobyException * */ public static List mergeCollections(List theList, String name) throws MobyException { if (theList == null) return new ArrayList(); Element mainCollection = new Element("Collection", MOBY_NS); mainCollection.setAttribute("articleName", name, MOBY_NS); String queryID = ""; for (Iterator iter = theList.iterator(); iter.hasNext();) { Element mobyData = (Element) iter.next(); queryID = getQueryID(mobyData); Element collection = mobyData.getChild("Collection"); if (collection == null) collection = mobyData.getChild("Collection", MOBY_NS); if (collection == null) continue; mainCollection.addContent(collection.cloneContent()); } theList = new ArrayList(); theList .add((createMobyDataElementWrapper(mainCollection, queryID, null))); return theList; } /** * * @param element * a full moby message (root element called MOBY) and may be * prefixed * @return the serviceNotes element if it exists, null otherwise. */ public static Element getServiceNotes(Element element) { Element serviceNotes = null; Element e = (Element) element.clone(); Element mobyContent = e.getChild("mobyContent"); if (mobyContent == null) mobyContent = e.getChild("mobyContent", MOBY_NS); // should throw exception? if (mobyContent == null) return serviceNotes; serviceNotes = mobyContent.getChild("serviceNotes"); if (serviceNotes == null) serviceNotes = mobyContent.getChild("serviceNotes", MOBY_NS); // note: servicenotes may be null return serviceNotes; } /** * * @param xml * a full moby message (root element called MOBY) and may be * prefixed * @return the serviceNotes element as a string if it exists, null * otherwise. */ public static String getServiceNotes(String xml) { try { Element e = getServiceNotes(getDOMDocument(xml).getRootElement()); if (e == null) return null; XMLOutputter out = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return out.outputString(e); } catch (MobyException ex) { return null; } } /** * * @param xml * a full moby message (root element called MOBY) and may be * prefixed * @return the serviceNotes element if it exists, null otherwise. */ public static Element getServiceNotesAsElement(String xml) { try { Element e = getServiceNotes(getDOMDocument(xml).getRootElement()); return e; } catch (MobyException ex) { return null; } } /** * * @param element * the xml element * @param articleName * the name of the child to extract * @return an element that represents the direct child or null if it wasnt * found. */ public static Element getDirectChildByArticleName(Element element, String articleName) { Element e = (Element) element.clone(); List list = e.getChildren(); for (Iterator iter = list.iterator(); iter.hasNext();) { Object object = iter.next(); if (object instanceof Element) { Element child = (Element) object; if (child.getAttributeValue("articleName") != null) { if (child.getAttributeValue("articleName").equals( articleName)) return child; } else if (child.getAttributeValue("articleName", MOBY_NS) != null) { if (child.getAttributeValue("articleName", MOBY_NS).equals( articleName)) { return child; } } } } return null; } /** * * @param xml * the string of xml * @param articleName * the name of the child to extract * @return an xml string that represents the direct child or null if it * wasnt found. */ public static String getDirectChildByArticleName(String xml, String articleName) { try { Element e = getDirectChildByArticleName(getDOMDocument(xml) .getRootElement(), articleName); if (e == null) return null; XMLOutputter out = new XMLOutputter(Format.getPrettyFormat() .setOmitDeclaration(false)); return out.outputString(e); } catch (MobyException me) { return null; } } /** * * @param xml * the xml message to test whether or not there is stuff in the * mobyData portion of a message. * @return true if there is data, false otherwise. */ public static boolean isThereData(Element xml) { Element e = null; e = (Element) xml.clone(); try { e = extractMobyData(e); if (e.getChildren().size() > 0) { // make sure we dont have empty collections or simples if (e.getChild("Collection") != null) { return e.getChild("Collection").getChildren().size() > 0; } if (e.getChild("Collection", MOBY_NS) != null) { return e.getChild("Collection", MOBY_NS).getChildren() .size() > 0; } if (e.getChild("Simple") != null) { return e.getChild("Simple").getChildren().size() > 0; } if (e.getChild("Simple", MOBY_NS) != null) { return e.getChild("Simple", MOBY_NS).getChildren().size() > 0; } return false; } } catch (MobyException e1) { return false; } return false; } /** * * @param xml * the xml message to test whether or not there is stuff in the * mobyData portion of a message. * @return true if there is data, false otherwise. */ public static boolean isThereData(String xml) { try { return isThereData(getDOMDocument(xml).getRootElement()); } catch (Exception e) { return false; } } public static void main(String[] args) throws MobyException { String msg = "<moby:MOBY xmlns:moby=\"http: + " <moby:mobyContent>\r\n" + " <moby:mobyData moby:queryID=\"a2_+_s65_+_s165_+_s1290_a2_+_s65_+_s165_+_s1290_+_s1408_a0_+_s3_+_s1409\">\r\n" + " <moby:Collection moby:articleName=\"alleles\">\r\n" + " <moby:Simple>\r\n" + " <Object xmlns=\"http: + " </moby:Simple>\r\n" + " <moby:Simple>\r\n" + " <Object xmlns=\"http: + " </moby:Simple>\r\n" + " <moby:Simple>\r\n" + " <Object xmlns=\"http: + " </moby:Simple>\r\n" + " <moby:Simple>\r\n" + " <Object xmlns=\"http: + " </moby:Simple>\r\n" + " <moby:Simple>\r\n" + " <Object xmlns=\"http: + " </moby:Simple>\r\n" + " </moby:Collection>\r\n" + " </moby:mobyData>\r\n" + " </moby:mobyContent>\r\n" + "</moby:MOBY>"; Element inputElement = getDOMDocument(msg).getRootElement(); String queryID = XMLUtilities.getQueryID(inputElement); Element[] simples = XMLUtilities.getSimplesFromCollection(inputElement); ArrayList list = new ArrayList(); for (int j = 0; j < simples.length; j++) { Element wrappedSimple = XMLUtilities .createMobyDataElementWrapper(simples[j]); wrappedSimple = XMLUtilities.renameSimple("Allele", "Object", wrappedSimple); wrappedSimple = XMLUtilities.setQueryID(wrappedSimple, queryID + "_+_" + XMLUtilities.getQueryID(wrappedSimple)); list.add(XMLUtilities.extractMobyData(wrappedSimple)); } } /* * * @param current the Element that you would like to search @param name the * name of the element that you would like to find @param list the list to * put the elements that are found in @return a list containing the elements * that are named name */ private static List listChildren(Element current, String name, List list) { if (list == null) list = new ArrayList(); if (current.getName().equals(name)) list.add(current); List children = current.getChildren(); Iterator iterator = children.iterator(); while (iterator.hasNext()) { Element child = (Element) iterator.next(); if (child instanceof Element) listChildren(child, name, list); } return list; } /** * * @param collectionName * the name you would like the collection to be called * @param simples2makeCollection * the list of Elements to merge into a collection * @return null if a collection wasnt made, otherwise a fully wrapped * collection is returned. * @throws MobyException */ public static Element createCollectionFromListOfSimples( String collectionName, List<Element> simples2makeCollection) throws MobyException { if (simples2makeCollection.size() > 0) { // create a collection from the list of // simples Element mimCollection = new Element("Collection", XMLUtilities.MOBY_NS); for (Element simple : simples2makeCollection) { Element theSimple = XMLUtilities.extractMobyData(simple); if (theSimple.getChild("Simple") != null) theSimple = theSimple.getChild("Simple"); else if (theSimple.getChild("Simple", XMLUtilities.MOBY_NS) != null) theSimple = theSimple.getChild("Simple", XMLUtilities.MOBY_NS); mimCollection.addContent(theSimple.detach()); } String mimQueryID = "merged_" + queryCount++; mimCollection = XMLUtilities.createMobyDataElementWrapper( mimCollection, mimQueryID, null); mimCollection = XMLUtilities.renameCollection(collectionName, mimCollection); mimCollection = XMLUtilities.createMobyDataElementWrapper( mimCollection, mimQueryID, null); return mimCollection; } return null; } }
package net.tropicraft.core.common.block; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.DoorBlock; import net.minecraft.block.FenceBlock; import net.minecraft.block.FenceGateBlock; import net.minecraft.block.FlowerBlock; import net.minecraft.block.FlowerPotBlock; import net.minecraft.block.LadderBlock; import net.minecraft.block.LeavesBlock; import net.minecraft.block.LogBlock; import net.minecraft.block.RotatedPillarBlock; import net.minecraft.block.SaplingBlock; import net.minecraft.block.SlabBlock; import net.minecraft.block.SoundType; import net.minecraft.block.StairsBlock; import net.minecraft.block.TallFlowerBlock; import net.minecraft.block.TrapDoorBlock; import net.minecraft.block.WallBlock; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialColor; import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.ToolType; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.tropicraft.Constants; import net.tropicraft.Tropicraft; import net.tropicraft.core.client.tileentity.SimpleItemStackRenderer; import net.tropicraft.core.common.block.tileentity.AirCompressorTileEntity; import net.tropicraft.core.common.block.tileentity.BambooChestTileEntity; import net.tropicraft.core.common.block.tileentity.DrinkMixerTileEntity; import net.tropicraft.core.common.block.tileentity.TropicraftTileEntityTypes; import net.tropicraft.core.common.item.TropicraftItems; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; public class TropicraftBlocks { public static final DeferredRegister<Block> BLOCKS = new DeferredRegister<>(ForgeRegistries.BLOCKS, Constants.MODID); public static final DeferredRegister<Item> ITEMS = TropicraftItems.ITEMS; public static final RegistryObject<PortalWaterBlock> PORTAL_WATER = registerNoItem( "portal_water", () -> new PortalWaterBlock(Block.Properties.create(Material.WATER).noDrops())); public static final RegistryObject<Block> CHUNK = register( "chunk", Builder.block(Block.Properties.create(Material.ROCK, MaterialColor.BLACK).hardnessAndResistance(6.0F, 30F))); public static final RegistryObject<Block> AZURITE_ORE = register( "azurite_ore", Builder.ore(MaterialColor.GRAY)); public static final RegistryObject<Block> EUDIALYTE_ORE = register( "eudialyte_ore", Builder.ore(MaterialColor.GRAY)); public static final RegistryObject<Block> MANGANESE_ORE = register( "manganese_ore", Builder.ore(MaterialColor.BLACK)); public static final RegistryObject<Block> SHAKA_ORE = register( "shaka_ore", Builder.ore(MaterialColor.BLACK)); public static final RegistryObject<Block> ZIRCON_ORE = register( "zircon_ore", Builder.ore(MaterialColor.GRAY)); public static final RegistryObject<Block> AZURITE_BLOCK = register( "azurite_block", Builder.oreBlock(MaterialColor.LIGHT_BLUE)); public static final RegistryObject<Block> EUDIALYTE_BLOCK = register( "eudialyte_block", Builder.oreBlock(MaterialColor.PINK)); public static final RegistryObject<Block> MANGANESE_BLOCK = register( "manganese_block", Builder.oreBlock(MaterialColor.PURPLE)); public static final RegistryObject<Block> SHAKA_BLOCK = register( "shaka_block", Builder.oreBlock(MaterialColor.BLUE)); public static final RegistryObject<Block> ZIRCON_BLOCK = register( "zircon_block", Builder.oreBlock(MaterialColor.RED)); public static final RegistryObject<Block> ZIRCONIUM_BLOCK = register( "zirconium_block", Builder.oreBlock(MaterialColor.PINK)); public static final Map<TropicraftFlower, RegistryObject<FlowerBlock>> FLOWERS = Arrays.<TropicraftFlower>stream(TropicraftFlower.values()) .collect(Collectors.toMap(Function.identity(), f -> register(f.getId(), Builder.flower(f)), (f1, f2) -> { throw new IllegalStateException(); }, () -> new EnumMap<>(TropicraftFlower.class))); public static final RegistryObject<Block> PURIFIED_SAND = register("purified_sand", Builder.sand(MaterialColor.SAND)); public static final RegistryObject<Block> PACKED_PURIFIED_SAND = register("packed_purified_sand", Builder.sand(MaterialColor.SAND, 2, 30)); public static final RegistryObject<Block> CORAL_SAND = register("coral_sand", Builder.sand(MaterialColor.PINK)); public static final RegistryObject<Block> FOAMY_SAND = register("foamy_sand", Builder.sand(MaterialColor.GREEN)); public static final RegistryObject<Block> VOLCANIC_SAND = register("volcanic_sand", Builder.sand(MaterialColor.LIGHT_GRAY)); public static final RegistryObject<Block> MINERAL_SAND = register("mineral_sand", Builder.sand(MaterialColor.SAND)); public static final RegistryObject<RotatedPillarBlock> BAMBOO_BUNDLE = register( "bamboo_bundle", Builder.bundle(Block.Properties.from(Blocks.BAMBOO).hardnessAndResistance(0.2F, 5.0F))); public static final RegistryObject<RotatedPillarBlock> THATCH_BUNDLE = register( "thatch_bundle", Builder.bundle(Block.Properties.create(Material.ORGANIC, MaterialColor.WOOD).sound(SoundType.PLANT).hardnessAndResistance(0.2F, 5.0F))); public static final RegistryObject<Block> MAHOGANY_PLANKS = register("mahogany_planks", Builder.plank(MaterialColor.BROWN)); public static final RegistryObject<Block> PALM_PLANKS = register("palm_planks", Builder.plank(MaterialColor.WOOD)); public static final RegistryObject<LogBlock> MAHOGANY_LOG = register("mahogany_log", Builder.log(MaterialColor.WOOD, MaterialColor.BROWN)); public static final RegistryObject<LogBlock> PALM_LOG = register("palm_log", Builder.log(MaterialColor.GRAY, MaterialColor.BROWN)); public static final RegistryObject<RotatedPillarBlock> MAHOGANY_WOOD = register("mohogany_wood", Builder.wood(MaterialColor.WOOD)); public static final RegistryObject<RotatedPillarBlock> PALM_WOOD = register("palm_wood", Builder.wood(MaterialColor.GRAY)); public static final RegistryObject<StairsBlock> PALM_STAIRS = register( "palm_stairs", Builder.stairs(PALM_PLANKS)); public static final RegistryObject<StairsBlock> MAHOGANY_STAIRS = register( "mahogany_stairs", Builder.stairs(MAHOGANY_PLANKS)); public static final RegistryObject<StairsBlock> THATCH_STAIRS = register( "thatch_stairs", Builder.stairs(THATCH_BUNDLE)); public static final RegistryObject<StairsBlock> THATCH_STAIRS_FUZZY = register( "thatch_stairs_fuzzy", Builder.stairs(THATCH_BUNDLE)); public static final RegistryObject<StairsBlock> BAMBOO_STAIRS = register( "bamboo_stairs", Builder.stairs(BAMBOO_BUNDLE)); public static final RegistryObject<StairsBlock> CHUNK_STAIRS = register( "chunk_stairs", Builder.stairs(CHUNK)); public static final RegistryObject<Block> COCONUT = register( "coconut", () -> new CoconutBlock(Block.Properties.create(Material.GOURD).hardnessAndResistance(2.0f).harvestTool(ToolType.AXE).sound(SoundType.STONE))); public static final RegistryObject<SlabBlock> BAMBOO_SLAB = register( "bamboo_slab", Builder.slab(BAMBOO_BUNDLE)); public static final RegistryObject<SlabBlock> THATCH_SLAB = register( "thatch_slab", Builder.slab(THATCH_BUNDLE)); public static final RegistryObject<SlabBlock> CHUNK_SLAB = register( "chunk_slab", Builder.slab(CHUNK)); public static final RegistryObject<SlabBlock> PALM_SLAB = register( "palm_slab", Builder.slab(PALM_PLANKS)); public static final RegistryObject<SlabBlock> MAHOGANY_SLAB = register( "mahogany_slab", Builder.slab(MAHOGANY_PLANKS)); public static final RegistryObject<LeavesBlock> MAHOGANY_LEAVES = register("mahogany_leaves", Builder.leaves(false)); public static final RegistryObject<LeavesBlock> PALM_LEAVES = register("palm_leaves", Builder.leaves(false)); public static final RegistryObject<LeavesBlock> KAPOK_LEAVES = register("kapok_leaves", Builder.leaves(false)); public static final RegistryObject<LeavesBlock> FRUIT_LEAVES = register("fruit_leaves", Builder.leaves(true)); public static final RegistryObject<LeavesBlock> GRAPEFRUIT_LEAVES = register("grapefruit_leaves", Builder.leaves(true)); public static final RegistryObject<LeavesBlock> LEMON_LEAVES = register("lemon_leaves", Builder.leaves(true)); public static final RegistryObject<LeavesBlock> LIME_LEAVES = register("lime_leaves", Builder.leaves(true)); public static final RegistryObject<LeavesBlock> ORANGE_LEAVES = register("orange_leaves", Builder.leaves(true)); public static final RegistryObject<SaplingBlock> GRAPEFRUIT_SAPLING = register("grapefruit_sapling", Builder.sapling(TropicraftTrees.GRAPEFRUIT)); public static final RegistryObject<SaplingBlock> LEMON_SAPLING = register("lemon_sapling", Builder.sapling(TropicraftTrees.LEMON)); public static final RegistryObject<SaplingBlock> LIME_SAPLING = register("lime_sapling", Builder.sapling(TropicraftTrees.LIME)); public static final RegistryObject<SaplingBlock> ORANGE_SAPLING = register("orange_sapling", Builder.sapling(TropicraftTrees.ORANGE)); public static final RegistryObject<SaplingBlock> MAHOGANY_SAPLING = register("mahogany_sapling", Builder.sapling(TropicraftTrees.RAINFOREST)); public static final RegistryObject<SaplingBlock> PALM_SAPLING = register( "palm_sapling", Builder.sapling(TropicraftTrees.PALM, () -> Blocks.SAND, CORAL_SAND, FOAMY_SAND, VOLCANIC_SAND, PURIFIED_SAND, MINERAL_SAND)); public static final RegistryObject<FenceBlock> BAMBOO_FENCE = register("bamboo_fence", Builder.fence(BAMBOO_BUNDLE)); public static final RegistryObject<FenceBlock> THATCH_FENCE = register("thatch_fence", Builder.fence(THATCH_BUNDLE)); public static final RegistryObject<FenceBlock> CHUNK_FENCE = register("chunk_fence", Builder.fence(CHUNK)); public static final RegistryObject<FenceBlock> PALM_FENCE = register("palm_fence", Builder.fence(PALM_PLANKS)); public static final RegistryObject<FenceBlock> MAHOGANY_FENCE = register("mahogany_fence", Builder.fence(MAHOGANY_PLANKS)); public static final RegistryObject<FenceGateBlock> BAMBOO_FENCE_GATE = register("bamboo_fence_gate", Builder.fenceGate(BAMBOO_BUNDLE)); public static final RegistryObject<FenceGateBlock> THATCH_FENCE_GATE = register("thatch_fence_gate", Builder.fenceGate(THATCH_BUNDLE)); public static final RegistryObject<FenceGateBlock> CHUNK_FENCE_GATE = register("chunk_fence_gate", Builder.fenceGate(CHUNK)); public static final RegistryObject<FenceGateBlock> PALM_FENCE_GATE = register("palm_fence_gate", Builder.fenceGate(PALM_PLANKS)); public static final RegistryObject<FenceGateBlock> MAHOGANY_FENCE_GATE = register("mahogany_fence_gate", Builder.fenceGate(MAHOGANY_PLANKS)); public static final RegistryObject<WallBlock> CHUNK_WALL = register("chunk_wall", Builder.wall(CHUNK)); public static final RegistryObject<DoorBlock> BAMBOO_DOOR = register( "bamboo_door", () -> new DoorBlock(Block.Properties.from(BAMBOO_BUNDLE.get()).hardnessAndResistance(1.0F)) {}); public static final RegistryObject<DoorBlock> PALM_DOOR = register( "palm_door", () -> new DoorBlock(Block.Properties.from(Blocks.OAK_DOOR)) {}); public static final RegistryObject<DoorBlock> MAHOGANY_DOOR = register( "mahogany_door", () -> new DoorBlock(Block.Properties.from(Blocks.OAK_DOOR)) {}); public static final RegistryObject<DoorBlock> THATCH_DOOR = register( "thatch_door", () -> new DoorBlock(Block.Properties.from(THATCH_BUNDLE.get())) {}); public static final RegistryObject<TrapDoorBlock> BAMBOO_TRAPDOOR = register( "bamboo_trapdoor", () -> new TrapDoorBlock(Block.Properties.from(BAMBOO_DOOR.get())) {}); public static final RegistryObject<TrapDoorBlock> PALM_TRAPDOOR = register( "palm_trapdoor", () -> new TrapDoorBlock(Block.Properties.from(PALM_DOOR.get())) {}); public static final RegistryObject<TrapDoorBlock> MAHOGANY_TRAPDOOR = register( "mahogany_trapdoor", () -> new TrapDoorBlock(Block.Properties.from(MAHOGANY_DOOR.get())) {}); public static final RegistryObject<TrapDoorBlock> THATCH_TRAPDOOR = register( "thatch_trapdoor", () -> new TrapDoorBlock(Block.Properties.from(THATCH_BUNDLE.get())) {}); public static final RegistryObject<TallFlowerBlock> IRIS = register( "iris", () -> new TallFlowerBlock(Block.Properties.create(Material.TALL_PLANTS).doesNotBlockMovement().hardnessAndResistance(0).sound(SoundType.PLANT))); public static final RegistryObject<PineappleBlock> PINEAPPLE = register( "pineapple", () -> new PineappleBlock(Block.Properties.create(Material.TALL_PLANTS).tickRandomly().doesNotBlockMovement().hardnessAndResistance(0).sound(SoundType.PLANT))); public static final RegistryObject<BongoDrumBlock> SMALL_BONGO_DRUM = register("small_bongo_drum", Builder.bongo(BongoDrumBlock.Size.SMALL)); public static final RegistryObject<BongoDrumBlock> MEDIUM_BONGO_DRUM = register("medium_bongo_drum", Builder.bongo(BongoDrumBlock.Size.MEDIUM)); public static final RegistryObject<BongoDrumBlock> LARGE_BONGO_DRUM = register("large_bongo_drum", Builder.bongo(BongoDrumBlock.Size.LARGE)); public static final RegistryObject<LadderBlock> BAMBOO_LADDER = register( "bamboo_ladder", () -> new LadderBlock(Block.Properties.from(Blocks.BAMBOO)) {}); public static final RegistryObject<BambooChestBlock> BAMBOO_CHEST = register( "bamboo_chest", () -> new BambooChestBlock(Block.Properties.from(BAMBOO_BUNDLE.get()).hardnessAndResistance(1), () -> TropicraftTileEntityTypes.BAMBOO_CHEST.get()), () -> chestRenderer()); public static final RegistryObject<SifterBlock> SIFTER = register( "sifter", () -> new SifterBlock(Block.Properties.from(Blocks.OAK_PLANKS).notSolid())); public static final RegistryObject<DrinkMixerBlock> DRINK_MIXER = register( "drink_mixer", () -> new DrinkMixerBlock(Block.Properties.create(Material.ROCK).hardnessAndResistance(2, 30).notSolid()), () -> drinkMixerRenderer()); public static final RegistryObject<AirCompressorBlock> AIR_COMPRESSOR = register( "air_compressor", () -> new AirCompressorBlock(Block.Properties.create(Material.ROCK).hardnessAndResistance(2, 30).notSolid()), () -> airCompressorRenderer()); public static final RegistryObject<VolcanoBlock> VOLCANO = registerNoItem( "volcano", () -> new VolcanoBlock(Block.Properties.from(Blocks.BEDROCK).noDrops())); public static final RegistryObject<TikiTorchBlock> TIKI_TORCH = register( "tiki_torch", () -> new TikiTorchBlock(Block.Properties.from(Blocks.TORCH).sound(SoundType.WOOD).lightValue(0))); public static final RegistryObject<FlowerPotBlock> BAMBOO_FLOWER_POT = register( "bamboo_flower_pot", Builder.tropicraftPot()); public static final RegistryObject<CoffeeBushBlock> COFFEE_BUSH = register( "coffee_bush", () -> new CoffeeBushBlock(Block.Properties.create(Material.PLANTS, MaterialColor.GRASS).hardnessAndResistance(0.15f).sound(SoundType.PLANT).notSolid())); @SuppressWarnings("unchecked") private static final Set<RegistryObject<? extends Block>> POTTABLE_PLANTS = ImmutableSet.<RegistryObject<? extends Block>>builder() .add(PALM_SAPLING, MAHOGANY_SAPLING, GRAPEFRUIT_SAPLING, LEMON_SAPLING, LIME_SAPLING, ORANGE_SAPLING) .addAll(FLOWERS.values()) .build(); public static final List<RegistryObject<FlowerPotBlock>> BAMBOO_POTTED_TROPICS_PLANTS = ImmutableList.copyOf(POTTABLE_PLANTS.stream() .map(b -> registerNoItem("bamboo_potted_" + b.getId().getPath(), Builder.tropicraftPot(b))) .collect(Collectors.toList())); public static final List<RegistryObject<FlowerPotBlock>> VANILLA_POTTED_TROPICS_PLANTS = ImmutableList.copyOf(POTTABLE_PLANTS.stream() .map(b -> registerNoItem("potted_" + b.getId().getPath(), Builder.vanillaPot(b))) .collect(Collectors.toList())); public static final List<RegistryObject<FlowerPotBlock>> BAMBOO_POTTED_VANILLA_PLANTS = ImmutableList.copyOf( Stream.of(Blocks.OAK_SAPLING, Blocks.SPRUCE_SAPLING, Blocks.BIRCH_SAPLING, Blocks.JUNGLE_SAPLING, Blocks.ACACIA_SAPLING, Blocks.DARK_OAK_SAPLING, Blocks.FERN, Blocks.DANDELION, Blocks.POPPY, Blocks.BLUE_ORCHID, Blocks.ALLIUM, Blocks.AZURE_BLUET, Blocks.RED_TULIP, Blocks.ORANGE_TULIP, Blocks.WHITE_TULIP, Blocks.PINK_TULIP, Blocks.OXEYE_DAISY, Blocks.CORNFLOWER, Blocks.LILY_OF_THE_VALLEY, Blocks.WITHER_ROSE, Blocks.RED_MUSHROOM, Blocks.BROWN_MUSHROOM, Blocks.DEAD_BUSH, Blocks.CACTUS) .map(b -> registerNoItem("bamboo_potted_" + b.getRegistryName().getPath(), Builder.tropicraftPot(() -> b))) .collect(Collectors.toList())); public static final List<RegistryObject<FlowerPotBlock>> ALL_POTTED_PLANTS = ImmutableList.<RegistryObject<FlowerPotBlock>>builder() .addAll(BAMBOO_POTTED_TROPICS_PLANTS) .addAll(VANILLA_POTTED_TROPICS_PLANTS) .addAll(BAMBOO_POTTED_VANILLA_PLANTS) .build(); private static <T extends Block> RegistryObject<T> register(String name, Supplier<? extends T> sup) { return register(name, sup, TropicraftBlocks::itemDefault); } private static <T extends Block> RegistryObject<T> register(String name, Supplier<? extends T> sup, Supplier<Callable<ItemStackTileEntityRenderer>> renderMethod) { return register(name, sup, block -> item(block, renderMethod)); } private static <T extends Block> RegistryObject<T> register(String name, Supplier<? extends T> sup, ItemGroup tab) { return register(name, sup, block -> item(block, tab)); } private static <T extends Block> RegistryObject<T> register(String name, Supplier<? extends T> sup, Function<RegistryObject<T>, Supplier<? extends Item>> itemCreator) { RegistryObject<T> ret = registerNoItem(name, sup); ITEMS.register(name, itemCreator.apply(ret)); return ret; } private static <T extends Block> RegistryObject<T> registerNoItem(String name, Supplier<? extends T> sup) { return BLOCKS.register(name, sup); } private static Supplier<BlockItem> itemDefault(final RegistryObject<? extends Block> block) { return item(block, Tropicraft.TROPICRAFT_ITEM_GROUP); } private static Supplier<BlockItem> item(final RegistryObject<? extends Block> block, final Supplier<Callable<ItemStackTileEntityRenderer>> renderMethod) { return () -> new BlockItem(block.get(), new Item.Properties().group(Tropicraft.TROPICRAFT_ITEM_GROUP).setISTER(renderMethod)); } private static Supplier<BlockItem> item(final RegistryObject<? extends Block> block, final ItemGroup itemGroup) { return () -> new BlockItem(block.get(), new Item.Properties().group(itemGroup)); } @OnlyIn(Dist.CLIENT) private static Callable<ItemStackTileEntityRenderer> chestRenderer() { return () -> new SimpleItemStackRenderer<>(BambooChestTileEntity::new); } @OnlyIn(Dist.CLIENT) private static Callable<ItemStackTileEntityRenderer> drinkMixerRenderer() { return () -> new SimpleItemStackRenderer<>(DrinkMixerTileEntity::new); } @OnlyIn(Dist.CLIENT) private static Callable<ItemStackTileEntityRenderer> airCompressorRenderer() { return () -> new SimpleItemStackRenderer<>(AirCompressorTileEntity::new); } }
package org.dannil.httpdownloader.service; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import org.apache.log4j.Logger; import org.dannil.httpdownloader.model.Download; import org.dannil.httpdownloader.model.User; import org.dannil.httpdownloader.repository.DownloadRepository; import org.dannil.httpdownloader.utility.FileUtility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Class which handles back end operations for downloads. * * @author Daniel Nilsson */ @Service(value = "DownloadService") public final class DownloadService implements IDownloadService { final static Logger LOGGER = Logger.getLogger(DownloadService.class.getName()); @Autowired DownloadRepository downloadRepository; /** * Find a download by it's id. * * @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable) */ @Override public final Download findById(final long downloadId) { return this.downloadRepository.findOne(downloadId); } /** * Find downloads for the specified user. * * @see org.dannil.httpdownloader.repository.DownloadRepository#findByUser(User) */ @Override public final LinkedList<Download> findByUser(final User user) { return new LinkedList<Download>(this.downloadRepository.findByUser(user)); } /** * Delete a persisted download which matches the specified download. * * @see org.springframework.data.repository.CrudRepository#delete(Object) */ @Override public final void delete(final Download download) { Thread t = new Thread(new Runnable() { @Override public void run() { try { FileUtility.deleteFromDrive(download); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); this.downloadRepository.delete(download); } /** * Delete a persisted download with the specified id. * * @see org.springframework.data.repository.CrudRepository#delete(Object) * */ @Override public final void delete(final long downloadId) { this.downloadRepository.delete(downloadId); } /** * Persist the specified download. * * @see org.springframework.data.repository.CrudRepository#save(Object) */ @Override public final Download save(final Download download) { return this.downloadRepository.save(download); } /** * Initiate the specified download and save it to the disk. * * @see org.dannil.httpdownloader.utility.FileUtility#saveToDrive(File) */ @Override public Download saveToDisk(final Download download) { Thread t = new Thread(new Runnable() { @Override public void run() { final File file; try { LOGGER.info("Trying to save download..."); file = FileUtility.getFileFromURL(download); FileUtility.saveToDrive(file); download.setEndDate(new Date()); save(download); } catch (IOException e) { e.printStackTrace(); } ; } }); t.start(); return download; } }
package org.develnext.jphp.site.controller; import org.develnext.jphp.site.github.GithubWikiResolver; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/") public class SiteController { protected GithubWikiResolver resolver = new GithubWikiResolver("jphp-compiler/jphp"); @RequestMapping public String index(ModelMap vars) { vars.put("currPage", "index"); return "site/index"; } @RequestMapping("donate/") public String donate(ModelMap vars) { vars.put("currPage", "donate"); return "site/donate"; } @RequestMapping("documentation/") public String documentation(ModelMap vars) { vars.put("currPage", "documentation"); vars.put("source", resolver.get("_DOCUMENTATION")); vars.put("path", "_DOCUMENTATION"); vars.put("title", "Documentation"); return "site/wiki"; } @RequestMapping("faq/") public String faq(ModelMap vars) { vars.put("currPage", "faq"); vars.put("source", resolver.get("_FAQ")); vars.put("path", "_FAQ"); vars.put("title", "F.A.Q."); return "site/wiki"; } @RequestMapping("download/") public String download(ModelMap vars) { vars.put("currPage", "download"); vars.put("source", resolver.get("_DOWNLOAD")); vars.put("path", "_DOWNLOAD"); vars.put("title", "Download"); return "site/wiki"; } }
package org.embulk.output.mailchimp; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import org.embulk.base.restclient.jackson.JacksonServiceRecord; import org.embulk.base.restclient.record.RecordBuffer; import org.embulk.base.restclient.record.ServiceRecord; import org.embulk.config.TaskReport; import org.embulk.output.mailchimp.model.AddressMergeFieldAttribute; import org.embulk.output.mailchimp.model.InterestResponse; import org.embulk.output.mailchimp.model.MergeField; import org.embulk.output.mailchimp.model.ReportResponse; import org.embulk.spi.Column; import org.embulk.spi.DataException; import org.embulk.spi.Exec; import org.embulk.spi.Schema; import org.slf4j.Logger; import javax.annotation.Nullable; import java.io.IOException; 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 java.util.TreeMap; import java.util.TreeSet; import static com.google.common.base.Joiner.on; import static java.lang.String.CASE_INSENSITIVE_ORDER; import static java.lang.String.format; import static org.embulk.output.mailchimp.MailChimpOutputPluginDelegate.PluginTask; import static org.embulk.output.mailchimp.helper.MailChimpHelper.fromCommaSeparatedString; import static org.embulk.output.mailchimp.helper.MailChimpHelper.jsonGetIgnoreCase; import static org.embulk.output.mailchimp.helper.MailChimpHelper.orderJsonNode; import static org.embulk.output.mailchimp.helper.MailChimpHelper.toJsonNode; import static org.embulk.output.mailchimp.model.MemberStatus.PENDING; import static org.embulk.output.mailchimp.model.MemberStatus.SUBSCRIBED; public class MailChimpRecordBuffer extends RecordBuffer { private static final Logger LOG = Exec.getLogger(MailChimpRecordBuffer.class); private final MailChimpOutputPluginDelegate.PluginTask task; private final MailChimpClient mailChimpClient; private final ObjectMapper mapper; private final Schema schema; private int requestCount; private int errorCount; private long totalCount; private List<JsonNode> records; private Map<String, Map<String, InterestResponse>> categories; private Map<String, MergeField> availableMergeFields; private List<JsonNode> uniqueRecords; private List<JsonNode> duplicatedRecords; /** * Instantiates a new Mail chimp abstract record buffer. * * @param schema the schema * @param task the task */ public MailChimpRecordBuffer(final Schema schema, final PluginTask task) { this.schema = schema; this.task = task; this.mapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, false); this.records = new ArrayList<>(); this.uniqueRecords = new ArrayList<>(); this.duplicatedRecords = new ArrayList<>(); this.mailChimpClient = new MailChimpClient(task); } @Override public void bufferRecord(ServiceRecord serviceRecord) { JacksonServiceRecord jacksonServiceRecord; try { jacksonServiceRecord = (JacksonServiceRecord) serviceRecord; JsonNode record = mapper.readTree(jacksonServiceRecord.toString()).get("record"); requestCount++; totalCount++; records.add(record); if (requestCount >= task.getMaxRecordsPerRequest()) { filterDuplicatedRecords(); pushData(); if (totalCount % 1000 == 0) { LOG.info("Pushed {} records", totalCount); } records = new ArrayList<>(); uniqueRecords = new ArrayList<>(); duplicatedRecords = new ArrayList<>(); requestCount = 0; } } catch (JsonProcessingException jpe) { throw new DataException(jpe); } catch (ClassCastException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw Throwables.propagate(ex); } } @Override public TaskReport commitWithTaskReportUpdated(TaskReport taskReport) { try { if (records.size() > 0) { filterDuplicatedRecords(); pushData(); records = new ArrayList<>(); uniqueRecords = new ArrayList<>(); duplicatedRecords = new ArrayList<>(); } return Exec.newTaskReport().set("pushed", totalCount).set("error_count", errorCount); } catch (JsonProcessingException jpe) { throw new DataException(jpe); } catch (Exception ex) { throw Throwables.propagate(ex); } } @Override public void finish() { // Do not close here } @Override public void close() { // // Do not close here } /** * Receive data and build payload json that contains subscribers * * @param data the data * @param task the task * @return the object node */ private ObjectNode processSubcribers(final List<JsonNode> data, final PluginTask task) throws JsonProcessingException { // Should loop the names and get the id of interest categories. // The reason why we put categories validation here because we can not share data between instance. if (categories == null) { categories = mailChimpClient.extractInterestCategoriesByGroupNames(task); Set<String> categoriesNames = new HashSet<>(categories.keySet()); Set<String> columnNames = caseInsensitiveColumnNames(); if (!columnNames.containsAll(categoriesNames)) { categoriesNames.removeAll(columnNames); LOG.warn("Data column for category '{}' could not be found", on(", ").join(categoriesNames)); } } // Extract merge fields detail if (availableMergeFields == null) { availableMergeFields = mailChimpClient.extractMergeFieldsFromList(task); } // Required merge fields Map<String, String> map = new HashMap<>(); map.put("FNAME", task.getFnameColumn()); map.put("LNAME", task.getLnameColumn()); List<JsonNode> subscribersList = FluentIterable.from(data) .transform(contactMapper(map)) .toList(); ObjectNode subscribers = JsonNodeFactory.instance.objectNode(); subscribers.putArray("members").addAll(subscribersList); subscribers.put("update_existing", task.getUpdateExisting()); return subscribers; } private Function<JsonNode, JsonNode> contactMapper(final Map<String, String> allowColumns) { return new Function<JsonNode, JsonNode>() { @Override public JsonNode apply(JsonNode input) { ObjectNode property = JsonNodeFactory.instance.objectNode(); property.put("email_address", input.findPath(task.getEmailColumn()).asText()); property.put("status", task.getDoubleOptIn() ? PENDING.getType() : SUBSCRIBED.getType()); ObjectNode mergeFields = JsonNodeFactory.instance.objectNode(); for (String allowColumn : allowColumns.keySet()) { String value = input.hasNonNull(allowColumns.get(allowColumn)) ? input.findValue(allowColumns.get(allowColumn)).asText() : ""; mergeFields.put(allowColumn, value); } // Update additional merge fields if exist if (task.getMergeFields().isPresent() && !task.getMergeFields().get().isEmpty()) { Map<String, String> columnNameCaseInsensitiveLookup = new TreeMap<>(CASE_INSENSITIVE_ORDER); for (Column col : schema.getColumns()) { columnNameCaseInsensitiveLookup.put(col.getName(), col.getName()); } Map<String, MergeField> availableMergeFieldsCaseInsensitiveLookup = new TreeMap<>(CASE_INSENSITIVE_ORDER); availableMergeFieldsCaseInsensitiveLookup.putAll(availableMergeFields); for (String field : task.getMergeFields().get()) { if (!columnNameCaseInsensitiveLookup.containsKey(field)) { LOG.warn(format("Field '%s' is configured on data transfer but cannot be found on any columns.", field)); continue; } String columnName = columnNameCaseInsensitiveLookup.get(field); if (!availableMergeFieldsCaseInsensitiveLookup.containsKey(columnName)) { LOG.warn(format("Field '%s' is configured on data transfer but is not predefined on Mailchimp.", field)); continue; } String value = input.hasNonNull(columnName) ? input.findValue(columnName).asText() : ""; // Try to convert to Json from string with the merge field's type is address if (availableMergeFieldsCaseInsensitiveLookup.get(columnName).getType().equals(MergeField.MergeFieldType.ADDRESS.getType())) { JsonNode addressNode = toJsonNode(value); if (addressNode instanceof NullNode) { mergeFields.put(columnName.toUpperCase(), value); } else { mergeFields.set(columnName.toUpperCase(), orderJsonNode(addressNode, AddressMergeFieldAttribute.values())); } } else { mergeFields.put(columnName.toUpperCase(), value); } } } property.set("merge_fields", mergeFields); // Update interest categories if exist if (task.getGroupingColumns().isPresent() && !task.getGroupingColumns().get().isEmpty()) { property.set("interests", buildInterestCategories(input)); } // Update language if exist if (task.getLanguageColumn().isPresent() && !task.getLanguageColumn().get().isEmpty()) { property.put("language", input.findPath(task.getLanguageColumn().get()).asText()); } return property; } }; } private ObjectNode buildInterestCategories(final JsonNode input) { ObjectNode interests = JsonNodeFactory.instance.objectNode(); if (task.getGroupingColumns().isPresent()) { for (String category : task.getGroupingColumns().get()) { Optional<JsonNode> inputValue = jsonGetIgnoreCase(input, category); if (!inputValue.isPresent()) { // Silently ignore if the grouping column is absent continue; } List<String> recordInterests = fromCommaSeparatedString(inputValue.get().asText()); // `categories` is guaranteed to contain the `category` as it already did an early check Map<String, InterestResponse> availableInterests = categories.get(category); // Only update user-predefined categories if replace interests != true if (!task.getReplaceInterests()) { for (String recordInterest : recordInterests) { if (availableInterests.get(recordInterest) != null) { interests.put(availableInterests.get(recordInterest).getId(), true); } } } // Otherwise, force update all categories include user-predefined categories else if (task.getReplaceInterests()) { for (String availableInterest : availableInterests.keySet()) { if (recordInterests.contains(availableInterest)) { interests.put(availableInterests.get(availableInterest).getId(), true); } else { interests.put(availableInterests.get(availableInterest).getId(), false); } } } } } return interests; } private void filterDuplicatedRecords() { Set<String> uniqueEmails = new HashSet<>(); for (JsonNode node : records) { if (uniqueEmails.contains(node.findPath(task.getEmailColumn()).asText())) { duplicatedRecords.add(node); } else { uniqueEmails.add(node.findPath(task.getEmailColumn()).asText()); uniqueRecords.add(node); } } } private void pushData() throws JsonProcessingException { long startTime = System.currentTimeMillis(); ObjectNode subscribers = processSubcribers(uniqueRecords, task); ReportResponse reportResponse = mailChimpClient.push(subscribers, task); LOG.info("Done with {} record(s). Response from MailChimp: {} records created, {} records updated, {} records failed. Batch took {} ms ", records.size(), reportResponse.getTotalCreated(), reportResponse.getTotalUpdated(), reportResponse.getErrorCount(), System.currentTimeMillis() - startTime); errorCount += reportResponse.getErrors().size(); mailChimpClient.handleErrors(reportResponse.getErrors()); mailChimpClient.avoidFloodAPI("Process next request", task.getSleepBetweenRequestsMillis()); if (duplicatedRecords.size() > 0) { LOG.info("Start to process {} duplicated record(s)", duplicatedRecords.size()); for (JsonNode duplicatedRecord : duplicatedRecords) { startTime = System.currentTimeMillis(); subscribers = processSubcribers(Arrays.asList(duplicatedRecord), task); reportResponse = mailChimpClient.push(subscribers, task); LOG.info("Done. Response from MailChimp: {} records created, {} records updated, {} records failed. Batch took {} ms ", reportResponse.getTotalCreated(), reportResponse.getTotalUpdated(), reportResponse.getErrorCount(), System.currentTimeMillis() - startTime); mailChimpClient.handleErrors(reportResponse.getErrors()); } } } private Set<String> caseInsensitiveColumnNames() { Set<String> columns = new TreeSet<>(CASE_INSENSITIVE_ORDER); columns.addAll(FluentIterable .from(schema.getColumns()) .transform(new Function<Column, String>() { @Nullable @Override public String apply(@Nullable Column col) { return col.getName(); } }) .toSet()); return columns; } }
package org.jvnet.hudson.plugins.backup.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.AutoCloseInputStream; /** * This is the restore task, run in background and log to a file * * @author vsellier * */ public class RestoreTask implements Runnable { private final static Logger LOGGER = Logger.getLogger(RestoreTask.class .getName()); private boolean verbose; private String logFileName; private String sourceFileName; private String configurationDirectory; private List<String> exclusions = new ArrayList<String>(); private BackupLogger logger; private Date startDate; private Date endDate; private boolean finished = false; public RestoreTask() { exclusions.addAll(getDefaultsExclusions()); } public void run() { assert (logFileName != null); assert (sourceFileName != null); startDate = new Date(); try { logger = new BackupLogger(logFileName, verbose); } catch (IOException e) { LOGGER.severe("Unable to open log file for writing : " + logFileName); return; } logger.info("Restore started at " + getTimestamp(startDate)); logger.info("Removing old configuration files"); File directory = new File(configurationDirectory); try { FileUtils.deleteDirectory(directory); } catch (IOException e) { logger.error("Unable to delete old configuration directory"); e.printStackTrace(logger.getWriter()); logger.error("Hudson could be in a inconsistent state."); logger.error("Try to uncompress manually " + sourceFileName + " into " + configurationDirectory + " directory."); return; } if ( ! directory.mkdir()) { logger.error("Unable to create " + configurationDirectory + " directory."); return; } File archive = new File(sourceFileName); ZipInputStream input; try { input = new ZipInputStream(new AutoCloseInputStream(new FileInputStream(archive))); } catch (IOException e) { logger.error("Unable to open archive."); return; } ZipEntry entry; try { while ((entry = input.getNextEntry()) != null) { logger.debug("Decompression de " + entry.getName()); } } catch (IOException e) { logger.error("Error uncompressing zip file."); return; } // FileFilter filter = createFileFilter(exclusions); // try { // ZipBackupEngine backupEngine = new ZipBackupEngine(logger, // configurationDirectory, targetFileName, filter); // backupEngine.doBackup(); // } catch (IOException e) { // e.printStackTrace(logger.getWriter()); endDate = new Date(); logger.info("Backup end at " + getTimestamp(endDate)); BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime()); delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP); delay = delay.divide(new BigDecimal("1000")); logger.info("[" + delay.toPlainString() + "s]"); finished = true; logger.close(); } public void setLogFileName(String logFileName) { this.logFileName = logFileName; } public void setSourceFileName(String sourceFileName) { this.sourceFileName = sourceFileName; } public void setConfigurationDirectory(String configurationDirectory) { this.configurationDirectory = configurationDirectory; } public boolean isFinished() { return finished; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public List<String> getDefaultsExclusions() { List<String> defaultExclusion = new ArrayList<String>(); defaultExclusion.add("workspace"); return defaultExclusion; } /** * Gets the formatted current time stamp. */ private static String getTimestamp(Date date) { return String.format("[%1$tD %1$tT]", date); } }
package org.lightmare.jndi; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; import org.lightmare.jndi.JndiManager.JNDIParameters; import org.lightmare.utils.ObjectUtils; /** * Implementation of {@link InitialContextFactory} factory class to register and * instantiate JNDI {@link Context} instance * * @author Levan Tsinadze * @since 0.0.60-SNAPSHOT */ public class LightmareInitialContextFactory implements InitialContextFactory { /** * Puts if absent shared parameter to JNDI properties before initialization * * @param sharingEnv * @param parameter */ private void putToEnv(Hashtable<Object, Object> sharingEnv, JNDIParameters parameter) { String key = parameter.key; String value = parameter.value; // all instances will share stored data boolean notContainsKey = ObjectUtils.notTrue(sharingEnv .containsKey(key)); if (notContainsKey) { sharingEnv.put(key, value); } } @Override public Context getInitialContext(Hashtable<?, ?> properties) throws NamingException { // clone the environment Hashtable<Object, Object> sharingEnv = ObjectUtils.cast(properties .clone()); putToEnv(sharingEnv, JNDIParameters.SHARED_PARAMETER); Context lightmareContext = new LightmareContext(sharingEnv); return lightmareContext; } }
package org.nnsoft.shs.dispatcher.file; import static org.nnsoft.shs.http.Headers.CONTENT_TYPE; import static org.nnsoft.shs.http.Response.Status.NOT_FOUND; import static org.nnsoft.shs.lang.Preconditions.checkArgument; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.nnsoft.shs.dispatcher.BaseRequestHandler; import org.nnsoft.shs.http.Request; import org.nnsoft.shs.http.Response; /** * A simple request handler that serves static files. * * <b>NOTE</b> the current handler doesn't check any content negotiation. */ public final class FileRequestHandler extends BaseRequestHandler { /** * The files content types, extracted from conf/web.xml in Tomcat. */ private final Map<String, String> contentTypes = new HashMap<String, String>(); /** * The main directory where static files are stored. */ private final File baseDir; public FileRequestHandler( File baseDir ) { checkArgument( baseDir != null, "Basedir where getting files must be not null" ); checkArgument( baseDir.exists(), "Basedir where getting files must exist" ); checkArgument( baseDir.isDirectory(), "Basedir where getting files must be a directory" ); this.baseDir = baseDir; contentTypes.put( "abs", "audio/x-mpeg" ); contentTypes.put( "ai", "application/postscript" ); contentTypes.put( "aif", "audio/x-aiff" ); contentTypes.put( "aifc", "audio/x-aiff" ); contentTypes.put( "aiff", "audio/x-aiff" ); contentTypes.put( "aim", "application/x-aim" ); contentTypes.put( "art", "image/x-jg" ); contentTypes.put( "asf", "video/x-ms-asf" ); contentTypes.put( "asx", "video/x-ms-asf" ); contentTypes.put( "au", "audio/basic" ); contentTypes.put( "avi", "video/x-msvideo" ); contentTypes.put( "avx", "video/x-rad-screenplay" ); contentTypes.put( "bcpio", "application/x-bcpio" ); contentTypes.put( "bin", "application/octet-stream" ); contentTypes.put( "bmp", "image/bmp" ); contentTypes.put( "body", "text/html" ); contentTypes.put( "cdf", "application/x-cdf" ); contentTypes.put( "cer", "application/x-x509-ca-cert" ); contentTypes.put( "class", "application/java" ); contentTypes.put( "cpio", "application/x-cpio" ); contentTypes.put( "csh", "application/x-csh" ); contentTypes.put( "css", "text/css" ); contentTypes.put( "dib", "image/bmp" ); contentTypes.put( "doc", "application/msword" ); contentTypes.put( "dtd", "application/xml-dtd" ); contentTypes.put( "dv", "video/x-dv" ); contentTypes.put( "dvi", "application/x-dvi" ); contentTypes.put( "eps", "application/postscript" ); contentTypes.put( "etx", "text/x-setext" ); contentTypes.put( "exe", "application/octet-stream" ); contentTypes.put( "gif", "image/gif" ); contentTypes.put( "gtar", "application/x-gtar" ); contentTypes.put( "gz", "application/x-gzip" ); contentTypes.put( "hdf", "application/x-hdf" ); contentTypes.put( "hqx", "application/mac-binhex40" ); contentTypes.put( "htc", "text/x-component" ); contentTypes.put( "htm", "text/html" ); contentTypes.put( "html", "text/html" ); contentTypes.put( "hqx", "application/mac-binhex40" ); contentTypes.put( "ief", "image/ief" ); contentTypes.put( "jad", "text/vnd.sun.j2me.app-descriptor" ); contentTypes.put( "jar", "application/java-archive" ); contentTypes.put( "java", "text/plain" ); contentTypes.put( "jnlp", "application/x-java-jnlp-file" ); contentTypes.put( "jpe", "image/jpeg" ); contentTypes.put( "jpeg", "image/jpeg" ); contentTypes.put( "jpg", "image/jpeg" ); contentTypes.put( "js", "text/javascript" ); contentTypes.put( "jsf", "text/plain" ); contentTypes.put( "jspf", "text/plain" ); contentTypes.put( "kar", "audio/x-midi" ); contentTypes.put( "latex", "application/x-latex" ); contentTypes.put( "m3u", "audio/x-mpegurl" ); contentTypes.put( "mac", "image/x-macpaint" ); contentTypes.put( "man", "application/x-troff-man" ); contentTypes.put( "mathml", "application/mathml+xml" ); contentTypes.put( "me", "application/x-troff-me" ); contentTypes.put( "mid", "audio/x-midi" ); contentTypes.put( "midi", "audio/x-midi" ); contentTypes.put( "mif", "application/x-mif" ); contentTypes.put( "mov", "video/quicktime" ); contentTypes.put( "movie", "video/x-sgi-movie" ); contentTypes.put( "mp1", "audio/x-mpeg" ); contentTypes.put( "mp2", "audio/x-mpeg" ); contentTypes.put( "mp3", "audio/x-mpeg" ); contentTypes.put( "mp4", "video/mp4" ); contentTypes.put( "mpa", "audio/x-mpeg" ); contentTypes.put( "mpe", "video/mpeg" ); contentTypes.put( "mpeg", "video/mpeg" ); contentTypes.put( "mpega", "audio/x-mpeg" ); contentTypes.put( "mpg", "video/mpeg" ); contentTypes.put( "mpv2", "video/mpeg2" ); contentTypes.put( "ms", "application/x-wais-source" ); contentTypes.put( "nc", "application/x-netcdf" ); contentTypes.put( "oda", "application/oda" ); contentTypes.put( "odb", "application/vnd.oasis.opendocument.database" ); contentTypes.put( "odc", "application/vnd.oasis.opendocument.chart" ); contentTypes.put( "odf", "application/vnd.oasis.opendocument.formula" ); contentTypes.put( "odg", "application/vnd.oasis.opendocument.graphics" ); contentTypes.put( "odi", "application/vnd.oasis.opendocument.image" ); contentTypes.put( "odm", "application/vnd.oasis.opendocument.text-master" ); contentTypes.put( "odp", "application/vnd.oasis.opendocument.presentation" ); contentTypes.put( "ods", "application/vnd.oasis.opendocument.spreadsheet" ); contentTypes.put( "odt", "application/vnd.oasis.opendocument.text" ); contentTypes.put( "ogg", "application/ogg" ); contentTypes.put( "otg", "application/vnd.oasis.opendocument.graphics-template" ); contentTypes.put( "oth", "application/vnd.oasis.opendocument.text-web" ); contentTypes.put( "otp", "application/vnd.oasis.opendocument.presentation-template" ); contentTypes.put( "ots", "application/vnd.oasis.opendocument.spreadsheet-template" ); contentTypes.put( "ott", "application/vnd.oasis.opendocument.text-template" ); contentTypes.put( "pbm", "image/x-portable-bitmap" ); contentTypes.put( "pct", "image/pict" ); contentTypes.put( "pdf", "application/pdf" ); contentTypes.put( "pgm", "image/x-portable-graymap" ); contentTypes.put( "pic", "image/pict" ); contentTypes.put( "pict", "image/pict" ); contentTypes.put( "pls", "audio/x-scpls" ); contentTypes.put( "png", "image/png" ); contentTypes.put( "pnm", "image/x-portable-anymap" ); contentTypes.put( "pnt", "image/x-macpaint" ); contentTypes.put( "ppm", "image/x-portable-pixmap" ); contentTypes.put( "ppt", "application/vnd.ms-powerpoint" ); contentTypes.put( "pps", "application/vnd.ms-powerpoint" ); contentTypes.put( "ps", "application/postscript" ); contentTypes.put( "psd", "image/x-photoshop" ); contentTypes.put( "qt", "video/quicktime" ); contentTypes.put( "qti", "image/x-quicktime" ); contentTypes.put( "qtif", "image/x-quicktime" ); contentTypes.put( "ras", "image/x-cmu-raster" ); contentTypes.put( "rdf", "application/rdf+xml" ); contentTypes.put( "rgb", "image/x-rgb" ); contentTypes.put( "rm", "application/vnd.rn-realmedia" ); contentTypes.put( "roff", "application/x-troff" ); contentTypes.put( "rtf", "application/rtf" ); contentTypes.put( "rtx", "text/richtext" ); contentTypes.put( "sh", "application/x-sh" ); contentTypes.put( "shar", "application/x-shar" ); contentTypes.put( "smf", "audio/x-midi" ); contentTypes.put( "sit", "application/x-stuffit" ); contentTypes.put( "snd", "audio/basic" ); contentTypes.put( "src", "application/x-wais-source" ); contentTypes.put( "sv4cpio", "application/x-sv4cpio" ); contentTypes.put( "sv4crc", "application/x-sv4crc" ); contentTypes.put( "svg", "image/svg+xml" ); contentTypes.put( "svgz", "image/svg+xml" ); contentTypes.put( "swf", "application/x-shockwave-flash" ); contentTypes.put( "t", "application/x-troff" ); contentTypes.put( "tar", "application/x-tar" ); contentTypes.put( "tcl", "application/x-tcl" ); contentTypes.put( "tex", "application/x-tex" ); contentTypes.put( "texi", "application/x-texinfo" ); contentTypes.put( "texinfo", "application/x-texinfo" ); contentTypes.put( "tif", "image/tiff" ); contentTypes.put( "tiff", "image/tiff" ); contentTypes.put( "tr", "application/x-troff" ); contentTypes.put( "tsv", "text/tab-separated-values" ); contentTypes.put( "txt", "text/plain" ); contentTypes.put( "ulw", "audio/basic" ); contentTypes.put( "ustar", "application/x-ustar" ); contentTypes.put( "vxml", "application/voicexml+xml" ); contentTypes.put( "xbm", "image/x-xbitmap" ); contentTypes.put( "xht", "application/xhtml+xml" ); contentTypes.put( "xhtml", "application/xhtml+xml" ); contentTypes.put( "xls", "application/vnd.ms-excel" ); contentTypes.put( "xml", "application/xml" ); contentTypes.put( "xpm", "image/x-xpixmap" ); contentTypes.put( "xsl", "application/xml" ); contentTypes.put( "xslt", "application/xslt+xml" ); contentTypes.put( "xul", "application/vnd.mozilla.xul+xml" ); contentTypes.put( "xwd", "image/x-xwindowdump" ); contentTypes.put( "vsd", "application/x-visio" ); contentTypes.put( "wav", "audio/x-wav" ); contentTypes.put( "wbmp", "image/vnd.wap.wbmp" ); contentTypes.put( "wml", "text/vnd.wap.wml" ); contentTypes.put( "wmlc", "application/vnd.wap.wmlc" ); contentTypes.put( "wmls", "text/vnd.wap.wmlscript" ); contentTypes.put( "wmlscriptc", "application/vnd.wap.wmlscriptc" ); contentTypes.put( "wmv", "video/x-ms-wmv" ); contentTypes.put( "wrl", "x-world/x-vrml" ); contentTypes.put( "wspolicy", "application/wspolicy+xml" ); contentTypes.put( "Z", "application/x-compress" ); contentTypes.put( "z", "application/x-compress" ); contentTypes.put( "zip", "application/zip" ); } /** * Provides static files as they are in the File System. */ @Override protected void get( final Request request, final Response response ) throws IOException { File requested = new File( baseDir, request.getPath() ); if ( !requested.exists() ) { response.setStatus( NOT_FOUND ); return; } if ( requested.isDirectory() ) { requested = new File( requested, "index.html" ); } if ( requested.exists() ) { response.setBody( new FileResponseBodyWriter( requested ) ); String contentType = getContentType( requested ); if ( contentType != null ) { response.addHeader( CONTENT_TYPE, contentType ); } } else { response.setStatus( NOT_FOUND ); return; } } /** * Retrieves the input file Content-Type, depending on the file name extension. * * @param file the file for which the content type has to be retrieved. * @return the input file content type, null if not found. */ private String getContentType( File file ) { int extensionSeparator = file.getName().lastIndexOf( '.' ); String extension = file.getName().substring( ++extensionSeparator ); return contentTypes.get( extension ); } }
package org.osiam.shell.command.update; import java.io.IOException; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.client.query.QueryBuilder; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.SCIMSearchResult; import org.osiam.resources.scim.UpdateGroup; import org.osiam.resources.scim.User; import org.osiam.shell.command.AbstractBuilderCommand; import de.raysha.lib.jsimpleshell.Shell; import de.raysha.lib.jsimpleshell.ShellBuilder; import de.raysha.lib.jsimpleshell.ShellDependent; import de.raysha.lib.jsimpleshell.annotation.Command; import de.raysha.lib.jsimpleshell.annotation.Param; import de.raysha.lib.jsimpleshell.io.OutputBuilder; import de.raysha.lib.jsimpleshell.io.OutputDependent; /** * This class contains commands that can update groups. * * @author rainu */ public class UpdateGroupCommand implements ShellDependent, OutputDependent { private AccessToken accessToken; private final OsiamConnector connector; private Shell shell; private OutputBuilder output; public UpdateGroupCommand(AccessToken at, OsiamConnector connector) { this.accessToken = at; this.connector = connector; } @Override public void cliSetShell(Shell theShell) { this.shell = theShell; } @Override public void cliSetOutput(OutputBuilder output) { this.output = output; } @Command(description = "Update the given group.") public Object updateGroup( @Param(name = "groupName", description = "The name of the group.") String groupName) throws IOException{ final Group group = getGroup(groupName); if(group == null) return "There is no group with the name \"" + groupName + "\"!"; final UpdateGroupBuilder builder = new UpdateGroupBuilder(group); final Shell subShell = ShellBuilder.subshell("update-group", shell) .addHandler(builder) .build(); output.out() .normal("In this subshell you can edit the group. Leave this sub shell via \"commit\" to persist the changes.") .println(); subShell.commandLoop(); final UpdateGroup update = builder.build(); if(update == null) return null; return connector.updateGroup(group.getId(), update, accessToken); } protected Group getGroup(String groupName) { final Query query = new QueryBuilder().filter("displayName eq \"" + groupName + "\"").build(); final SCIMSearchResult<Group> result = connector.searchGroups(query, accessToken); if (result.getTotalResults() > 0) { return result.getResources().get(0); } return null; } public class UpdateGroupBuilder extends AbstractBuilderCommand<UpdateGroup> { private final Group group; private UpdateGroup.Builder builder = new UpdateGroup.Builder(); public UpdateGroupBuilder(Group group) { this.group = group; } @Command(description = "Shows the current (persited) group that will be updated.") public Group showGroup(){ return group; } @Command(description = "Shows the group state. This state is not persisted yet!") public Group showState(){ return build().getScimConformUpdateGroup(); } @Command(description = "Add the given user to the given group.") public String addUser( @Param(name = "userName", description = "The name of the user.") String userName){ final User user = getUser(userName); if(user == null) return "There is no user with the name \"" + userName + "\"!"; builder.addMember(user.getId()); return null; } @Command(description = "Remove the given user from the given group.") public String removeUser( @Param(name = "userName", description = "The name of the user.") String userName){ final User user = getUser(userName); if(user == null) return "There is no user with the name \"" + userName + "\"!"; builder.deleteMember(user.getId()); return null; } @Command(description = "Remove all members from the given group.") public void removeAll(){ builder.deleteMembers(); } @Command(description = "Remove the given user from the given group.") public void rename( @Param(name = "name", description = "The new group display name.") String newName){ builder.updateDisplayName(newName); } @Command(description = "Set the externalId for the group.") public void setExternalId( @Param(name = "externalId", description = "The new externalId for the group.") String externalId){ builder.updateExternalId(externalId); } private User getUser(String userName) { final Query query = new QueryBuilder().filter("userName eq \"" + userName + "\"").build(); final SCIMSearchResult<User> result = connector.searchUsers(query, accessToken); if (result.getTotalResults() > 0) { return result.getResources().get(0); } return null; } @Override protected UpdateGroup _build() { return builder.build(); } } }
package org.sejda.impl.itext5.component; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.sejda.impl.itext5.util.TransitionUtils.getTransition; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.io.IOUtils; import org.sejda.core.Sejda; import org.sejda.model.exception.TaskException; import org.sejda.model.exception.TaskIOException; import org.sejda.model.pdf.PdfMetadataKey; import org.sejda.model.pdf.PdfVersion; import org.sejda.model.pdf.transition.PdfPageTransition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfObject; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfStream; import com.itextpdf.text.pdf.PdfTransition; /** * Component responsible for handling operations related to a {@link PdfStamper} instance. * * @author Andrea Vacondio * */ public final class PdfStamperHandler implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(PdfStamperHandler.class); private PdfStamper stamper = null; private FileOutputStream ouputStream = null; /** * Creates a new instance initializing the inner {@link PdfStamper} instance. * * @param reader * input reader * @param ouputFile * {@link File} to stamp on * @param version * version for the created stamper, if null the version number is taken from the input {@link PdfReader} * @throws TaskException * in case of error */ public PdfStamperHandler(PdfReader reader, File ouputFile, PdfVersion version) throws TaskException { try { ouputStream = new FileOutputStream(ouputFile); if (version != null) { stamper = new PdfStamper(reader, ouputStream, version.getVersionAsCharacter()); } else { stamper = new PdfStamper(reader, ouputStream); } Map<String, String> meta = reader.getInfo(); meta.put(PdfMetadataKey.CREATOR.getKey(), Sejda.CREATOR); stamper.setMoreInfo(meta); } catch (DocumentException e) { throw new TaskException("An error occurred opening the PdfStamper.", e); } catch (IOException e) { throw new TaskIOException("An IO error occurred opening the PdfStamper.", e); } } /** * Enables compression if compress is true * * @param compress * @throws TaskException */ public void setCompression(boolean compress, PdfReader reader) throws TaskException { if (compress) { try { stamper.getWriter().setCompressionLevel(PdfStream.BEST_COMPRESSION); int total = reader.getNumberOfPages() + 1; for (int i = 1; i < total; i++) { reader.setPageContent(i, reader.getPageContent(i)); } stamper.setFullCompression(); } catch (DocumentException de) { throw new TaskException("Unable to set compression on stamper", de); } catch (IOException e) { throw new TaskException("Unable to set compression on stamper", e); } } } public void close() throws IOException { try { stamper.close(); } catch (DocumentException e) { LOG.error("Error closing the PdfStamper.", e); } IOUtils.closeQuietly(ouputStream); } /** * Adds the input set of metadata to the info dictionary that will be written by the {@link PdfStamper} * * @param meta */ public void setMetadata(Set<Entry<PdfMetadataKey, String>> meta) { Map<String, String> info = stamper.getMoreInfo(); for (Entry<PdfMetadataKey, String> current : meta) { LOG.trace("'{}' -> '{}'", current.getKey().getKey(), current.getValue()); info.put(current.getKey().getKey(), current.getValue()); } } public void setEncryption(int encryptionType, String userPassword, String ownerPassword, int permissions) throws TaskException { try { if (isBlank(ownerPassword)) { LOG.warn("Owner password not specified, using the user password as per Pdf reference 1.7, Chap. 3.5.2, Algorithm 3.3, Step 1."); stamper.setEncryption(encryptionType, userPassword, userPassword, permissions); } else { stamper.setEncryption(encryptionType, userPassword, ownerPassword, permissions); } } catch (DocumentException e) { throw new TaskException("An error occured while setting encryption on the document", e); } } /** * Applies the given transition to the given page. * * @param page * @param transition */ public void setTransition(Integer page, PdfPageTransition transition) { Integer transitionStyle = getTransition(transition.getStyle()); if (transitionStyle != null) { stamper.setDuration(transition.getDisplayDuration(), page); stamper.setTransition(new PdfTransition(transitionStyle, transition.getTransitionDuration()), page); } else { LOG.warn("Transition {} not applied to page {}. Not supported by iText.", transition.getStyle(), page); } } /** * Sets the viewer preferences on the stamper * * @see PdfStamper#setViewerPreferences(int) * @param preferences */ public void setViewerPreferences(int preferences) { stamper.setViewerPreferences(preferences); } /** * adds the viewer preferences to the stamper * * @see PdfStamper#addViewerPreference(PdfName, PdfObject) * @param preferences * a map of preferences with corresponding value to be set on the documents */ public void addViewerPreferences(Map<PdfName, PdfObject> preferences) { for (Entry<PdfName, PdfObject> entry : preferences.entrySet()) { stamper.addViewerPreference(entry.getKey(), entry.getValue()); } } /** * * @return the inner {@link PdfStamper} instance */ public PdfStamper getStamper() { return stamper; } }
package org.threadly.concurrent; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Delayed; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import org.threadly.concurrent.lock.LockFactory; import org.threadly.concurrent.lock.TestableLock; import org.threadly.concurrent.lock.VirtualLock; import org.threadly.util.Clock; import org.threadly.util.ListUtils; /** * Scheduler which is designed to be used during unit testing. * Although it actually runs multiple threads, it only has one * thread actively executing at a time (thus simulating single threaded). * * The scheduler uses .awaits() and .sleep()'s to TestableLock's as opportunities * to simulate multiple threads. When you call .tick() you progress forward * externally scheduled threads, or possibly threads which are sleeping. * * @author jent - Mike Jensen */ public class TestablePriorityScheduler implements PrioritySchedulerInterface, LockFactory { private final Executor executor; private final TaskPriority defaultPriority; private final LinkedList<RunnableContainer> taskQueue; private final Map<TestableLock, NotifyObject> waitingThreads; private final Object queueLock; private final Object tickLock; private final BlockingQueue<Object> threadQueue; private volatile int waitingForThreadCount; private volatile Object runningLock; private long nowInMillis; /** * Constructs a new TestablePriorityScheduler with the backed thread pool. * Because this only simulates threads running in a single threaded way, * it must have a sufficiently large thread pool to back that. * * @param scheduler Scheduler which will be used to execute new threads are necessary */ public TestablePriorityScheduler(PriorityScheduledExecutor scheduler) { this(scheduler, scheduler.getDefaultPriority()); } /** * Constructs a new TestablePriorityScheduler with the backed thread pool. * Because this only simulates threads running in a single threaded way, * it must have a sufficiently large thread pool to back that. * * @param executor Executor which will be used to execute new threads are necessary * @param defaultPriority Default priority for tasks where it is not provided */ public TestablePriorityScheduler(Executor executor, TaskPriority defaultPriority) { if (executor == null) { throw new IllegalArgumentException("Must provide backing scheduler"); } if (defaultPriority == null) { defaultPriority = PriorityScheduledExecutor.GLOBAL_DEFAULT_PRIORITY; } this.executor = executor; this.defaultPriority = defaultPriority; taskQueue = new LinkedList<RunnableContainer>(); waitingThreads = new HashMap<TestableLock, NotifyObject>(); queueLock = new Object(); tickLock = new Object(); threadQueue = new ArrayBlockingQueue<Object>(1, true); threadQueue.offer(new Object()); waitingForThreadCount = 0; runningLock = null; nowInMillis = Clock.accurateTime(); } @Override public void execute(Runnable task) { schedule(task, 0, defaultPriority); } @Override public void execute(Runnable task, TaskPriority priority) { schedule(task, 0, priority); } @Override public void schedule(Runnable task, long delayInMs) { schedule(task, delayInMs, defaultPriority); } @Override public void schedule(Runnable task, long delayInMs, TaskPriority priority) { add(new OneTimeRunnable(task, delayInMs, priority)); } @Override public void scheduleWithFixedDelay(Runnable task, long initialDelay, long recurringDelay) { scheduleWithFixedDelay(task, initialDelay, recurringDelay, defaultPriority); } @Override public void scheduleWithFixedDelay(Runnable task, long initialDelay, long recurringDelay, TaskPriority priority) { add(new RecurringRunnable(task, initialDelay, recurringDelay, priority)); } private void add(RunnableContainer runnable) { synchronized (queueLock) { int insertionIndex = ListUtils.getInsertionEndIndex(taskQueue, runnable); taskQueue.add(insertionIndex, runnable); } } @Override public boolean isShutdown() { return false; } private void wantToRun(boolean mainThread, Runnable runBeforeBlocking) { synchronized (tickLock) { System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " waiting for thread count: " + waitingForThreadCount); waitingForThreadCount++; if (runBeforeBlocking != null) { runBeforeBlocking.run(); } while (mainThread && waitingForThreadCount > 1) { System.out.println(System.nanoTime() + " - waiting for other threads: " + waitingForThreadCount); // give others a chance try { tickLock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (mainThread) { System.out.println(System.nanoTime() + " - other threads now finished"); } } try { System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " attempting to take runningLock"); Object runningLock = threadQueue.take(); System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " thread now has lock"); if (this.runningLock != null) { throw new IllegalStateException("Running lock already set: " + this.runningLock); } else { this.runningLock = runningLock; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private void yielding() { if (runningLock == null) { throw new IllegalStateException("No running lock to provide"); } synchronized (tickLock) { System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " decrementing waiting count"); waitingForThreadCount tickLock.notify(); } Object runningLock = this.runningLock; this.runningLock = null; System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " returning runningLock"); threadQueue.offer(runningLock); System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " lock now returned"); } /** * This ticks forward one step based off the current time of calling. * It runs as many events are ready for the time provided, and will block * until all those events have completed (or are waiting or sleeping). * * @return qty of steps taken forward. Returns zero if no events to run. */ public int tick() { return tick(Clock.accurateTime()); } /** * This ticks forward one step based off the current time of calling. * It runs as many events are ready for the time provided, and will block * until all those events have completed (or are waiting or sleeping). * * @param currentTime time reference for the scheduler to use to look for waiting events * @return qty of steps taken forward. Returns zero if no events to run for provided time. */ public int tick(long currentTime) { System.out.println(System.nanoTime() + " - " + "Tick called with time: " + currentTime); if (currentTime < nowInMillis) { throw new IllegalArgumentException("Can not go backwards in time"); } wantToRun(true, null); nowInMillis = currentTime; int ranTasks = 0; RunnableContainer nextTask = getNextTask(currentTime); while (nextTask != null) { ranTasks++; try { handleTask(nextTask); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } nextTask = getNextTask(currentTime); } // we must yield right before we return so next tick can run yielding(); // TODO - remove check /*try { Thread.sleep(10); } catch (InterruptedException e) { // ignored }*/ if (threadQueue.size() != 1) { throw new IllegalStateException(System.nanoTime() + " - Someone took the lock before we returned: " + threadQueue.size() + " - " + waitingForThreadCount); } else if (waitingForThreadCount != 0) { throw new IllegalStateException(System.nanoTime() + " - Still threads waiting to run: " + waitingForThreadCount); } return ranTasks; } private RunnableContainer getNextTask(long nowInMs) { synchronized (queueLock) { RunnableContainer firstResult = null; long nextDelay = Long.MIN_VALUE; Iterator<RunnableContainer> it = taskQueue.iterator(); while (it.hasNext() && nextDelay <= 0) { RunnableContainer next = it.next(); nextDelay = next.getDelay(TimeUnit.MILLISECONDS); if (nextDelay <= 0) { if (firstResult == null) { if (next.priority == TaskPriority.Low) { firstResult = next; } else { it.remove(); return next; } } else if (next.priority == TaskPriority.High) { it.remove(); return next; } } } if (firstResult != null) { taskQueue.removeFirst(); } return firstResult; } } private void handleTask(RunnableContainer nextTask) throws InterruptedException { System.out.println(System.nanoTime() + " - " + "Handling task: " + nextTask + " - " + nextTask.runnable); nextTask.prepareForExcute(); executor.execute(nextTask); yielding(); // yield to new task nextTask.blockTillStarted(); wantToRun(true, null); // wait till we can run again } @Override public VirtualLock makeLock() { return new TestableLock(this); } /** * should only be called from TestableVirtualLock * * @param lock lock referencing calling into scheduler * @throws InterruptedException */ @SuppressWarnings("javadoc") public void waiting(TestableLock lock) throws InterruptedException { NotifyObject no = waitingThreads.get(lock); if (no == null) { no = new NotifyObject(lock); waitingThreads.put(lock, no); } no.yield(); } /** * should only be called from TestableVirtualLock * * @param lock lock referencing calling into scheduler * @param waitTimeInMs time to wait on lock * @throws InterruptedException */ @SuppressWarnings("javadoc") public void waiting(final TestableLock lock, long waitTimeInMs) throws InterruptedException { final boolean[] notified = new boolean[] { false }; // schedule runnable to wake up in case not signaled schedule(new Runnable() { @Override public void run() { if (! notified[0]) { signal(lock); } } }, waitTimeInMs); waiting(lock); notified[0] = true; } /** * should only be called from TestableVirtualLock * * @param lock lock referencing calling into scheduler */ public void signal(TestableLock lock) { NotifyObject no = waitingThreads.get(lock); if (no != null) { // schedule task to wake up other thread add(new WakeUpThread(no, false, 0)); } } /** * should only be called from TestableVirtualLock * * @param lock lock referencing calling into scheduler */ public void signalAll(TestableLock lock) { NotifyObject no = waitingThreads.get(lock); if (no != null) { // schedule task to wake up other thread add(new WakeUpThread(no, true, 0)); } } /** * should only be called from TestableVirtualLock or * the running thread inside the scheduler * * @param sleepTime time for thread to sleep * @throws InterruptedException */ @SuppressWarnings("javadoc") public void sleep(long sleepTime) throws InterruptedException { NotifyObject sleepLock = new NotifyObject(new Object()); add(new WakeUpThread(sleepLock, false, sleepTime)); System.out.println(System.nanoTime() + " - " + Thread.currentThread() + " about to sleep on: " + sleepLock); sleepLock.yield(); } @Override public TaskPriority getDefaultPriority() { return defaultPriority; } private abstract class RunnableContainer implements Runnable, Delayed { protected final Runnable runnable; protected final TaskPriority priority; protected final Exception creationStack; private volatile boolean running; protected RunnableContainer(Runnable runnable, TaskPriority priority) { this.runnable = runnable; this.priority = priority; creationStack = new Exception(); running = false; } public void blockTillStarted() { while (! running) { // spin } } public void prepareForExcute() { running = false; } @Override public void run() { wantToRun(false, null); // must become running thread running = true; try { run(TestablePriorityScheduler.this); } finally { handleDone(); } } protected void handleDone() { yielding(); } @Override public int compareTo(Delayed o) { if (this == o) { return 0; } else { long thisDelay = this.getDelay(TimeUnit.MILLISECONDS); long otherDelay = o.getDelay(TimeUnit.MILLISECONDS); if (thisDelay == otherDelay) { return 0; } else if (thisDelay > otherDelay) { return 1; } else { return -1; } } } public abstract void run(LockFactory scheduler); } private class OneTimeRunnable extends RunnableContainer { private final long runTime; private OneTimeRunnable(Runnable runnable, long delay, TaskPriority priority) { super(runnable, priority); this.runTime = nowInMillis + delay; } @Override public void run(LockFactory scheduler) { System.out.println(System.nanoTime() + " - " + "Starting: " + this + " - " + runnable); //creationStack.printStackTrace(); if (runnable instanceof VirtualRunnable) { ((VirtualRunnable)runnable).run(scheduler); } else { runnable.run(); } } @Override public long getDelay(TimeUnit timeUnit) { return timeUnit.convert(runTime - nowInMillis, TimeUnit.MILLISECONDS); } } private class RecurringRunnable extends RunnableContainer { private final long recurringDelay; private long nextRunTime; public RecurringRunnable(Runnable runnable, long initialDelay, long recurringDelay, TaskPriority priority) { super(runnable, priority); this.recurringDelay = recurringDelay; nextRunTime = nowInMillis + initialDelay; } @Override public void run(LockFactory scheduler) { System.out.println("Starting: " + this); //creationStack.printStackTrace(); try { if (runnable instanceof VirtualRunnable) { ((VirtualRunnable)runnable).run(scheduler); } else { runnable.run(); } } finally { nextRunTime = nowInMillis + recurringDelay; synchronized (queueLock) { taskQueue.add(this); } } } @Override public long getDelay(TimeUnit timeUnit) { return timeUnit.convert(nextRunTime - nowInMillis, TimeUnit.MILLISECONDS); } } private class WakeUpThread extends OneTimeRunnable { private WakeUpThread(final NotifyObject lock, final boolean notifyAll, long delay) { super(new Runnable() { @Override public void run() { if (notifyAll) { lock.wakeUpAll(); } else { lock.wakeUp(); } try { lock.waitForWantingToRun(); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } yielding(); try { lock.waitForWakeup(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }, delay, TaskPriority.High); } @Override protected void handleDone() { // prevent yield call in super class, since we already yielded } } private class NotifyObject { private final Object obj; private volatile boolean wantingToRun; private boolean awake; private NotifyObject(Object obj) { this.obj = obj; wantingToRun = false; awake = false; } public void wakeUpAll() { synchronized (obj) { obj.notifyAll(); } } public void wakeUp() { synchronized (obj) { obj.notify(); } } public void waitForWantingToRun() throws InterruptedException { while (! wantingToRun) { // spin } } public void waitForWakeup() throws InterruptedException { synchronized (this) { while (! awake) { this.wait(); } } } public void yield() throws InterruptedException { synchronized (this) { synchronized (obj) { try { awake = false; wantingToRun = false; yielding(); obj.wait(); } finally { wantToRun(false, new Runnable() { @Override public void run() { wantingToRun = true; } }); awake = true; this.notify(); } } } } } }
package permafrost.tundra.tn.delivery; import com.wm.app.b2b.server.InvokeState; import com.wm.app.b2b.server.Service; import com.wm.app.b2b.server.ServiceException; import com.wm.app.b2b.server.Session; import com.wm.app.tn.db.Datastore; import com.wm.app.tn.db.QueueOperations; import com.wm.app.tn.db.SQLWrappers; import com.wm.app.tn.delivery.DeliveryQueue; import com.wm.app.tn.delivery.GuaranteedJob; import com.wm.app.tn.doc.BizDocEnvelope; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataUtil; import com.wm.lang.ns.NSName; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.lang.ExceptionHelper; import permafrost.tundra.server.ServerThreadFactory; import permafrost.tundra.tn.document.BizDocEnvelopeHelper; import permafrost.tundra.tn.profile.ProfileCache; import permafrost.tundra.util.concurrent.BlockingRejectedExecutionHandler; import permafrost.tundra.util.concurrent.DirectExecutorService; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * A collection of convenience methods for working with Trading Networks delivery queues. */ public class DeliveryQueueHelper { /** * SQL statement to select head of a delivery queue in job creation datetime order. */ private static final String SELECT_NEXT_DELIVERY_JOB_ORDERED_SQL = "SELECT JobID FROM DeliveryJob WHERE QueueName = ? AND JobStatus = 'QUEUED' AND TimeCreated = (SELECT MIN(TimeCreated) FROM DeliveryJob WHERE QueueName = ? AND JobStatus = 'QUEUED') AND TimeUpdated <= ?"; /** * SQL statement to select head of a delivery queue in indeterminate order. */ private static final String SELECT_NEXT_DELIVERY_JOB_UNORDERED_SQL = "SELECT JobID FROM DeliveryJob WHERE QueueName = ? AND JobStatus = 'QUEUED' AND TimeCreated = (SELECT MIN(TimeCreated) FROM DeliveryJob WHERE QueueName = ? AND JobStatus = 'QUEUED' AND TimeUpdated <= ?)"; /** * The name of the service that Trading Networks uses to invoke delivery queue processing services. */ private static final String DELIVER_BATCH_SERVICE_NAME = "wm.tn.queuing:deliverBatch"; /** * The name of the service used to update the completion status of a delivery queue job. */ private static final NSName UPDATE_QUEUED_TASK_SERVICE_NAME = NSName.create("wm.tn.queuing:updateQueuedTask"); /** * The name of the service used to update a delivery queue. */ private static final NSName UPDATE_QUEUE_SERVICE_NAME = NSName.create("wm.tn.queuing:updateQueue"); /** * How long to wait between each poll of a delivery queue for more jobs. */ private static final long WAIT_BETWEEN_DELIVERY_QUEUE_POLLS_MILLISECONDS = 50; /** * How long to wait for an executor to shut down or terminate. */ private static final long EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS = 60; /** * Disallow instantiation of this class. */ private DeliveryQueueHelper() {} /** * Returns the Trading Networks delivery queue associated with the given name. * * @param queueName The name of the queue to return. * @return The delivery queue with the given name. * @throws ServiceException If a database error occurs. */ public static DeliveryQueue get(String queueName) throws ServiceException { if (queueName == null) return null; DeliveryQueue queue = null; try { queue = QueueOperations.selectByName(queueName); } catch(SQLException ex) { ExceptionHelper.raise(ex); } catch(IOException ex) { ExceptionHelper.raise(ex); } return queue; } /** * Refreshes the given Trading Networks delivery queue from the database. * * @param queue The queue to be refreshed. * @return The given queue, refreshed from the database. * @throws ServiceException If a database error occurs. */ public static DeliveryQueue refresh(DeliveryQueue queue) throws ServiceException { return get(queue.getQueueName()); } /** * Returns a list of all registered Trading Networks delivery queues. * * @return A list of all registered Trading Networks delivery queues. * @throws ServiceException If a database error occurs. */ public static DeliveryQueue[] list() throws ServiceException { DeliveryQueue[] output = null; try { output = QueueOperations.select(null); } catch(SQLException ex) { ExceptionHelper.raise(ex); } catch(IOException ex) { ExceptionHelper.raise(ex); } return output; } /** * Enables the delivery of the given Trading Networks delivery queue. * * @param queue The queue to enable delivery on. * @throws ServiceException If a database error occurs. */ public static void enable(DeliveryQueue queue) throws ServiceException { if (queue == null) return; queue.setState(DeliveryQueue.STATE_ENABLED); save(queue); } /** * Disables the delivery of the given Trading Networks delivery queue. * * @param queue The queue to enable delivery on. * @throws ServiceException If a database error occurs. */ public static void disable(DeliveryQueue queue) throws ServiceException { if (queue == null) return; queue.setState(DeliveryQueue.STATE_DISABLED); save(queue); } /** * Drains the delivery of the given Trading Networks delivery queue. * * @param queue The queue to enable delivery on. * @throws ServiceException If a database error occurs. */ public static void drain(DeliveryQueue queue) throws ServiceException { if (queue == null) return; queue.setState(DeliveryQueue.STATE_DRAINING); save(queue); } /** * Suspends the delivery of the given Trading Networks delivery queue. * * @param queue The queue to enable delivery on. * @throws ServiceException If a database error occurs. */ public static void suspend(DeliveryQueue queue) throws ServiceException { if (queue == null) return; queue.setState(DeliveryQueue.STATE_SUSPENDED); save(queue); } /** * Returns the number of jobs currently queued in the given Trading Networks delivery queue. * * @param queue The queue to return the length of. * @return The length of the given queue, which is the number of delivery jobs with a status * of QUEUED or DELIVERING. * @throws ServiceException If a database error occurs. */ public static int length(DeliveryQueue queue) throws ServiceException { int length = 0; if (queue != null) { try { String[] jobs = QueueOperations.getQueuedJobs(queue.getQueueName()); if (jobs != null) length = jobs.length; } catch(SQLException ex) { ExceptionHelper.raise(ex); } } return length; } /** * Updates the given Trading Networks delivery queue with any changes that may have occurred. * * @param queue The queue whose changes are to be saved. * @throws ServiceException If a database error occurs. */ public static void save(DeliveryQueue queue) throws ServiceException { if (queue == null) return; try { IData pipeline = IDataFactory.create(); IDataCursor cursor = pipeline.getCursor(); IDataUtil.put(cursor, "queue", queue); cursor.destroy(); Service.doInvoke(UPDATE_QUEUE_SERVICE_NAME, pipeline); } catch(Exception ex) { ExceptionHelper.raise(ex); } } /** * Returns the head of the given delivery queue without dequeuing it. * * @param queue The delivery queue whose head job is to be returned. * @param ordered Whether jobs should be dequeued in strict creation datetime first in first out (FIFO) order. * @return The job at the head of the given queue, or null if the queue is empty. * @throws ServiceException */ public static GuaranteedJob peek(DeliveryQueue queue, boolean ordered) throws ServiceException { if (queue == null) return null; Connection connection = null; PreparedStatement statement = null; ResultSet results = null; GuaranteedJob job = null; try { connection = Datastore.getConnection(); statement = connection.prepareStatement(ordered ? SELECT_NEXT_DELIVERY_JOB_ORDERED_SQL : SELECT_NEXT_DELIVERY_JOB_UNORDERED_SQL); statement.clearParameters(); String queueName = queue.getQueueName(); SQLWrappers.setChoppedString(statement, 1, queueName, "DeliveryQueue.QueueName"); SQLWrappers.setChoppedString(statement, 2, queueName, "DeliveryQueue.QueueName"); SQLWrappers.setTimestamp(statement, 3, new Timestamp(new Date().getTime())); results = statement.executeQuery(); if (results.next()) { String id = results.getString(1); job = GuaranteedJobHelper.get(id); } connection.commit(); } catch (SQLException ex) { connection = Datastore.handleSQLException(connection, ex); ExceptionHelper.raise(ex); } finally { SQLWrappers.close(results); SQLWrappers.close(statement); Datastore.releaseConnection(connection); } return job; } /** * Dequeues the job at the head of the given delivery queue. * * @param queue The delivery queue to dequeue the head job from. * @param ordered Whether jobs should be dequeued in strict creation datetime first in first out (FIFO) order. * @return The dequeued job that was at the head of the given queue, or null if queue is empty. * @throws ServiceException If a database error is encountered. */ public static GuaranteedJob pop(DeliveryQueue queue, boolean ordered) throws ServiceException { GuaranteedJob job = peek(queue, ordered); GuaranteedJobHelper.setDelivering(job); return job; } /** * Callable for invoking a given service against a given job. */ private static class CallableGuaranteedJob implements Callable<IData> { /** * The job against which the service will be invoked. */ private GuaranteedJob job; /** * The delivery queue from which the job was dequeued. */ private DeliveryQueue queue; /** * The service to be invoked. */ private NSName service; /** * The pipeline the service is invoked with. */ private IData pipeline; /** * The session the service is invoked under. */ private Session session; /** * The retry settings to be used when retrying the job. */ private int retryLimit, retryFactor, timeToWait; /** * Whether the deliver queue should be suspended on retry exhaustion. */ private boolean suspend; /** * The time the job was dequeued. */ private long timeDequeued; /** * Creates a new CallableGuaranteedJob which when called invokes the given service against the given job. * * @param job The job to be processed. * @param service The service to be invoked to process the given job. * @param session The session used when invoking the given service. * @param pipeline The input pipeline used when invoking the given service. * @param retryLimit The number of retries this job should attempt. * @param retryFactor The factor used to extend the time to wait on each retry. * @param timeToWait The time in seconds to wait between each retry. * @param suspend Whether to suspend the delivery queue on job retry exhaustion. */ public CallableGuaranteedJob(DeliveryQueue queue, GuaranteedJob job, String service, Session session, IData pipeline, int retryLimit, int retryFactor, int timeToWait, boolean suspend) { this(queue, job, service == null ? null : NSName.create(service), session, pipeline, retryLimit, retryFactor, timeToWait, suspend); } /** * Creates a new CallableGuaranteedJob which when called invokes the given service against the given job. * * @param job The job to be processed. * @param service The service to be invoked to process the given job. * @param session The session used when invoking the given service. * @param pipeline The input pipeline used when invoking the given service. * @param retryLimit The number of retries this job should attempt. * @param retryFactor The factor used to extend the time to wait on each retry. * @param timeToWait The time in seconds to wait between each retry. * @param suspend Whether to suspend the delivery queue on job retry exhaustion. */ public CallableGuaranteedJob(DeliveryQueue queue, GuaranteedJob job, NSName service, Session session, IData pipeline, int retryLimit, int retryFactor, int timeToWait, boolean suspend) { if (queue == null) throw new NullPointerException("queue must not be null"); if (job == null) throw new NullPointerException("job must not be null"); if (service == null) throw new NullPointerException("service must not be null"); this.queue = queue; this.job = job; this.service = service; this.session = session; this.pipeline = pipeline == null ? IDataFactory.create() : IDataHelper.duplicate(pipeline); this.retryLimit = retryLimit; this.retryFactor = retryFactor; this.timeToWait = timeToWait; this.suspend = suspend; this.timeDequeued = System.currentTimeMillis(); } /** * Invokes the provided service with the provided pipeline and session against the job. * * @return The output pipeline returned by the invocation. * @throws Exception if the service encounters an error. */ public IData call() throws Exception { IData output = null; try { BizDocEnvelopeHelper.setStatus(job.getBizDocEnvelope(), null, "DEQUEUED"); GuaranteedJobHelper.log(job, "MESSAGE", "Processing", MessageFormat.format("Dequeued from {0} queue \"{1}\"", queue.getQueueType(), queue.getQueueName()), MessageFormat.format("Service \"{0}\" attempting to process document", service.getFullName())); GuaranteedJobHelper.setRetryStrategy(job, retryLimit, retryFactor, timeToWait); IDataCursor cursor = pipeline.getCursor(); IDataUtil.put(cursor, "$task", job); BizDocEnvelope bizdoc = job.getBizDocEnvelope(); if (bizdoc != null) { bizdoc = BizDocEnvelopeHelper.get(bizdoc.getInternalId(), true); IDataUtil.put(cursor, "bizdoc", bizdoc); IDataUtil.put(cursor, "sender", ProfileCache.getInstance().get(bizdoc.getSenderId())); IDataUtil.put(cursor, "receiver", ProfileCache.getInstance().get(bizdoc.getReceiverId())); } cursor.destroy(); output = Service.doInvoke(service, session, pipeline); setJobCompleted(output); } catch(Throwable ex) { setJobCompleted(output, ex); } return output; } /** * Sets the job as successfully completed. * * @param serviceOutput The output of the service used to process the job. * @throws Exception If a database error occurs. */ private void setJobCompleted(IData serviceOutput) throws Exception { setJobCompleted(serviceOutput, null); } /** * Sets the job as either successfully or unsuccessfully completed, depending on whether * and exception is provided. * * @param serviceOutput The output of the service used to process the job. * @param exception Optional exception encountered while processing the job. * @throws Exception If a database error occurs. */ private void setJobCompleted(IData serviceOutput, Throwable exception) throws Exception { IData input = IDataFactory.create(); IDataCursor cursor = input.getCursor(); IDataUtil.put(cursor, "taskid", job.getJobId()); IDataUtil.put(cursor, "queue", queue.getQueueName()); if (exception == null) { IDataUtil.put(cursor, "status", "success"); } else { IDataUtil.put(cursor, "status", "fail"); IDataUtil.put(cursor, "statusMsg", ExceptionHelper.getMessage(exception)); } IDataUtil.put(cursor, "timeDequeued", timeDequeued); if (serviceOutput != null) IDataUtil.put(cursor, "serviceOutput", serviceOutput); cursor.destroy(); Service.doInvoke(UPDATE_QUEUED_TASK_SERVICE_NAME, session, input); GuaranteedJobHelper.retry(job, suspend); } } /** * Dequeues each task on the given Trading Networks delivery queue, and processes the task using the given service * and input pipeline; if concurrency > 1, tasks will be processed by a thread pool whose size is equal to the * desired concurrency, otherwise they will be processed on the current thread. * * @param queueName The name of the delivery queue whose queued jobs are to be processed. * @param service The service to be invoked to process jobs on the given delivery queue. * @param pipeline The input pipeline used when invoking the given service. * @param concurrency If > 1, this is the number of threads used to process jobs simultaneously. * @param retryLimit The number of retries this job should attempt. * @param retryFactor The factor used to extend the time to wait on each retry. * @param timeToWait The time in seconds to wait between each retry. * @param ordered Whether delivery queue jobs should be processed in job creation datetime order. * @param suspend Whether to suspend the delivery queue on job retry exhaustion. * @throws ServiceException If an error is encountered while processing jobs. */ public static void each(String queueName, String service, IData pipeline, int concurrency, int retryLimit, int retryFactor, int timeToWait, boolean ordered, boolean suspend) throws ServiceException { if (queueName == null) throw new NullPointerException("queueName must not be null"); if (service == null) throw new NullPointerException("service must not be null"); DeliveryQueue queue = DeliveryQueueHelper.get(queueName); if (queue == null) throw new ServiceException("Queue '" + queueName + "' does not exist"); each(queue, NSName.create(service), pipeline, concurrency, retryLimit, retryFactor, timeToWait, ordered, suspend); } /** * Dequeues each task on the given Trading Networks delivery queue, and processes the task using the given service * and input pipeline; if concurrency > 1, tasks will be processed by a thread pool whose size is equal to the * desired concurrency, otherwise they will be processed on the current thread. * * @param queue The delivery queue whose queued jobs are to be processed. * @param service The service to be invoked to process jobs on the given delivery queue. * @param pipeline The input pipeline used when invoking the given service. * @param concurrency If > 1, this is the number of threads used to process jobs simultaneously. * @param retryLimit The number of retries this job should attempt. * @param retryFactor The factor used to extend the time to wait on each retry. * @param timeToWait The time in seconds to wait between each retry. * @param ordered Whether delivery queue jobs should be processed in job creation datetime order. * @param suspend Whether to suspend the delivery queue on job retry exhaustion. * @throws ServiceException If an error is encountered while processing jobs. */ public static void each(DeliveryQueue queue, NSName service, IData pipeline, int concurrency, int retryLimit, int retryFactor, int timeToWait, boolean ordered, boolean suspend) throws ServiceException { boolean invokedByTradingNetworks = invokedByTradingNetworks(); Session session = Service.getSession(); ExecutorService executor = getExecutor(queue, InvokeState.getCurrentState(), concurrency); Queue<Future<IData>> results = new LinkedList<Future<IData>>(); try { while(true) { if (!invokedByTradingNetworks || queue.isEnabled() || queue.isDraining()) { GuaranteedJob job = DeliveryQueueHelper.pop(queue, ordered); if (job == null) { // there are no jobs currently waiting on the queue if (results.size() > 0) { // wait for first job to finish or polling timeout, then loop again and see if there are now jobs on the queue awaitFirst(results, WAIT_BETWEEN_DELIVERY_QUEUE_POLLS_MILLISECONDS, TimeUnit.MILLISECONDS); } else { // if all threads have finished and there are no more jobs, then exit break; } } else { // submit the job to the executor to be processed results.add(executor.submit(new CallableGuaranteedJob(queue, job, service, session, pipeline, retryLimit, retryFactor, timeToWait, suspend))); } if (invokedByTradingNetworks) queue = DeliveryQueueHelper.refresh(queue); } else { break; // if invoked by TN and queue is disabled or suspended, then exit } } } catch (Throwable ex) { ExceptionHelper.raise(ex); } finally { try { executor.shutdown(); // wait a while for existing tasks to terminate if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { executor.shutdownNow(); // cancel currently executing tasks // wait a while for tasks to respond to being cancelled executor.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS); } } catch (InterruptedException ex) { // cancel if current thread also interrupted executor.shutdownNow(); // preserve interrupt status Thread.currentThread().interrupt(); } finally { awaitAll(results); } } } /** * Returns an executor appropriate for the level of desired concurrency. * * @param queue The delivery queue to be processed. * @param state The invoke state to be used by the thread pool. * @param concurrency The level of desired concurrency. * @return An executor appropriate for the level of desired concurrency. */ private static ExecutorService getExecutor(DeliveryQueue queue, InvokeState state, int concurrency) { ExecutorService executor; if (concurrency <= 1) { executor = new DirectExecutorService(); } else { ThreadFactory threadFactory = new ServerThreadFactory(MessageFormat.format("TundraTN/Queue \"{0}\"", queue.getQueueName()), state); BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>(true); RejectedExecutionHandler handler = new BlockingRejectedExecutionHandler(); executor = new java.util.concurrent.ThreadPoolExecutor(concurrency, concurrency, 1, TimeUnit.MINUTES, workQueue, threadFactory, handler); } return executor; } // waits for all futures in the given queue to complete protected static List<IData> awaitAll(Queue<Future<IData>> futures) { List<IData> results = new ArrayList<IData>(futures.size()); while(futures.size() > 0) { try { results.add(awaitFirst(futures)); } catch (Throwable ex) { // ignore all exceptions } } return results; } /** * Waits for the first/head future in the given queue to complete. * * @param futures A queue of futures. * @param timeout How long to wait for the future to complete. * @param unit The time unit in which the timeout is specified. * @return The result returned by the first/head future in the given queue. * @throws Exception If an exception was encountered by the future when it was executed. */ private static IData awaitFirst(Queue<Future<IData>> futures, long timeout, TimeUnit unit) throws Exception { return await(futures.poll(), timeout, unit); } /** * Waits for the first/head future in the given queue to complete. * * @param futures A queue of futures. * @return The result returned by the first/head future in the given queue. * @throws Exception If an exception was encountered by the future when it was executed. */ private static IData awaitFirst(Queue<Future<IData>> futures) throws Exception { return await(futures.poll()); } /** * Waits for the given future to complete, then returns the result. * * @param future The future to wait to complete. * @param timeout How long to wait for the future to complete. * @param unit The time unit in which the timeout is specified. * @return The result returned by the future. * @throws Exception If an exception was encountered by the future when it was executed. */ private static IData await(Future<IData> future, long timeout, TimeUnit unit) throws Exception { return future == null ? null : future.get(timeout, unit); } /** * Waits for the given future to complete, then returns the result. * * @param future The future to wait to complete. * @return The result returned by the future. * @throws Exception If an exception was encountered by the future when it was executed. */ private static IData await(Future<IData> future) throws Exception { return future == null ? null : future.get(); } /** * Returns true if the invocation call stack includes the WmTN/wm.tn.queuing:deliverBatch service. * * @return True if the invocation call stack includes the WmTN/wm.tn.queuing:deliverBatch service. */ private static boolean invokedByTradingNetworks() { java.util.Iterator iterator = InvokeState.getCurrentState().getCallStack().iterator(); boolean result = false; while(iterator.hasNext()) { result = iterator.next().toString().equals(DELIVER_BATCH_SERVICE_NAME); if (result) break; } return result; } /** * Converts the given Trading Networks delivery queue to an IData doc. * * @param input The queue to convert to an IData doc representation. * @return An IData doc representation of the given queue. * @throws ServiceException If a database error occurs. */ public static IData toIData(DeliveryQueue input) throws ServiceException { if (input == null) return null; IData output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); IDataUtil.put(cursor, "name", input.getQueueName()); IDataUtil.put(cursor, "type", input.getQueueType()); IDataUtil.put(cursor, "status", input.getState()); IDataUtil.put(cursor, "length", "" + length(input)); cursor.destroy(); return output; } /** * Converts the given list of Trading Networks delivery queues to an IData[] doc list. * * @param input The list of queues to convert to an IData[] doc list representation. * @return An IData[] doc list representation of the given queues. * @throws ServiceException If a database error occurs. */ public static IData[] toIDataArray(DeliveryQueue[] input) throws ServiceException { if (input == null) return null; IData[] output = new IData[input.length]; for (int i = 0; i < input.length; i++) { output[i] = toIData(input[i]); } return output; } }
package romelo333.notenoughwands.network; import mcjty.lib.network.PacketHandler; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; public class NEWPacketHandler { public static SimpleNetworkWrapper INSTANCE; public static void registerMessages(SimpleNetworkWrapper network) { INSTANCE = network; // Server side INSTANCE.registerMessage(PacketToggleMode.Handler.class, PacketToggleMode.class, PacketHandler.nextID(), Side.SERVER); INSTANCE.registerMessage(PacketToggleSubMode.Handler.class, PacketToggleSubMode.class, PacketHandler.nextID(), Side.SERVER); INSTANCE.registerMessage(PacketGetProtectedBlocks.Handler.class, PacketGetProtectedBlocks.class, PacketHandler.nextID(), Side.SERVER); INSTANCE.registerMessage(PacketGetProtectedBlockCount.Handler.class, PacketGetProtectedBlockCount.class, PacketHandler.nextID(), Side.SERVER); INSTANCE.registerMessage(PacketGetProtectedBlocksAroundPlayer.Handler.class, PacketGetProtectedBlocksAroundPlayer.class, PacketHandler.nextID(), Side.SERVER); // Client side INSTANCE.registerMessage(PacketReturnProtectedBlocks.Handler.class, PacketReturnProtectedBlocks.class, PacketHandler.nextID(), Side.CLIENT); INSTANCE.registerMessage(PacketReturnProtectedBlockCount.Handler.class, PacketReturnProtectedBlockCount.class, PacketHandler.nextID(), Side.CLIENT); INSTANCE.registerMessage(PacketReturnProtectedBlocksAroundPlayer.Handler.class, PacketReturnProtectedBlocksAroundPlayer.class, PacketHandler.nextID(), Side.CLIENT); } }
package uk.co.epii.stephenson.parser; import uk.co.epii.stephenson.cif.NationalRailTime; import uk.co.epii.stephenson.cif.OriginLocation; public class OriginLocationParser extends AbstractParser<OriginLocation> { private final Parser<NationalRailTime> nationalRailTimeParser; private final Parser<NationalRailTime> publicRailTimeParser; public OriginLocationParser(Parser<NationalRailTime> nationalRailTimeParser, Parser<NationalRailTime> publicRailTimeParser) { this.nationalRailTimeParser = nationalRailTimeParser; this.publicRailTimeParser = publicRailTimeParser; } @Override public OriginLocation parse(String string) { setRawData(string); OriginLocationImpl originLocation = new OriginLocationImpl(); originLocation.setRecordIdentity(getNext(2)); originLocation.setLocation(getNext(8)); originLocation.setScheduledDeparture(nationalRailTimeParser.parse(getNext(5))); originLocation.setPublicDeparture(publicRailTimeParser.parse(getNext(4))); originLocation.setPlatform(getNext(3)); originLocation.setLine(getNext(3)); originLocation.setEngineeringAllowance(getNext(2)); originLocation.setPathingAllowance(getNext(2)); originLocation.setActivity(getNext(12)); originLocation.setPerformanceAllowance(getNext(2)); originLocation.setSpare(getNext(37)); return originLocation; } }
package uk.co.pols.bamboo.gitplugin.commands; import com.atlassian.bamboo.commit.Commit; import com.atlassian.bamboo.commit.CommitImpl; import com.atlassian.bamboo.commit.CommitFile; import com.atlassian.bamboo.commit.CommitFileImpl; import com.atlassian.bamboo.author.AuthorImpl; import com.atlassian.bamboo.author.Author; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormat; import org.joda.time.DateTime; public class GitLogParser { private static final String AUTHOR_LINE_PREFIX = "Author:"; private static final String NEW_COMMIT_LINE_PREFIX = "commit"; private static final DateTimeFormatter GIT_ISO_DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss +SSSS"); private static final String DATE_LINE_PREFIX = "Date:"; private static final String MERGE_LINE_PREFIX = "Merge"; private String log; private String mostRecentCommitDate = null; public GitLogParser(String log) { this.log = (log == null) ? "" : log; } public List<Commit> extractCommits() { List<Commit> commits = new ArrayList<Commit>(); GitCommitLogEntry commitLogEntry = new GitCommitLogEntry("Unknown"); for (String line : log.split("\n")) { if (line.startsWith(NEW_COMMIT_LINE_PREFIX)) { if (commitLogEntry.isValidCommit()) { commits.add(commitLogEntry.toBambooCommit()); } commitLogEntry = new GitCommitLogEntry(line.substring(NEW_COMMIT_LINE_PREFIX.length() + 1)); } else if (line.startsWith(AUTHOR_LINE_PREFIX)) { commitLogEntry.addAuthor(line); } else if (line.startsWith(DATE_LINE_PREFIX)) { commitLogEntry.addDate(line); } else if (line.length() > 0 && Character.isDigit(line.toCharArray()[0])) { commitLogEntry.addFileName(line); } else if (line.startsWith(MERGE_LINE_PREFIX)) { // ignore } else if (line.length() > 0 && !"\n".equals(line)) { commitLogEntry.addCommentLine(line); } } if (commitLogEntry.isValidCommit()) { commits.add(commitLogEntry.toBambooCommit()); } return commits; } public String getMostRecentCommitDate() { return mostRecentCommitDate; } public class GitCommitLogEntry { private StringBuffer comment = new StringBuffer(); private List<CommitFile> commitFiles = new ArrayList<CommitFile>(); private String commitId; private Author author = null; private DateTime date = null; public GitCommitLogEntry(String commitId) { this.commitId = commitId; } public void addFileName(String line) { StringTokenizer stringTokenizer = new StringTokenizer(line); try { skipLinesAdded(stringTokenizer); skipLinesDeleted(stringTokenizer); commitFiles.add(fileWithinCurrentCommit(stringTokenizer.nextToken(), commitId)); } catch (Exception e) { // can't parse, so lets add it to the comment, so we don't lose it comment.append(line).append("\n"); } } public void addCommentLine(String line) { comment.append(line).append("\n"); } public void addAuthor(String line) { author = extractAuthor(line); } public void addDate(String line) { String commitDate = line.substring(DATE_LINE_PREFIX.length()).trim(); if (mostRecentCommitDate == null) { mostRecentCommitDate = commitDate; } date = GIT_ISO_DATE_FORMAT.parseDateTime(commitDate); } public boolean isValidCommit() { return author != null && date != null; } public Commit toBambooCommit() { CommitImpl commit = new CommitImpl(author, comment.toString(), date.toDate()); commit.setFiles(commitFiles); return commit; } private int skipLinesDeleted(StringTokenizer stringTokenizer) { return Integer.parseInt(stringTokenizer.nextToken()); } private int skipLinesAdded(StringTokenizer st) { return Integer.parseInt(st.nextToken()); } private Author extractAuthor(String line) { String[] tokens = line.substring(AUTHOR_LINE_PREFIX.length()).trim().split(" "); if (tokens.length == 1 || tokens.length == 2) { return new AuthorImpl(tokens[0]); } if (tokens.length == 3) { return new AuthorImpl(tokens[0] + " " + tokens[1]); } return new AuthorImpl(Author.UNKNOWN_AUTHOR); } private CommitFileImpl fileWithinCurrentCommit(String filename, String commitId) { CommitFileImpl file = new CommitFileImpl(filename); file.setRevision(commitId); return file; } } }
package vicnode.daris.femur.upload; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.HashSet; import java.util.Set; import arc.mf.client.ServerClient; import vicnode.daris.femur.upload.ArcUtil.ArcType; public class CreateStudyAndDatasets { static void distributePICT() throws Throwable { File rootDir = new File( Configuration.root() + "/" + Configuration.tiles100umSony()); File imagesDir = new File(Configuration.root() + "/" + Configuration.tiles100umSony() + "/IMAGES"); File[] imageFiles = imagesDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("PICT.TIF"); } }); for (File imageFile : imageFiles) { File[] dirs = rootDir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() && f.getName() .startsWith(imageFile.getName().substring(0, 3)); } }); if (dirs != null) { for (File dir : dirs) { File targetFile = new File(dir, imageFile.getName()); if (!targetFile.exists()) { Files.copy(Paths.get(imageFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); System.out.println(imageFile.getName() + " -> " + dir.getName() + "/"); } } } } } public static void upload100umSonyDatasets() throws Throwable { File rootDir = new File( Configuration.root() + "/" + Configuration.tiles100umSony()); File[] dirs = rootDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.matches("^\\d+\\w*")) { int n = Integer.parseInt(name.substring(0, 3)); return n >= 231 && n <= 284; } return false; } }); if (dirs != null && dirs.length > 0) { MasterSpreadsheet sheet = LocalFileSystem.getMasterSpreadsheet(); ServerClient.Connection cxn = Server.connect(); try { for (File dir : dirs) { upload100umSonyDataset(dir, sheet, cxn); } } finally { Server.disconnect(); } } } public static void upload100umSonyDataset(File dir, MasterSpreadsheet spreadsheet, ServerClient.Connection cxn) throws Throwable { String name = dir.getName(); String specimenNo = name; if (!name.matches("\\d+")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isDigit(c)) { sb.append(c); } else { break; } } specimenNo = sb.toString(); } MasterSpreadsheet.SubjectRecord record = spreadsheet .getRecord(Integer.parseInt(specimenNo)); assert record != null; String subjectCid = SubjectUtil.findSubject(cxn, Integer.parseInt(specimenNo)); if (subjectCid == null) { throw new Exception("Could not find subject with specimen number: " + specimenNo); } String exMethodCid = subjectCid + ".1"; String source = LocalFileSystem.trimRoot(Configuration.root(), dir); String datasetCid = DatasetUtil.findDatasetBySource(cxn, subjectCid, source); if (datasetCid != null) { System.out.println("Dataset(cid: " + datasetCid + ") from " + source + " already exists."); return; } String studyCid = StudyUtil.findOrCreateStudy(cxn, exMethodCid, "1", "100µm Tiles Sony Camera", "100µm Tiles Sony Camera", record, null); System.out.println("Created study: " + studyCid + "."); datasetCid = DatasetUtil .createDerivedDataset(cxn, studyCid, null, null, "100 micrometre tiles sony camera", "tiff/series", ArcType.zip.mimeType(), null, true, "100µm_tiles_sony_camera-" + name + ".zip", exMethodCid, "1", source, new String[] { "microradiography", record.specimenType }, record.specimenType, "microradiography", dir, true, ArcType.zip); System.out.println( "Created dataset: " + datasetCid + " from " + source + "."); } public static void upload100umSpotDatasets() throws Throwable { File rootDir = new File( Configuration.root() + "/" + Configuration.tiles100umSpot()); File[] dirs = rootDir.listFiles(new FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) { String name = f.getName(); int n = Integer.parseInt(name.substring(0, 3)); return n >= 231 && n <= 284; } return false; } }); if (dirs != null && dirs.length > 0) { MasterSpreadsheet sheet = LocalFileSystem.getMasterSpreadsheet(); ServerClient.Connection cxn = Server.connect(); try { for (File dir : dirs) { upload100umSpotDataset(dir, sheet, cxn); } } finally { Server.disconnect(); } } } public static void upload100umSpotDataset(File dir, MasterSpreadsheet spreadsheet, ServerClient.Connection cxn) throws Throwable { String name = dir.getName(); String specimenNo = name; if (!name.matches("\\d+")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isDigit(c)) { sb.append(c); } else { break; } } specimenNo = sb.toString(); } MasterSpreadsheet.SubjectRecord record = spreadsheet .getRecord(Integer.parseInt(specimenNo)); assert record != null; String subjectCid = SubjectUtil.findSubject(cxn, Integer.parseInt(specimenNo)); if (subjectCid == null) { throw new Exception("Could not find subject with specimen number: " + specimenNo); } String exMethodCid = subjectCid + ".1"; String source = LocalFileSystem.trimRoot(Configuration.root(), dir); String datasetCid = DatasetUtil.findDatasetBySource(cxn, subjectCid, source); if (datasetCid != null) { System.out.println("Dataset(cid: " + datasetCid + ") from " + source + " already exists."); return; } String studyCid = StudyUtil.findOrCreateStudy(cxn, exMethodCid, "1", "100µm Tiles Spot Camera", "100µm Tiles Spot Camera", record, null); System.out.println("Created study: " + studyCid + "."); datasetCid = DatasetUtil .createDerivedDataset(cxn, studyCid, null, null, "100 micrometre tiles spot camera", "tiff/series", ArcType.zip.mimeType(), null, true, "100µm_tiles_spot_camera-" + name + ".zip", exMethodCid, "1", source, new String[] { "microradiography", record.specimenType }, record.specimenType, "microradiography", dir, true, ArcType.zip); System.out.println( "Created dataset: " + datasetCid + " from " + source + "."); } public static void uploadSpring8Sept2008Datasets(int specimenNo, String name, File dirPrimary, String namePrimary, File dirReconstructed, String nameReconstructed) throws Throwable { String sourcePrimary = LocalFileSystem.trimRoot(Configuration.root(), dirPrimary); String sourceReconstructed = LocalFileSystem .trimRoot(Configuration.root(), dirReconstructed); MasterSpreadsheet sheet = LocalFileSystem.getMasterSpreadsheet(); MasterSpreadsheet.SubjectRecord record = sheet.getRecord(specimenNo); assert record != null; ServerClient.Connection cxn = Server.connect(); try { String subjectCid = SubjectUtil.findSubject(cxn, specimenNo); if (subjectCid == null) { throw new Exception( "Could not find subject with specimen number: " + specimenNo); } String exMethodCid = subjectCid + ".1"; /* * check if datasets exist */ String primaryDatasetCid = DatasetUtil.findDatasetBySource(cxn, subjectCid, sourcePrimary); String reconstructedDatasetCid = DatasetUtil .findDatasetBySource(cxn, subjectCid, sourceReconstructed); if (primaryDatasetCid != null && reconstructedDatasetCid != null) { System.out.println("Primary Dataset(cid: " + primaryDatasetCid + ") from " + sourcePrimary + " already exists."); System.out.println("Reconstructed Dataset(cid: " + reconstructedDatasetCid + ") from " + sourceReconstructed + " already exists."); return; } /* * create / find study */ String studyName = "Spring8 Sept 2008"; String studyCid = StudyUtil.findOrCreateStudy(cxn, exMethodCid, "2", studyName, studyName + " - " + name.toLowerCase(), record, new String[] { "Clinical CT", "microCT" }); System.out.println("Created/Found study " + studyCid); /* * create primary dataset */ if (primaryDatasetCid == null) { System.out.println("Uploading primary dataset: from " + sourcePrimary + "."); primaryDatasetCid = DatasetUtil.createPrimaryDataset(cxn, studyCid, namePrimary, "Spring8 raw data in Hipic format", "hipic/series", ArcType.aar.mimeType(), null, true, "Spring8_Sept_2008-" + name.toLowerCase() + ".aar", exMethodCid, "2", sourcePrimary, new String[] { "Clinical CT", "microCT", record.specimenType }, record.specimenType, "microCT", dirPrimary, false, ArcType.aar); System.out.println("Created primary dataset: " + primaryDatasetCid + " from " + sourcePrimary + "."); } /* * create reconstructed dataset */ if (reconstructedDatasetCid == null) { System.out.println("Uploading reconstructed dataset: from " + sourceReconstructed + "."); reconstructedDatasetCid = DatasetUtil.createDerivedDataset(cxn, studyCid, new String[] { primaryDatasetCid }, nameReconstructed, "Reconstructed Spring8 data in TIFF format", "tiff/series", ArcType.aar.mimeType(), null, true, "Spring8_Sept_2008-" + name + "-Reconstructed.aar", exMethodCid, "2", sourceReconstructed, new String[] { "Clinical CT", "microCT", record.specimenType }, record.specimenType, "microCT", dirReconstructed, true, ArcType.aar); System.out.println("Created reconstructed dataset: " + reconstructedDatasetCid + " from " + sourceReconstructed + "."); } } finally { Server.disconnect(); } } public static void uploadSpring8Sept2008Datasets(String name, File dirPrimary, File dirReconstructed) throws Throwable { int specimenNo = Integer.parseInt(StringUtil.trimNonDigits(name)); uploadSpring8Sept2008Datasets(specimenNo, name, dirPrimary, "Spring8 Raw - " + name, dirReconstructed, "Spring8 Reconstructed - " + name); } public static void uploadSpring8Sept2008Datasets(File parent, String name) throws Throwable { File dirPrimary = new File(parent, name); File dirReconstructed = new File(dirPrimary, "Reconstructed sections"); if (!dirReconstructed.exists()) { dirReconstructed = new File(dirPrimary, "reconstructed sections"); } uploadSpring8Sept2008Datasets(name, dirPrimary, dirReconstructed); } public static String uploadPrimaryDataset(File datasetDir, boolean recursive, int specimenNo, String methodStep, String studyName, String[] studyTags, String datasetName, String datasetDescription, String mimeType, ArcType arcType, String[] datasetTags, String imageType) throws Throwable { String source = LocalFileSystem.trimRoot(Configuration.root(), datasetDir); MasterSpreadsheet sheet = LocalFileSystem.getMasterSpreadsheet(); MasterSpreadsheet.SubjectRecord record = sheet.getRecord(specimenNo); assert record != null; ServerClient.Connection cxn = Server.connect(); try { String subjectCid = SubjectUtil.findSubject(cxn, specimenNo); if (subjectCid == null) { throw new Exception( "Could not find subject with specimen number: " + specimenNo); } String exMethodCid = subjectCid + ".1"; /* * check if datasets exist */ String datasetCid = DatasetUtil.findDatasetBySource(cxn, subjectCid, source); if (datasetCid != null) { System.out.println("Primary Dataset(cid: " + datasetCid + ") from " + source + " already exists."); return datasetCid; } /* * create / find study */ String studyCid = StudyUtil.findOrCreateStudy(cxn, exMethodCid, methodStep, studyName, studyName + " - " + datasetDir.getName().toLowerCase(), record, studyTags); System.out.println("Created/Found study " + studyCid); /* * create primary dataset */ System.out .println("Uploading primary dataset: from " + source + "."); String filename = studyName + "-" + datasetDir.getName() + "." + arcType.ext(); filename = filename.replace(' ', '_'); Set<String> tags = new HashSet<String>(); tags.add(record.specimenType); if (datasetTags != null) { for (String dt : datasetTags) { tags.add(dt); } } datasetCid = DatasetUtil.createPrimaryDataset(cxn, studyCid, datasetName, datasetDescription, mimeType, arcType.mimeType(), null, true, filename, exMethodCid, methodStep, source, tags.toArray(new String[tags.size()]), record.specimenType, imageType, datasetDir, recursive, arcType); System.out.println("Created primary dataset: " + datasetCid + " from " + source + "."); return datasetCid; } finally { Server.disconnect(); } } public static String uploadDerivedDataset(File datasetDir, boolean recursive, int specimenNo, String methodStep, String studyName, String[] studyTags, String datasetName, String datasetDescription, String mimeType, ArcType arcType, String[] datasetTags, String imageType, String input) throws Throwable { String source = LocalFileSystem.trimRoot(Configuration.root(), datasetDir); MasterSpreadsheet sheet = LocalFileSystem.getMasterSpreadsheet(); MasterSpreadsheet.SubjectRecord record = sheet.getRecord(specimenNo); assert record != null; ServerClient.Connection cxn = Server.connect(); try { String subjectCid = SubjectUtil.findSubject(cxn, specimenNo); if (subjectCid == null) { throw new Exception( "Could not find subject with specimen number: " + specimenNo); } String exMethodCid = subjectCid + ".1"; /* * check if datasets exist */ String datasetCid = DatasetUtil.findDatasetBySource(cxn, subjectCid, source); if (datasetCid != null) { System.out.println("Primary Dataset(cid: " + datasetCid + ") from " + source + " already exists."); return datasetCid; } /* * create / find study */ String studyCid = StudyUtil.findOrCreateStudy(cxn, exMethodCid, methodStep, studyName, studyName + " - " + datasetDir.getName().toLowerCase(), record, studyTags); System.out.println("Created/Found study " + studyCid); /* * create derived dataset */ String filename = studyName + "-" + datasetDir.getName() + "." + arcType.ext(); filename = filename.replace(' ', '_'); Set<String> tags = new HashSet<String>(); tags.add(record.specimenType); if (datasetTags != null) { for (String dt : datasetTags) { tags.add(dt); } } System.out .println("Uploading derived dataset: from " + source + "."); datasetCid = DatasetUtil.createDerivedDataset(cxn, studyCid, new String[] { input }, datasetName, datasetDescription, mimeType, arcType.mimeType(), null, true, filename, exMethodCid, methodStep, source, tags.toArray(new String[tags.size()]), record.specimenType, imageType, datasetDir, recursive, arcType); System.out.println("Created derived dataset: " + datasetCid + " from " + source + "."); return datasetCid; } finally { Server.disconnect(); } } public static void main(String[] args) throws Throwable { if (args.length != 12 && args.length != 13) { System.out.println( "Usage: upload <dir> <recursive> <specimen-no> <method-step> <study-name> <study-tags> <name> <description> <mime-type> <atype> <tags> <image-type> [input-cid]"); System.exit(1); } File datasetDir = new File(args[0]); boolean recursive = Boolean.parseBoolean(args[1]); int specimenNo = Integer.parseInt(args[2]); String methodStep = args[3]; String studyName = args[4]; String[] studyTags = args[5].split(","); String datasetName = args[6]; String datasetDesc = args[7]; String mimeType = args[8]; ArcType arcType = args[9].equalsIgnoreCase("AAR") ? ArcType.aar : ArcType.zip; String[] datasetTags = args[10].split(","); String imageType = args[11]; if (args.length > 12) { String input = args[12]; uploadDerivedDataset(datasetDir, recursive, specimenNo, methodStep, studyName, studyTags, datasetName, datasetDesc, mimeType, arcType, datasetTags, imageType, input); } else { uploadPrimaryDataset(datasetDir, recursive, specimenNo, methodStep, studyName, studyTags, datasetName, datasetDesc, mimeType, arcType, datasetTags, imageType); } } }
package net.finmath.marketdata.model.curves; import java.io.Serializable; import java.util.Date; import java.util.logging.Logger; import org.threeten.bp.Instant; import org.threeten.bp.LocalDate; import org.threeten.bp.ZoneId; import net.finmath.marketdata.model.AnalyticModelInterface; import net.finmath.time.businessdaycalendar.BusinessdayCalendarExcludingWeekends; import net.finmath.time.businessdaycalendar.BusinessdayCalendarInterface; /** * A container for a forward (rate) curve. The forward curve is based on the {@link net.finmath.marketdata.model.curves.Curve} class. * It thus features all interpolation and extrapolation methods and interpolation entities as {@link net.finmath.marketdata.model.curves.Curve}. * * The forward F(t) of an index is such that * F(t) * D(t+p) equals the market price of the corresponding * index fixed in t and paid in t+d, where t is the fixing time of the index and t+p is the payment time of the index. * F(t) is the corresponding forward and D is the associated discount curve. * * @author Christian Fries */ public class ForwardCurve extends AbstractForwardCurve implements Serializable { private static final long serialVersionUID = -4126228588123963885L; private static Logger logger = Logger.getLogger("net.finmath"); /** * Additional choice of interpolation entities for forward curves. */ public enum InterpolationEntityForward { /** Interpolation is performed on the forward **/ FORWARD, /** Interpolation is performed on the value = forward * discount factor **/ FORWARD_TIMES_DISCOUNTFACTOR, /** Interpolation is performed on the zero rate **/ ZERO, /** Interpolation is performed on the (synthetic) discount factor **/ DISCOUNTFACTOR } private InterpolationEntityForward interpolationEntityForward = InterpolationEntityForward.FORWARD; /** * Generate a forward curve using a given discount curve and payment offset. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param paymentBusinessdayCalendar The business day calendar used for adjusting the payment date. * @param paymentDateRollConvention The date roll convention used for adjusting the payment date. * @param interpolationMethod The interpolation method used for the curve. * @param extrapolationMethod The extrapolation method used for the curve. * @param interpolationEntity The entity interpolated/extrapolated. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. */ public ForwardCurve(String name, LocalDate referenceDate, String paymentOffsetCode, BusinessdayCalendarInterface paymentBusinessdayCalendar, BusinessdayCalendarInterface.DateRollConvention paymentDateRollConvention, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity, InterpolationEntityForward interpolationEntityForward, String discountCurveName) { super(name, referenceDate, paymentOffsetCode, paymentBusinessdayCalendar, paymentDateRollConvention, interpolationMethod, extrapolationMethod, interpolationEntity, discountCurveName); this.interpolationEntityForward = interpolationEntityForward; if(interpolationEntityForward == InterpolationEntityForward.DISCOUNTFACTOR) { super.addPoint(0.0, 1.0, false); } } /** * Generate a forward curve using a given discount curve and payment offset. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. */ public ForwardCurve(String name, LocalDate referenceDate, String paymentOffsetCode, InterpolationEntityForward interpolationEntityForward, String discountCurveName) { this(name, referenceDate, paymentOffsetCode, new BusinessdayCalendarExcludingWeekends(), BusinessdayCalendarInterface.DateRollConvention.FOLLOWING, InterpolationMethod.LINEAR, ExtrapolationMethod.CONSTANT, InterpolationEntity.VALUE, interpolationEntityForward, discountCurveName); } /** * Generate a forward curve using a given discount curve and payment offset. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. */ public ForwardCurve(String name, LocalDate referenceDate, String paymentOffsetCode, String discountCurveName) { this(name, referenceDate, paymentOffsetCode, InterpolationEntityForward.FORWARD, discountCurveName); } /** * Generate a forward curve using a given discount curve and payment offset. * * @param name The name of this curve. * @param paymentOffset The maturity of the underlying index modeled by this curve. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. */ public ForwardCurve(String name, double paymentOffset, InterpolationEntityForward interpolationEntityForward, String discountCurveName) { // What is the use case of this constructor? Can it be deleted? super(name, null, paymentOffset, discountCurveName); this.interpolationEntityForward = interpolationEntityForward; } /** * Create a forward curve from given times and given forwards. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param paymentBusinessdayCalendar The business day calendar used for adjusting the payment date. * @param paymentDateRollConvention The date roll convention used for adjusting the payment date. * @param interpolationMethod The interpolation method used for the curve. * @param extrapolationMethod The extrapolation method used for the curve. * @param interpolationEntity The entity interpolated/extrapolated. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. * @param model The model to be used to fetch the discount curve, if needed. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, BusinessdayCalendarInterface paymentBusinessdayCalendar, BusinessdayCalendarInterface.DateRollConvention paymentDateRollConvention, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity, InterpolationEntityForward interpolationEntityForward, String discountCurveName, AnalyticModelInterface model, double[] times, double[] givenForwards) { ForwardCurve forwardCurve = new ForwardCurve(name, referenceDate, paymentOffsetCode, paymentBusinessdayCalendar, paymentDateRollConvention, interpolationMethod, extrapolationMethod, interpolationEntity, interpolationEntityForward, discountCurveName); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { forwardCurve.addForward(model, times[timeIndex], givenForwards[timeIndex], false); } return forwardCurve; } /** * Create a forward curve from given times and given forwards. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param paymentBusinessdayCalendar The business day calendar used for adjusting the payment date. * @param paymentDateRollConvention The date roll convention used for adjusting the payment date. * @param interpolationMethod The interpolation method used for the curve. * @param extrapolationMethod The extrapolation method used for the curve. * @param interpolationEntity The entity interpolated/extrapolated. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. * @param model The model to be used to fetch the discount curve, if needed. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, Date referenceDate, String paymentOffsetCode, BusinessdayCalendarInterface paymentBusinessdayCalendar, BusinessdayCalendarInterface.DateRollConvention paymentDateRollConvention, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity, InterpolationEntityForward interpolationEntityForward, String discountCurveName, AnalyticModelInterface model, double[] times, double[] givenForwards) { LocalDate referenceDataAsLocalDate = Instant.ofEpochMilli(referenceDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); return createForwardCurveFromForwards(name, referenceDataAsLocalDate, paymentOffsetCode, paymentBusinessdayCalendar, paymentDateRollConvention, interpolationMethod, extrapolationMethod, interpolationEntity, interpolationEntityForward, discountCurveName, model, times, givenForwards); } /** * Create a forward curve from given times and given forwards. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. * @param model The model to be used to fetch the discount curve, if needed. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, String interpolationEntityForward, String discountCurveName, AnalyticModelInterface model, double[] times, double[] givenForwards) { return createForwardCurveFromForwards(name, referenceDate, paymentOffsetCode, InterpolationEntityForward.valueOf(interpolationEntityForward), discountCurveName, model, times, givenForwards); } /** * Create a forward curve from given times and given forwards. * * @param name The name of this curve. * @param referenceDate The reference date for this code, i.e., the date which defines t=0. * @param paymentOffsetCode The maturity of the index modeled by this curve. * @param interpolationEntityForward Interpolation entity used for forward rate interpolation. * @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. * @param model The model to be used to fetch the discount curve, if needed. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, InterpolationEntityForward interpolationEntityForward, String discountCurveName, AnalyticModelInterface model, double[] times, double[] givenForwards) { ForwardCurve forwardCurve = new ForwardCurve(name, referenceDate, paymentOffsetCode, interpolationEntityForward, discountCurveName); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { forwardCurve.addForward(model, times[timeIndex], givenForwards[timeIndex], false); } return forwardCurve; } /** * Create a forward curve from given times and given forwards. * * @param name The name of this curve. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @param paymentOffset The maturity of the underlying index modeled by this curve. * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, double[] times, double[] givenForwards, double paymentOffset) { ForwardCurve forwardCurve = new ForwardCurve(name, paymentOffset, InterpolationEntityForward.FORWARD, null); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurve.addForward(null, fixingTime, givenForwards[timeIndex], isParameter); } return forwardCurve; } /** * Create a forward curve from given times and discount factors. * * The forward curve will have times.length-1 fixing times from times[0] to times[times.length-2] * where the forwards are calculated via * <code> * forward[timeIndex] = (givenDiscountFactors[timeIndex]/givenDiscountFactors[timeIndex+1]-1.0) / (times[timeIndex+1] - times[timeIndex]); * </code> * Note: If time[0] &gt; 0, then the discount factor 1.0 will inserted at time 0.0 * * @param name The name of this curve. * @param times A vector of given time points. * @param givenDiscountFactors A vector of given discount factors (corresponding to the given time points). * @param paymentOffset The maturity of the underlying index modeled by this curve. * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors, double paymentOffset) { ForwardCurve forwardCurve = new ForwardCurve(name, paymentOffset, InterpolationEntityForward.FORWARD, null); if(times.length == 0) { throw new IllegalArgumentException("Vector of times must not be empty."); } if(times[0] > 0) { // Add first forward double forward = (1.0/givenDiscountFactors[0]-1.0) / (times[0] - 0); forwardCurve.addForward(null, 0.0, forward, true); } for(int timeIndex=0; timeIndex<times.length-1;timeIndex++) { double forward = (givenDiscountFactors[timeIndex]/givenDiscountFactors[timeIndex+1]-1.0) / (times[timeIndex+1] - times[timeIndex]); double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurve.addForward(null, fixingTime, forward, isParameter); } return forwardCurve; } /** * Create a forward curve from given times and given forwards with respect to an associated discount curve and payment offset. * * @param name The name of this curve. * @param times A vector of given time points. * @param givenForwards A vector of given forwards (corresponding to the given time points). * @param model An analytic model providing a context. The discount curve (if needed) is obtained from this model. * @param discountCurveName Name of the discount curve associated with this index (associated with it's funding or collateralization). * @param paymentOffset Time between fixing and payment. * @return A new ForwardCurve object. */ public static ForwardCurve createForwardCurveFromForwards(String name, double[] times, double[] givenForwards, AnalyticModelInterface model, String discountCurveName, double paymentOffset) { ForwardCurve forwardCurve = new ForwardCurve(name, paymentOffset, InterpolationEntityForward.FORWARD, discountCurveName); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurve.addForward(model, fixingTime, givenForwards[timeIndex], isParameter); } return forwardCurve; } @Override public double getForward(AnalyticModelInterface model, double fixingTime) { double paymentOffset = this.getPaymentOffset(fixingTime); double interpolationEntityForwardValue = this.getValue(model, fixingTime); switch(interpolationEntityForward) { case FORWARD: default: return interpolationEntityForwardValue; case FORWARD_TIMES_DISCOUNTFACTOR: if(model==null) { throw new IllegalArgumentException("model==null. Not allowed for interpolationEntityForward " + interpolationEntityForward); } return interpolationEntityForwardValue / model.getDiscountCurve(discountCurveName).getValue(model, fixingTime+paymentOffset); case ZERO: { double interpolationEntityForwardValue2 = this.getValue(model, fixingTime+paymentOffset); return (Math.exp(interpolationEntityForwardValue2 * (fixingTime+paymentOffset) - interpolationEntityForwardValue * fixingTime) - 1.0) / (paymentOffset); } case DISCOUNTFACTOR: { double interpolationEntityForwardValue2 = this.getValue(model, fixingTime+paymentOffset); return (interpolationEntityForwardValue / interpolationEntityForwardValue2 - 1.0) / (paymentOffset); } } } /** * Returns the forward for the corresponding fixing time. * * <b>Note:</b> This implementation currently ignores the provided <code>paymentOffset</code>. * Instead it uses the payment offset calculate from the curve specification. * * @param model An analytic model providing a context. Some curves do not need this (can be null). * @param fixingTime The fixing time of the index associated with this forward curve. * @param paymentOffset The payment offset (as internal day count fraction) specifying the payment of this index. Used only as a fallback and/or consistency check. * * @return The forward. */ @Override public double getForward(AnalyticModelInterface model, double fixingTime, double paymentOffset) { double forward = this.getForward(model, fixingTime); double curvePaymentOffset = this.getPaymentOffset(fixingTime); if(paymentOffset != curvePaymentOffset) { forward = (Math.exp(Math.log(1+forward*curvePaymentOffset) * paymentOffset/curvePaymentOffset)-1.0)/paymentOffset; // logger.warning("Requesting forward with paymentOffsets not agreeing with original calibration. Requested: " + paymentOffset +". Calibrated: " + curvePaymentOffset + "."); } return forward; } /** * Add a forward to this curve. * * @param model An analytic model providing a context. The discount curve (if needed) is obtained from this model. * @param fixingTime The given fixing time. * @param forward The given forward. * @param isParameter If true, then this point is server via {@link #getParameter()} and changed via {@link #setParameter(double[])} and {@link #getCloneForParameter(double[])}, i.e., it can be calibrated. */ private void addForward(AnalyticModelInterface model, double fixingTime, double forward, boolean isParameter) { double interpolationEntitiyTime; double interpolationEntityForwardValue; switch(interpolationEntityForward) { case FORWARD: default: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward; break; case FORWARD_TIMES_DISCOUNTFACTOR: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward * model.getDiscountCurve(discountCurveName).getValue(model, fixingTime+getPaymentOffset(fixingTime)); break; case ZERO: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = Math.log(1.0 + forward * paymentOffset) / paymentOffset; } break; case DISCOUNTFACTOR: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = getValue(fixingTime) / (1.0 + forward * paymentOffset); } break; } super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter); } @Override protected void addPoint(double time, double value, boolean isParameter) { if(interpolationEntityForward == InterpolationEntityForward.DISCOUNTFACTOR) { time += getPaymentOffset(time); } super.addPoint(time, value, isParameter); } /** * Returns the special interpolation method used for this forward curve. * * @return The interpolation method used for the forward. */ public InterpolationEntityForward getInterpolationEntityForward() { return interpolationEntityForward; } @Override public String toString() { return "ForwardCurve [" + super.toString() + ", interpolationEntityForward=" + interpolationEntityForward + "]"; } }
package org.codehaus.groovy.runtime; import groovy.lang.Closure; /** * This class defines all the new static groovy methods which appear on normal JDK * classes inside the Groovy environment. Static methods are used with the * first parameter as the destination class. * * @author Guillaume Laforge * @version $Revision$ */ public class DefaultGroovyStaticMethods { // @todo should be removed, was there for testing purpose public static void hello(String stringClass, String msg) { System.out.println("Hello " + msg); } /** * Start a Thread with the given closure as a Runnable instance. * * @param closure the Runnable closure * @return the started thread */ public static Thread start(Thread self, Closure closure) { Thread thread = new Thread(closure); thread.start(); return thread; } /** * Start a daemon Thread with the given closure as a Runnable instance. * * @param closure the Runnable closure * @return the started thread */ public static Thread startDaemon(Thread self, Closure closure) { Thread thread = new Thread(closure); thread.setDaemon(true); thread.start(); return thread; } }
package me.deftware.client.framework.Wrappers.Classes; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.inventory.GuiEditSign; import net.minecraft.util.text.TextComponentString; /** * Allows direct access to modify data in classes */ public class IClassHandler { /** * Returns a instance of a given IClass subclass * * @param clazz * @return * @throws Exception */ public static <T extends IClass> T getClass(Class<T> clazz) throws Exception { return clazz.newInstance(); } /** * The superclass all subclasses must extend for the generic casting to work */ public static class IClass { protected GuiScreen screen = Minecraft.getMinecraft().currentScreen; protected Class<?> clazz; public IClass(Class<?> clazz) { this.clazz = clazz; } public boolean isInstance() { return screen.getClass() == clazz; } } /* * Classes */ public static class IGuiEditSign extends IClass { public IGuiEditSign() { super(GuiEditSign.class); } public int getCurrentLine() { return ((GuiEditSign) this.screen).editLine; } public String getText(int line) { return ((GuiEditSign) this.screen).tileSign.signText[line].getUnformattedText(); } public void setText(String text, int line) { ((GuiEditSign) this.screen).tileSign.signText[line] = new TextComponentString(text); } public void save() { ((GuiEditSign) this.screen).tileSign.markDirty(); } } }
package net.java.sip.communicator.impl.gui.main.chat; import java.awt.*; import java.awt.Container; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.text.html.*; import javax.swing.undo.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.event.*; import net.java.sip.communicator.impl.gui.main.chat.conference.*; import net.java.sip.communicator.impl.gui.main.chat.menus.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.gui.event.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.resources.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.skin.*; import org.jitsi.service.configuration.*; import org.osgi.framework.*; /** * The <tt>ChatWritePanel</tt> is the panel, where user writes her messages. * It is located at the bottom of the split in the <tt>ChatPanel</tt> and it * contains an editor, where user writes the text. * * @author Yana Stamcheva * @author Lyubomir Marinov * @author Adam Netocny */ public class ChatWritePanel extends TransparentPanel implements ActionListener, KeyListener, MouseListener, UndoableEditListener, DocumentListener, PluginComponentListener, Skinnable { /** * The <tt>Logger</tt> used by the <tt>ChatWritePanel</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(ChatWritePanel.class); private final JEditorPane editorPane = new JEditorPane(); private final UndoManager undo = new UndoManager(); private final ChatPanel chatPanel; private final Timer stoppedTypingTimer = new Timer(2 * 1000, this); private final Timer typingTimer = new Timer(5 * 1000, this); private int typingState = OperationSetTypingNotifications.STATE_STOPPED; private WritePanelRightButtonMenu rightButtonMenu; private final ArrayList<ChatMenuListener> menuListeners = new ArrayList<ChatMenuListener>(); private final SIPCommScrollPane scrollPane = new SIPCommScrollPane(); private ChatTransportSelectorBox transportSelectorBox; private final Container centerPanel; private SIPCommToggleButton smsButton; private JLabel smsCharCountLabel; private JLabel smsNumberLabel; private int smsNumberCount = 1; private int smsCharCount = 160; private boolean smsMode = false; /** * A timer used to reset the transport resource to the bare ID if there was * no activity from this resource since a bunch of time. */ private java.util.Timer outdatedResourceTimer = null; /** * Tells if the current resource is outdated. A timer has already been * triggered, but when there is only a single resource there is no bare ID * available. Thus, flag this resource as outdated to switch to the bare ID * when available. */ private boolean isOutdatedResource = true; /** * Creates an instance of <tt>ChatWritePanel</tt>. * * @param panel The parent <tt>ChatPanel</tt>. */ public ChatWritePanel(ChatPanel panel) { super(new BorderLayout()); this.chatPanel = panel; centerPanel = createCenter(); int chatAreaSize = ConfigurationUtils.getChatWriteAreaSize(); Dimension writeMessagePanelDefaultSize = new Dimension(500, (chatAreaSize > 0) ? chatAreaSize : 28); Dimension writeMessagePanelMinSize = new Dimension(500, 28); Dimension writeMessagePanelMaxSize = new Dimension(500, 100); setMinimumSize(writeMessagePanelMinSize); setMaximumSize(writeMessagePanelMaxSize); setPreferredSize(writeMessagePanelDefaultSize); this.add(centerPanel, BorderLayout.CENTER); this.rightButtonMenu = new WritePanelRightButtonMenu(chatPanel.getChatContainer()); this.typingTimer.setRepeats(true); // initialize send command to Ctrl+Enter ConfigurationService configService = GuiActivator.getConfigurationService(); String messageCommandProperty = "service.gui.SEND_MESSAGE_COMMAND"; String messageCommand = configService.getString(messageCommandProperty); if(messageCommand == null) messageCommand = GuiActivator.getResources(). getSettingsString(messageCommandProperty); this.changeSendCommand((messageCommand == null || messageCommand .equalsIgnoreCase("enter"))); if(ConfigurationUtils.isFontSupportEnabled()) initDefaultFontConfiguration(); } /** * Initializes the default font configuration for this chat write area. */ private void initDefaultFontConfiguration() { String fontFamily = ConfigurationUtils.getChatDefaultFontFamily(); int fontSize = ConfigurationUtils.getChatDefaultFontSize(); // Font family and size if (fontFamily != null && fontSize > 0) setFontFamilyAndSize(fontFamily, fontSize); // Font style setBoldStyleEnable(ConfigurationUtils.isChatFontBold()); setItalicStyleEnable(ConfigurationUtils.isChatFontItalic()); setUnderlineStyleEnable(ConfigurationUtils.isChatFontUnderline()); // Font color Color fontColor = ConfigurationUtils.getChatDefaultFontColor(); if (fontColor != null) setFontColor(fontColor); } /** * Creates the center panel. * * @return the created center panel */ private Container createCenter() { JPanel centerPanel = new JPanel(new GridBagLayout()); centerPanel.setBackground(Color.WHITE); centerPanel.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 3)); GridBagConstraints constraints = new GridBagConstraints(); initSmsLabel(centerPanel); initTextArea(centerPanel); smsCharCountLabel = new JLabel(String.valueOf(smsCharCount)); smsCharCountLabel.setForeground(Color.GRAY); smsCharCountLabel.setVisible(false); constraints.anchor = GridBagConstraints.NORTHEAST; constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 0; constraints.weightx = 0f; constraints.weighty = 0f; constraints.insets = new Insets(0, 2, 0, 2); constraints.gridheight = 1; constraints.gridwidth = 1; centerPanel.add(smsCharCountLabel, constraints); smsNumberLabel = new JLabel(String.valueOf(smsNumberCount)) { @Override public void paintComponent(Graphics g) { AntialiasingManager.activateAntialiasing(g); g.setColor(getBackground()); g.fillOval(0, 0, getWidth(), getHeight()); super.paintComponent(g); } }; smsNumberLabel.setHorizontalAlignment(JLabel.CENTER); smsNumberLabel.setPreferredSize(new Dimension(18, 18)); smsNumberLabel.setMinimumSize(new Dimension(18, 18)); smsNumberLabel.setForeground(Color.WHITE); smsNumberLabel.setBackground(Color.GRAY); smsNumberLabel.setVisible(false); constraints.anchor = GridBagConstraints.NORTHEAST; constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 0f; constraints.weighty = 0f; constraints.insets = new Insets(0, 2, 0, 2); constraints.gridheight = 1; constraints.gridwidth = 1; centerPanel.add(smsNumberLabel, constraints); return centerPanel; } /** * Initializes the sms menu. * * @param centerPanel the parent panel */ private void initSmsLabel(final JPanel centerPanel) { GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.NORTHWEST; constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 0; constraints.gridheight = 1; constraints.weightx = 0f; constraints.weighty = 0f; constraints.insets = new Insets(0, 3, 0, 0); ImageID smsIcon = new ImageID("service.gui.icons.SEND_SMS"); ImageID selectedIcon = new ImageID("service.gui.icons.SEND_SMS_SELECTED"); smsButton = new SIPCommToggleButton( ImageLoader.getImage(smsIcon), ImageLoader.getImage(selectedIcon), ImageLoader.getImage(smsIcon), ImageLoader.getImage(selectedIcon)); smsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { smsMode = smsButton.isSelected(); Color bgColor; if (smsMode) { bgColor = new Color(GuiActivator.getResources() .getColor("service.gui.LIST_SELECTION_COLOR")); smsCharCountLabel.setVisible(true); smsNumberLabel.setVisible(true); } else { bgColor = Color.WHITE; smsCharCountLabel.setVisible(false); smsNumberLabel.setVisible(false); } centerPanel.setBackground(bgColor); editorPane.setBackground(bgColor); } }); // We hide the sms label until we know if the chat supports sms. smsButton.setVisible(false); centerPanel.add(smsButton, constraints); } private void initTextArea(JPanel centerPanel) { GridBagConstraints constraints = new GridBagConstraints(); editorPane.setContentType("text/html"); editorPane.putClientProperty( JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); editorPane.setCaretPosition(0); editorPane.setEditorKit(new SIPCommHTMLEditorKit(this)); editorPane.getDocument().addUndoableEditListener(this); editorPane.getDocument().addDocumentListener(this); editorPane.addKeyListener(this); editorPane.addMouseListener(this); editorPane.setCursor( Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); editorPane.setDragEnabled(true); editorPane.setTransferHandler(new ChatTransferHandler(chatPanel)); scrollPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setOpaque(false); scrollPane.getViewport().setOpaque(false); scrollPane.setBorder(null); scrollPane.setViewportView(editorPane); constraints.anchor = GridBagConstraints.NORTHWEST; constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 1f; constraints.weighty = 1f; constraints.gridheight = 1; constraints.gridwidth = 1; constraints.insets = new Insets(0, 0, 0, 0); centerPanel.add(scrollPane, constraints); } /** * Runs clean-up for associated resources which need explicit disposal (e.g. * listeners keeping this instance alive because they were added to the * model which operationally outlives this instance). */ public void dispose() { /* * Stop the Timers because they're implicitly globally referenced and * thus don't let them retain this instance. */ typingTimer.stop(); typingTimer.removeActionListener(this); stoppedTypingTimer.stop(); stoppedTypingTimer.removeActionListener(this); if (typingState != OperationSetTypingNotifications.STATE_STOPPED) stopTypingTimer(); if(outdatedResourceTimer != null) { outdatedResourceTimer.cancel(); outdatedResourceTimer.purge(); outdatedResourceTimer = null; } editorPane.removeKeyListener(this); menuListeners.clear(); if(rightButtonMenu != null) { rightButtonMenu.dispose(); rightButtonMenu = null; } scrollPane.dispose(); } /** * Returns the editor panel, contained in this <tt>ChatWritePanel</tt>. * * @return The editor panel, contained in this <tt>ChatWritePanel</tt>. */ public JEditorPane getEditorPane() { return editorPane; } /** * Replaces the Ctrl+Enter send command with simple Enter. * * @param isEnter indicates if the new send command is enter or cmd-enter */ public void changeSendCommand(boolean isEnter) { ActionMap actionMap = editorPane.getActionMap(); actionMap.put("send", new SendMessageAction()); actionMap.put("newLine", new NewLineAction()); InputMap im = this.editorPane.getInputMap(); if (isEnter) { im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "send"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK), "newLine"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK), "newLine"); this.setToolTipText( "<html>" + GuiActivator.getResources() .getI18NString("service.gui.SEND_MESSAGE") + " - Enter <br> " + "Use Ctrl-Enter or Shift-Enter to make a new line" + "</html>"); } else { im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK), "send"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "newLine"); this.setToolTipText( GuiActivator.getResources() .getI18NString("service.gui.SEND_MESSAGE") + " Ctrl-Enter"); } } /** * Enables/disables the sms mode. * * @param selected <tt>true</tt> to enable sms mode, <tt>false</tt> - * otherwise */ public void setSmsSelected(boolean selected) { if((selected && !smsButton.isSelected()) || (!selected && smsButton.isSelected())) { smsButton.doClick(); } } /** * Returns <tt>true</tt> if the sms mode is enabled, otherwise returns * <tt>false</tt>. * @return <tt>true</tt> if the sms mode is enabled, otherwise returns * <tt>false</tt> */ public boolean isSmsSelected() { return smsMode; } /** * The <tt>SendMessageAction</tt> is an <tt>AbstractAction</tt> that * sends the text that is currently in the write message area. */ private class SendMessageAction extends AbstractAction { public void actionPerformed(ActionEvent e) { // chatPanel.stopTypingNotifications(); chatPanel.sendButtonDoClick(); } } /** * The <tt>NewLineAction</tt> is an <tt>AbstractAction</tt> that types * an enter in the write message area. */ private class NewLineAction extends AbstractAction { public void actionPerformed(ActionEvent e) { int caretPosition = editorPane.getCaretPosition(); HTMLDocument doc = (HTMLDocument) editorPane.getDocument(); try { doc.insertString(caretPosition, "\n", null); } catch (BadLocationException e1) { logger.error("Could not insert <br> to the document.", e1); } editorPane.setCaretPosition(caretPosition + 1); } } /** * Handles the <tt>UndoableEditEvent</tt>, by adding the content edit to * the <tt>UndoManager</tt>. * * @param e The <tt>UndoableEditEvent</tt>. */ public void undoableEditHappened(UndoableEditEvent e) { this.undo.addEdit(e.getEdit()); } /** * Implements the undo operation. */ private void undo() { try { undo.undo(); } catch (CannotUndoException e) { logger.error("Unable to undo.", e); } } /** * Implements the redo operation. */ private void redo() { try { undo.redo(); } catch (CannotRedoException e) { logger.error("Unable to redo.", e); } } /** * Sends typing notifications when user types. * * @param e the event. */ public void keyTyped(KeyEvent e) { if (ConfigurationUtils.isSendTypingNotifications() && !smsMode) { if (typingState != OperationSetTypingNotifications.STATE_TYPING) { stoppedTypingTimer.setDelay(2 * 1000); typingState = OperationSetTypingNotifications.STATE_TYPING; int result = chatPanel.getChatSession() .getCurrentChatTransport() .sendTypingNotification(typingState); if (result == ChatPanel.TYPING_NOTIFICATION_SUCCESSFULLY_SENT) typingTimer.start(); } if (!stoppedTypingTimer.isRunning()) stoppedTypingTimer.start(); else stoppedTypingTimer.restart(); } } /** * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code> * method, when CTRL+R is pressed invokes the * <code>ChatWritePanel.redo()</code> method. * * @param e the <tt>KeyEvent</tt> that notified us */ public void keyPressed(KeyEvent e) { if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z) // And not ALT(right ALT gives CTRL + ALT). && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) { if (undo.canUndo()) undo(); } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_R) // And not ALT(right ALT gives CTRL + ALT). && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) { if (undo.canRedo()) redo(); } else if(e.getKeyCode() == KeyEvent.VK_TAB) { if(!(chatPanel.getChatSession() instanceof ConferenceChatSession)) return; e.consume(); int index = ((JEditorPane)e.getSource()).getCaretPosition(); StringBuffer message = new StringBuffer(chatPanel.getMessage()); int position = index-1; while (position > 0 && (message.charAt(position) != ' ')) { position } if(position != 0) position++; String sequence = message.substring(position, index); if (sequence.length() <= 0) { // Do not look for matching contacts if the matching pattern is // 0 chars long, since all contacts will match. return; } Iterator<ChatContact<?>> iter = chatPanel.getChatSession() .getParticipants(); ArrayList<String> contacts = new ArrayList<String>(); while(iter.hasNext()) { ChatContact<?> c = iter.next(); if(c.getName().length() >= (index-position) && c.getName().substring(0,index-position).equals(sequence)) { message.replace(position, index, c.getName() .substring(0,index-position)); contacts.add(c.getName()); } } if(contacts.size() > 1) { char key = contacts.get(0).charAt(index-position-1); int pos = index-position-1; boolean flag = true; while(flag) { try { for(String name : contacts) { if(key != name.charAt(pos)) { flag = false; } } if(flag) { pos++; key = contacts.get(0).charAt(pos); } } catch(IndexOutOfBoundsException exp) { flag = false; } } message.replace(position, index, contacts.get(0) .substring(0,pos)); Iterator<String> contactIter = contacts.iterator(); String contactList = "<DIV align='left'><h5>"; while(contactIter.hasNext()) { contactList += contactIter.next() + " "; } contactList += "</h5></DIV>"; chatPanel.getChatConversationPanel() .appendMessageToEnd(contactList, ChatHtmlUtils.HTML_CONTENT_TYPE); } else if(contacts.size() == 1) { String limiter = (position == 0) ? ": " : ""; message.replace(position, index, contacts.get(0) + limiter); } try { ((JEditorPane)e.getSource()).getDocument().remove(0, ((JEditorPane)e.getSource()).getDocument().getLength()); ((JEditorPane)e.getSource()).getDocument().insertString(0, message.toString(), null); } catch (BadLocationException ex) { ex.printStackTrace(); } } else if (e.getKeyCode() == KeyEvent.VK_UP) { // Only enters editing mode if the write panel is empty in // order not to lose the current message contents, if any. if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) { this.chatPanel.startLastMessageCorrection(); e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { if (chatPanel.isMessageCorrectionActive()) { Document doc = editorPane.getDocument(); if (editorPane.getCaretPosition() == doc.getLength()) { chatPanel.stopMessageCorrection(); } } } } public void keyReleased(KeyEvent e) {} /** * Performs actions when typing timer has expired. * * @param e the <tt>ActionEvent</tt> that notified us */ public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (typingTimer.equals(source)) { if (typingState == OperationSetTypingNotifications.STATE_TYPING) { chatPanel.getChatSession().getCurrentChatTransport() .sendTypingNotification( OperationSetTypingNotifications.STATE_TYPING); } } else if (stoppedTypingTimer.equals(source)) { typingTimer.stop(); if (typingState == OperationSetTypingNotifications.STATE_TYPING) { try { typingState = OperationSetTypingNotifications.STATE_PAUSED; int result = chatPanel.getChatSession() .getCurrentChatTransport(). sendTypingNotification(typingState); if (result == ChatPanel.TYPING_NOTIFICATION_SUCCESSFULLY_SENT) stoppedTypingTimer.setDelay(3 * 1000); } catch (Exception ex) { logger.error("Failed to send typing notifications.", ex); } } else if (typingState == OperationSetTypingNotifications.STATE_PAUSED) { stopTypingTimer(); } } } /** * Stops the timer and sends a notification message. */ public void stopTypingTimer() { typingState = OperationSetTypingNotifications.STATE_STOPPED; int result = chatPanel.getChatSession().getCurrentChatTransport() .sendTypingNotification(typingState); if (result == ChatPanel.TYPING_NOTIFICATION_SUCCESSFULLY_SENT) stoppedTypingTimer.stop(); } /** * Opens the <tt>WritePanelRightButtonMenu</tt> when user clicks with the * right mouse button on the editor area. * * @param e the <tt>MouseEvent</tt> that notified us */ public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0 || (e.isControlDown() && !e.isMetaDown())) { Point p = e.getPoint(); SwingUtilities.convertPointToScreen(p, e.getComponent()); //SPELLCHECK ArrayList <JMenuItem> contributedMenuEntries = new ArrayList<JMenuItem>(); for(ChatMenuListener listener : this.menuListeners) { contributedMenuEntries.addAll( listener.getMenuElements(this.chatPanel, e)); } for(JMenuItem item : contributedMenuEntries) { rightButtonMenu.add(item); } JPopupMenu rightMenu = rightButtonMenu.makeMenu(contributedMenuEntries); rightMenu.setInvoker(editorPane); rightMenu.setLocation(p.x, p.y); rightMenu.setVisible(true); } } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} /** * Returns the <tt>WritePanelRightButtonMenu</tt> opened in this panel. * Used by the <tt>ChatWindow</tt>, when the ESC button is pressed, to * check if there is an open menu, which should be closed. * * @return the <tt>WritePanelRightButtonMenu</tt> opened in this panel */ public WritePanelRightButtonMenu getRightButtonMenu() { return rightButtonMenu; } /** * Returns the write area text as an html text. * * @return the write area text as an html text. */ public String getTextAsHtml() { String msgText = editorPane.getText(); String formattedString = msgText.replaceAll( "<html>|<head>|<body>|</html>|</head>|</body>", ""); formattedString = extractFormattedText(formattedString); // Returned string is formatted with newlines, etc. so we need to get // rid of them before checking for the ending <br/>. formattedString = formattedString.trim(); if (formattedString.endsWith("<BR/>")) formattedString = formattedString .substring(0, formattedString.lastIndexOf("<BR/>")); return formattedString; } /** * Returns the write area text as a plain text without any formatting. * * @return the write area text as a plain text without any formatting. */ public String getText() { try { Document doc = editorPane.getDocument(); return doc.getText(0, doc.getLength()); } catch (BadLocationException e) { logger.error("Could not obtain write area text.", e); } return null; } /** * Clears write message area. */ public void clearWriteArea() { try { this.editorPane.getDocument() .remove(0, editorPane.getDocument().getLength()); if(smsMode) { // use this to reset sms counter setSmsLabelVisible(true); // set the reset values smsCharCountLabel.setText(String.valueOf(smsCharCount)); smsNumberLabel.setText(String.valueOf(smsNumberCount)); } } catch (BadLocationException e) { logger.error("Failed to obtain write panel document content.", e); } } /** * Appends the given text to the end of the contained HTML document. This * method is used to insert smileys when user selects a smiley from the * menu. * * @param text the text to append. */ public void appendText(String text) { HTMLDocument doc = (HTMLDocument) editorPane.getDocument(); Element currentElement = doc.getCharacterElement(editorPane.getCaretPosition()); try { doc.insertAfterEnd(currentElement, text); } catch (BadLocationException e) { logger.error("Insert in the HTMLDocument failed.", e); } catch (IOException e) { logger.error("Insert in the HTMLDocument failed.", e); } this.editorPane.setCaretPosition(doc.getLength()); } /** * Return all html paragraph content separated by <BR/> tags. * * @param msgText the html text. * @return the string containing only paragraph content. */ private String extractFormattedText(String msgText) { String resultString = msgText.replaceAll("<p\\b[^>]*>", ""); return resultString.replaceAll("<\\/p>", "<BR/>"); } /** * Initializes the send via label and selector box. * * @return the chat transport selector box */ private Component createChatTransportSelectorBox() { // Initialize the "send via" selector box and adds it to the send panel. if (transportSelectorBox == null) { transportSelectorBox = new ChatTransportSelectorBox( chatPanel, chatPanel.getChatSession(), chatPanel.getChatSession().getCurrentChatTransport()); if(ConfigurationUtils.isHideAccountSelectionWhenPossibleEnabled() && transportSelectorBox.getMenu().getItemCount() <= 1) transportSelectorBox.setVisible(false); } return transportSelectorBox; } /** * * @param isVisible */ public void setTransportSelectorBoxVisible(boolean isVisible) { if (isVisible) { if (transportSelectorBox == null) { createChatTransportSelectorBox(); if (!transportSelectorBox.getMenu().isEnabled()) { // Show a message to the user that IM is not possible. chatPanel.getChatConversationPanel() .appendMessageToEnd("<h5>" + GuiActivator.getResources(). getI18NString("service.gui.MSG_NOT_POSSIBLE") + "</h5>", ChatHtmlUtils.HTML_CONTENT_TYPE); } else { GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.NORTHEAST; constraints.fill = GridBagConstraints.NONE; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 0f; constraints.weighty = 0f; constraints.gridheight = 1; constraints.gridwidth = 1; centerPanel.add(transportSelectorBox, constraints, 0); } } else { if( ConfigurationUtils .isHideAccountSelectionWhenPossibleEnabled() && transportSelectorBox.getMenu().getItemCount() <= 1) { transportSelectorBox.setVisible(false); } { transportSelectorBox.setVisible(true); } centerPanel.repaint(); } } else if (transportSelectorBox != null) { transportSelectorBox.setVisible(false); centerPanel.repaint(); } } /** * Selects the given chat transport in the send via box. * * @param chatTransport The chat transport to be selected. * @param isMessageOrFileTransferReceived Boolean telling us if this change * of the chat transport correspond to an effective switch to this new * transform (a mesaage received from this transport, or a file transfer * request received, or if the resource timeouted), or just a status update * telling us a new chatTransport is now available (i.e. another device has * startup). */ public void setSelectedChatTransport( final ChatTransport chatTransport, final boolean isMessageOrFileTransferReceived) { // We need to be sure that the following code is executed in the event // dispatch thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { setSelectedChatTransport( chatTransport, isMessageOrFileTransferReceived); } }); return; } // Check if this contact provider can manages several resources and thus // provides a resource timeout via the basic IM operation set. long timeout = -1; OperationSetBasicInstantMessaging opSetBasicIM = chatTransport.getProtocolProvider().getOperationSet( OperationSetBasicInstantMessaging.class); if(opSetBasicIM != null) { timeout = opSetBasicIM.getInactivityTimeout(); } if(isMessageOrFileTransferReceived) { isOutdatedResource = false; } // If this contact supports several resources, then schedule the timer: // - If the resource is outdated, then trigger the timer now (to try to // switch to the bare ID if now available). // - If the new reousrce transport is really effective (i.e. we have // received a message from this resource). if(timeout != -1 && (isMessageOrFileTransferReceived || isOutdatedResource)) { // If there was already a timeout, but the bare ID was not available // (i.e. a single resource present). Then call the timeout procedure // now in order to switch to the bare ID. if(isOutdatedResource) { timeout = 0; } // Cancels the preceding timer. if(outdatedResourceTimer != null) { outdatedResourceTimer.cancel(); outdatedResourceTimer.purge(); } // Schedules the timer. if(chatTransport.getResourceName() != null) { OutdatedResourceTimerTask task = new OutdatedResourceTimerTask(); outdatedResourceTimer = new java.util.Timer(); outdatedResourceTimer.schedule(task, timeout); } } // Sets the new resource transport is really effective (i.e. we have // received a message from this resource). // if we do not have any selected resource, or the currently selected // if offline if(transportSelectorBox != null && (isMessageOrFileTransferReceived || (!transportSelectorBox.hasSelectedTransport() || !chatPanel.getChatSession().getCurrentChatTransport() .getStatus().isOnline()))) { transportSelectorBox.setSelected(chatTransport); } } /** * Adds the given chatTransport to the given send via selector box. * * @param chatTransport the transport to add */ public void addChatTransport(final ChatTransport chatTransport) { // We need to be sure that the following code is executed in the event // dispatch thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { addChatTransport(chatTransport); } }); return; } if (transportSelectorBox != null) { transportSelectorBox.addChatTransport(chatTransport); // it was hidden cause we wanted to hide when there is only one // provider if(!transportSelectorBox.isVisible() && ConfigurationUtils .isHideAccountSelectionWhenPossibleEnabled() && transportSelectorBox.getMenu().getItemCount() > 1) { transportSelectorBox.setVisible(true); } } } /** * Updates the status of the given chat transport in the send via selector * box and notifies the user for the status change. * @param chatTransport the <tt>chatTransport</tt> to update */ public void updateChatTransportStatus(final ChatTransport chatTransport) { // We need to be sure that the following code is executed in the event // dispatch thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateChatTransportStatus(chatTransport); } }); return; } if (transportSelectorBox != null) transportSelectorBox.updateTransportStatus(chatTransport); } /** * Opens the selector box containing the protocol contact icons. * This is the menu, where user could select the protocol specific * contact to communicate through. */ public void openChatTransportSelectorBox() { transportSelectorBox.getMenu().doClick(); } /** * Removes the given chat status state from the send via selector box. * * @param chatTransport the transport to remove */ public void removeChatTransport(final ChatTransport chatTransport) { // We need to be sure that the following code is executed in the event // dispatch thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { removeChatTransport(chatTransport); } }); return; } if (transportSelectorBox != null) transportSelectorBox.removeChatTransport(chatTransport); if(transportSelectorBox != null && transportSelectorBox.getMenu().getItemCount() == 1 && ConfigurationUtils.isHideAccountSelectionWhenPossibleEnabled()) { transportSelectorBox.setVisible(false); } } /** * Show the sms menu. * @param isVisible <tt>true</tt> to show the sms menu, <tt>false</tt> - * otherwise */ public void setSmsLabelVisible(boolean isVisible) { // Re-init sms count properties. smsCharCount = 160; smsNumberCount = 1; smsButton.setVisible(isVisible); centerPanel.repaint(); } /** * Saves the given font configuration as default, thus making it the default * configuration for all chats. * * @param fontFamily the font family * @param fontSize the font size * @param isBold indicates if the font is bold * @param isItalic indicates if the font is italic * @param isUnderline indicates if the font is underline */ public void saveDefaultFontConfiguration( String fontFamily, int fontSize, boolean isBold, boolean isItalic, boolean isUnderline, Color color) { ConfigurationUtils.setChatDefaultFontFamily(fontFamily); ConfigurationUtils.setChatDefaultFontSize(fontSize); ConfigurationUtils.setChatFontIsBold(isBold); ConfigurationUtils.setChatFontIsItalic(isItalic); ConfigurationUtils.setChatFontIsUnderline(isUnderline); ConfigurationUtils.setChatDefaultFontColor(color); } /** * Sets the font family and size * @param family the family name * @param size the size */ public void setFontFamilyAndSize(String family, int size) { // Family ActionEvent evt = new ActionEvent( editorPane, ActionEvent.ACTION_PERFORMED, family); Action action = new StyledEditorKit.FontFamilyAction(family, family); action.actionPerformed(evt); // Size evt = new ActionEvent(editorPane, ActionEvent.ACTION_PERFORMED, Integer.toString(size)); action = new StyledEditorKit.FontSizeAction( Integer.toString(size), size); action.actionPerformed(evt); } /** * Enables the bold style * @param b TRUE enable - FALSE disable */ public void setBoldStyleEnable(boolean b) { StyledEditorKit editorKit = (StyledEditorKit) editorPane.getEditorKit(); MutableAttributeSet attr = editorKit.getInputAttributes(); if (b && !StyleConstants.isBold(attr)) { setStyleConstant( new HTMLEditorKit.BoldAction(), StyleConstants.Bold); } } /** * Enables the italic style * @param b TRUE enable - FALSE disable */ public void setItalicStyleEnable(boolean b) { StyledEditorKit editorKit = (StyledEditorKit) editorPane.getEditorKit(); MutableAttributeSet attr = editorKit.getInputAttributes(); if (b && !StyleConstants.isItalic(attr)) { setStyleConstant( new HTMLEditorKit.ItalicAction(), StyleConstants.Italic); } } /** * Enables the underline style * @param b TRUE enable - FALSE disable */ public void setUnderlineStyleEnable(boolean b) { StyledEditorKit editorKit = (StyledEditorKit) editorPane.getEditorKit(); MutableAttributeSet attr = editorKit.getInputAttributes(); if (b && !StyleConstants.isUnderline(attr)) { setStyleConstant( new HTMLEditorKit.UnderlineAction(), StyleConstants.Underline); } } /** * Sets the font color * @param color the color */ public void setFontColor(Color color) { ActionEvent evt = new ActionEvent(editorPane, ActionEvent.ACTION_PERFORMED, ""); Action action = new HTMLEditorKit.ForegroundAction( Integer.toString(color.getRGB()), color); action.actionPerformed(evt); } /** * Sets the given style constant. * * @param action the action * @param styleConstant the style constant */ private void setStyleConstant(Action action, Object styleConstant) { ActionEvent event = new ActionEvent(editorPane, ActionEvent.ACTION_PERFORMED, styleConstant.toString()); action.actionPerformed(event); } /** * Adds the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void addChatEditorMenuListener(ChatMenuListener l) { this.menuListeners.add(l); } /** * Removes the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void removeChatEditorMenuListener(ChatMenuListener l) { this.menuListeners.remove(l); } /** * Reloads menu. */ public void loadSkin() { getRightButtonMenu().loadSkin(); } public void changedUpdate(DocumentEvent documentevent) {} /** * Updates write panel size and adjusts sms properties if the sms menu * is visible. * * @param event the <tt>DocumentEvent</tt> that notified us */ public void insertUpdate(DocumentEvent event) { // If we're in sms mode count the chars typed. if (smsButton.isVisible()) { if (smsCharCount == 0) { smsCharCount = 159; smsNumberCount ++; } else smsCharCount smsCharCountLabel.setText(String.valueOf(smsCharCount)); smsNumberLabel.setText(String.valueOf(smsNumberCount)); } } /** * Updates write panel size and adjusts sms properties if the sms menu * is visible. * * @param event the <tt>DocumentEvent</tt> that notified us */ public void removeUpdate(DocumentEvent event) { // If we're in sms mode count the chars typed. if (smsButton.isVisible()) { if (smsCharCount == 160 && smsNumberCount > 1) { smsCharCount = 0; smsNumberCount } else smsCharCount++; smsCharCountLabel.setText(String.valueOf(smsCharCount)); smsNumberLabel.setText(String.valueOf(smsNumberCount)); } } /** * Sets the background of the write area to the specified color. * * @param color The color to set the background to. */ public void setEditorPaneBackground(Color color) { this.centerPanel.setBackground(color); this.editorPane.setBackground(color); } /** * The task called when the current transport resource timed-out (no * acitivty since a long time). Then this task resets the destination to the * bare id. */ private class OutdatedResourceTimerTask extends TimerTask { /** * The action to be performed by this timer task. */ public void run() { outdatedResourceTimer = null; if(chatPanel.getChatSession() != null) { Iterator<ChatTransport> transports = chatPanel.getChatSession().getChatTransports(); ChatTransport transport = null; while(transports.hasNext()) { transport = transports.next(); // We found the bare ID, then set it as the current resource // transport. // choose only online resources if(transport.getResourceName() == null && transport.getStatus().isOnline()) { isOutdatedResource = false; setSelectedChatTransport(transport, true); return; } } } // If there is no bare ID available, then set the current resource // transport as outdated. isOutdatedResource = true; } } /** * Initializes plug-in components for this container. */ void initPluginComponents() { // Search for plugin components registered through the OSGI bundle // context. ServiceReference[] serRefs = null; String osgiFilter = "(" + net.java.sip.communicator.service.gui.Container.CONTAINER_ID + "="+net.java.sip.communicator.service.gui.Container. CONTAINER_CHAT_WRITE_PANEL.getID()+")"; try { serRefs = GuiActivator.bundleContext.getServiceReferences( PluginComponentFactory.class.getName(), osgiFilter); } catch (InvalidSyntaxException exc) { logger.error("Could not obtain plugin reference.", exc); } if (serRefs != null) { for (int i = 0; i < serRefs.length; i ++) { PluginComponentFactory factory = (PluginComponentFactory) GuiActivator .bundleContext.getService(serRefs[i]); PluginComponent component = factory.getPluginComponentInstance(this); ChatSession chatSession = chatPanel.getChatSession(); if (chatSession != null) { ChatTransport currentTransport = chatSession.getCurrentChatTransport(); Object currentDescriptor = currentTransport.getDescriptor(); if (currentDescriptor instanceof Contact) { Contact contact = (Contact) currentDescriptor; component.setCurrentContact( contact, currentTransport.getResourceName()); } } if (component.getComponent() == null) continue; GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.NORTHEAST; constraints.fill = GridBagConstraints.NONE; constraints.gridy = 0; constraints.gridheight = 1; constraints.weightx = 0f; constraints.weighty = 0f; constraints.insets = new Insets(0, 3, 0, 0); centerPanel.add( (Component)component.getComponent(), constraints); } } GuiActivator.getUIService().addPluginComponentListener(this); this.centerPanel.repaint(); } /** * Indicates that a new plugin component has been added. Adds it to this * container if it belongs to it. * * @param event the <tt>PluginComponentEvent</tt> that notified us */ public void pluginComponentAdded(PluginComponentEvent event) { PluginComponentFactory factory = event.getPluginComponentFactory(); if (!factory.getContainer().equals( net.java.sip.communicator.service. gui.Container.CONTAINER_CHAT_WRITE_PANEL)) return; PluginComponent component = factory.getPluginComponentInstance(this); ChatSession chatSession = chatPanel.getChatSession(); if (chatSession != null) { ChatTransport currentTransport = chatSession.getCurrentChatTransport(); Object currentDescriptor = currentTransport.getDescriptor(); if (currentDescriptor instanceof Contact) { Contact contact = (Contact) currentDescriptor; component.setCurrentContact( contact, currentTransport.getResourceName()); } } GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.NORTHEAST; constraints.fill = GridBagConstraints.NONE; constraints.gridy = 0; constraints.gridheight = 1; constraints.weightx = 0f; constraints.weighty = 0f; constraints.insets = new Insets(0, 3, 0, 0); centerPanel.add((Component) component.getComponent(), constraints); this.centerPanel.repaint(); } /** * Removes the according plug-in component from this container. * * @param event the <tt>PluginComponentEvent</tt> that notified us */ public void pluginComponentRemoved(PluginComponentEvent event) { PluginComponentFactory factory = event.getPluginComponentFactory(); if (!factory.getContainer().equals( net.java.sip.communicator.service. gui.Container.CONTAINER_CHAT_WRITE_PANEL)) return; Component c = (Component)factory.getPluginComponentInstance(this) .getComponent(); this.centerPanel.remove(c); this.centerPanel.repaint(); } }
package net.java.sip.communicator.impl.protocol.irc; import java.util.*; import java.util.concurrent.atomic.*; import net.java.sip.communicator.util.*; import com.ircclouds.irc.api.*; import com.ircclouds.irc.api.domain.*; import com.ircclouds.irc.api.domain.messages.*; import com.ircclouds.irc.api.state.*; /** * Manager for presence status of IRC connection. * * There is (somewhat primitive) support for online presence by periodically * querying IRC server with ISON requests for each of the members in the contact * list. * * TODO Support for 'a' (Away) user mode. (Check this again, since I also see * 'a' used for other purposes. This may be one of those ambiguous letters that * every server interprets differently.) * * TODO Jitsi is currently missing support for presence in MUC (ChatRoomMember). * * TODO Improve presence watcher by using WATCH or MONITOR. (Monitor does not * seem to support away status, though) * * @author Danny van Heumen */ public class PresenceManager { /** * Logger. */ private static final Logger LOGGER = Logger .getLogger(PresenceManager.class); /** * Delay before starting the presence watcher task for the first time. */ private static final long INITIAL_PRESENCE_WATCHER_DELAY = 10000L; /** * Period for the presence watcher timer. */ private static final long PRESENCE_WATCHER_PERIOD = 60000L; /** * IRC client library instance. * * Instance must be thread-safe! */ private final IRCApi irc; /** * IRC client connection state. */ private final IIRCState connectionState; /** * Instance of OperationSetPersistentPresence for updates. */ private final OperationSetPersistentPresenceIrcImpl operationSet; /** * Synchronized set of nicks to watch for presence changes. */ private final SortedSet<String> nickWatchList; /** * Maximum away message length according to server ISUPPORT instructions. * * <p>This value is not guaranteed, so it may be <tt>null</tt>.</p> */ private final Integer isupportAwayLen; /** * Server identity. */ private final AtomicReference<String> serverIdentity = new AtomicReference<String>(null); /** * Current presence status. */ private volatile boolean away = false; /** * Active away message. */ private volatile String currentMessage = ""; /** * Proposed away message. */ private volatile String submittedMessage = "Away"; /** * Constructor. * * @param irc thread-safe irc client library instance * @param connectionState irc client connection state instance * @param operationSet OperationSetPersistentPresence irc implementation for * handling presence changes. * @param persistentNickWatchList persistent nick watch list to use (The * sortedset implementation must be synchronized!) */ public PresenceManager(final IRCApi irc, final IIRCState connectionState, final OperationSetPersistentPresenceIrcImpl operationSet, final SortedSet<String> persistentNickWatchList) { if (connectionState == null) { throw new IllegalArgumentException( "connectionState cannot be null"); } this.connectionState = connectionState; if (operationSet == null) { throw new IllegalArgumentException("operationSet cannot be null"); } this.operationSet = operationSet; if (irc == null) { throw new IllegalArgumentException("irc cannot be null"); } this.irc = irc; if (persistentNickWatchList == null) { this.nickWatchList = Collections.synchronizedSortedSet(new TreeSet<String>()); } else { this.nickWatchList = persistentNickWatchList; } this.irc.addListener(new PresenceListener()); this.isupportAwayLen = parseISupportAwayLen(this.connectionState); setUpPresenceWatcher(); } /** * Set up a timer for watching the presence of nicks in the watch list. */ private void setUpPresenceWatcher() { // FIFO query list to be shared between presence watcher task and // presence reply listener. final List<List<String>> queryList = Collections.synchronizedList(new LinkedList<List<String>>()); final Timer presenceWatcher = new Timer(); irc.addListener(new PresenceReplyListener(presenceWatcher, queryList)); final PresenceWatcherTask task = new PresenceWatcherTask(this.nickWatchList, queryList, this.irc, this.connectionState, this.serverIdentity); presenceWatcher.schedule(task, INITIAL_PRESENCE_WATCHER_DELAY, PRESENCE_WATCHER_PERIOD); LOGGER.trace("Presence watcher set up."); } /** * Parse the ISUPPORT parameter for server's away message length. * * @param state the connection state * @return returns instance with max away message length or <tt>null</tt> if * not specified. */ private Integer parseISupportAwayLen(final IIRCState state) { final String value = state.getServerOptions().getKey(ISupport.AWAYLEN.name()); if (value == null) { return null; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Setting ISUPPORT parameter " + ISupport.AWAYLEN.name() + " to " + value); } return new Integer(value); } /** * Check current Away state. * * @return returns <tt>true</tt> if away or <tt>false</tt> if not away */ public boolean isAway() { return this.away; } /** * Get away message. * * @return returns currently active away message or "" if currently not * away. */ public String getMessage() { return this.currentMessage; } /** * Set away status and message. Disable away status by providing * <tt>null</tt> message. * * @param isAway <tt>true</tt> to enable away mode + message, or * <tt>false</tt> to disable * @param awayMessage away message, the message is only available when the * local user is set to away. If <tt>null</tt> is provided, don't * set a new away message. */ public void away(final boolean isAway, final String awayMessage) { if (awayMessage != null) { this.submittedMessage = verifyMessage(awayMessage); } if (isAway && (!this.away || awayMessage != null)) { // In case we aren't AWAY yet, or if there is a message to set. this.irc.rawMessage("AWAY :" + this.submittedMessage); } else if (isAway != this.away) { this.irc.rawMessage("AWAY"); } } /** * Set new prepared away message for later moment when IRC connection is set * to away. * * @param message the away message to prepare * @return returns message after verification */ private String verifyMessage(final String message) { if (message == null || message.isEmpty()) { throw new IllegalArgumentException( "away message must be non-null and non-empty"); } if (this.isupportAwayLen != null && message.length() > this.isupportAwayLen.intValue()) { throw new IllegalArgumentException( "the away message must not be longer than " + this.isupportAwayLen.intValue() + " characters according to server's parameters."); } return message; } /** * Add new nick to watch list. * * @param nick nick to add to watch list */ public void addNickWatch(final String nick) { this.nickWatchList.add(nick); } /** * Remove nick from watch list. * * @param nick nick to remove from watch list */ public void removeNickWatch(final String nick) { this.nickWatchList.remove(nick); } /** * Presence listener implementation for keeping track of presence changes in * the IRC connection. * * @author Danny van Heumen */ private final class PresenceListener extends AbstractIrcMessageListener { /** * Reply for acknowledging transition to available (not away any * longer). */ private static final int IRC_RPL_UNAWAY = 305; /** * Reply for acknowledging transition to away. */ private static final int IRC_RPL_NOWAWAY = 306; /** * Constructor. */ public PresenceListener() { super(PresenceManager.this.irc, PresenceManager.this.connectionState); } /** * Handle events for presence-related server replies. */ @Override public void onServerNumericMessage(final ServerNumericMessage msg) { if (PresenceManager.this.serverIdentity.get() == null) { PresenceManager.this.serverIdentity.set(msg.getSource() .getHostname()); } Integer msgCode = msg.getNumericCode(); if (msgCode == null) { return; } int code = msgCode.intValue(); switch (code) { case IRC_RPL_UNAWAY: PresenceManager.this.currentMessage = ""; PresenceManager.this.away = false; operationSet.updatePresenceStatus(IrcStatusEnum.AWAY, IrcStatusEnum.ONLINE); LOGGER.debug("Away status disabled."); break; case IRC_RPL_NOWAWAY: PresenceManager.this.currentMessage = PresenceManager.this.submittedMessage; PresenceManager.this.away = true; operationSet.updatePresenceStatus(IrcStatusEnum.ONLINE, IrcStatusEnum.AWAY); LOGGER.debug("Away status enabled with message \"" + PresenceManager.this.currentMessage + "\""); break; default: break; } } } /** * Task for watching nick presence. * * @author Danny van Heumen */ private static final class PresenceWatcherTask extends TimerTask { /** * Static overhead for ISON response message. * * Additional 10 chars extra overhead as fail-safe, as I was not able to * find the exact number in the overhead computation. */ private static final int ISON_RESPONSE_STATIC_MESSAGE_OVERHEAD = 18; /** * List containing nicks that must be watched. */ private final SortedSet<String> watchList; /** * FIFO list storing each ISON query that is sent, for use when * responses return. */ private final List<List<String>> queryList; /** * IRC instance. */ private final IRCApi irc; /** * IRC connection state. */ private final IIRCState connectionState; /** * Reference to the current server identity. */ private final AtomicReference<String> serverIdentity; /** * Constructor. * * @param watchList the list of nicks to watch * @param queryList list containing list of nicks of each ISON query * @param irc the irc instance * @param connectionState the connection state instance * @param serverIdentity container with the current server identity for * use in overhead calculation */ public PresenceWatcherTask(final SortedSet<String> watchList, final List<List<String>> queryList, final IRCApi irc, final IIRCState connectionState, final AtomicReference<String> serverIdentity) { if (watchList == null) { throw new IllegalArgumentException("watchList cannot be null"); } this.watchList = watchList; if (queryList == null) { throw new IllegalArgumentException("queryList cannot be null"); } this.queryList = queryList; if (irc == null) { throw new IllegalArgumentException("irc cannot be null"); } this.irc = irc; if (connectionState == null) { throw new IllegalArgumentException( "connectionState cannot be null"); } this.connectionState = connectionState; if (serverIdentity == null) { throw new IllegalArgumentException( "serverIdentity reference cannot be null"); } this.serverIdentity = serverIdentity; } /** * The implementation of the task. */ @Override public void run() { if (this.watchList.isEmpty()) { LOGGER.trace("Watch list is empty. Not querying for online " + "presence."); return; } if (this.serverIdentity.get() == null) { LOGGER.trace("Server identity not available yet. Skipping " + "this presence status query."); return; } LOGGER .trace("Watch list contains nicks: querying presence status."); final StringBuilder query = new StringBuilder(); final LinkedList<String> list; synchronized (this.watchList) { list = new LinkedList<String>(this.watchList); } LinkedList<String> nicks = new LinkedList<String>(); // The ISON reply contains the most overhead, so base the maximum // number of nicks limit on that. final int maxQueryLength = MessageManager.IRC_PROTOCOL_MAXIMUM_MESSAGE_SIZE - overhead(); for (String nick : list) { if (query.length() + nick.length() >= maxQueryLength) { this.queryList.add(nicks); this.irc.rawMessage(createQuery(query)); // Initialize new data types query.delete(0, query.length()); nicks = new LinkedList<String>(); } query.append(nick); query.append(' '); nicks.add(nick); } if (query.length() > 0) { // Send remaining entries. this.queryList.add(nicks); this.irc.rawMessage(createQuery(query)); } } /** * Create an ISON query from the StringBuilder containing the list of * nicks. * * @param nicklist the list of nicks as a StringBuilder instance * @return returns the ISON query string */ private String createQuery(final StringBuilder nicklist) { return "ISON " + nicklist; } /** * Calculate overhead for ISON response message. * * @return returns amount of overhead in response message */ private int overhead() { return ISON_RESPONSE_STATIC_MESSAGE_OVERHEAD + this.serverIdentity.get().length() + this.connectionState.getNickname().length(); } } /** * Presence reply listener. * * Listener that acts on various replies that give an indication of actual * presence or presence changes, such as RPL_ISON and ERR_NOSUCHNICKCHAN. * * @author Danny van Heumen */ private final class PresenceReplyListener extends AbstractIrcMessageListener { /** * Reply for ISON query. */ private static final int RPL_ISON = 303; /** * Error reply in case nick does not exist on server. */ private static final int ERR_NOSUCHNICK = 401; /** * Timer for presence watcher task. */ private final Timer timer; /** * FIFO list containing list of nicks for each query. */ private final List<List<String>> queryList; /** * Constructor. * * @param timer Timer for presence watcher task * @param queryList List of executed queries with expected nicks lists. */ public PresenceReplyListener(final Timer timer, final List<List<String>> queryList) { super(PresenceManager.this.irc, PresenceManager.this.connectionState); if (timer == null) { throw new IllegalArgumentException("timer cannot be null"); } this.timer = timer; if (queryList == null) { throw new IllegalArgumentException("queryList cannot be null"); } this.queryList = queryList; } /** * Update nick watch list upon receiving a nick change message for a * nick that is on the watch list. * * NOTE: This nick change event could be handled earlier than the * handler that fires the contact rename event. This will result in a * missed presence update. However, since the nick change was just * announced, it is reasonable to assume that the user is still online. * * @param msg the nick message */ @Override public void onNickChange(final NickMessage msg) { if (msg == null || msg.getSource() == null) { return; } final String oldNick = msg.getSource().getNick(); final String newNick = msg.getNewNick(); if (oldNick == null || newNick == null) { LOGGER.error("Incomplete nick change message. Old nick: '" + oldNick + "', new nick: '" + newNick + "'."); return; } synchronized (PresenceManager.this.nickWatchList) { if (PresenceManager.this.nickWatchList.contains(oldNick)) { PresenceManager.this.nickWatchList.remove(oldNick); PresenceManager.this.nickWatchList.add(newNick); } } } /** * Message handling for RPL_ISON message and other indicators. * * @param msg the message */ @Override public void onServerNumericMessage(final ServerNumericMessage msg) { if (msg == null || msg.getNumericCode() == null) { return; } switch (msg.getNumericCode()) { case RPL_ISON: final String[] nicks = msg.getText().substring(1).split(" "); final List<String> offline; if (this.queryList.isEmpty()) { // If no query list exists, we can only update nicks that // are online, since we do not know who we have actually // queried for. offline = new LinkedList<String>(); } else { offline = this.queryList.remove(0); } for (String nick : nicks) { update(nick, IrcStatusEnum.ONLINE); offline.remove(nick); } for (String nick : offline) { update(nick, IrcStatusEnum.OFFLINE); } break; case ERR_NOSUCHNICK: final String errortext = msg.getText(); final int idx = errortext.indexOf(' '); if (idx == -1) { LOGGER.info("ERR_NOSUCHNICK message does not have " + "expected format."); return; } final String errNick = errortext.substring(0, idx); update(errNick, IrcStatusEnum.OFFLINE); break; default: break; } } /** * Upon receiving a private message from a user, conclude that the user * must then be online and update its presence status. * * @param msg the message */ @Override public void onUserPrivMessage(final UserPrivMsg msg) { if (msg == null || msg.getSource() == null) { return; } final IRCUser user = msg.getSource(); update(user.getNick(), IrcStatusEnum.ONLINE); } /** * Upon receiving a notice from a user, conclude that the user * must then be online and update its presence status. * * @param msg the message */ @Override public void onUserNotice(final UserNotice msg) { if (msg == null || msg.getSource() == null) { return; } final IRCUser user = msg.getSource(); update(user.getNick(), IrcStatusEnum.ONLINE); } /** * Upon receiving an action from a user, conclude that the user * must then be online and update its presence status. * * @param msg the message */ @Override public void onUserAction(final UserActionMsg msg) { if (msg == null || msg.getSource() == null) { return; } final IRCUser user = msg.getSource(); update(user.getNick(), IrcStatusEnum.ONLINE); } /** * Handler for channel join events. */ @Override public void onChannelJoin(final ChanJoinMessage msg) { if (msg == null || msg.getSource() == null) { return; } final String user = msg.getSource().getNick(); update(user, IrcStatusEnum.ONLINE); } /** * Handler for user quit events. * * @param msg the quit message */ @Override public void onUserQuit(final QuitMessage msg) { super.onUserQuit(msg); final String user = msg.getSource().getNick(); if (user == null) { return; } if (localUser(user)) { // Stop presence watcher task. this.timer.cancel(); updateAll(IrcStatusEnum.OFFLINE); } else { update(user, IrcStatusEnum.OFFLINE); } } /** * In case a fatal error occurs, remove the listener. * * @param msg the error message */ @Override public void onError(final ErrorMessage msg) { super.onError(msg); // Stop presence watcher task. this.timer.cancel(); updateAll(IrcStatusEnum.OFFLINE); } /** * Update the status of a single nick. * * @param nick the nick to update * @param status the new status */ private void update(final String nick, final IrcStatusEnum status) { // User is some other user, so check if we are watching that nick. if (!PresenceManager.this.nickWatchList.contains(nick)) { return; } PresenceManager.this.operationSet.updateNickContactPresence(nick, status); } /** * Update the status of all contacts in the nick watch list. * * @param status the new status */ private void updateAll(final IrcStatusEnum status) { final LinkedList<String> list; synchronized (PresenceManager.this.nickWatchList) { list = new LinkedList<String>(PresenceManager.this.nickWatchList); } for (String nick : list) { PresenceManager.this.operationSet.updateNickContactPresence( nick, status); } } } }
package net.java.sip.communicator.impl.protocol.sip; import static net.java.sip.communicator.service.protocol.OperationSetBasicTelephony.*; import gov.nist.javax.sip.header.*; import java.net.*; import java.text.*; import java.util.*; import javax.sip.*; import javax.sip.address.*; import javax.sip.address.URI; import javax.sip.header.*; import javax.sip.message.*; import net.java.sip.communicator.impl.protocol.sip.sdp.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.Contact; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.media.*; import net.java.sip.communicator.util.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.MediaType; // disambiguate import org.jitsi.service.neomedia.control.*; /** * Our SIP implementation of the default CallPeer; * * @author Emil Ivov * @author Lubomir Marinov */ public class CallPeerSipImpl extends MediaAwareCallPeer<CallSipImpl, CallPeerMediaHandlerSipImpl, ProtocolProviderServiceSipImpl> { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(CallPeerSipImpl.class); /** * The sub-type of the content carried by SIP INFO <tt>Requests</tt> for the * purposes of <tt>picture_fast_update</tt>. */ static final String PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE = "media_control+xml"; /** * The sip address of this peer */ private Address peerAddress = null; private Dialog jainSipDialog = null; /** * The SIP transaction that established this call. This was previously kept * in the jain-sip dialog but got deprecated there so we're now keeping it * here. */ private Transaction latestInviteTransaction = null; /** * The jain sip provider instance that is responsible for sending and * receiving requests and responses related to this call peer. */ private SipProvider jainSipProvider = null; /** * The transport address that we are using to address the peer or the * first one that we'll try when we next send them a message (could be the * address of our sip registrar). */ private InetSocketAddress transportAddress = null; /** * A reference to the <tt>SipMessageFactory</tt> instance that we should * use when creating requests. */ private final SipMessageFactory messageFactory; /** * The <tt>List</tt> of <tt>MethodProcessorListener</tt>s interested in how * this <tt>CallPeer</tt> processes SIP signaling. */ private final List<MethodProcessorListener> methodProcessorListeners = new LinkedList<MethodProcessorListener>(); /** * The indicator which determines whether the local peer may send * <tt>picture_fast_update</tt> to this remote peer (as part of the * execution of {@link #requestKeyFrame()}). */ private boolean sendPictureFastUpdate = KeyFrameControl.KeyFrameRequester.SIGNALING.equals( SipActivator.getConfigurationService().getString( KeyFrameControl.KeyFrameRequester.PREFERRED_PNAME, KeyFrameControl.KeyFrameRequester.DEFAULT_PREFERRED)); /** * Creates a new call peer with address <tt>peerAddress</tt>. * * @param peerAddress the JAIN SIP <tt>Address</tt> of the new call peer. * @param owningCall the call that contains this call peer. * @param containingTransaction the transaction that created the call peer. * @param sourceProvider the provider that the containingTransaction belongs * to. */ public CallPeerSipImpl(Address peerAddress, CallSipImpl owningCall, Transaction containingTransaction, SipProvider sourceProvider) { super(owningCall); this.peerAddress = peerAddress; this.messageFactory = getProtocolProvider().getMessageFactory(); super.setMediaHandler( new CallPeerMediaHandlerSipImpl(this) { @Override protected boolean requestKeyFrame() { return CallPeerSipImpl.this.requestKeyFrame(); } }); setDialog(containingTransaction.getDialog()); setLatestInviteTransaction(containingTransaction); setJainSipProvider(sourceProvider); } /** * Returns a String locator for that peer. * * @return the peer's address or phone number. */ public String getAddress() { SipURI sipURI = (SipURI) peerAddress.getURI(); return sipURI.getUser() + "@" + sipURI.getHost(); } /** * Returns full URI of the address. * * @return full URI of the address */ public String getURI() { return getPeerAddress().getURI().toString(); } /** * Returns the address of the remote party (making sure that it corresponds * to the latest address we've received) and caches it. * * @return the most recent <tt>javax.sip.address.Address</tt> that we have * for the remote party. */ public Address getPeerAddress() { Dialog dialog = getDialog(); if (dialog != null) { Address remoteParty = dialog.getRemoteParty(); if (remoteParty != null) { //update the address we've cached. peerAddress = remoteParty; } } return peerAddress; } /** * Returns a human readable name representing this peer. * * @return a String containing a name for that peer. */ public String getDisplayName() { String displayName = getPeerAddress().getDisplayName(); if(displayName == null) { Contact contact = getContact(); if (contact != null) displayName = contact.getDisplayName(); else { URI peerURI = getPeerAddress().getURI(); if (peerURI instanceof SipURI) { String userName = ((SipURI) peerURI).getUser(); if (userName != null && userName.length() > 0) displayName = userName; } if (displayName == null) { displayName = peerURI.toString(); } } } if(displayName.startsWith("sip:")) displayName = displayName.substring(4); return displayName; } /** * Sets a human readable name representing this peer. * * @param displayName the peer's display name */ public void setDisplayName(String displayName) { String oldName = getDisplayName(); try { this.peerAddress.setDisplayName(displayName); } catch (ParseException ex) { //couldn't happen logger.error(ex.getMessage(), ex); throw new IllegalArgumentException(ex.getMessage()); } //Fire the Event fireCallPeerChangeEvent( CallPeerChangeEvent.CALL_PEER_DISPLAY_NAME_CHANGE, oldName, displayName); } public void setDialog(Dialog dialog) { this.jainSipDialog = dialog; } public Dialog getDialog() { return jainSipDialog; } /** * Sets the transaction instance that contains the INVITE which started * this call. * * @param transaction the Transaction that initiated this call. */ public void setLatestInviteTransaction(Transaction transaction) { this.latestInviteTransaction = transaction; } /** * Returns the transaction instance that contains the INVITE which started * this call. * * @return the Transaction that initiated this call. */ public Transaction getLatestInviteTransaction() { return latestInviteTransaction; } /** * Sets the jain sip provider instance that is responsible for sending and * receiving requests and responses related to this call peer. * * @param jainSipProvider the <tt>SipProvider</tt> that serves this call * peer. */ public void setJainSipProvider(SipProvider jainSipProvider) { this.jainSipProvider = jainSipProvider; } /** * Returns the jain sip provider instance that is responsible for sending * and receiving requests and responses related to this call peer. * * @return the jain sip provider instance that is responsible for sending * and receiving requests and responses related to this call peer. */ public SipProvider getJainSipProvider() { return jainSipProvider; } /** * The address that we have used to contact this peer. In cases * where no direct connection has been established with the peer, * this method will return the address that will be first tried when * connection is established (often the one used to connect with the * protocol server). The address may change during a session and * * @param transportAddress The address that we have used to contact this * peer. */ public void setTransportAddress(InetSocketAddress transportAddress) { InetSocketAddress oldTransportAddress = this.transportAddress; this.transportAddress = transportAddress; this.fireCallPeerChangeEvent( CallPeerChangeEvent.CALL_PEER_TRANSPORT_ADDRESS_CHANGE, oldTransportAddress, transportAddress); } /** * Returns the contact corresponding to this peer or null if no * particular contact has been associated. * <p> * @return the <tt>Contact</tt> corresponding to this peer or null * if no particular contact has been associated. */ public Contact getContact() { // if this peer has no call, most probably it means // its disconnected and no more in call // and we cannot obtain the contact if(getCall() == null) return null; ProtocolProviderService pps = getCall().getProtocolProvider(); OperationSetPresenceSipImpl opSetPresence = (OperationSetPresenceSipImpl) pps .getOperationSet(OperationSetPresence.class); if(opSetPresence != null) return opSetPresence.resolveContactID(getAddress()); else return null; } /** * Returns a URL pointing to a location with call control information for * this peer or <tt>null</tt> if no such URL is available for this * call peer. * * @return a URL link to a location with call information or a call control * web interface related to this peer or <tt>null</tt> if no such URL * is available. */ @Override public URL getCallInfoURL() { return getMediaHandler().getCallInfoURL(); } void processPictureFastUpdate( ClientTransaction clientTransaction, Response response) { /* * Disable the sending of picture_fast_update because it seems to be * unsupported by this remote peer. */ if ((response.getStatusCode() != 200) && sendPictureFastUpdate) sendPictureFastUpdate = false; } boolean processPictureFastUpdate( ServerTransaction serverTransaction, Request request) throws OperationFailedException { CallPeerMediaHandlerSipImpl mediaHandler = getMediaHandler(); boolean requested = (mediaHandler == null) ? false : mediaHandler.processKeyFrameRequest(); Response response; try { response = getProtocolProvider().getMessageFactory().createResponse( Response.OK, request); } catch (ParseException pe) { throw new OperationFailedException( "Failed to create OK Response.", OperationFailedException.INTERNAL_ERROR, pe); } if (!requested) { ContentType ct = new ContentType( "application", PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE); String content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" + "<media_control>\r\n" + "<general_error>\r\n" + "Failed to process picture_fast_update request.\r\n" + "</general_error>\r\n" + "</media_control>"; try { response.setContent(content, ct); } catch (ParseException pe) { throw new OperationFailedException( "Failed to set content of OK Response.", OperationFailedException.INTERNAL_ERROR, pe); } } try { serverTransaction.sendResponse(response); } catch (Exception e) { throw new OperationFailedException( "Failed to send OK Response.", OperationFailedException.INTERNAL_ERROR, e); } return true; } /** * Reinitializes the media session of the <tt>CallPeer</tt> that this * INVITE request is destined to. * * @param serverTransaction a reference to the {@link ServerTransaction} * that contains the reINVITE request. */ public void processReInvite(ServerTransaction serverTransaction) { Request invite = serverTransaction.getRequest(); setLatestInviteTransaction(serverTransaction); // SDP description may be in ACKs - bug report Laurent Michel String sdpOffer = null; ContentLengthHeader cl = invite.getContentLength(); if (cl != null && cl.getContentLength() > 0) sdpOffer = SdpUtils.getContentAsString(invite); Response response = null; try { response = messageFactory.createResponse(Response.OK, invite); /* * If the local peer represented by the Call of this CallPeer is * acting as a conference focus, it must indicate it in its Contact * header. */ reflectConferenceFocus(response); String sdpAnswer; if(sdpOffer != null) sdpAnswer = getMediaHandler().processOffer( sdpOffer ); else sdpAnswer = getMediaHandler().createOffer(); response.setContent( sdpAnswer, getProtocolProvider() .getHeaderFactory().createContentTypeHeader( "application", "sdp")); if (logger.isTraceEnabled()) logger.trace("will send an OK response: " + response); serverTransaction.sendResponse(response); if (logger.isDebugEnabled()) logger.debug("OK response sent"); } catch (Exception ex)//no need to distinguish among exceptions. { logger.error("Error while trying to send a response", ex); setState(CallPeerState.FAILED, "Internal Error: " + ex.getMessage()); getProtocolProvider().sayErrorSilently( serverTransaction, Response.SERVER_INTERNAL_ERROR); return; } reevalRemoteHoldStatus(); fireRequestProcessed(invite, response); } /** * Sets the state of the corresponding call peer to DISCONNECTED and * sends an OK response. * * @param byeTran the ServerTransaction the the BYE request arrived in. */ public void processBye(ServerTransaction byeTran) { Request byeRequest = byeTran.getRequest(); // Send OK Response ok = null; try { ok = messageFactory.createResponse(Response.OK, byeRequest); } catch (ParseException ex) { logger.error("Error while trying to send a response to a bye", ex); /* * No need to let the user know about the error since it doesn't * affect them. And just as the comment on sendResponse bellow * says, this is not really a problem according to the RFC so we * should proceed with the execution bellow in order to gracefully * hangup the call. */ } if (ok != null) try { byeTran.sendResponse(ok); if (logger.isDebugEnabled()) logger.debug("sent response " + ok); } catch (Exception ex) { /* * This is not really a problem according to the RFC so just * dump to stdout should someone be interested. */ logger.error("Failed to send an OK response to BYE request," + "exception was:\n", ex); } // change status boolean dialogIsAlive; try { dialogIsAlive = EventPackageUtils.processByeThenIsDialogAlive( byeTran.getDialog()); } catch (SipException ex) { dialogIsAlive = false; logger.error( "Failed to determine whether the dialog should stay alive.",ex); } //if the Dialog is still alive (i.e. we are in the middle of a xfer) //then only stop streaming, otherwise Disconnect. if (dialogIsAlive) { getMediaHandler().close(); } else { ReasonHeader reasonHeader = (ReasonHeader)byeRequest.getHeader(ReasonHeader.NAME); if(reasonHeader != null) { setState( CallPeerState.DISCONNECTED, reasonHeader.getText(), reasonHeader.getCause()); } else setState(CallPeerState.DISCONNECTED); } } /** * Sets the state of the specifies call peer as DISCONNECTED. * * @param serverTransaction the transaction that the cancel was received in. */ public void processCancel(ServerTransaction serverTransaction) { // Cancels should be OK-ed and the initial transaction - terminated // (report and fix by Ranga) Request cancel = serverTransaction.getRequest(); try { Response ok = messageFactory.createResponse(Response.OK, cancel); serverTransaction.sendResponse(ok); if (logger.isDebugEnabled()) logger.debug("sent an ok response to a CANCEL request:\n" + ok); } catch (ParseException ex) { logAndFail("Failed to create an OK Response to a CANCEL.", ex); return; } catch (Exception ex) { logAndFail("Failed to send an OK Response to a CANCEL.", ex); return; } try { // stop the invite transaction as well Transaction tran = getLatestInviteTransaction(); // should be server transaction and misplaced cancels should be // filtered by the stack but it doesn't hurt checking anyway if (!(tran instanceof ServerTransaction)) { logger.error("Received a misplaced CANCEL request!"); return; } ServerTransaction inviteTran = (ServerTransaction) tran; Request invite = getLatestInviteTransaction().getRequest(); Response requestTerminated = messageFactory .createResponse(Response.REQUEST_TERMINATED, invite); inviteTran.sendResponse(requestTerminated); if (logger.isDebugEnabled()) logger.debug("sent request terminated response:\n" + requestTerminated); } catch (ParseException ex) { logger.error("Failed to create a REQUEST_TERMINATED Response to " + "an INVITE request.", ex); } catch (Exception ex) { logger.error("Failed to send an REQUEST_TERMINATED Response to " + "an INVITE request.", ex); } ReasonHeader reasonHeader = (ReasonHeader)cancel.getHeader(ReasonHeader.NAME); if(reasonHeader != null) { setState( CallPeerState.DISCONNECTED, reasonHeader.getText(), reasonHeader.getCause()); } else setState(CallPeerState.DISCONNECTED); } /** * Updates the session description and sends the state of the corresponding * call peer to CONNECTED. * * @param serverTransaction the transaction that the ACK was received in. * @param ack the ACK <tt>Request</tt> we need to process */ public void processAck(ServerTransaction serverTransaction, Request ack) { ContentLengthHeader contentLength = ack.getContentLength(); if ((contentLength != null) && (contentLength.getContentLength() > 0)) { try { getMediaHandler().processAnswer( SdpUtils.getContentAsString(ack)); } catch (Exception exc) { logAndFail("There was an error parsing the SDP description of " + getDisplayName() + "(" + getAddress() + ")", exc); return; } } // change status CallPeerState peerState = getState(); if (!CallPeerState.isOnHold(peerState)) { setState(CallPeerState.CONNECTED); getMediaHandler().start(); // as its connected, set initial mute status, // corresponding call status // this would also unmute calls that were previously mute because // of early media. if(this.getCall() != null && isMute() != this.getCall().isMute()) setMute(this.getCall().isMute()); } } /** * Handles early media in 183 Session Progress responses. Retrieves the SDP * and makes sure that we start transmitting and playing early media that we * receive. Puts the call into a CONNECTING_WITH_EARLY_MEDIA state. * * @param tran the <tt>ClientTransaction</tt> that the response * arrived in. * @param response the 183 <tt>Response</tt> to process */ public void processSessionProgress(ClientTransaction tran, Response response) { if (response.getContentLength().getContentLength() == 0) { if (logger.isDebugEnabled()) logger.debug("Ignoring a 183 with no content"); return; } ContentTypeHeader contentTypeHeader = (ContentTypeHeader) response .getHeader(ContentTypeHeader.NAME); if (!contentTypeHeader.getContentType().equalsIgnoreCase("application") || !contentTypeHeader.getContentSubType().equalsIgnoreCase("sdp")) { //This can happen when receiving early media for a second time. logger.warn("Ignoring invite 183 since call peer is " + "already exchanging early media."); return; } //handle media try { getMediaHandler().processAnswer( SdpUtils.getContentAsString(response)); } catch (Exception exc) { logAndFail("There was an error parsing the SDP description of " + getDisplayName() + "(" + getAddress() + ")", exc); return; } //change status setState(CallPeerState.CONNECTING_WITH_EARLY_MEDIA); getMediaHandler().start(); // set the call on mute. we don't want the user to be heard unless they //know they are. setMute(true); } /** * Sets our state to CONNECTED, sends an ACK and processes the SDP * description in the <tt>ok</tt> <tt>Response</tt>. * * @param clientTransaction the <tt>ClientTransaction</tt> that the response * arrived in. * @param ok the OK <tt>Response</tt> to process */ public void processInviteOK(ClientTransaction clientTransaction, Response ok) { try { // Send the ACK. Do it now since we already got all the info we need // and processSdpAnswer() can take a while (patch by Michael Koch) getProtocolProvider().sendAck(clientTransaction); } catch (InvalidArgumentException ex) { // Shouldn't happen logAndFail("Error creating an ACK (CSeq?)", ex); return; } catch (SipException ex) { logAndFail("Failed to create ACK request!", ex); return; } try { //Process SDP unless we've just had an answer in a 18X response if (!CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(getState())) { getMediaHandler() .processAnswer(SdpUtils.getContentAsString(ok)); } } //at this point we have already sent our ack so in addition to logging //an error we also need to hangup the call peer. catch (Exception exc)//Media or parse exception. { logger.error("There was an error parsing the SDP description of " + getDisplayName() + "(" + getAddress() + ")", exc); try { //we are connected from a SIP point of view (cause we sent our //ACK) so make sure we set the state accordingly or the hangup //method won't know how to end the call. setState(CallPeerState.CONNECTED, "Error:" + exc.getLocalizedMessage()); hangup(); } catch (Exception e) { //handle in finally. } finally { logAndFail("Remote party sent a faulty session description.", exc); } return; } // change status if (!CallPeerState.isOnHold(getState())) { setState(CallPeerState.CONNECTED); getMediaHandler().start(); // as its connected, set initial mute status, // corresponding call status if(isMute() != this.getCall().isMute()) setMute(this.getCall().isMute()); } fireResponseProcessed(ok, null); } /** * Sends a <tt>picture_fast_update</tt> SIP INFO request to this remote * peer. * * @throws OperationFailedException if anything goes wrong while sending the * <tt>picture_fast_update</tt> SIP INFO request to this remote peer */ private void pictureFastUpdate() throws OperationFailedException { Request info = getProtocolProvider().getMessageFactory().createRequest( getDialog(), Request.INFO); //here we add the body ContentType ct = new ContentType( "application", PICTURE_FAST_UPDATE_CONTENT_SUB_TYPE); String content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" + "<media_control>\r\n" + "<vc_primitive>\r\n" + "<to_encoder>\r\n" + "<picture_fast_update/>\r\n" + "</to_encoder>\r\n" + "</vc_primitive>\r\n" + "</media_control>"; ContentLength cl = new ContentLength(content.length()); info.setContentLength(cl); try { info.setContent(content.getBytes(), ct); } catch (ParseException ex) { logger.error("Failed to construct the INFO request", ex); throw new OperationFailedException( "Failed to construct a client the INFO request", OperationFailedException.INTERNAL_ERROR, ex); } //body ended ClientTransaction clientTransaction = null; try { clientTransaction = getJainSipProvider().getNewClientTransaction(info); } catch (TransactionUnavailableException ex) { logger.error( "Failed to construct a client transaction from the INFO request", ex); throw new OperationFailedException( "Failed to construct a client transaction from the INFO request", OperationFailedException.INTERNAL_ERROR, ex); } try { if (getDialog().getState() == DialogState.TERMINATED) { //this is probably because the call has just ended, so don't //throw an exception. simply log and get lost. logger.warn( "Trying to send a dtmf tone inside a " + "TERMINATED dialog."); return; } getDialog().sendRequest(clientTransaction); if (logger.isDebugEnabled()) logger.debug("sent request:\n" + info); } catch (SipException ex) { throw new OperationFailedException( "Failed to send the INFO request", OperationFailedException.NETWORK_FAILURE, ex); } } /** * Ends the call with for this <tt>CallPeer</tt>. Depending on the state * of the peer the method would send a CANCEL, BYE, or BUSY_HERE message * and set the new state to DISCONNECTED. * * @throws OperationFailedException if we fail to terminate the call. */ public void hangup() throws OperationFailedException { // By default we hang up by indicating no failure has happened. hangup(HANGUP_REASON_NORMAL_CLEARING, null); } /** * Ends the call with for this <tt>CallPeer</tt>. Depending on the state * of the peer the method would send a CANCEL, BYE, or BUSY_HERE message * and set the new state to DISCONNECTED. * * @param reasonCode indicates if the hangup is following to a call failure * or simply a disconnect indicate by the reason. * @param reason the reason of the hangup. If the hangup is due to a call * failure, then this string could indicate the reason of the failure * * @throws OperationFailedException if we fail to terminate the call. */ public void hangup(int reasonCode, String reason) throws OperationFailedException { // do nothing if the call is already ended if (CallPeerState.DISCONNECTED.equals(getState()) || CallPeerState.FAILED.equals(getState())) { if (logger.isDebugEnabled()) logger.debug("Ignoring a request to hangup a call peer " + "that is already DISCONNECTED"); return; } boolean failed = (reasonCode != HANGUP_REASON_NORMAL_CLEARING); CallPeerState peerState = getState(); if (peerState.equals(CallPeerState.CONNECTED) || CallPeerState.isOnHold(peerState)) { // if we fail to send the bye, lets close the call anyway try { boolean dialogIsAlive = sayBye(reasonCode, reason); if (!dialogIsAlive) { setDisconnectedState(failed, reason); } } catch(Throwable ex) { logger.error( "Error while trying to hangup, trying to handle!", ex); // make sure we end media if exception occurs setDisconnectedState(true, null); // if its the handled OperationFailedException, pass it if(ex instanceof OperationFailedException) throw (OperationFailedException)ex; } } else if (CallPeerState.CONNECTING.equals(getState()) || CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(getState()) || CallPeerState.ALERTING_REMOTE_SIDE.equals(getState())) { if (getLatestInviteTransaction() != null) { // Someone knows about us. Let's be polite and say we are // leaving sayCancel(); } setDisconnectedState(failed, reason); } else if (peerState.equals(CallPeerState.INCOMING_CALL)) { setDisconnectedState(failed, reason); sayBusyHere(); } // For FAILED and BUSY we only need to update CALL_STATUS else if (peerState.equals(CallPeerState.BUSY)) { setDisconnectedState(failed, reason); } else if (peerState.equals(CallPeerState.FAILED)) { setDisconnectedState(failed, reason); } else { setDisconnectedState(failed, reason); logger.error("Could not determine call peer state!"); } } /** * Sends a BUSY_HERE response to the peer represented by this instance. * * @throws OperationFailedException if we fail to create or send the * response */ private void sayBusyHere() throws OperationFailedException { if (!(getLatestInviteTransaction() instanceof ServerTransaction)) { logger.error("Cannot send BUSY_HERE in a client transaction"); throw new OperationFailedException( "Cannot send BUSY_HERE in a client transaction", OperationFailedException.INTERNAL_ERROR); } Request request = getLatestInviteTransaction().getRequest(); Response busyHere = null; try { busyHere = messageFactory.createResponse( Response.BUSY_HERE, request); } catch (ParseException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create the BUSY_HERE response!", OperationFailedException.INTERNAL_ERROR, ex, logger); } ServerTransaction serverTransaction = (ServerTransaction) getLatestInviteTransaction(); try { serverTransaction.sendResponse(busyHere); if (logger.isDebugEnabled()) logger.debug("sent response:\n" + busyHere); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send the BUSY_HERE response", OperationFailedException.NETWORK_FAILURE, ex, logger); } } /** * Sends a Cancel request to the peer represented by this instance. * * @throws OperationFailedException we failed to construct or send the * CANCEL request. */ private void sayCancel() throws OperationFailedException { if (getLatestInviteTransaction() instanceof ServerTransaction) { logger.error("Cannot cancel a server transaction"); throw new OperationFailedException( "Cannot cancel a server transaction", OperationFailedException.INTERNAL_ERROR); } ClientTransaction clientTransaction = (ClientTransaction) getLatestInviteTransaction(); try { Request cancel = clientTransaction.createCancel(); ClientTransaction cancelTransaction = getJainSipProvider().getNewClientTransaction( cancel); cancelTransaction.sendRequest(); if (logger.isDebugEnabled()) logger.debug("sent request:\n" + cancel); } catch (SipException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send the CANCEL request", OperationFailedException.NETWORK_FAILURE, ex, logger); } } /** * Sends a BYE request to <tt>callPeer</tt>. * * @return <tt>true</tt> if the <tt>Dialog</tt> should be considered * alive after sending the BYE request (e.g. when there're still active * subscriptions); <tt>false</tt>, otherwise * * @throws OperationFailedException if we failed constructing or sending a * SIP Message. */ private boolean sayBye(int reasonCode, String reason) throws OperationFailedException { Dialog dialog = getDialog(); Request bye = messageFactory.createRequest(dialog, Request.BYE); if(reasonCode != HANGUP_REASON_NORMAL_CLEARING && reason != null) { int sipCode = convertReasonCodeToSIPCode(reasonCode); if(sipCode != -1) { try { // indicate reason for failure // using Reason header rfc3326 ReasonHeader reasonHeader = getProtocolProvider().getHeaderFactory() .createReasonHeader( "SIP", sipCode, reason); bye.setHeader(reasonHeader); } catch(Throwable e) { logger.error("Cannot set reason header", e); } } } getProtocolProvider().sendInDialogRequest( getJainSipProvider(), bye, dialog); /* * Let subscriptions such as the ones associated with REFER requests * keep the dialog alive and correctly delete it when they are * terminated. */ try { return EventPackageUtils.processByeThenIsDialogAlive(dialog); } catch (SipException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to determine whether the dialog should stay alive.", OperationFailedException.INTERNAL_ERROR, ex, logger); return false; } } /** * Converts the codes for hangup from OperationSetBasicTelephony one * to the sip codes. * @param reasonCode the reason code. * @return the sip code or -1 if not found. */ private static int convertReasonCodeToSIPCode(int reasonCode) { switch(reasonCode) { case HANGUP_REASON_NORMAL_CLEARING : return Response.ACCEPTED; case HANGUP_REASON_ENCRYPTION_REQUIRED : return Response.SESSION_NOT_ACCEPTABLE; case HANGUP_REASON_TIMEOUT : return Response.REQUEST_TIMEOUT; case HANGUP_REASON_BUSY_HERE : return Response.BUSY_HERE; default : return -1; } } /** * Indicates a user request to answer an incoming call from this * <tt>CallPeer</tt>. * * Sends an OK response to <tt>callPeer</tt>. Make sure that the call * peer contains an SDP description when you call this method. * * @throws OperationFailedException if we fail to create or send the * response. */ public synchronized void answer() throws OperationFailedException { Transaction transaction = getLatestInviteTransaction(); if (transaction == null || !(transaction instanceof ServerTransaction)) { setState(CallPeerState.DISCONNECTED); throw new OperationFailedException( "Failed to extract a ServerTransaction " + "from the call's associated dialog!", OperationFailedException.INTERNAL_ERROR); } CallPeerState peerState = getState(); if (peerState.equals(CallPeerState.CONNECTED) || CallPeerState.isOnHold(peerState)) { if (logger.isInfoEnabled()) logger.info("Ignoring user request to answer a CallPeer " + "that is already connected. CP:"); return; } ServerTransaction serverTransaction = (ServerTransaction) transaction; Request invite = serverTransaction.getRequest(); Response ok = null; try { ok = messageFactory.createResponse(Response.OK, invite); /* * If the local peer represented by the Call of this CallPeer is * acting as a conference focus, it must indicate it in its Contact * header. */ reflectConferenceFocus(ok); } catch (ParseException ex) { setState(CallPeerState.DISCONNECTED); ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to construct an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } // Content ContentTypeHeader contentTypeHeader = null; try { // content type should be application/sdp (not applications) // reported by Oleg Shevchenko (Miratech) contentTypeHeader = getProtocolProvider().getHeaderFactory() .createContentTypeHeader("application", "sdp"); } catch (ParseException ex) { // Shouldn't happen setState(CallPeerState.DISCONNECTED); ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create a content type header for the OK response", OperationFailedException.INTERNAL_ERROR, ex, logger); } // This is the sdp offer that came from the initial invite, // also that invite can have no offer. String sdpOffer = null; try { // extract the SDP description. // beware: SDP description may be in ACKs so it could be that // there's nothing here - bug report Laurent Michel ContentLengthHeader cl = invite.getContentLength(); if (cl != null && cl.getContentLength() > 0) { sdpOffer = SdpUtils.getContentAsString(invite); } String sdp; // if the offer was in the invite create an SDP answer if ((sdpOffer != null) && (sdpOffer.length() > 0)) { sdp = getMediaHandler().processOffer(sdpOffer); } // if there was no offer in the invite - create an offer else { sdp = getMediaHandler().createOffer(); } ok.setContent(sdp, contentTypeHeader); } catch (Exception ex) { //log, the error and tell the remote party. do not throw an //exception as it would go to the stack and there's nothing it could //do with it. logger.error( "Failed to create an SDP description for an OK response " + "to an INVITE request!", ex); getProtocolProvider().sayError( serverTransaction, Response.NOT_ACCEPTABLE_HERE); //do not continue processing - we already canceled the peer here setState(CallPeerState.FAILED, ex.getMessage()); return; } try { serverTransaction.sendResponse(ok); if (logger.isDebugEnabled()) logger.debug("sent response\n" + ok); } catch (Exception ex) { setState(CallPeerState.DISCONNECTED); ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send an OK response to an INVITE request", OperationFailedException.NETWORK_FAILURE, ex, logger); } fireRequestProcessed(invite, ok); // the ACK to our answer might already be processed before we get here if(CallPeerState.INCOMING_CALL.equals(getState())) { if(sdpOffer != null && sdpOffer.length() > 0) setState(CallPeerState.CONNECTING_INCOMING_CALL_WITH_MEDIA); else setState(CallPeerState.CONNECTING_INCOMING_CALL); } } /** * Puts the <tt>CallPeer</tt> represented by this instance on or off hold. * * @param onHold <tt>true</tt> to have the <tt>CallPeer</tt> put on hold; * <tt>false</tt>, otherwise * * @throws OperationFailedException if we fail to construct or send the * INVITE request putting the remote side on/off hold. */ public void putOnHold(boolean onHold) throws OperationFailedException { CallPeerMediaHandlerSipImpl mediaHandler = getMediaHandler(); mediaHandler.setLocallyOnHold(onHold); try { sendReInvite(mediaHandler.createOffer()); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create SDP offer to hold.", OperationFailedException.INTERNAL_ERROR, ex, logger); } reevalLocalHoldStatus(); } /** * Sends a reINVITE request to this <tt>CallPeer</tt> within its current * <tt>Dialog</tt>. * * @throws OperationFailedException if sending the reINVITE request fails */ void sendReInvite() throws OperationFailedException { sendReInvite(getMediaHandler().createOffer()); } /** * Sends a reINVITE request with a specific <tt>sdpOffer</tt> (description) * within the current <tt>Dialog</tt> with the call peer represented by * this instance. * * @param sdpOffer the offer that we'd like to use for the newly created * INVITE request. * * @throws OperationFailedException if sending the request fails for some * reason. */ private void sendReInvite(String sdpOffer) throws OperationFailedException { Dialog dialog = getDialog(); Request invite = messageFactory.createRequest(dialog, Request.INVITE); try { // Content-Type invite.setContent( sdpOffer, getProtocolProvider() .getHeaderFactory() .createContentTypeHeader("application", "sdp")); /* * If the local peer represented by the Call of this CallPeer is * acting as a conference focus, it must indicate it in its Contact * header. */ reflectConferenceFocus(invite); } catch (ParseException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to parse SDP offer for the new invite.", OperationFailedException.INTERNAL_ERROR, ex, logger); } getProtocolProvider().sendInDialogRequest( getJainSipProvider(), invite, dialog); } /** * Creates a <tt>CallPeerSipImpl</tt> from <tt>calleeAddress</tt> and sends * them an invite request. The invite request will be initialized according * to any relevant parameters in the <tt>cause</tt> message (if different * from <tt>null</tt>) that is the reason for creating this call. * * @throws OperationFailedException with the corresponding code if we fail * to create the call or in case we someone calls us mistakenly while we * are actually wrapped around an invite transaction. */ public void invite() throws OperationFailedException { try { ClientTransaction inviteTran = (ClientTransaction) getLatestInviteTransaction(); Request invite = inviteTran.getRequest(); // Content-Type ContentTypeHeader contentTypeHeader = getProtocolProvider() .getHeaderFactory() .createContentTypeHeader("application", "sdp"); invite.setContent( getMediaHandler().createOffer(), contentTypeHeader); /* * If the local peer represented by the Call of this CallPeer is * acting as a conference focus, it must indicate it in its Contact * header. */ reflectConferenceFocus(invite); inviteTran.sendRequest(); if (logger.isDebugEnabled()) logger.debug("sent request:\n" + inviteTran.getRequest()); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "An error occurred while sending invite request", OperationFailedException.NETWORK_FAILURE, ex, logger); } } /** * Reflects the value of the <tt>conferenceFocus</tt> property of the * <tt>Call</tt> of this <tt>CallPeer</tt> in the specified SIP * <tt>Message</tt>. * * @param message the SIP <tt>Message</tt> in which the value of the * <tt>conferenceFocus</tt> property of the <tt>Call</tt> of this * <tt>CallPeer</tt> is to be reflected * @throws ParseException if modifying the specified SIP <tt>Message</tt> to * reflect the <tt>conferenceFocus</tt> property of the <tt>Call</tt> of * this <tt>CallPeer</tt> fails */ private void reflectConferenceFocus(javax.sip.message.Message message) throws ParseException { ContactHeader contactHeader = (ContactHeader) message.getHeader(ContactHeader.NAME); if (contactHeader != null) { // we must set the value of the parameter as null // in order to avoid wrong generation of the tag - ';isfocus=' // as it must be ';isfocus' if (getCall().isConferenceFocus()) contactHeader.setParameter("isfocus", null); else contactHeader.removeParameter("isfocus"); } } /** * Registers a specific <tt>MethodProcessorListener</tt> with this * <tt>CallPeer</tt> so that it gets notified by this instance about the * processing of SIP signaling. If the specified <tt>listener</tt> is * already registered with this instance, does nothing * * @param listener the <tt>MethodProcessorListener</tt> to be registered * with this <tt>CallPeer</tt> so that it gets notified by this instance * about the processing of SIP signaling */ void addMethodProcessorListener(MethodProcessorListener listener) { if (listener == null) throw new NullPointerException("listener"); synchronized (methodProcessorListeners) { if (!methodProcessorListeners.contains(listener)) methodProcessorListeners.add(listener); } } /** * Notifies the <tt>MethodProcessorListener</tt>s registered with this * <tt>CallPeer</tt> that it has processed a specific SIP <tt>Request</tt> * by sending a specific SIP <tt>Response</tt>. * * @param request the SIP <tt>Request</tt> processed by this * <tt>CallPeer</tt> * @param response the SIP <tt>Response</tt> this <tt>CallPeer</tt> sent as * part of its processing of the specified <tt>request</tt> */ protected void fireRequestProcessed(Request request, Response response) { Iterable<MethodProcessorListener> listeners; synchronized (methodProcessorListeners) { listeners = new LinkedList<MethodProcessorListener>( methodProcessorListeners); } for (MethodProcessorListener listener : listeners) listener.requestProcessed(this, request, response); } /** * Notifies the <tt>MethodProcessorListener</tt>s registered with this * <tt>CallPeer</tt> that it has processed a specific SIP <tt>Response</tt> * by sending a specific SIP <tt>Request</tt>. * * @param response the SIP <tt>Response</tt> processed by this * <tt>CallPeer</tt> * @param request the SIP <tt>Request</tt> this <tt>CallPeer</tt> sent as * part of its processing of the specified <tt>response</tt> */ protected void fireResponseProcessed(Response response, Request request) { Iterable<MethodProcessorListener> listeners; synchronized (methodProcessorListeners) { listeners = new LinkedList<MethodProcessorListener>( methodProcessorListeners); } for (MethodProcessorListener listener : listeners) listener.responseProcessed(this, response, request); } /** * Unregisters a specific <tt>MethodProcessorListener</tt> from this * <tt>CallPeer</tt> so that it no longer gets notified by this instance * about the processing of SIP signaling. If the specified <tt>listener</tt> * is not registered with this instance, does nothing. * * @param listener the <tt>MethodProcessorListener</tt> to be unregistered * from this <tt>CallPeer</tt> so that it no longer gets notified by this * instance about the processing of SIP signaling */ void removeMethodProcessorListener(MethodProcessorListener listener) { if (listener != null) synchronized (methodProcessorListeners) { methodProcessorListeners.remove(listener); } } /** * Requests a (video) key frame from this remote peer of the associated. * * @return <tt>true</tt> if a key frame has indeed been requested from this * remote peer in response to the call; otherwise, <tt>false</tt> */ private boolean requestKeyFrame() { boolean requested = false; if (sendPictureFastUpdate) { try { pictureFastUpdate(); requested = true; } catch (OperationFailedException ofe) { /* * Apart from logging, it does not seem like there are a lot of * ways to handle it. */ } } return requested; } /** * Updates this call so that it would record a new transaction and dialog * that have been recreated because of a re-authentication. * * @param retryTran the new transaction */ public void handleAuthenticationChallenge(ClientTransaction retryTran) { // There is a new dialog that will be started with this request. Get // that dialog and record it into the Call object for later use (by // BYEs for example). // if the request was BYE then we need to authorize it anyway even // if the call and the call peer are no longer there setDialog(retryTran.getDialog()); setLatestInviteTransaction(retryTran); setJainSipProvider(jainSipProvider); } /** * Causes this CallPeer to enter either the DISCONNECTED or the FAILED * state. * * @param failed indicates if the disconnection is due to a failure * @param reason the reason of the disconnection */ private void setDisconnectedState(boolean failed, String reason) { if (failed) setState(CallPeerState.FAILED, reason); else setState(CallPeerState.DISCONNECTED, reason); } /** * {@inheritDoc} */ public String getEntity() { return AbstractOperationSetTelephonyConferencing .stripParametersFromAddress(getURI()); } /** * {@inheritDoc} * * Uses the direction of the media stream as a fallback. * TODO: return the direction negotiated via SIP */ @Override public MediaDirection getDirection(MediaType mediaType) { MediaStream stream = getMediaHandler().getStream(mediaType); if (stream != null) { MediaDirection direction = stream.getDirection(); return direction == null ? MediaDirection.INACTIVE : direction; } return MediaDirection.INACTIVE; } }
package nl.rubensten.texifyidea.structure; import com.intellij.ide.structureView.StructureViewTreeElement; import com.intellij.ide.util.treeView.smartTree.SortableTreeElement; import com.intellij.ide.util.treeView.smartTree.TreeElement; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.NavigationItem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import nl.rubensten.texifyidea.file.LatexFile; import nl.rubensten.texifyidea.file.LatexFileType; import nl.rubensten.texifyidea.file.StyleFileType; import nl.rubensten.texifyidea.index.LatexCommandsIndex; import nl.rubensten.texifyidea.lang.LatexNoMathCommand; import nl.rubensten.texifyidea.lang.RequiredFileArgument; import nl.rubensten.texifyidea.psi.LatexCommands; import nl.rubensten.texifyidea.psi.LatexTypes; import nl.rubensten.texifyidea.structure.SectionNumbering.DocumentClass; import nl.rubensten.texifyidea.util.TexifyUtil; import org.jetbrains.annotations.NotNull; import java.util.*; import static nl.rubensten.texifyidea.util.TexifyUtil.findFile; /** * @author Ruben Schellekens */ public class LatexStructureViewElement implements StructureViewTreeElement, SortableTreeElement { public static final List<String> SECTION_MARKERS = Arrays.asList( "\\part", "\\chapter", "\\section", "\\subsection", "\\subsubsection", "\\paragraph", "\\subparagraph" ); private final PsiElement element; public LatexStructureViewElement(PsiElement element) { this.element = element; } @Override public Object getValue() { return element; } @Override public void navigate(boolean requestFocus) { if (element instanceof NavigationItem) { ((NavigationItem)element).navigate(requestFocus); } } @Override public boolean canNavigate() { return (element instanceof NavigationItem) && ((NavigationItem)element).canNavigate(); } @Override public boolean canNavigateToSource() { return (element instanceof NavigationItem) && ((NavigationItem)element).canNavigateToSource(); } @NotNull @Override public String getAlphaSortKey() { if (element instanceof LatexCommands) { return ((LatexCommands)element).getCommandToken().getText().toLowerCase(); } else if (element instanceof PsiNamedElement) { return ((PsiNamedElement)element).getName().toLowerCase(); } else { return element.getText().toLowerCase(); } } @NotNull @Override public ItemPresentation getPresentation() { if (element instanceof LatexCommands) { return LatexPresentationFactory.getPresentation((LatexCommands)element); } else if (element instanceof PsiFile) { return new LatexFilePresentation((PsiFile)element); } return null; } @NotNull @Override public TreeElement[] getChildren() { if (!(element instanceof LatexFile)) { return EMPTY_ARRAY; } // Get document class. GlobalSearchScope scope = GlobalSearchScope.fileScope((PsiFile)element); String docClass = LatexCommandsIndex.getIndexedCommands(element.getProject(), scope) .stream() .filter(cmd -> cmd.getCommandToken().getText().equals("\\documentclass") && !cmd.getRequiredParameters().isEmpty()) .map(cmd -> cmd.getRequiredParameters().get(0)) .findFirst() .orElse("article"); // Fetch all commands in the active file. SectionNumbering numbering = new SectionNumbering(DocumentClass.getClassByName(docClass)); List<LatexCommands> commands = TexifyUtil.getAllCommands(element); List<TreeElement> treeElements = new ArrayList<>(); // Add includes. addIncludes(treeElements, commands); // Add sectioning. Deque<LatexStructureViewCommandElement> sections = new ArrayDeque<>(); for (LatexCommands currentCmd : commands) { String token = currentCmd.getCommandToken().getText(); // Update counter. if ((token.equals("\\addtocounter") || token.equals("\\setcounter"))) { updateNumbering(currentCmd, numbering); continue; } // Only consider section markers. if (!SECTION_MARKERS.contains(token)) { continue; } if (!docClass.equals("book") && (token.equals("\\part") || token.equals("\\chapter"))) { continue; } if (currentCmd.getRequiredParameters().isEmpty()) { continue; } LatexStructureViewCommandElement child = new LatexStructureViewCommandElement(currentCmd); // First section. if (sections.isEmpty()) { sections.addFirst(child); treeElements.add(child); setLevelHint(child, numbering); continue; } int currentIndex = order(current(sections)); int nextIndex = order(currentCmd); // Same level. if (currentIndex == nextIndex) { registerSameLevel(sections, child, currentCmd, treeElements, numbering); } // Go deeper else if (nextIndex > currentIndex) { registerDeeper(sections, child, numbering); } // Go higher else { registerHigher(sections, child, currentCmd, treeElements, numbering); } } // Add command definitions. addFromCommand(treeElements, commands, "\\newcommand"); addFromCommand(treeElements, commands, "\\let"); addFromCommand(treeElements, commands, "\\def"); // Add label definitions. addFromCommand(treeElements, commands, "\\label"); return treeElements.toArray(new TreeElement[treeElements.size()]); } private void addIncludes(List<TreeElement> treeElements, List<LatexCommands> commands) { for (LatexCommands cmd : commands) { String name = cmd.getCommandToken().getText(); if (!name.equals("\\include") && !name.equals("\\includeonly") && !name.equals("\\input")) { continue; } List<String> required = cmd.getRequiredParameters(); if (required.isEmpty()) { continue; } // Find file Optional<LatexNoMathCommand> latexCommandHuh = LatexNoMathCommand.get(name.substring(1)); if (!latexCommandHuh.isPresent()) { continue; } RequiredFileArgument argument = latexCommandHuh.get() .getArgumentsOf(RequiredFileArgument.class) .get(0); String fileName = required.get(0); VirtualFile directory = element.getContainingFile().getContainingDirectory().getVirtualFile(); Optional<VirtualFile> fileHuh = findFile(directory, fileName, argument.getSupportedExtensions()); if (!fileHuh.isPresent()) { continue; } PsiFile psiFile = PsiManager.getInstance(element.getProject()).findFile(fileHuh.get()); if (psiFile == null) { continue; } if (!LatexFileType.INSTANCE.equals(psiFile.getFileType()) && !StyleFileType.INSTANCE.equals(psiFile.getFileType())) { continue; } LatexStructureViewCommandElement elt = new LatexStructureViewCommandElement(cmd); elt.addChild(new LatexStructureViewElement(psiFile)); treeElements.add(elt); } } private void addFromCommand(List<TreeElement> treeElements, List<LatexCommands> commands, String commandName) { for (LatexCommands cmd : commands) { if (!cmd.getCommandToken().getText().equals(commandName)) { continue; } List<String> required = cmd.getRequiredParameters(); if (commandName.equals("\\newcommand") && required.isEmpty()) { continue; } TreeElement element = LatexStructureViewCommandElement.newCommand(cmd); if (element != null) { treeElements.add(element); } } } private void registerHigher(Deque<LatexStructureViewCommandElement> sections, LatexStructureViewCommandElement child, LatexCommands currentCmd, List<TreeElement> treeElements, SectionNumbering numbering) { int indexInsert = order(currentCmd); while (!sections.isEmpty()) { pop(sections); int index = order(current(sections)); if (index == indexInsert) { registerSameLevel(sections, child, currentCmd, treeElements, numbering); break; } if (indexInsert > index) { registerDeeper(sections, child, numbering); break; } } } private void registerDeeper(Deque<LatexStructureViewCommandElement> sections, LatexStructureViewCommandElement child, SectionNumbering numbering) { current(sections).addChild(child); queue(child, sections); setLevelHint(child, numbering); } private void registerSameLevel(Deque<LatexStructureViewCommandElement> sections, LatexStructureViewCommandElement child, LatexCommands currentCmd, List<TreeElement> treeElements, SectionNumbering numbering) { sections.removeFirst(); LatexStructureViewCommandElement parent = sections.peekFirst(); if (parent != null) { parent.addChild(child); } sections.addFirst(child); setLevelHint(child, numbering); if (currentCmd.getCommandToken().getText().equals(highestLevel(sections))) { treeElements.add(child); } } private void setLevelHint(LatexStructureViewCommandElement child, SectionNumbering numbering) { if (hasStar((LatexCommands)child.getValue())) { return; } int level = order(child); numbering.increase(level); child.setHint(numbering.getTitle(level)); } private void updateNumbering(LatexCommands cmd, SectionNumbering numbering) { String token = cmd.getCommandToken().getText(); List<String> required = cmd.getRequiredParameters(); if (required.size() < 2) { return; } // Get the level to modify. String name = required.get(0); int level = order("\\" + name); if (level == -1) { return; } // Get the amount to modify with. int amount = -1; try { amount = Integer.parseInt(required.get(1)); } catch (NumberFormatException nfe) { return; } // Setcounter if (token.equals("\\setcounter")) { numbering.setCounter(level, amount); } // Addcounter else { numbering.addCounter(level, amount); } } private boolean hasStar(LatexCommands commands) { LeafPsiElement[] leafs = PsiTreeUtil.getChildrenOfType(commands, LeafPsiElement.class); return Arrays.stream(leafs) .anyMatch(l -> l.getElementType().equals(LatexTypes.STAR)); } private String highestLevel(Deque<LatexStructureViewCommandElement> sections) { return sections.stream() .map(this::order) .min(Integer::compareTo) .map(SECTION_MARKERS::get) .orElse("\\section"); } private void pop(Deque<LatexStructureViewCommandElement> sections) { sections.removeFirst(); } private void queue(LatexStructureViewCommandElement child, Deque<LatexStructureViewCommandElement> sections) { sections.addFirst(child); } private LatexStructureViewCommandElement current(Deque<LatexStructureViewCommandElement> sections) { return sections.getFirst(); } private int order(LatexStructureViewCommandElement element) { return order(element.getCommandName()); } private int order(LatexCommands commands) { return order(commands.getCommandToken().getText()); } private int order(String commandName) { return SECTION_MARKERS.indexOf(commandName); } }
package org.cocolab.inpro.incremental.processor; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.cocolab.inpro.incremental.IUModule; import org.cocolab.inpro.incremental.listener.InstallmentHistoryViewer; import org.cocolab.inpro.incremental.unit.DialogueActIU; import org.cocolab.inpro.incremental.unit.EditMessage; import org.cocolab.inpro.incremental.unit.EditType; import org.cocolab.inpro.incremental.unit.IU; import org.cocolab.inpro.incremental.unit.IUList; import org.cocolab.inpro.incremental.unit.InstallmentIU; import org.cocolab.inpro.incremental.unit.WordIU; import org.cocolab.inpro.dm.RNLA; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Boolean; import edu.cmu.sphinx.util.props.S4Component; /** * Echo DM that sends prompts on timeouts repeating last input. * * @author timo, okko */ public class EchoDialogueManager extends IUModule implements AbstractFloorTracker.Listener, PentoActionManager.Listener { @S4Component(type = AudioActionManager.class, mandatory = true) public static final String PROP_AM = "actionManager"; private AudioActionManager am; @S4Boolean(defaultValue = true) public static final String PROP_ECHO = "echo"; private boolean echo; final IUList<InstallmentIU> installments = new IUList<InstallmentIU>(); final IUList<DialogueActIU> dialogueActIUs = new IUList<DialogueActIU>(); final List<RNLA> sentToDos = new ArrayList<RNLA>(); private List<WordIU> currentInstallment = new ArrayList<WordIU>(); InstallmentHistoryViewer ihv = new InstallmentHistoryViewer(); /** Sets up the DM. */ @Override public void newProperties(PropertySheet ps) throws PropertyException { super.newProperties(ps); am = (AudioActionManager) ps.getComponent(PROP_AM); echo = ps.getBoolean(PROP_ECHO); logger.info("Started EchoDialogueManager"); } /** Keeps the current installment hypothesis. */ @SuppressWarnings("unchecked") @Override public void leftBufferUpdate(Collection<? extends IU> ius, List<? extends EditMessage<? extends IU>> edits) { // faster and clearer way of saying "we keep a copy of the wordlist" currentInstallment = new ArrayList<WordIU>((Collection<WordIU>)ius); } /** Resets the DM and its AM */ @Override public void reset() { super.reset(); logger.info("DM resetting."); this.dialogueActIUs.clear(); this.am.reset(); this.currentInstallment.clear(); } /** Listens for floor changes and updates the InformationState */ @Override public void floor(AbstractFloorTracker.Signal signal, AbstractFloorTracker floorManager) { logger.info("Floor signal: " + signal); List<EditMessage<DialogueActIU>> ourEdits = null; switch (signal) { case START: { // Shut up this.am.shutUp(); break; } case EOT_RISING: { installments.add(new InstallmentIU(new ArrayList<WordIU>(currentInstallment))); ourEdits = reply("BCpr.wav"); break; } case EOT_FALLING: case EOT_NOT_RISING: { installments.add(new InstallmentIU(new ArrayList<WordIU>(currentInstallment))); ourEdits = reply("BCpf.wav"); } } this.dialogueActIUs.apply(ourEdits); this.rightBuffer.setBuffer(this.dialogueActIUs, ourEdits); this.rightBuffer.notify(this.iulisteners); ihv.hypChange(installments, null); } /** * convenience method against code-duplication. * @return a list of added DialogueActIUs */ private List<EditMessage<DialogueActIU>> reply(String filename) { List<IU> grin = new ArrayList<IU>(this.currentInstallment); String tts = WordIU.wordsToString(currentInstallment); ArrayList<EditMessage<DialogueActIU>> ourEdits = new ArrayList<EditMessage<DialogueActIU>>(); if (!tts.isEmpty()) { DialogueActIU daiu = new DialogueActIU(this.dialogueActIUs.getLast(), grin, new RNLA(RNLA.Act.PROMPT, filename)); ourEdits.add(new EditMessage<DialogueActIU>(EditType.ADD, daiu)); if (filename.equals("BCpr.wav")) { installments.add(new InstallmentIU(daiu, "OK+")); } else { installments.add(new InstallmentIU(daiu, "OK-")); } if (echo) { daiu = new DialogueActIU(this.dialogueActIUs.getLast(), grin, new RNLA(RNLA.Act.PROMPT, "tts: " + tts)); ourEdits.add(new EditMessage<DialogueActIU>(EditType.ADD, daiu)); installments.add(new InstallmentIU(daiu, tts)); } } else { DialogueActIU daiu = new DialogueActIU(this.dialogueActIUs.getLast(), grin, new RNLA(RNLA.Act.PROMPT, "BCn.wav")); ourEdits.add(new EditMessage<DialogueActIU>(EditType.ADD, daiu)); installments.add(new InstallmentIU(daiu, "hm")); } return ourEdits; } /** call this to notify the DM when a dialogueAct has been performed */ @Override public void done(DialogueActIU iu) { RNLA r = iu.getAct(); logger.info("Was notified about performed act " + r.toString()); this.sentToDos.remove(r); if (this.sentToDos.isEmpty()) { this.reset(); } } }
package org.ensembl.healthcheck.testcase.compara; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import java.sql.SQLException; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; /** * An EnsEMBL Healthcheck test case that looks for broken foreign-key * relationships. */ public class CheckSpeciesSetTag extends MultiDatabaseTestCase { /** * Create an ForeignKeyMethodLinkSpeciesSetId that applies to a specific set of databases. */ public CheckSpeciesSetTag() { addToGroup("compara_homology"); setDescription("Check the content of the species_set_tag table"); setTeamResponsible("compara"); } /** * Run the test. * * @param dbre * The database to use. * @return true if the test passed. * */ public boolean run(DatabaseRegistry dbr) { boolean result = true; // Get compara DB connection DatabaseRegistryEntry[] allPrimaryComparaDBs = DBUtils.getMainDatabaseRegistry().getAll(DatabaseType.COMPARA); if (allPrimaryComparaDBs.length == 0) { result = false; ReportManager.problem(this, "", "Cannot find compara database"); usage(); return false; } DatabaseRegistryEntry[] allSecondaryComparaDBs = DBUtils.getSecondaryDatabaseRegistry().getAll(DatabaseType.COMPARA); Map speciesDbrs = getSpeciesDatabaseMap(dbr, true); // For each compara connection... for (int i = 0; i < allPrimaryComparaDBs.length; i++) { // ... check the entries with a taxon id result &= checkSpeciesSetByTaxon(allPrimaryComparaDBs[i]); // ... check the entry for low-coverage genomes result &= checkLowCoverageSpecies(allPrimaryComparaDBs[i], speciesDbrs); // ... check that we have one name tag for every MSA result &= checkNameTagForMultipleAlignments(allPrimaryComparaDBs[i]); if (allSecondaryComparaDBs.length == 0) { result = false; ReportManager.problem(this, allPrimaryComparaDBs[i].getConnection(), "Cannot find the compara database in the secondary server"); usage(); } for (int j = 0; j < allSecondaryComparaDBs.length; j++) { // Check vs previous compara DB. result &= checkSetOfSpeciesSets(allPrimaryComparaDBs[i], allSecondaryComparaDBs[j]); } } return result; } public boolean checkSetOfSpeciesSets(DatabaseRegistryEntry primaryComparaDbre, DatabaseRegistryEntry secondaryComparaDbre) { boolean result = true; Connection con1 = primaryComparaDbre.getConnection(); Connection con2 = secondaryComparaDbre.getConnection(); HashMap primarySets = new HashMap(); HashMap secondarySets = new HashMap(); // Get list of species_set sets in the secondary server String sql = "SELECT value, count(*) FROM species_set_tag WHERE tag = 'name' GROUP BY value"; try { Statement stmt1 = con1.createStatement(); ResultSet rs1 = stmt1.executeQuery(sql); while (rs1.next()) { primarySets.put(rs1.getString(1), rs1.getInt(2)); } rs1.close(); stmt1.close(); Statement stmt2 = con2.createStatement(); ResultSet rs2 = stmt2.executeQuery(sql); while (rs2.next()) { secondarySets.put(rs2.getString(1), rs2.getInt(2)); } rs2.close(); stmt2.close(); } catch (Exception e) { e.printStackTrace(); } Iterator it = secondarySets.keySet().iterator(); while (it.hasNext()) { Object next = it.next(); Object primaryValue = primarySets.get(next); Integer secondaryValue = new Integer(secondarySets.get(next).toString()); if (primaryValue == null) { ReportManager.problem(this, con1, "Species set \"" + next.toString() + "\" is missing."); result = false; } else if (new Integer(primaryValue.toString()) < secondaryValue) { ReportManager.problem(this, con1, "Species set \"" + next.toString() + "\" is present only " + primaryValue + " times instead of " + secondaryValue + " as in " + DBUtils.getShortDatabaseName(con2)); result = false; } } return result; } public boolean checkLowCoverageSpecies(DatabaseRegistryEntry comparaDbre, Map speciesDbrs) { boolean result = true; Connection con = comparaDbre.getConnection(); // Get list of species (assembly_default) in compara Vector comparaSpeciesStr = new Vector(); Vector comparaSpecies = new Vector(); Vector comparaGenomeDBids = new Vector(); String sql2 = "SELECT DISTINCT genome_db.genome_db_id, genome_db.name FROM genome_db WHERE assembly_default = 1" + " AND name <> 'Ancestral sequences' AND name <> 'ancestral_sequences' ORDER BY genome_db.genome_db_id"; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql2); while (rs.next()) { comparaSpeciesStr.add(rs.getString(2)); comparaSpecies.add(Species.resolveAlias(rs.getString(2).toLowerCase().replace(' ', '_'))); comparaGenomeDBids.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } // Find which of these species are low-coverage by looking into the meta table // I don't know if this will work for multi-species DBs, but hopefully these don't have low-cov assemblies boolean allSpeciesFound = true; Vector lowCoverageSpecies = new Vector(); Vector lowCoverageGenomeDdIds = new Vector(); for (int i = 0; i < comparaSpecies.size(); i++) { Species species = (Species) comparaSpecies.get(i); DatabaseRegistryEntry[] speciesDbr = (DatabaseRegistryEntry[]) speciesDbrs.get(species); if (speciesDbr != null) { Connection speciesCon = speciesDbr[0].getConnection(); String coverageDepth = getRowColumnValue(speciesCon, "SELECT meta_value FROM meta WHERE meta_key = \"assembly.coverage_depth\""); if (coverageDepth.equals("low")) { lowCoverageSpecies.add(species); lowCoverageGenomeDdIds.add(comparaGenomeDBids.get(i)); } } else { ReportManager.problem(this, con, "No connection for " + comparaSpeciesStr.get(i).toString()); allSpeciesFound = false; } } if (!allSpeciesFound) { ReportManager.problem(this, con, "Cannot find all the species"); usage(); } // If there are low-coverage species, check the species_set_tag entry if (lowCoverageSpecies.size() > 0) { // Check that the low-coverage entry exists in the species_set_tag table String speciesSetId1 = getRowColumnValue(con, "SELECT species_set_id FROM species_set_tag WHERE tag = 'name' AND value = 'low-coverage'"); if (speciesSetId1.equals("")) { ReportManager.problem(this, con, "There is no species_set_tag entry for low-coverage genomes"); result = false; } // Check the species_set_id for the set of low-coverage assemblies String sql = "" + lowCoverageGenomeDdIds.get(0); for (int i = 1; i < lowCoverageGenomeDdIds.size(); i++) { sql += "," + lowCoverageGenomeDdIds.get(i); } String speciesSetId2 = getRowColumnValue(con, "SELECT species_set_id, GROUP_CONCAT(genome_db_id ORDER BY genome_db_id) gdbs" + " FROM species_set GROUP BY species_set_id HAVING gdbs = \"" + sql + "\""); if (speciesSetId2.equals("")) { ReportManager.problem(this, con, "Wrong set of low-coverage (" + speciesSetId1 + ") genome_db_ids. It must be: " + sql); result = false; } // Check that both are the same if (!speciesSetId1.equals("") && !speciesSetId2.equals("") && !speciesSetId1.equals(speciesSetId2)) { ReportManager.problem(this, con, "The species_set_id for low-coverage should be " + speciesSetId2 + " and not " + speciesSetId1); result = false; } } return result; } public boolean checkNameTagForMultipleAlignments(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); HashMap allSetsWithAName = new HashMap(); HashMap allSetsForMultipleAlignments = new HashMap(); if (tableHasRows(con, "species_set_tag")) { // Get list of species_set sets in the secondary server String sql1 = "SELECT species_set_id, value FROM species_set_tag WHERE tag = 'name'"; // Find all the species_set_ids for multiple alignments String sql2 = new String("SELECT species_set_id, name FROM method_link_species_set JOIN method_link USING (method_link_id) WHERE" + " class LIKE '%multiple_alignment%' OR class LIKE '%tree_alignment%' OR class LIKE '%ancestral_alignment%'"); try { Statement stmt1 = con.createStatement(); ResultSet rs1 = stmt1.executeQuery(sql1); while (rs1.next()) { allSetsWithAName.put(rs1.getInt(1), rs1.getString(2)); } rs1.close(); stmt1.close(); Statement stmt2 = con.createStatement(); ResultSet rs2 = stmt2.executeQuery(sql2); while (rs2.next()) { allSetsForMultipleAlignments.put(rs2.getInt(1), rs2.getString(2)); } rs2.close(); stmt2.close(); } catch (Exception e) { e.printStackTrace(); } Iterator it = allSetsForMultipleAlignments.keySet().iterator(); while (it.hasNext()) { Object next = it.next(); Object setName = allSetsWithAName.get(next); String multipleAlignmentName = allSetsForMultipleAlignments.get(next).toString(); if (setName == null) { ReportManager.problem(this, con, "There is no name entry in species_set_tag for MSA \"" + multipleAlignmentName + "\"."); result = false; } } } else { ReportManager.problem(this, con, "species_set_tag table is empty. There will be no aliases for multiple alignments"); result = false; } return result; } public boolean checkSpeciesSetByTaxon(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); if (tableHasRows(con, "species_set_tag")) { // Find all the entries with a taxon_id tag String sql_tag = new String("SELECT species_set_id, value FROM species_set_tag WHERE tag = 'taxon_id'"); try { Statement stmt_tag = con.createStatement(); ResultSet rs_tag = stmt_tag.executeQuery(sql_tag); while (rs_tag.next()) { // Check that all the genome_db_ids for that taxon are included // 1. genome_db_ids from ncbi_taxa_node + genome_db tables String sql_taxon = new String("SELECT GROUP_CONCAT(genome_db_id ORDER BY genome_db_id)" + " FROM ncbi_taxa_node nod1" + " LEFT JOIN ncbi_taxa_node nod2 ON (nod1.left_index < nod2.left_index and nod1.right_index > nod2.left_index)" + " LEFT JOIN genome_db ON (nod2.taxon_id = genome_db.taxon_id)" + " WHERE nod1.taxon_id = '" + rs_tag.getInt(2) + "'" + " AND genome_db_id IS NOT NULL AND genome_db.assembly_default = 1"); // 2. genome_db_ids from the species_set table String sql_sset = new String("SELECT GROUP_CONCAT(genome_db_id ORDER BY genome_db_id)" + " FROM species_set WHERE species_set_id = " + rs_tag.getInt(1)); Statement stmt_taxon = con.createStatement(); ResultSet rs_taxon = stmt_taxon.executeQuery(sql_taxon); Statement stmt_sset = con.createStatement(); ResultSet rs_sset = stmt_sset.executeQuery(sql_sset); // Check that 1 and 2 are the same if (rs_taxon.next() && rs_sset.next()) { if (!rs_taxon.getString(1).equals(rs_sset.getString(1))) { ReportManager.problem(this, con, "Species set " + rs_tag.getInt(1) + " has not the right set of genome_db_ids: " + rs_taxon.getString(1)); result = false; } } rs_taxon.close(); stmt_taxon.close(); rs_sset.close(); stmt_sset.close(); } rs_tag.close(); stmt_tag.close(); } catch (SQLException se) { se.printStackTrace(); result = false; } } else { ReportManager.problem(this, con, "species_set_tag table is empty. There will be no colouring in the gene tree view"); result = false; } return result; } private void usage() { ReportManager.problem(this, "USAGE", "run-healthcheck.sh -d ensembl_compara_.+ " + " -d2 .+_core_.+ -d2 .+_compara_.+ CheckSpeciesSetTag"); } } // CheckSpeciesSetTag
package org.helioviewer.jhv.viewmodel.metadata; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Optional; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.helioviewer.jhv.base.logging.Log; import org.w3c.dom.CharacterData; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.google.common.primitives.Doubles; import com.google.common.primitives.Ints; public class XMLMetaDataContainer implements MetaDataContainer { private NodeList nodeList; public void parseXML(String xml) throws Exception { try (InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); nodeList = builder.parse(in).getElementsByTagName("meta"); } catch (Exception e) { throw new Exception("Failed parsing XML data", e); } } public void destroyXML() { nodeList = null; } private String getValueFromXML(String key) { NodeList value = ((Element) nodeList.item(0)).getElementsByTagName(key); Element line = (Element) value.item(0); if (line == null) return null; Node child = line.getFirstChild(); if (child instanceof CharacterData) return ((CharacterData) child).getData(); return null; } @Override public String get(String key) { return getValueFromXML(key); } @Override public double tryGetDouble(String key) { String string = get(key); if (string != null) { try { return Double.parseDouble(string); } catch (NumberFormatException e) { Log.warn("NumberFormatException while trying to parse value \"" + string + "\" of key " + key); return Double.NaN; } } return 0.0; } @Override public int tryGetInt(String key) { String string = get(key); if (string != null) { try { return Integer.parseInt(string); } catch (NumberFormatException e) { Log.warn("NumberFormatException while trying to parse value \"" + string + "\" of key " + key); return Integer.MIN_VALUE; } } return 0; } @Override public Optional<String> getString(String key) { return Optional.ofNullable(getValueFromXML(key)); } @Override public Optional<Integer> getInteger(String key) { return getString(key).map(Ints::tryParse); } @Override public Optional<Double> getDouble(String key) { return getString(key).map(Doubles::tryParse); } }
package org.objectweb.proactive.ic2d.gui.jobmonitor; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.body.rmi.RemoteBodyAdapter; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.runtime.ProActiveRuntime; import org.objectweb.proactive.core.runtime.VMInformation; import org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime; import org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntimeAdapter; import org.objectweb.proactive.ic2d.gui.IC2DGUIController; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.DataAssociation; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredAO; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredHost; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredJVM; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredJob; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredNode; import org.objectweb.proactive.ic2d.gui.jobmonitor.data.MonitoredVN; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.DefaultListModel; public class NodeExploration implements JobMonitorConstants { private static final String PA_JVM = "PA_JVM"; private int maxDepth; private DataAssociation asso; private DefaultListModel skippedObjects; private Map aos; private Set visitedVM; private Map runtimes; private IC2DGUIController controller; public NodeExploration(DataAssociation asso, DefaultListModel skippedObjects, IC2DGUIController controller) { this.maxDepth = 10; this.asso = asso; this.skippedObjects = skippedObjects; this.aos = new HashMap(); this.runtimes = new HashMap(); this.controller = controller; } public int getMaxDepth() { return maxDepth; } public void setMaxDepth(int maxDepth) { if (maxDepth > 0) { this.maxDepth = maxDepth; } } private void log(Throwable e) { controller.log(e, false); } /* url : "//host:port/object" */ private ProActiveRuntime resolveURL(String url) { System.out.println(url); Pattern p = Pattern.compile("(.* Matcher m = p.matcher(url); if (!m.matches()) { return null; } String host = m.group(2); String port = m.group(3); String object = m.group(4); try { Registry registry; if (!port.equals("")) { int portNumber = Integer.parseInt(port); registry = LocateRegistry.getRegistry(host, portNumber); } else { registry = LocateRegistry.getRegistry(host); } RemoteProActiveRuntime r = (RemoteProActiveRuntime) registry.lookup(object); return new RemoteProActiveRuntimeAdapter(r); } catch (Exception e) { log(e); return null; } } private ProActiveRuntime urlToRuntime(String url) { ProActiveRuntime rt = (ProActiveRuntime) runtimes.get(url); if (rt != null) { return rt; } rt = resolveURL(url); if (rt != null) { runtimes.put(url, rt); } return rt; } private List getKnownRuntimes(ProActiveRuntime from) { List known; String[] parents; try { ProActiveRuntime[] registered = from.getProActiveRuntimes(); known = new ArrayList(Arrays.asList(registered)); parents = from.getParents(); } catch (ProActiveException e) { log(e); return new ArrayList(); } for (int i = 0; i < parents.length; i++) { ProActiveRuntime rt = urlToRuntime(parents[i]); if (rt != null) { known.add(urlToRuntime(parents[i])); } } return known; } public void exploreHost(String hostname, int port) { Registry registry; String[] list; MonitoredHost hostObject = new MonitoredHost(hostname); if (skippedObjects.contains(hostObject)) { return; } try { registry = LocateRegistry.getRegistry(hostname, port); list = registry.list(); } catch (Exception e) { log(e); return; } for (int idx = 0; idx < list.length; ++idx) { String id = list[idx]; if (id.indexOf(PA_JVM) != -1) { ProActiveRuntime part; try { RemoteProActiveRuntime r = (RemoteProActiveRuntime) registry.lookup(id); part = new RemoteProActiveRuntimeAdapter(r); handleProActiveRuntime(part, 1); } catch (Exception e) { log(e); continue; } } } } private void handleProActiveRuntime(ProActiveRuntime pr, int depth) { if (pr instanceof RemoteProActiveRuntime && !(pr instanceof RemoteProActiveRuntimeAdapter)) { try { pr = new RemoteProActiveRuntimeAdapter((RemoteProActiveRuntime) pr); } catch (ProActiveException e) { log(e); return; } } VMInformation infos = pr.getVMInformation(); String vmName = infos.getName(); MonitoredJVM jvmObject = new MonitoredJVM(infos.getInetAddress() .getCanonicalHostName(), vmName, depth); if (visitedVM.contains(vmName) || skippedObjects.contains(jvmObject)) { return; } String jobID = pr.getJobID(); MonitoredJob jobObject = new MonitoredJob(jobID); if (skippedObjects.contains(jobObject)) { return; } String hostname = pr.getVMInformation().getInetAddress() .getCanonicalHostName(); MonitoredHost hostObject = new MonitoredHost(hostname); if (skippedObjects.contains(hostObject)) { return; } visitedVM.add(vmName); try { String[] nodes = pr.getLocalNodeNames(); for (int i = 0; i < nodes.length; ++i) { String nodeName = nodes[i]; handleNode(pr, jvmObject, vmName, nodeName); } } catch (ProActiveException e) { log(e); return; } asso.addChild(hostObject, jvmObject); asso.addChild(jobObject, jvmObject); if (depth < maxDepth) { List known = getKnownRuntimes(pr); Iterator iter = known.iterator(); while (iter.hasNext()) handleProActiveRuntime((ProActiveRuntime) iter.next(), depth + 1); } } private void handleNode(ProActiveRuntime pr, MonitoredJVM jvmObject, String vmName, String nodeName) { try { MonitoredNode nodeObject = new MonitoredNode(nodeName); if (skippedObjects.contains(nodeObject)) { return; } String jobID = pr.getJobID(pr.getURL() + "/" + nodeName); MonitoredJob jobObject = new MonitoredJob(jobID); if (skippedObjects.contains(jobObject)) { return; } String vnName = pr.getVNName(nodeName); MonitoredJob vnJobIDObject = null; if (vnName != null) { MonitoredVN vnObject = new MonitoredVN(vnName); if (skippedObjects.contains(vnObject)) { return; } VirtualNode vn = pr.getVirtualNode(vnName); if (vn != null) { vnJobIDObject = new MonitoredJob(vn.getJobID()); if (skippedObjects.contains(vnJobIDObject)) { return; } asso.addChild(vnJobIDObject, vnObject); } asso.addChild(vnObject, nodeObject); } ArrayList activeObjects = pr.getActiveObjects(nodeName); handleActiveObjects(nodeObject, activeObjects); asso.addChild(jvmObject, nodeObject); asso.addChild(jobObject, nodeObject); } catch (ProActiveException e) { log(e); return; } } private void handleActiveObjects(MonitoredNode nodeObject, ArrayList activeObjects) { for (int i = 0, size = activeObjects.size(); i < size; ++i) { ArrayList aoWrapper = (ArrayList) activeObjects.get(i); RemoteBodyAdapter rba = (RemoteBodyAdapter) aoWrapper.get(0); String className = (String) aoWrapper.get(1); if (className.equalsIgnoreCase( "org.objectweb.proactive.ic2d.spy.Spy")) { continue; } String jobID = rba.getJobID(); MonitoredJob jobObject = new MonitoredJob(jobID); if (skippedObjects.contains(jobObject)) { continue; } className = className.substring(className.lastIndexOf(".") + 1); String aoName = (String) aos.get(rba.getID()); if (aoName == null) { aoName = className + "#" + (aos.size() + 1); aos.put(rba.getID(), aoName); } MonitoredAO aoObject = new MonitoredAO(aoName); if (!skippedObjects.contains(aoObject)) { asso.addChild(nodeObject, aoObject); asso.addChild(jobObject, aoObject); } } } public void exploreKnownJVM() { Iterator iter = asso.getJVM().iterator(); while (iter.hasNext()) { MonitoredJVM jvmObject = (MonitoredJVM) iter.next(); ProActiveRuntime pr = urlToRuntime(jvmObject.getFullName()); if (pr != null) { handleProActiveRuntime(pr, jvmObject.getDepth()); } } } public void startExploration() { visitedVM = new TreeSet(); } public void endExploration() { visitedVM = null; asso.updateReallyDeleted(); } }
// 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.frc692.AerialAssist2014.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc692.AerialAssist2014.Robot; public class MoveGathererUp extends Command { public MoveGathererUp() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.gatherer); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { //Robot.gatherer.gatherGo(); } // Called repeatedly when this Command is scheduled to run protected void execute() { if(Robot.gatherer.isBackGatherLimitNotPressed()) { Robot.gatherer.gathererGoUp(); //Robot.gatherer.gatherGo(); System.out.println("Back limit is not pressed; the gatherer is moving forward"); } /* * if the gatherer back limit switch is not pressed the gatherer will go up and * the system will print out "Front limit is not pressed; the gatherer is moving forward" * AO 1/17/14 */ else { System.out.println("Back limit is pressed."); } /* * if the back gather limit switch is not pressed * the system will print out "Gatherer is not moving" * AO 1/17/14 */ } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { if(Robot.gatherer.isBackGatherLimitPressed()) { System.out.println("Back gather limit is pressed."); return true; } /* * if the front gather limit switch is pressed the system will print * out "Front gather limit is pressed" and the statement will come * out true * AO 1/17/14 */ else { return false; } /* * if the back gather limit switch is not pressed then the staememtn will be false * AO 1/17/14 */ } // Called once after isFinished returns true protected void end() { //Robot.gatherer.gatherStop(); Robot.gatherer.gathererAirStop(); System.out.println("Gatherer is calling the end method."); } /* * if the air pressure stops the system will print out "Gatherer is calling the * end of the method" and the statement will end * AO 1/17/14 */ // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { while(Robot.gatherer.isBackGatherLimitNotPressed()) { Robot.gatherer.gathererGoUp(); System.out.println("Front gather limit is not pressed."); } /* * if the statement is interrupted and the front gather limit swith is * not pressed, the gatherer will go up and the system will print out * "Front gather limit is not pressed" * AO 1/17/14 */ end(); } }
package at.ac.tuwien.inso.service_tests; import at.ac.tuwien.inso.controller.lecturer.GradeAuthorizationDTO; import at.ac.tuwien.inso.entity.*; import at.ac.tuwien.inso.exception.*; import at.ac.tuwien.inso.repository.*; import at.ac.tuwien.inso.service.*; import at.ac.tuwien.inso.service.impl.*; import org.jboss.aerogear.security.otp.Totp; import org.junit.*; import org.junit.runner.*; import org.mockito.*; import org.mockito.runners.*; import org.springframework.security.test.context.support.*; import org.springframework.test.context.*; import org.springframework.transaction.annotation.Transactional; import java.math.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) @ActiveProfiles("test") @Transactional public class GradeServiceTests { private static final int TWO_FACTOR_AUTHENTICATION_TIMEOUT_SECONDS = 30; private static final Long VALID_STUDENT_ID = 1L; private static final Long VALID_UNREGISTERED_STUDENT_ID = 2L; private static final Long INVALID_STUDENT_ID = 1337L; private static final Long VALID_COURSE_ID = 3L; private static final Long INVALID_COURSE_ID = 337L; private GradeService gradeService; @Mock private LecturerService lecturerService; @Mock private StudentService studentService; @Mock private CourseService courseService; @Mock private UserAccountService userAccountService; @Mock private GradeRepository gradeRepository; private Course course = new Course(new Subject("ASE", BigDecimal.ONE), new Semester("WS16")); private Student student = new Student("Student", "Student", "Student@student.com"); private Student unregisteredStudent = new Student("Student2", "Student2", "not@registered.com"); private UserAccount user = new UserAccount("lecturer1", "pass", Role.LECTURER); private Lecturer lecturer = new Lecturer("Lecturer", "Lecturer", "lecturer@lecturer.com", user); private Grade validGrade = new Grade(course, lecturer, student, Mark.SATISFACTORY); @Before public void setUp() { course.getStudents().add(student); MockitoAnnotations.initMocks(this); when(courseService.findOne(VALID_COURSE_ID)).thenReturn(course); when(courseService.findOne(INVALID_COURSE_ID)).thenReturn(null); when(studentService.findOne(VALID_STUDENT_ID)).thenReturn(student); when(studentService.findOne(VALID_UNREGISTERED_STUDENT_ID)).thenReturn(unregisteredStudent); when(studentService.findOne(INVALID_STUDENT_ID)).thenReturn(null); when(lecturerService.getLoggedInLecturer()).thenReturn(lecturer); when(gradeRepository.save(validGrade)).thenReturn(validGrade); gradeService = new GradeServiceImpl( gradeRepository, studentService, courseService, lecturerService, userAccountService ); } @Test @WithMockUser(roles = "Lecturer") public void getDefaultGradeForStudentAndCourseTest() { GradeAuthorizationDTO gradeAuth = gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(VALID_STUDENT_ID, VALID_COURSE_ID); Grade grade = gradeAuth.getGrade(); assertEquals(grade.getCourse(), course); assertEquals(grade.getStudent(), student); assertEquals(grade.getLecturer(), lecturer); assertEquals(grade.getMark(), Mark.FAILED); assertNull(grade.getId()); } @Test(expected = BusinessObjectNotFoundException.class) @WithMockUser(roles = "Lecturer") public void getDefaultGradeForInvalidStudentAndCourseTest() { gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(INVALID_STUDENT_ID, VALID_COURSE_ID); } @Test(expected = BusinessObjectNotFoundException.class) @WithMockUser(roles = "Lecturer") public void getDefaultGradeForStudentAndInvalidCourseTest() { gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(VALID_STUDENT_ID, INVALID_COURSE_ID); } @Test(expected = BusinessObjectNotFoundException.class) @WithMockUser(roles = "Lecturer") public void getDefaultGradeForInvalidStudentAndInvalidCourseTest() { gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(INVALID_STUDENT_ID, INVALID_COURSE_ID); } @Test(expected = ValidationException.class) @WithMockUser(roles = "Lecturer") public void getDefaultGradeForUnregisteredStudentAndCourseTest() { gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(VALID_UNREGISTERED_STUDENT_ID, VALID_COURSE_ID); } @Test @WithUserDetails("lecturer1") public void saveNewGradeForStudentAndCourseTest() { Totp totp = new Totp(lecturer.getTwoFactorSecret()); Grade result = gradeService.saveNewGradeForStudentAndCourse(new GradeAuthorizationDTO(validGrade, totp.now())); assertEquals(validGrade.getLecturer(), result.getLecturer()); assertEquals(validGrade.getStudent(), result.getStudent()); assertEquals(validGrade.getCourse(), result.getCourse()); assertEquals(validGrade.getMark(), result.getMark()); } @Ignore //Takes more than a minute @Test(expected = ValidationException.class) @WithUserDetails("lecturer1") public void saveNewGradeForStudentAndCourseTestTwoFactorAuthFail() throws InterruptedException { Totp totp = new Totp(lecturer.getTwoFactorSecret()); String code = totp.now(); Thread.sleep(2 * TWO_FACTOR_AUTHENTICATION_TIMEOUT_SECONDS * 1000); gradeService.saveNewGradeForStudentAndCourse(new GradeAuthorizationDTO(validGrade, code)); } @Test(expected = ValidationException.class) @WithUserDetails("lecturer1") public void saveNewGradeForStudentAndCourseTestTwoFactorAuthFailWrongCode() throws InterruptedException { Totp totp = new Totp(lecturer.getTwoFactorSecret()); String code = "123456"; gradeService.saveNewGradeForStudentAndCourse(new GradeAuthorizationDTO(validGrade, code)); } }
package br.com.caelum.brutal.validators; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import br.com.caelum.brutal.dao.UserDAO; import br.com.caelum.brutal.model.User; import br.com.caelum.vraptor.Validator; import br.com.caelum.vraptor.util.test.JSR303MockValidator; public class UserValidatorTest { private UserDAO users; private Validator validator; private UserValidator userValidator; @Before public void setup() { users = mock(UserDAO.class); validator = new JSR303MockValidator(); userValidator = new UserValidator(validator, users); } @Test public void should_verify_email() { when(users.existsWithEmail("used@gmail.com")).thenReturn(true); User user = new User("nome", "used@gmail.com", "123"); boolean valid = userValidator.validate(user, "123", "123"); assertFalse(valid); } @Test public void should_verify_passwords() throws Exception { when(users.existsWithEmail("valid@gmail.com")).thenReturn(false); User user = new User("nome", "valid@gmail.com", "123"); boolean valid = userValidator.validate(user, "123", "1234"); assertFalse(valid); } @Test public void should_verify_null() throws Exception { boolean valid = userValidator.validate(null, "123", "1234"); assertFalse(valid); } @Test public void should_valid_user() throws Exception { when(users.existsWithEmail("used@gmail.com")).thenReturn(false); User user = new User("nome", "used@gmail.com", "123"); boolean valid = userValidator.validate(user, "123", "123"); assertTrue(valid); } }
package com.github.kolorobot.execution; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(JUnit4.class) // Tests can be run with different runners public class JunitExecutionTest { private static final Logger LOGGER = LoggerFactory.getLogger(JunitExecutionTest.class); private Helper helper = new Helper(); // No-arg constructor public JunitExecutionTest() { LOGGER.info("JunitExecutionTest ctor"); } // Test Fixture @BeforeClass public static void beforeClass() { LOGGER.info("beforeClass"); } @Before public void before() { LOGGER.info("before"); } @AfterClass public static void afterClass() { LOGGER.info("afterClass"); } @After public void after() { LOGGER.info("after"); } // Test Cases @Test public void test1() { // must be public and void LOGGER.info("test1"); Assert.assertTrue(true); } @Test public void test2() throws Exception { // can declare exceptions LOGGER.info("test2"); Assert.assertTrue(true); } @Test @Ignore public void ignored() { // won't run LOGGER.info("ignored"); Assert.assertTrue(false); } class Helper { Helper() { LOGGER.info("Helper ctor"); } } }
package com.j256.ormlite.dao; import org.junit.Ignore; import org.junit.Test; public class SqlServerJtdsBaseDaoImplTest extends JdbcBaseDaoImplTest { @Override protected void setDatabaseParams() { databaseHost = "wfs2.jprinc.net"; databaseUrl = "jdbc:jtds:sqlserver://" + databaseHost + ":1433/ormlite;ssl=request"; userName = "gwatson"; password = "ormlite"; } @Test @Override @Ignore("sql server needs some special flags to allow inserts into table") public void testInsertAutoGeneratedId() throws Exception { super.testInsertAutoGeneratedId(); } @Test @Ignore("always seems to fail") @Override public void testUniqueAndUniqueCombo() throws Exception { super.testUniqueAndUniqueCombo(); } }
package de.bmoth.backend.translator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; import com.microsoft.z3.*; import de.bmoth.backend.SolutionFinder; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import de.bmoth.backend.FormulaToZ3Translator; import java.util.HashMap; import java.util.Map; import java.util.Set; public class FormulaEvaluationTest { private Context ctx; private Solver s; @Before public void setup() { ctx = new Context(); s = ctx.mkSolver(); } @After public void cleanup() { ctx.close(); } @Test public void testAdditionFormula() throws Exception { String formula = "x = 2 + 3"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(5), s.getModel().eval(x, true)); } @Test public void testSubtractionFormula() throws Exception { String formula = "x = 2 - 3"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(-1), s.getModel().eval(x, true)); } @Test public void testEqualityFormula() throws Exception { String formula = "x = 5"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(5), s.getModel().eval(x, true)); } @Test public void testInequalityFormula() throws Exception { String formula = "x /= 0"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertNotEquals(ctx.mkInt(0), s.getModel().eval(x, true)); } @Test public void testModuloFormula() throws Exception { String formula = "x = 3 mod 2"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(1), s.getModel().eval(x, true)); } @Test public void testMultiplicationFormula() throws Exception { String formula = "x = 3 * 2"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(6), s.getModel().eval(x, true)); } @Test public void testAddMulOrderFormula() throws Exception { /** * Tests order of multiplication and addition */ String formula = "x = 4 + 3 * 2 * 2"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(16), s.getModel().eval(x, true)); } @Test public void testDivisionFormula() throws Exception { String formula = "x = 8 / 2"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(4), s.getModel().eval(x, true)); } @Test public void testPowerFormula() throws Exception { String formula = "x = 2 ** 8"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); assertEquals(Status.SATISFIABLE, check); assertEquals(ctx.mkInt(256), s.getModel().eval(x, true)); } @Test public void testLessThanFormula() throws Exception { String formula = "1 < 2"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); assertEquals(Status.SATISFIABLE, check); } @Test public void testGreaterThanFormula() throws Exception { String formula = "2 > 1"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); assertEquals(Status.SATISFIABLE, check); } @Test public void testLessEqualFormula() throws Exception { String formula = "x <= 4 & x > 0"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); SolutionFinder finder = new SolutionFinder(constraint, s, ctx); Set<Model> solutions = finder.findSolutions(20); assertEquals(4, solutions.size()); for (Model solution : solutions) { String solutionAsString = z3ModelToString(solution); switch (solutionAsString) { case "{x=1}": case "{x=2}": case "{x=3}": case "{x=4}": break; default: fail(solutionAsString + " is not part of found solutions"); } } } @Test public void testGreaterEqualFormula() throws Exception { String formula = "x >= 4 & x < 8"; // getting the translated z3 representation of the formula BoolExpr constraint = FormulaToZ3Translator.translatePredicate(formula, ctx); s.add(constraint); Status check = s.check(); Expr x = ctx.mkIntConst("x"); SolutionFinder finder = new SolutionFinder(constraint, s, ctx); Set<Model> solutions = finder.findSolutions(20); assertEquals(4, solutions.size()); for (Model solution : solutions) { String solutionAsString = z3ModelToString(solution); switch (solutionAsString) { case "{x=4}": case "{x=5}": case "{x=6}": case "{x=7}": break; default: fail(solutionAsString + " is not part of found solutions"); } } } static String z3ModelToString(Model m) { Map<String,String> values = new HashMap<>(); for(FuncDecl constant : m.getConstDecls()) { String value = m.eval(constant.apply(),true).toString(); values.put(constant.apply().toString(),value); } return values.toString(); } }
package edu.emory.cci.aiw.umls; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.arp.javautil.sql.DatabaseAPI; import org.junit.After; import org.junit.Before; import org.junit.Test; public class UMLSDatabaseConnectionTest { private UMLSDatabaseConnection conn; private List<SAB> sabs; public UMLSDatabaseConnectionTest() { } @org.junit.BeforeClass public static void setUpClass() throws Exception { } @org.junit.AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { String url = "jdbc:mysql://aiwdev02.eushc.org:3307/umls_2010AA", user = "umlsuser", pass = "3SqQgPOh"; this.conn = UMLSDatabaseConnection.getConnection( DatabaseAPI.DRIVERMANAGER, url, user, pass); sabs = new ArrayList<SAB>(); sabs.add(SAB.withName("SNOMEDCT")); sabs.add(SAB.withName("RXNORM")); } @After public void tearDown() throws Exception { this.conn = null; } @Test public void testGetCUI() throws Exception { List<ConceptUID> cuis = conn.getCUI(UMLSQueryStringValue .fromString("Malignant tumour of prostate"), sabs, false); assertEquals(1, cuis.size()); assertEquals(ConceptUID.fromString("C0376358"), cuis.get(0)); } @Test public void testGetCUIMultByCUI() throws Exception { } @Test public void testGetCUIMultByAUI() { } @Test public void testGetCUIMultByLUI() { } @Test public void testGetCUIMultBySUI() { } @Test public void testCUIMultByString() { } @Test public void testGetAUI() throws Exception { List<AtomUID> auis = conn.getAUI(UMLSQueryStringValue .fromString("Malignant tumour of prostate"), sabs.get(0)); assertEquals(2, auis.size()); Set<AtomUID> actual = new HashSet<AtomUID>(auis); Set<AtomUID> expected = new HashSet<AtomUID>(); expected.add(AtomUID.fromString("A4786634")); expected.add(AtomUID.fromString("A3042752")); assertEquals(expected, actual); } @Test public void testGetSTR() throws Exception { List<UMLSQueryStringValue> strings = conn.getSTR(AtomUID .fromString("A3042752"), sabs.get(0), null, UMLSPreferred.NO_PREFERENCE); assertEquals(1, strings.size()); assertEquals(UMLSQueryStringValue .fromString("Malignant tumour of prostate"), strings.get(0)); } @Test public void testGetTUI() throws Exception { List<TermUID> tuis = conn.getTUI(UMLSQueryStringValue .fromString("Malignant tumour of prostate"), sabs.get(0)); assertEquals(1, tuis.size()); assertEquals(TermUID.fromString("T191"), tuis.get(0)); } @Test public void testGetSAB() throws Exception { List<SAB> sabs = conn.getSAB(UMLSQueryStringValue .fromString("prostate")); assertEquals(2, sabs.size()); Set<SAB> actual = new HashSet<SAB>(sabs); Set<SAB> expected = new HashSet<SAB>(); expected.add(sabs.get(0)); expected.add(sabs.get(1)); assertEquals(expected, actual); } @Test public void testMapToCUI() throws Exception { Map<String, MapToIdResult<ConceptUID>> results = conn.mapToCUI( "intraductal carcinoma of prostate", sabs); assertEquals(6, results.size()); Map<String, MapToIdResult<ConceptUID>> expected = new HashMap<String, MapToIdResult<ConceptUID>>(); expected.put("intraductal", MapToIdResult.fromUidAndStr(ConceptUID .fromString("C1644197"), UMLSQueryStringValue .fromString("Intraductal"))); expected.put("intraductal carcinoma", MapToIdResult.fromUidAndStr( ConceptUID.fromString("C0007124"), UMLSQueryStringValue .fromString("Intraductal carcinoma"))); expected.put("carcinoma", MapToIdResult.fromUidAndStr(ConceptUID .fromString("C0007097"), UMLSQueryStringValue .fromString("Carcinoma"))); expected.put("carcinoma of prostate", MapToIdResult.fromUidAndStr( ConceptUID.fromString("C0600139"), UMLSQueryStringValue .fromString("Carcinoma of prostate"))); expected.put("prostate", MapToIdResult.fromUidAndStr(ConceptUID .fromString("C0033572"), UMLSQueryStringValue .fromString("Prostate"))); expected.put("prostate carcinoma", MapToIdResult.fromUidAndStr( ConceptUID.fromString("C0600139"), UMLSQueryStringValue .fromString("Prostate carcinoma"))); assertEquals(expected, results); } @Test public void testMapToAUI() { } @Test public void testMapToLUI() { } @Test public void testMapToSUI() { } @Test public void testGetParents() throws Exception { Map<PTR, AtomUID> parents = conn.getParents(ConceptUID .fromString("C0007124"), "isa", null); assertEquals(675, parents.size()); parents = conn.getParents(ConceptUID.fromString("C0600139"), "isa", null); assertEquals(370, parents.size()); } @Test public void testGetParentsMultByCUI() { } @Test public void testGetParentsMultByAUI() { } @Test public void testGetCommonParent() throws Exception { CommonParent<ConceptUID> cp = conn.getCommonParent(ConceptUID .fromString("C0600139"), ConceptUID.fromString("C0007124"), null, null); assertEquals(AtomUID.fromString("A3684559"), cp.getParent()); assertEquals(3, cp.getChild1Links()); assertEquals(8, cp.getChild2Links()); } @Test public void testGetChildrenCUI() throws Exception { List<ConceptUID> children = conn.getChildren(ConceptUID .fromString("C0376358"), "isa", null); assertEquals(6, children.size()); Set<ConceptUID> actual = new HashSet<ConceptUID>(children); Set<ConceptUID> expected = new HashSet<ConceptUID>(); expected.add(ConceptUID.fromString("C1330959")); expected.add(ConceptUID.fromString("C1328504")); expected.add(ConceptUID.fromString("C0347001")); expected.add(ConceptUID.fromString("C1297952")); expected.add(ConceptUID.fromString("C1302530")); expected.add(ConceptUID.fromString("C1282482")); assertEquals(expected, actual); } @Test public void testGetChildrenAUI() throws Exception { List<AtomUID> children = conn.getChildren(AtomUID .fromString("A3323363"), "isa", null); assertEquals(9, children.size()); Set<AtomUID> actual = new HashSet<AtomUID>(children); Set<AtomUID> expected = new HashSet<AtomUID>(); expected.add(AtomUID.fromString("A2949514")); expected.add(AtomUID.fromString("A2949516")); expected.add(AtomUID.fromString("A3295134")); expected.add(AtomUID.fromString("A3095622")); expected.add(AtomUID.fromString("A3184304")); expected.add(AtomUID.fromString("A3594641")); expected.add(AtomUID.fromString("A3567685")); expected.add(AtomUID.fromString("A3586937")); expected.add(AtomUID.fromString("A16962310")); assertEquals(expected, actual); } @Test public void testGetCommonChildCUI() throws Exception { ConceptUID child = conn.getCommonChild(ConceptUID .fromString("C0376358"), ConceptUID.fromString("C0346554"), "", null); assertEquals(null, child); } @Test public void testGetCommonChildAUI() throws Exception { AtomUID child = conn.getCommonChild(AtomUID.fromString("A3261244"), AtomUID.fromString("A3339540"), "", null); assertEquals(null, child); } @Test public void testGetAvailableSAB() throws Exception { Set<SAB> actual = conn.getAvailableSAB("SNOMED"); Set<SAB> expected = new HashSet<SAB>(); expected.add(SAB.withNameAndDescription("SNMI", "SNOMED Clinical Terms, 2009_07_31")); expected .add(SAB .withNameAndDescription( "SCTSPA", "SNOMED Terminos Clinicos (SNOMED CT), Edicion en Espanol, Distribucion Internacional, Octubre de 2009, 2009_10_31")); expected.add(SAB.withNameAndDescription("SNM", "SNOMED-2, 2")); expected.add(SAB.withNameAndDescription("SNOMEDCT", "SNOMED International, 1998")); assertEquals(expected, actual); } @Test public void testGetDistBF() throws Exception { assertEquals(2, conn.getDistBF(ConceptUID.fromString("C0600139"), ConceptUID.fromString("C0007124"), "", null, 0)); } @Test public void testGetNeighbors() { } @Test public void testUidToCode() throws Exception { SAB sab = SAB.withName("ICD9CM"); ConceptUID cui = ConceptUID.fromString("C0271635"); List<TerminologyCode> actual = conn.uidToCode(cui, sab); List<TerminologyCode> expected = new ArrayList<TerminologyCode>(); expected.add(TerminologyCode.fromStringAndSAB("250.0", sab)); assertEquals(expected, actual); actual.clear(); expected.clear(); sab = SAB.withName("SNOMEDCT"); actual = conn.uidToCode(cui, sab); expected.add(TerminologyCode.fromStringAndSAB("111552007", sab)); expected.add(TerminologyCode.fromStringAndSAB("190321005", sab)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab)); expected.add(TerminologyCode.fromStringAndSAB("190324002", sab)); expected.add(TerminologyCode.fromStringAndSAB("190321005", sab)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab)); expected.add(TerminologyCode.fromStringAndSAB("190324002", sab)); expected.add(TerminologyCode.fromStringAndSAB("111552007", sab)); assertEquals(expected, actual); AtomUID aui = AtomUID.fromString("A8340910"); sab = SAB.withName("ICD9CM"); actual = conn.uidToCode(aui, sab); expected.clear(); expected.add(TerminologyCode.fromStringAndSAB("250.0", sab)); assertEquals(expected, actual); } @Test public void testCodeToUid() throws Exception { ConceptUID expected = ConceptUID.fromString("C0271635"); TerminologyCode icd9Code = TerminologyCode.fromStringAndSAB("250.0", SAB.withName("ICD9CM")); TerminologyCode snomedCode = TerminologyCode.fromStringAndSAB( "111552007", SAB.withName("SNOMEDCT")); ConceptUID cui = conn.codeToUID(icd9Code); assertEquals(expected, cui); cui = conn.codeToUID(snomedCode); assertEquals(expected, cui); } @Test public void testTranslateCode() throws Exception { SAB sab1 = SAB.withName("ICD9CM"); SAB sab2 = SAB.withName("SNOMEDCT"); List<TerminologyCode> actual = conn.translateCode(TerminologyCode .fromStringAndSAB("250.0", sab1), sab2); List<TerminologyCode> expected = new ArrayList<TerminologyCode>(); expected.add(TerminologyCode.fromStringAndSAB("111552007", sab2)); expected.add(TerminologyCode.fromStringAndSAB("190321005", sab2)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab2)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab2)); expected.add(TerminologyCode.fromStringAndSAB("190324002", sab2)); expected.add(TerminologyCode.fromStringAndSAB("190321005", sab2)); expected.add(TerminologyCode.fromStringAndSAB("154674007", sab2)); expected.add(TerminologyCode.fromStringAndSAB("190324002", sab2)); expected.add(TerminologyCode.fromStringAndSAB("111552007", sab2)); assertEquals(expected, actual); } }
package net.openhft.chronicle.queue; import net.openhft.chronicle.core.time.SetTimeProvider; import net.openhft.chronicle.queue.impl.RollingChronicleQueue; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder; import net.openhft.chronicle.threads.NamedThreadFactory; import net.openhft.chronicle.wire.DocumentContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static net.openhft.chronicle.queue.ChronicleQueueTestBase.getTmpDir; import static net.openhft.chronicle.queue.RollCycles.TEST_SECONDLY; /** * @author Rob Austin. */ public class MultiThreadedRollTest { final ExecutorService reader = Executors.newSingleThreadExecutor(new NamedThreadFactory ("reader", true)); @Before public void before() { reader = Executors.newSingleThreadExecutor(new NamedThreadFactory ("reader", true)); } @After public void after() { if (reader != null) reader.shutdown(); } @Test(timeout = 1000) public void test() throws ExecutionException, InterruptedException { final SetTimeProvider timeProvider = new SetTimeProvider(); timeProvider.currentTimeMillis(1000); final String path = getTmpDir() + "/backRoll.q"; final RollingChronicleQueue wqueue = SingleChronicleQueueBuilder.binary(path) .timeProvider(timeProvider) .rollCycle(TEST_SECONDLY) .build(); wqueue.acquireAppender().writeText("hello world"); final RollingChronicleQueue rqueue = SingleChronicleQueueBuilder.binary(path) .timeProvider(timeProvider) .rollCycle(TEST_SECONDLY) .build(); ExcerptTailer tailer = rqueue.createTailer(); Future f = reader.submit(() -> { long index = 0; do { try (DocumentContext documentContext = tailer.readingDocument()) { index = documentContext.index(); System.out.println("documentContext.isPresent=" + documentContext.isPresent() + ",index=" + Long.toHexString(index)); } } while (index != 0x200000000L && !reader.isShutdown()); }); timeProvider.currentTimeMillis(2000); wqueue.acquireAppender().writeText("hello world"); f.get(); } }
package org.concordion.cubano.utils; import org.junit.Test; import javax.xml.datatype.XMLGregorianCalendar; import java.text.ParseException; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.TimeZone; import static org.junit.Assert.assertEquals; public class ISODateTimeFormatTest { public ISODateTimeFormatTest() { TimeZone.setDefault(TimeZone.getTimeZone("NZ")); } @Test public void custom() throws ParseException { LocalDateTime date; // Custom date = ISODateTimeFormat.parse("2016-07-01T02:09:18.76Z"); assertEquals("ISO8601 Local Date", "2016-07-01T02:09:18.760Z", ISODateTimeFormat.formatAsUTCDateTimeBPM(date)); date = ISODateTimeFormat.parse("2016-07-01T02:09:18.7Z"); assertEquals("ISO8601 Local Date", "2016-07-01T02:09:18.700Z", ISODateTimeFormat.formatAsUTCDateTimeBPM(date)); date = ISODateTimeFormat.parse("2016-07-01T02:09:00.76Z"); assertEquals("ISO8601 Local Date", "2016-07-01T02:09:00.760Z", ISODateTimeFormat.formatAsUTCDateTimeBPM(date)); date = ISODateTimeFormat.parse("2016-07-01T02:09:00Z"); assertEquals("ISO8601 Local Date", "2016-07-01T02:09:00.000Z", ISODateTimeFormat.formatAsUTCDateTimeBPM(date)); } @Test public void zeroMinutesSeconds() throws ParseException { LocalDateTime date; // Zero Minutes/Seconds date = ISODateTimeFormat.parse("2016-04-26T15:00:00"); assertEquals("ISO8601 Local Date", "2016-04-26T15:00", ISODateTimeFormat.formatAsLocalDateTimeString(date)); assertEquals("ISO8601 UTC TimeZone", "2016-04-26T03:00Z", ISODateTimeFormat.formatAsUTCDateTimeString(date)); assertEquals("ISO8601 Local Date", "2016-04-26T15:00:00", ISODateTimeFormat.formatAsLocalDateTime(date)); assertEquals("ISO8601 UTC TimeZone", "2016-04-26T03:00:00Z", ISODateTimeFormat.formatAsUTCDateTime(date)); // Non Zero Minutes/Seconds date = ISODateTimeFormat.parse("2016-04-26T15:16:55"); assertEquals("Local Date", "2016-04-26T15:16:55", date.toString()); assertEquals("ISO8601 Local Date", "2016-04-26T15:16:55", ISODateTimeFormat.formatAsLocalDateTimeString(date)); assertEquals("ISO8601 UTC TimeZone", "2016-04-26T03:16:55Z", ISODateTimeFormat.formatAsUTCDateTimeString(date)); assertEquals("ISO8601 Default TimeZone", "2016-04-26T15:16:55+12:00[" + ZoneId.systemDefault().getId() + "]", ISODateTimeFormat.format(date, ZoneId.systemDefault())); } @Test public void daylightSavings() throws ParseException { LocalDateTime date; // Daylight Savings date = ISODateTimeFormat.parse("2016-03-26T15:16:55"); assertEquals("ISO8601 Local Date Daylight Savings", "2016-03-26T15:16:55", ISODateTimeFormat.formatAsLocalDateTimeString(date)); assertEquals("ISO8601 Local Date Daylight Savings", "2016-03-26T02:16:55Z", ISODateTimeFormat.formatAsUTCDateTimeString(date)); assertEquals("ISO8601 Default TimeZone Daylight Savings", "2016-03-26T15:16:55+13:00[" + ZoneId.systemDefault().getId() + "]", ISODateTimeFormat.format(date, ZoneId.systemDefault())); date = ISODateTimeFormat.parse("2016-04-26T03:16:55Z"); assertEquals("UTC Date", "2016-04-26T15:16:55", date.toString()); assertEquals("ISO8601 UTC Date", "2016-04-26T03:16:55Z", ISODateTimeFormat.formatAsUTCDateTimeString(date)); } @Test public void nanosecods() throws ParseException { LocalDateTime date; // Nanoseconds date = ISODateTimeFormat.parse("2016-04-26T03:16:55.189Z"); assertEquals("ISO8601 Local NANO", "2016-04-26T15:16:55.189", ISODateTimeFormat.formatAsLocalDateTimeString(date)); date = ISODateTimeFormat.parse("2016-04-26T03:16:55.1Z"); assertEquals("ISO8601 Local NANO", "2016-04-26T15:16:55.100", ISODateTimeFormat.formatAsLocalDateTimeString(date)); date = ISODateTimeFormat.parse("2016-04-26T03:16:55.100200300Z"); assertEquals("ISO8601 Local NANO", "2016-04-26T15:16:55.100200300", ISODateTimeFormat.formatAsLocalDateTimeString(date)); } @Test public void customFormat() throws ParseException { LocalDateTime date; // Custom Format date = ISODateTimeFormat.parse("2016-04-26T03:16:55.923Z"); assertEquals("Custom Format", "2016-04-26", ISODateTimeFormat.format(date, ISODateTimeFormat.SHORT_DATE)); assertEquals("Custom Format", "26/04/2016 15:16:55", ISODateTimeFormat.format(date, ISODateTimeFormat.DISPLAY_LONG_DATE)); } @Test public void gregorianCalendar() throws ParseException { LocalDateTime date; // XMLGregorianCalendar XMLGregorianCalendar xcal = ISODateTimeFormat.toXMLGregorianCalendar("2016-04-26T03:16:55.923Z"); assertEquals("XMLGregorianCalendar", "Tue Apr 26 15:16:55 NZST 2016", xcal.toGregorianCalendar().getTime().toString()); assertEquals("XMLGregorianCalendar", "2016-04-26T03:16:55.923Z", xcal.toGregorianCalendar().getTime().toInstant().toString()); assertEquals("XMLGregorianCalendar", "2016-04-26T03:16:55.923Z", ISODateTimeFormat.fromXMLGregorianCalendarToString(xcal)); date = ISODateTimeFormat.fromXMLGregorianCalendarToLocalDT(xcal); assertEquals("XMLGregorianCalendar", "2016-04-26T15:16:55.923", ISODateTimeFormat.formatAsLocalDateTime(date)); } }
package tr.com.srdc.cda2fhir; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.eclipse.emf.common.util.EList; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.openhealthtools.mdht.uml.cda.ClinicalDocument; import org.openhealthtools.mdht.uml.cda.PatientRole; import org.openhealthtools.mdht.uml.cda.consol.ContinuityOfCareDocument; import org.openhealthtools.mdht.uml.cda.util.CDAUtil; import org.openhealthtools.mdht.uml.hl7.datatypes.EN; import org.openhealthtools.mdht.uml.hl7.datatypes.ENXP; import org.openhealthtools.mdht.uml.hl7.datatypes.II; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.ExtensionDt; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.dstu2.resource.Patient; import ca.uhn.fhir.parser.IParser; import tr.com.srdc.cda2fhir.impl.ResourceTransformerImpl; import tr.com.srdc.cda2fhir.impl.ValueSetsTransformerImpl; public class ResourceTransformerTestNecip { // Test one method at a time. Use annotation @Ignore for the remaining methods. // context private static final FhirContext myCtx = FhirContext.forDstu2(); ResourceTransformerImpl rt = new ResourceTransformerImpl(); DataTypesTransformerTest dtt = new DataTypesTransformerTest(); ValueSetsTransformerImpl vsti = new ValueSetsTransformerImpl(); private FileInputStream fisCDA; private FileInputStream fisCCD; private ClinicalDocument cda; private ContinuityOfCareDocument ccd; private void printJSON(IResource res) { IParser jsonParser = myCtx.newJsonParser(); jsonParser.setPrettyPrint(true); System.out.println(jsonParser.encodeResourceToString(res)); } public ResourceTransformerTestNecip() { CDAUtil.loadPackages(); try { fisCDA = new FileInputStream("src/test/resources/SampleCDADocument.xml"); // fisCCD = new FileInputStream("src/test/resources/C-CDA_R2-1_CCD.xml"); fisCCD = new FileInputStream("src/test/resources/Vitera_CCDA_SMART_Sample.xml"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } try { if( fisCDA != null ) { cda = CDAUtil.load(fisCDA); } if( fisCCD != null ) { // To validate the file, use the following two lines instead of the third line // ValidationResult result = new ValidationResult(); // ccd = (ContinuityOfCareDocument) CDAUtil.load(fisCCD,result); ccd = (ContinuityOfCareDocument) CDAUtil.load(fisCCD); } } catch (Exception e) { e.printStackTrace(); } } @Test public void testEncounter2Encounter(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int encounterCount = 0; // if( test.ccd.getEncountersSection() != null && !test.ccd.getEncountersSection().isSetNullFlavor() && test.ccd.getEncountersSection() != null ){ if( test.ccd.getAllSections() != null && !test.ccd.getAllSections().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Section section : test.ccd.getAllSections() ){ if( section != null && !section.isSetNullFlavor() ){ for( org.openhealthtools.mdht.uml.cda.Encounter cdaEncounter : section.getEncounters() ){ if( cdaEncounter != null && !cdaEncounter.isSetNullFlavor() ){ System.out.println("Encounter["+encounterCount+"]"); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Encounter fhirEncounter = rt.Encounter2Encounter(cdaEncounter); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( fhirEncounter ); System.out.println("End of print."); System.out.print("\n***\n"); // to visualize } encounterCount++; } } } } } @Ignore public void testGuardian2Contact(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int patientRoleCount = 0; if( test.ccd.getPatientRoles() != null && !test.ccd.getPatientRoles().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.PatientRole patientRole : test.ccd.getPatientRoles() ){ if( patientRole != null && !patientRole.isSetNullFlavor() && patientRole.getPatient() != null && !patientRole.getPatient().isSetNullFlavor() ){ int guardianCount = 0; for( org.openhealthtools.mdht.uml.cda.Guardian guardian : patientRole.getPatient().getGuardians() ){ if( guardian != null && !guardian.isSetNullFlavor()){ System.out.println("PatientRole["+patientRoleCount+"], Guardian["+guardianCount+"]"); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Patient.Contact contact = rt.Guardian2Contact(guardian); System.out.println("End of transformation. Printing the resource as JSON object.."); ca.uhn.fhir.model.dstu2.resource.Patient patient = new Patient().addContact(contact); printJSON( patient ); System.out.println("End of print."); System.out.print("\n***\n"); // to visualize } guardianCount++; } } patientRoleCount++; } } } @Ignore public void testProcedure2Procedure(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int procedureCount = 0; if( test.ccd.getProceduresSection() != null && !test.ccd.getProceduresSection().isSetNullFlavor() ){ if( test.ccd.getProceduresSection().getProcedures() != null && !test.ccd.getProceduresSection().getProcedures().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Procedure cdaProcedure : test.ccd.getProceduresSection().getProcedures() ){ // traversing procedures System.out.println( "Procedure["+ procedureCount++ +"]" ); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Procedure fhirProcedure = rt.Procedure2Procedure(cdaProcedure); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( fhirProcedure ); System.out.println("End of print."); System.out.print("\n***\n"); // to visualize } } } int encounterProceduresCount = 0; if( test.ccd.getEncountersSection() != null && !test.ccd.getEncountersSection().isSetNullFlavor() ){ if( test.ccd.getEncountersSection().getProcedures() != null && !test.ccd.getEncountersSection().getProcedures().isEmpty() ){ System.out.println("**** ENCOUNTERS -> PROCEDURES *****"); for( org.openhealthtools.mdht.uml.cda.Procedure cdaProcedure : test.ccd.getEncountersSection().getProcedures() ){ // traversing procedures System.out.println( "Procedure["+ encounterProceduresCount++ +"]" ); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Procedure fhirProcedure = rt.Procedure2Procedure(cdaProcedure); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( fhirProcedure ); System.out.println("End of print."); System.out.print("\n***\n"); // to visualize } } } if( test.ccd.getAllSections() != null && !test.ccd.getAllSections().isEmpty() ){ System.out.println( "*** SECTIONS ****" ); int sectionCount = 0; for( org.openhealthtools.mdht.uml.cda.Section section : test.ccd.getAllSections() ){ if( section.getProcedures() != null && !section.getProcedures().isEmpty() ){ int procedureCount2 = 0; for( org.openhealthtools.mdht.uml.cda.Procedure cdaProcedure: section.getProcedures() ){ // traversing procedures System.out.println("Section["+sectionCount+"]"+" -> Procedure["+ procedureCount2++ +"]"); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Procedure fhirProcedure = rt.Procedure2Procedure(cdaProcedure); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( fhirProcedure ); System.out.println("End of print."); System.out.println("\n***\n"); // to visualize } } sectionCount++; } } } @Ignore public void testPerformer22Performer(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int procedureCount = 0; if( test.ccd.getProceduresSection() != null && !test.ccd.getProceduresSection().isSetNullFlavor() ){ if( test.ccd.getProceduresSection().getProcedures() != null && !test.ccd.getProceduresSection().getProcedures().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Procedure procedure : test.ccd.getProceduresSection().getProcedures() ){ // traversing procedures int performerCount = 0; if( procedure.getPerformers() != null && !procedure.getPerformers().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Performer2 cdaPerformer : procedure.getPerformers() ){ if( cdaPerformer != null && !cdaPerformer.isSetNullFlavor() ){ // traversing performers System.out.println("Procedure["+ procedureCount++ +"]-> Performer["+ performerCount++ +"]" ); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Procedure.Performer fhirPerformer = rt.Performer22Performer(cdaPerformer); System.out.println("End of transformation. Printing the resource as JSON object.."); // Since we cannot print fhirPerformer directly, we add it to a fhirProcedure resource, then we print it ca.uhn.fhir.model.dstu2.resource.Procedure fhirProcedure = new ca.uhn.fhir.model.dstu2.resource.Procedure(); fhirProcedure.addPerformer( fhirPerformer ); printJSON( fhirProcedure ); System.out.println("\nEnd of print."); System.out.print("\n***\n"); // to visualize } } } } } } } @Ignore public void testAssignedEntity2Practitioner(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int procedureCount = 0; if( test.ccd.getProceduresSection() != null && !test.ccd.getProceduresSection().isSetNullFlavor() ){ if( test.ccd.getProceduresSection().getProcedures() != null && !test.ccd.getProceduresSection().getProcedures().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Procedure procedure : test.ccd.getProceduresSection().getProcedures() ){ // traversing procedures System.out.print( "Procedure["+ procedureCount++ +"]" ); int performerCount = 0; if( procedure.getPerformers() != null && !procedure.getPerformers().isEmpty() ){ for( org.openhealthtools.mdht.uml.cda.Performer2 performer : procedure.getPerformers() ){ System.out.print( "-> Performer["+ performerCount++ +"]" ); if( performer.getAssignedEntity() != null && !performer.getAssignedEntity().isSetNullFlavor() ){ System.out.println("-> AssignedEntity"); System.out.println("Transformation starting.."); ca.uhn.fhir.model.dstu2.resource.Practitioner practitioner = rt.AssignedEntity2Practitioner(performer.getAssignedEntity() ); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( practitioner ); System.out.println("End of print."); } } } System.out.print("\n***\n"); // to visualize } } } } // Following method just prints the [FHIR]Organization in JSON form. // One example transformed to fhir form and there was no error. @Ignore public void testOrganization2Organization(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int patientCount = 0; for( org.openhealthtools.mdht.uml.cda.PatientRole patRole : test.ccd.getPatientRoles() ){ System.out.print("PatientRole["+patientCount++ +"]."); org.openhealthtools.mdht.uml.cda.Organization cdaOrg = patRole.getProviderOrganization(); System.out.println( "Transformation starting..." ); ca.uhn.fhir.model.dstu2.resource.Organization fhirOrg = rt.Organization2Organization(cdaOrg); System.out.println("End of transformation. Printing the resource as JSON object.."); printJSON( fhirOrg ); System.out.println("End of print."); } } // Following method just prints the [FHIR]Communication in JSON form. // One example transformed to fhir form and there was no error. @Ignore public void testLanguageCommunication2Communication(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); int patientCount = 0; for( org.openhealthtools.mdht.uml.cda.Patient patient : test.ccd.getPatients() ){ System.out.print("Patient["+patientCount++ +"]."); int lcCount = 0; for( org.openhealthtools.mdht.uml.cda.LanguageCommunication LC : patient.getLanguageCommunications() ){ System.out.print("LC["+ lcCount++ +"]\n"); System.out.println( "Transformating starting..." ); ca.uhn.fhir.model.dstu2.resource.Patient.Communication fhirCommunication = rt.LanguageCommunication2Communication(LC); System.out.println("End of transformation. Building a patient resource.."); ca.uhn.fhir.model.dstu2.resource.Patient fhirPatient = new ca.uhn.fhir.model.dstu2.resource.Patient(); fhirPatient.addCommunication(fhirCommunication); System.out.println("End of build. Printing the resource as JSON object.."); printJSON( fhirPatient ); System.out.println("End of print."); } } } @Ignore public void testPatientRole2Patient(){ ResourceTransformerTestNecip test = new ResourceTransformerTestNecip(); EList<PatientRole> patientRoles = test.ccd.getPatientRoles(); // We traverse each of the patientRoles included in the document // We apply the tests for each of them for( PatientRole pr : patientRoles ){ // here we do the transformation by calling the method rt.PatientRole2Patient Patient patient = rt.PatientRole2Patient(pr); // ta-ta-ta-taa! System.out.println("Printing the resource as JSON object.."); printJSON( patient ); System.out.println("End of print"); // patient.identifier int idCount = 0; for( II id : pr.getIds() ){ // To see the values, you can use the following print lines. // System.out.println( id.getRoot() ); // System.out.println( id.getExtension() ); // System.out.println( id.getAssigningAuthorityName() ); // cdoeSystem method is changed and tested // Assert.assertEquals("pr.id.root #"+ idCount +" was not transformed",id.getRoot(), patient.getIdentifier().get(idCount).getSystem() ); Assert.assertEquals("pr.id.assigningAuthorityName #"+ idCount +" was not transformed",id.getAssigningAuthorityName(), patient.getIdentifier().get(idCount).getAssigner().getReference().getValue() ); idCount++; } // patient.name // Notice that patient.name is fullfilled by the method EN2HumanName. int nameCount = 0; for( EN pn : pr.getPatient().getNames() ){ // patient.name.use if( pn.getUses() == null || pn.getUses().isEmpty() ){ Assert.assertNull( patient.getName().get(nameCount).getUse() ); } else{ Assert.assertEquals("pr.patient.name["+nameCount+"]"+".use was not transformed", vsti.EntityNameUse2NameUseEnum(pn.getUses().get(0)).toString().toLowerCase(), patient.getName().get(nameCount).getUse() ); } // patient.name.text Assert.assertEquals("pr.patient.name["+nameCount+"].text was not transformed", pn.getText(),patient.getName().get(nameCount).getText() ); // patient.name.family int familyCount = 0; for( ENXP family : pn.getFamilies() ){ if( family == null || family.isSetNullFlavor() ){ // It can return null or an empty list Assert.assertTrue( patient.getName().get(nameCount).getFamily() == null || patient.getName().get(nameCount).getFamily().size() == 0 ); } else{ Assert.assertEquals("pr.patient.name["+nameCount+"].family was not transformed", family.getText(),patient.getName().get(nameCount).getFamily().get(familyCount).getValue()); } familyCount++; } // patient.name.given int givenCount = 0; for( ENXP given : pn.getGivens() ){ if( given == null || given.isSetNullFlavor() ){ // It can return null or an empty list Assert.assertTrue( patient.getName().get(nameCount).getGiven() == null || patient.getName().get(nameCount).getGiven().size() == 0 ); } else{ Assert.assertEquals("pr.patient.name["+nameCount+"].given was not transformed", given.getText(),patient.getName().get(nameCount).getGiven().get(givenCount).getValue()); } givenCount++; } // patient.name.prefix int prefixCount = 0; for( ENXP prefix : pn.getPrefixes() ){ if( prefix == null || prefix.isSetNullFlavor() ){ // It can return null or an empty list Assert.assertTrue( patient.getName().get(nameCount).getPrefix() == null || patient.getName().get(nameCount).getPrefix().size() == 0 ); } else{ Assert.assertEquals("pr.patient.name["+nameCount+"].prefix was not transformed", prefix.getText(),patient.getName().get(nameCount).getPrefix().get(prefixCount).getValue()); } prefixCount++; } // patient.name.suffix int suffixCount = 0; for( ENXP suffix : pn.getPrefixes() ){ if( suffix == null || suffix.isSetNullFlavor() ){ // It can return null or an empty list Assert.assertTrue( patient.getName().get(nameCount).getSuffix() == null || patient.getName().get(nameCount).getSuffix().size() == 0 ); } else{ Assert.assertEquals("pr.patient.name["+nameCount+"].suffix was not transformed", suffix.getText(),patient.getName().get(nameCount).getSuffix().get(suffixCount).getValue()); } suffixCount++; } // patient.name.period if( pn.getValidTime() == null || pn.getValidTime().isSetNullFlavor() ){ // It can return null or an empty list Assert.assertTrue( patient.getName().get(nameCount).getPeriod() == null || patient.getName().get(nameCount).getPeriod().isEmpty() ); } else{ // start of non-null period test if( pn.getValidTime().getLow() == null || pn.getValidTime().getLow().isSetNullFlavor() ){ Assert.assertTrue( patient.getName().get(nameCount).getPeriod().getStart() == null ); } else{ System.out.println("Following lines should contain identical non-null dates:"); System.out.println("[FHIR] " + patient.getName().get(nameCount).getPeriod().getStart()); System.out.println("[CDA] "+ pn.getValidTime().getLow()); } if( pn.getValidTime().getHigh() == null || pn.getValidTime().getHigh().isSetNullFlavor() ){ Assert.assertTrue( patient.getName().get(nameCount).getPeriod().getEnd() == null ); } else{ System.out.println("Following lines should contain identical non-null dates:"); System.out.println("[FHIR] " + patient.getName().get(nameCount).getPeriod().getEnd()); System.out.println("[CDA] "+ pn.getValidTime().getHigh()); } } // end of non-null period test nameCount++; } // end of patient.name tests // patient.telecom // Notice that patient.telecom is fullfilled by the method dtt.TEL2ContactPoint if( pr.getTelecoms() == null || pr.getTelecoms().isEmpty() ){ Assert.assertTrue( patient.getTelecom() == null || patient.getTelecom().isEmpty() ); } else{ // size check Assert.assertTrue( pr.getTelecoms().size() == patient.getTelecom().size() ); // We have already tested the method TEL2ContactPoint. Therefore, null-check and size-check is enough for now. } // patient.gender // vst.AdministrativeGenderCode2AdministrativeGenderEnum is used in this transformation. // Following test aims to test that ValueSetTransformer method. if( pr.getPatient().getAdministrativeGenderCode() == null || pr.getPatient().getAdministrativeGenderCode().isSetNullFlavor() ){ Assert.assertTrue( patient.getGender() == null || patient.getGender().isEmpty() ); } else{ System.out.println( "Following lines should contain two lines of non-null gender information which are relevant(male,female,unknown):" ); System.out.println(" [FHIR]: " + patient.getGender() ); System.out.println( " [CDA]: " + pr.getPatient().getAdministrativeGenderCode().getCode() ); } // patient.birthDate // Notice that patient.birthDate is fullfilled by the method dtt.TS2Date if( pr.getPatient().getBirthTime() == null || pr.getPatient().getBirthTime().isSetNullFlavor() ){ Assert.assertTrue( patient.getBirthDate() == null ); } else{ System.out.println( "Following lines should contain two lines of non-null, equivalent birthdate information:" ); System.out.println(" [FHIR]: " + patient.getBirthDate() ); System.out.println(" [CDA]: "+ pr.getPatient().getBirthTime().getValue()); } // patient.address // Notice that patient.address is fullfilled by the method dtt.AD2Address if( pr.getAddrs() == null || pr.getAddrs().isEmpty() ){ Assert.assertTrue( patient.getAddress() == null || patient.getAddress().isEmpty() ); } else{ // We have already tested the method AD2Address. Therefore, null-check and size-check is enough for now. Assert.assertTrue( pr.getAddrs().size() == patient.getAddress().size() ); } // patient.maritalStatus // vst.MaritalStatusCode2MaritalStatusCodesEnum is used in this transformation. // Following test aims to test that ValueSetTransformer method. if( pr.getPatient().getMaritalStatusCode() == null || pr.getPatient().getMaritalStatusCode().isSetNullFlavor() ){ Assert.assertTrue( patient.getMaritalStatus() == null || patient.getMaritalStatus().isEmpty() ); } else{ System.out.println( "Following lines should contain two lines of non-null, equivalent marital status information:" ); System.out.println(" [FHIR]: " + patient.getMaritalStatus().getCoding().get(0).getCode() ); System.out.println(" [CDA]: "+ pr.getPatient().getMaritalStatusCode().getCode() ); } // patient.languageCommunication if( pr.getPatient().getLanguageCommunications() == null || pr.getPatient().getLanguageCommunications().isEmpty() ){ Assert.assertTrue( patient.getCommunication() == null || patient.getCommunication().isEmpty() ); } else{ Assert.assertTrue( pr.getPatient().getLanguageCommunications().size() == patient.getCommunication().size() ); int sizeCommunication = pr.getPatient().getLanguageCommunications().size() ; while( sizeCommunication != 0){ //language if( pr.getPatient().getLanguageCommunications().get(sizeCommunication - 1).getLanguageCode() == null || pr.getPatient().getLanguageCommunications().get(0).getLanguageCode().isSetNullFlavor() ){ Assert.assertTrue( patient.getCommunication().get(sizeCommunication - 1).getLanguage() == null || patient.getCommunication().get(sizeCommunication -1 ).getLanguage().isEmpty() ); } else{ // We have already tested the method CD2CodeableConcept. Therefore, null-check is enough for now. } // preference if( pr.getPatient().getLanguageCommunications().get(sizeCommunication - 1).getPreferenceInd() == null || pr.getPatient().getLanguageCommunications().get(sizeCommunication - 1).getPreferenceInd().isSetNullFlavor() ){ Assert.assertTrue( patient.getCommunication().get(sizeCommunication - 1).getPreferred() == null ); } else{ Assert.assertEquals(pr.getPatient().getLanguageCommunications().get(sizeCommunication - 1).getPreferenceInd().getValue(), patient.getCommunication().get(sizeCommunication - 1).getPreferred()); } sizeCommunication } } // providerOrganization if( pr.getProviderOrganization() == null || pr.getProviderOrganization().isSetNullFlavor() ){ Assert.assertTrue( patient.getManagingOrganization() == null || patient.getManagingOrganization().isEmpty() ); } else{ if( pr.getProviderOrganization().getNames() == null ){ Assert.assertTrue( patient.getManagingOrganization().getDisplay() == null ); } System.out.println("[FHIR] Reference for managing organization: "+ patient.getManagingOrganization().getReference() ); } // guardian if( pr.getPatient().getGuardians() == null || pr.getPatient().getGuardians().isEmpty() ){ Assert.assertTrue( patient.getContact() == null || patient.getContact().isEmpty() ); } else{ // Notice that, inside this mapping, the methods dtt.TEL2ContactPoint and dtt.AD2Address are used. // Therefore, null-check and size-check are enough Assert.assertTrue( pr.getPatient().getGuardians().size() == patient.getContact().size() ); } // extensions int extCount = 0; for( ExtensionDt extension : patient.getUndeclaredExtensions() ){ Assert.assertTrue( extension.getUrl() != null ); Assert.assertTrue( extension.getValue() != null ); System.out.println("[FHIR] Extension["+extCount+"] url: "+extension.getUrl()); System.out.println("[FHIR] Extension["+ extCount++ +"] value: "+extension.getValue()); } } } }
package ubic.basecode.dataStructure.matrix; import java.io.File; import java.io.FileWriter; import java.io.IOException; import no.uib.cipr.matrix.sparse.FlexCompRowMatrix; import no.uib.cipr.matrix.sparse.SparseVector; /** * Named compressed sparse bit matrix. Elements of the matrix are stored in the <code>long</code> data type. * * @author xwan */ public class CompressedNamedBitMatrix extends AbstractNamedMatrix { private static final long serialVersionUID = 1775002416710933373L; private FlexCompRowMatrix[] matrix; public static int DOUBLE_LENGTH = 63; // java doesn't support unsigned long. private int totalBitsPerItem; private int rows = 0, cols = 0; public static long BIT1 = 0x0000000000000001L; /** * Constructs a matrix with specified rows, columns, and total bits per element * * @param rows - number of rows in the matrix * @param cols - number of columns in the matrix * @param totalBitsPerItem - the number of bits for each element */ public CompressedNamedBitMatrix( int rows, int cols, int totalBitsPerItem ) { super(); // calculate number of matrices required int num = ( int ) ( totalBitsPerItem / CompressedNamedBitMatrix.DOUBLE_LENGTH ) + 1; matrix = new FlexCompRowMatrix[num]; for ( int i = 0; i < num; i++ ) matrix[i] = new FlexCompRowMatrix( rows, cols ); this.totalBitsPerItem = totalBitsPerItem; this.rows = rows; this.cols = cols; } /** * Returns the total number of bits in a matrix element * * @return the number of bits per element */ public int getBitNum() { return this.totalBitsPerItem; } /** * Returns all of the bits for an element * * @param row - the element row * @param col - the element column * @return all the bits encoded as an array of <code>longs</code> */ public long[] getAllBits( int row, int col ) { long[] allBits = new long[this.matrix.length]; for ( int i = 0; i < this.matrix.length; i++ ) allBits[i] = Double.doubleToRawLongBits( this.matrix[i].get( row, col ) ); return allBits; } /** * Sets the bit of the specified element at the specified index to 1. * * @param row - matrix row * @param col - matrix column * @param index - bit vector index */ public void set( int row, int col, int index ) { if ( index >= this.totalBitsPerItem || row > this.rows || col > this.cols ) throw new ArrayIndexOutOfBoundsException( "Attempt to access row=" + row + " col=" + col + " index=" + index ); int num = ( int ) ( index / CompressedNamedBitMatrix.DOUBLE_LENGTH ); int bit_index = index % CompressedNamedBitMatrix.DOUBLE_LENGTH; long binVal = Double.doubleToRawLongBits( matrix[num].get( row, col ) ); double res = Double.longBitsToDouble( binVal | CompressedNamedBitMatrix.BIT1 << bit_index ); matrix[num].set( row, col, res ); } public void reset( int rows, int cols ) { for ( int i = 0; i < this.matrix.length; i++ ) this.matrix[i].set( rows, cols, 0 ); } /** * Checks the bit of the specified element at the specified index. * * @param row - matrix row * @param col - matrix column * @param index - bit vector index * @return true if bit is 1, false if 0. */ public boolean check( int row, int col, int index ) { if ( index >= this.totalBitsPerItem || row > this.rows || col > this.cols ) throw new ArrayIndexOutOfBoundsException( "Attempt to access row=" + row + " col=" + col + " index=" + index ); int num = ( int ) ( index / CompressedNamedBitMatrix.DOUBLE_LENGTH ); int bit_index = index % CompressedNamedBitMatrix.DOUBLE_LENGTH; long binVal = Double.doubleToRawLongBits( matrix[num].get( row, col ) ); long res = binVal & CompressedNamedBitMatrix.BIT1 << bit_index; if ( res == 0 ) return false; return true; } /** * Count the number of one-bits of the passed-in <code>double</code>. * * @param val * @return number of bits in val */ static public int countBits( double val ) { if ( val == 0.0 ) return 0; long binVal = Double.doubleToRawLongBits( val ); return Long.bitCount( binVal ); } /** * @param row * @return - array of counts of one-bits for each element in the row. */ public int[] getRowBitCount( int row ) { int[] bits = new int[columns()]; for ( int i = 0, k = this.matrix.length; i < k; i++ ) { SparseVector vector = this.matrix[i].getRow( row ); double[] data = vector.getData(); int[] indices = vector.getIndex(); for ( int j = 0; j < data.length; j++ ) { if ( indices[j] == 0 && j > 0 ) break; if ( data[j] != 0.0 ) bits[indices[j]] += countBits( data[j] ); } } return bits; } /** * Count the number of one-bits at the specified element position * * @param rows * @param cols * @return */ public int bitCount( int rows, int cols ) { int bits = 0; if ( rows > this.rows || cols > this.cols ) return bits; for ( int i = 0; i < this.matrix.length; i++ ) { double val = this.matrix[i].get( rows, cols ); if ( val != 0 ) bits = bits + countBits( val ); } return bits; } /** * Counts the number of one-bits that are in common between the two specified elements; i.e. performs an AND operation * on the two bit vectors and counts the remaining 1 bits. * * @param row1 - element 1 row * @param col1 - element 1 column * @param row2 - element 2 row * @param col2 - element 2 column * @return number of bits in common */ public int overlap( int row1, int col1, int row2, int col2 ) { int bits = 0; for ( int i = 0; i < this.matrix.length; i++ ) { double val1 = this.matrix[i].get( row1, col1 ); double val2 = this.matrix[i].get( row2, col2 ); if ( val1 == 0 || val2 == 0 ) continue; long binVal1 = Double.doubleToRawLongBits( val1 ); long binVal2 = Double.doubleToRawLongBits( val2 ); bits = bits + countBits( binVal1 & binVal2 ); } return bits; } /** * Return the number of columns in the matrix * * @return number of columns */ public int columns() { return this.cols; } /* * (non-Javadoc) * * @see ubic.basecode.dataStructure.matrix.AbstractNamedMatrix#getColObj(int) */ public Object[] getColObj( int i ) { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see ubic.basecode.dataStructure.matrix.AbstractNamedMatrix#getRowObj(int) */ public Object[] getRowObj( int i ) { throw new UnsupportedOperationException(); } public Object getObj( int row, int col ) { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see ubic.basecode.dataStructure.matrix.AbstractNamedMatrix#isMissing(int, int) */ public boolean isMissing( int i, int j ) { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see ubic.basecode.dataStructure.matrix.AbstractNamedMatrix#rows() */ public int rows() { return this.rows; } /* * (non-Javadoc) * * @see ubic.basecode.dataStructure.matrix.AbstractNamedMatrix#set(int, int, java.lang.Object) */ public void set( int i, int j, Object val ) { throw new UnsupportedOperationException(); } /** * Set the matrix element to the specified bit vector * * @param row * @param col * @param val * @return true if set successfully */ public boolean set( int row, int col, double[] val ) { if ( val.length != this.matrix.length || row >= this.rows || col >= this.cols ) return false; for ( int mi = 0; mi < val.length; mi++ ) this.matrix[mi].set( row, col, val[mi] ); return true; } /** * Save the matrix to the specified file * * @param fileName - save file */ public void toFile( String fileName ) throws IOException { FileWriter out = new FileWriter( new File( fileName ) ); out.write( this.rows + "\t" + this.cols + "\t" + this.totalBitsPerItem + "\n" ); Object[] rowNames = this.getRowNames().toArray(); for ( int i = 0; i < rowNames.length; i++ ) { out.write( rowNames[i].toString() ); if ( i != rowNames.length - 1 ) out.write( "\t" ); } out.write( "\n" ); Object[] colNames = this.getColNames().toArray(); for ( int i = 0; i < colNames.length; i++ ) { out.write( colNames[i].toString() ); if ( i != colNames.length - 1 ) out.write( "\t" ); } out.write( "\n" ); for ( int i = 0; i < this.rows; i++ ) for ( int j = 0; j < this.cols; j++ ) { if ( this.bitCount( i, j ) != 0 ) { out.write( i + "\t" + j ); for ( int k = 0; k < this.matrix.length; k++ ) { long binVal = Double.doubleToRawLongBits( this.matrix[k].get( i, j ) ); /* Long.parseLong( hexString, 16) to get it back; */ String hexString = Long.toHexString( binVal ); out.write( "\t" + hexString ); } out.write( "\n" ); } } out.close(); } }
package org.kobjects.nativehtml.swing; import org.kobjects.nativehtml.dom.Platform; import org.kobjects.nativehtml.util.ElementImpl; import java.awt.Desktop; import java.awt.Image; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.Base64; import java.util.Dictionary; import java.util.Hashtable; import javax.imageio.ImageIO; import org.kobjects.nativehtml.dom.Document; import org.kobjects.nativehtml.dom.Element; import org.kobjects.nativehtml.dom.ElementType; public class SwingPlatform implements Platform { static String fakeDataUrl(String url) { if (url.startsWith("data:")) { int cut = url.indexOf(',') + 1; return "http://240.0.0.0/base64hash" + url.substring(cut).hashCode(); } return url; } Dictionary<URL, Image> imageCache = new Hashtable<URL, Image>(); @Override public Element createElement(Document document, ElementType elementType, String elementName) { switch (elementType) { case COMPONENT: if (elementName.equals("select")) { return new SwingHtmlSelectElement(document, elementName); } if (elementName.equals("input")) { return new SwingHtmlInputElement(document, elementName); } if (elementName.equals("text-component")) { return new SwingTextComponent(document); } return new SwingComponentContainerElement(document, elementName); default: return null; } } public Image getImage(final Element element, final URI uri) { try { String s = uri.toString(); boolean isDataUrl = s.startsWith("data:"); final URL url = new URL(fakeDataUrl(s)); Image cached = imageCache.get(url); if (cached != null) { return cached; } if (isDataUrl) { String base64 = s.substring(s.indexOf(',') + 1); byte[] data = Base64.getDecoder().decode(base64); Image image = ImageIO.read(new ByteArrayInputStream(data)); imageCache.put(url, image); return image; } else { new Thread(new Runnable() { @Override public void run() { try { Image image = ImageIO.read(uri.toURL().openStream()); imageCache.put(url, image); setImage(element, url, image); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); } } catch (Exception e) { e.printStackTrace(); } return null; } void setImage(Element element, URL url, Image image) { while (element instanceof ElementImpl) { element = element.getParentElement(); } if (element instanceof SwingTextComponent) { ((SwingTextComponent) element).notifyContentChanged(); } } @Override public void openInBrowser(URI uri) { Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); } catch (IOException e) { } } } @Override public float getPixelPerDp() { return 1; } }
package io.enmasse.systemtest.plans; import io.enmasse.systemtest.*; import io.enmasse.systemtest.amqp.AmqpClient; import io.enmasse.systemtest.bases.TestBase; import io.enmasse.systemtest.resources.AddressPlan; import io.enmasse.systemtest.resources.AddressResource; import io.enmasse.systemtest.resources.AddressSpacePlan; import io.enmasse.systemtest.resources.AddressSpaceResource; import io.enmasse.systemtest.standard.QueueTest; import io.enmasse.systemtest.standard.TopicTest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; @Category(IsolatedAddressSpace.class) public class PlansTest extends TestBase { private static Logger log = CustomLogger.getLogger(); @Before public void setUp() { plansProvider.setUp(); } @After public void tearDown() { plansProvider.tearDown(); } @Override protected String getDefaultPlan(AddressType addressType) { return null; } @Test public void testCreateAddressSpacePlan() throws Exception { //define and create address plans List<AddressResource> addressResourcesQueue = Arrays.asList(new AddressResource("broker", 1.0)); List<AddressResource> addressResourcesTopic = Arrays.asList( new AddressResource("broker", 1.0), new AddressResource("router", 1.0)); AddressPlan weakQueuePlan = new AddressPlan("standard-queue-weak", AddressType.QUEUE, addressResourcesQueue); AddressPlan weakTopicPlan = new AddressPlan("standard-topic-weak", AddressType.TOPIC, addressResourcesTopic); plansProvider.createAddressPlanConfig(weakQueuePlan); plansProvider.createAddressPlanConfig(weakTopicPlan); //define and create address space plan List<AddressSpaceResource> resources = Arrays.asList( new AddressSpaceResource("broker", 0.0, 9.0), new AddressSpaceResource("router", 1.0, 5.0), new AddressSpaceResource("aggregate", 0.0, 10.0)); List<AddressPlan> addressPlans = Arrays.asList(weakQueuePlan, weakTopicPlan); AddressSpacePlan weakSpacePlan = new AddressSpacePlan("weak-plan", "weak", "standard-space", AddressSpaceType.STANDARD, resources, addressPlans); plansProvider.createAddressSpacePlanConfig(weakSpacePlan); //create address space plan with new plan AddressSpace weakAddressSpace = new AddressSpace("weak-address-space", AddressSpaceType.STANDARD, weakSpacePlan.getName()); createAddressSpace(weakAddressSpace, AuthService.STANDARD.toString()); //deploy destinations Destination weakQueueDest = Destination.queue("weak-queue", weakQueuePlan.getName()); Destination weakTopicDest = Destination.topic("weak-topic", weakTopicPlan.getName()); setAddresses(weakAddressSpace, weakQueueDest, weakTopicDest); //get destinations Future<List<Address>> getWeakQueue = getAddressesObjects(weakAddressSpace, Optional.of(weakQueueDest.getAddress())); Future<List<Address>> getWeakTopic = getAddressesObjects(weakAddressSpace, Optional.of(weakTopicDest.getAddress())); String assertMessage = "Queue plan wasn't set properly"; assertEquals(assertMessage, getWeakQueue.get(20, TimeUnit.SECONDS).get(0).getPlan(), weakQueuePlan.getName()); assertEquals(assertMessage, getWeakTopic.get(20, TimeUnit.SECONDS).get(0).getPlan(), weakTopicPlan.getName()); //simple send/receive String username = "test_newplan_name"; String password = "test_newplan_password"; getKeycloakClient().createUser(weakAddressSpace.getName(), username, password, 20, TimeUnit.SECONDS); AmqpClient queueClient = amqpClientFactory.createQueueClient(weakAddressSpace); queueClient.getConnectOptions().setUsername(username); queueClient.getConnectOptions().setPassword(password); QueueTest.runQueueTest(queueClient, weakQueueDest, 42); AmqpClient topicClient = amqpClientFactory.createTopicClient(weakAddressSpace); topicClient.getConnectOptions().setUsername(username); topicClient.getConnectOptions().setPassword(password); TopicTest.runTopicTest(topicClient, weakQueueDest, 42); } @Test public void testQuotaLimits() throws Exception { //define and create address plans AddressPlan queuePlan = new AddressPlan("queue-test1", AddressType.QUEUE, Collections.singletonList(new AddressResource("broker", 0.6))); AddressPlan topicPlan = new AddressPlan("queue-test2", AddressType.TOPIC, Arrays.asList( new AddressResource("broker", 0.4), new AddressResource("router", 0.2))); AddressPlan anycastPlan = new AddressPlan("anycast-test1", AddressType.ANYCAST, Collections.singletonList(new AddressResource("router", 0.3))); plansProvider.createAddressPlanConfig(queuePlan); plansProvider.createAddressPlanConfig(topicPlan); plansProvider.createAddressPlanConfig(anycastPlan); //define and create address space plan List<AddressSpaceResource> resources = Arrays.asList( new AddressSpaceResource("broker", 0.0, 2.0), new AddressSpaceResource("router", 1.0, 1.0), new AddressSpaceResource("aggregate", 0.0, 2.0)); List<AddressPlan> addressPlans = Arrays.asList(queuePlan, topicPlan, anycastPlan); AddressSpacePlan addressSpacePlan = new AddressSpacePlan("test1", "test", "standard-space", AddressSpaceType.STANDARD, resources, addressPlans); plansProvider.createAddressSpacePlanConfig(addressSpacePlan); //create address space with new plan AddressSpace addressSpace = new AddressSpace("test1", AddressSpaceType.STANDARD, addressSpacePlan.getName()); createAddressSpace(addressSpace, AuthService.STANDARD.toString()); //check router limits checkLimits(addressSpace, Arrays.asList( Destination.anycast("a1", anycastPlan.getName()), Destination.anycast("a2", anycastPlan.getName()), Destination.anycast("a3", anycastPlan.getName()) ), Collections.singletonList( Destination.anycast("a4", anycastPlan.getName()) )); //check broker limits checkLimits(addressSpace, Arrays.asList( Destination.queue("q1", queuePlan.getName()), Destination.queue("q2", queuePlan.getName()) ), Collections.singletonList( Destination.queue("q3", queuePlan.getName()) )); //check aggregate limits checkLimits(addressSpace, Arrays.asList( Destination.topic("t1", topicPlan.getName()), Destination.topic("t2", topicPlan.getName()) ), Collections.singletonList( Destination.topic("t3", topicPlan.getName()) )); } private void checkLimits(AddressSpace addressSpace, List<Destination> allowedDest, List<Destination> notAllowedDest) throws Exception { setAddresses(addressSpace, allowedDest.toArray(new Destination[0])); List<Future<List<Address>>> getAddresses = new ArrayList<>(); for (Destination dest : allowedDest) { getAddresses.add(getAddressesObjects(addressSpace, Optional.of(dest.getAddress()))); } for (Future<List<Address>> getAddress : getAddresses) { List<Address> address = getAddress.get(20, TimeUnit.SECONDS); String assertMessage = String.format("Address from notAllowed %s is not ready", address.get(0).getName()); assertEquals(assertMessage, "Active", address.get(0).getPhase()); } getAddresses.clear(); try { appendAddresses(addressSpace, notAllowedDest.toArray(new Destination[0])); } catch (IllegalStateException ex) { if (!ex.getMessage().contains("addresses are not ready") && !ex.getMessage().contains("Unable to find")) { throw ex; } } for (Destination dest : notAllowedDest) { getAddresses.add(getAddressesObjects(addressSpace, Optional.of(dest.getAddress()))); } for (Future<List<Address>> getAddress : getAddresses) { List<Address> address = getAddress.get(20, TimeUnit.SECONDS); String assertMessage = String.format("Address from notAllowed %s is ready", address.get(0).getName()); assertEquals(assertMessage, "Pending", address.get(0).getPhase()); } setAddresses(addressSpace); } }
package clarifai2.integration_tests; import clarifai2.api.ClarifaiBuilder; import clarifai2.api.ClarifaiClient; import clarifai2.api.ClarifaiResponse; import clarifai2.api.request.input.SearchClause; import clarifai2.api.request.model.Action; import clarifai2.api.request.model.PredictRequest; import clarifai2.dto.ClarifaiStatus; import clarifai2.dto.PointF; import clarifai2.dto.Radius; import clarifai2.dto.input.ClarifaiImage; import clarifai2.dto.input.ClarifaiInput; import clarifai2.dto.input.Crop; import clarifai2.dto.input.SearchHit; import clarifai2.dto.model.ConceptModel; import clarifai2.dto.model.Model; import clarifai2.dto.model.ModelTrainingStatus; import clarifai2.dto.model.ModelVersion; import clarifai2.dto.model.output.ClarifaiOutput; import clarifai2.dto.model.output_info.ConceptOutputInfo; import clarifai2.dto.prediction.Color; import clarifai2.dto.prediction.Concept; import clarifai2.dto.prediction.Embedding; import clarifai2.dto.prediction.Focus; import clarifai2.dto.prediction.Frame; import clarifai2.dto.prediction.Logo; import clarifai2.dto.prediction.Region; import clarifai2.exception.ClarifaiClientClosedException; import clarifai2.internal.JSONObjectBuilder; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.kevinmost.junit_retry_rule.Retry; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static clarifai2.api.request.input.SearchClause.matchConcept; import static clarifai2.internal.InternalUtil.assertNotNull; import static clarifai2.internal.InternalUtil.sleep; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; // TODO(Rok) MEDIUM: Inspect what tests here are present elsewhere and remove them. @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VariousIntTests extends BaseIntTest { private static long startTime; @BeforeClass public static void recordTime() { startTime = System.nanoTime(); } // Workaround since we can't delete models right now, so we'll make a new model every time that is different every // time we run the app @NotNull private static String getModelID() { return "mod1ID" + startTime; } @Retry @Test public void t00_deleteAllInputs() { sleep(5000); assertSuccess(client.deleteAllInputs()); retryAndTimeout(1, TimeUnit.MINUTES, () -> client.getInputs().build().getPage(1).executeSync().get().isEmpty() ); } @Retry @Test public void t01a_addInputs() throws Exception { final String inputID = assertSuccess(client.addInputs() .plus(ClarifaiInput.forInputValue(ClarifaiImage.of(KOTLIN_LOGO_IMAGE_FILE)) .withID("foo1") .withConcepts(Concept.forID("concept1").withValue(false)) )).get(0).id(); // We wait here so the next tests using this input pass properly. waitForInputToDownload(client, inputID); } @Retry @Test public void t01b_addInputs_bulk() throws Exception { final Concept ferrari23 = Concept.forID("ferrari23"); final Concept outdoors23 = Concept.forID("outdoors23"); final List<ClarifaiInput> inputs = assertSuccess(client.addInputs() .allowDuplicateURLs(true) .plus( ClarifaiInput.forImage(FERRARI_IMAGE_URL) .withConcepts( ferrari23.withValue(true) ), ClarifaiInput.forImage(FERRARI_IMAGE_URL2) .withConcepts( ferrari23.withValue(true), outdoors23.withValue(false) ), ClarifaiInput.forImage(HONDA_IMAGE_URL) .withConcepts( ferrari23.withValue(true), outdoors23 ).withGeo(PointF.at(30, -24)), ClarifaiInput.forImage(HONDA_IMAGE_URL2) .withConcepts( ferrari23.withValue(false), outdoors23 ), ClarifaiInput.forImage(FERRARI_IMAGE_URL3) .withConcepts( ferrari23.withValue(false), outdoors23 ), ClarifaiInput.forImage(TOYOTA_IMAGE_URL) .withConcepts( ferrari23.withValue(false), outdoors23 ), ClarifaiInput.forImage(HONDA_IMAGE_URL) .withConcepts( ferrari23.withValue(false), outdoors23 ) ) ); inputs.forEach(input -> waitForInputToDownload(client, input.id())); } @Retry @Test public void t01c_addInputWithMetadata() { final String inputID = assertSuccess(client.addInputs() .plus(ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE) .withID("inputWithMetadata") .withMetadata(new JSONObjectBuilder() .add("foo", "bar") .build()))).get(0).id(); // We wait here so the next tests using this input pass properly. waitForInputToDownload(client, inputID); } @Retry @Test public void t02_addConceptsToInput() { assertSuccess(client.mergeConceptsForInput("foo1") .plus( Concept.forID("concept2"), Concept.forID("concept3") ) ); } @Retry @Test public void t03_getAllInputs() { assertSuccess(client.getInputs()); } @Retry @Test public void t04_getInputByID() { assertSuccess(client.getInputByID("foo1")); } @Retry @Test public void t05_deleteInput() { assertSuccess(client.deleteInput("foo1")); } @Retry @Test public void t06_getInputsStatus() { assertSuccess(client.getInputsStatus()); } @Retry @Test public void t07_getConcepts() { assertSuccess(client.getConcepts()); } @Retry @Test public void t08_getConceptByID() { assertSuccess(client.getConceptByID("concept2")); } @Retry @Test public void t09_searchConcepts() { assertSuccess(client.searchConcepts("conc*")); } @Retry @Test public void t09b_searchConcepts_multi_language() { assertSuccess(client.searchConcepts("*").withLanguage("zh")); // "zh" = Chinese } @Retry @Test public void t10_getAllModels() { assertSuccess(client.getModels()); } @Retry @Test public void t11_deleteAllModels() { assertSuccess(client.deleteAllModels()); } @Retry @Test public void t12a_createModel() { assertSuccess(client.createModel(getModelID()) .withOutputInfo(ConceptOutputInfo.forConcepts( Concept.forID("ferrari23") )) ); } @Retry @Test public void t13_getModelByID() { assertSuccess(client.getModelByID(getModelID())); } @Retry @Test public void t14a_addConceptsToModel() { assertSuccess(client.modifyModel(getModelID()) .withConcepts(Action.MERGE, Concept.forID("outdoors23")) ); } @Retry @Test public void t14b_addConceptsToModel() { assertSuccess(client.getModelByID(getModelID()).executeSync().get().asConceptModel() .modify().withConcepts(Action.MERGE, Concept.forID("outdoors23")) ); } @Retry @Test public void t14c_addConceptsToModel_multi_lang() { assertSuccess(client.getModelByID(getModelID()).executeSync().get().asConceptModel() .modify().withConcepts(Action.MERGE, Concept.forID("outdoors23")).withLanguage("zh")); } @Retry @Test public void t15_trainModel() { final String inputID = assertSuccess(client.addInputs() .plus(ClarifaiInput.forImage(PENGUIN_IMAGE_URL) .withConcepts(Concept.forID("outdoors23")) ) .allowDuplicateURLs(true) ).get(0).id(); waitForInputToDownload(client, inputID); assertSuccess(client.trainModel(getModelID())); retryAndTimeout(2, TimeUnit.MINUTES, () -> { final ModelVersion version = assertSuccess(client.getModelByID(getModelID())).modelVersion(); assertNotNull(version); final ModelTrainingStatus status = version.status(); if (!status.isTerminalEvent()) { return false; } if (status == ModelTrainingStatus.TRAINED) { return true; } fail("Version had error while training: " + version.status()); return false; }); } @Retry @Test public void t16a_predictWithModel() { assertSuccess(client.predict(client.getDefaultModels().generalModel().id()) .withInputs(ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE)) ); } @Retry @Test public void t16b_predictBatchWithModel() { List<ClarifaiInput> inputs = new ArrayList<>(); inputs.add(ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL).withID("myID1")); inputs.add(ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL).withID("myID2")); PredictRequest<Concept> request = client.getDefaultModels().generalModel().predict() .withInputs(inputs); assertSuccess(request); ClarifaiResponse<List<ClarifaiOutput<Concept>>> response = request.executeSync(); assertSuccess(response); } @Retry @Test public void t16c_predictBatchBase64WithModel() { List<ClarifaiInput> inputs = new ArrayList<>(); inputs.add(ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE).withID("myID1")); inputs.add(ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE).withID("myID2")); PredictRequest<Concept> request = client.getDefaultModels().generalModel().predict() .withInputs(inputs); assertSuccess(request); ClarifaiResponse<List<ClarifaiOutput<Concept>>> response = request.executeSync(); assertSuccess(response); } @Retry @Test public void t16d_predictWithModel_multi_lang() { assertSuccess(client.predict(client.getDefaultModels().generalModel().id()) .withInputs(ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE)) .withLanguage("zh") ); } @Retry @Test public void t17a_searchInputsWithModel() { assertSuccess(client.searchInputs( SearchClause.matchImageURL(ClarifaiImage.of(METRO_NORTH_IMAGE_URL)) )); } @Retry @Test public void t17b_searchInputsWithModel_complexSearch() { assertSuccess( client.searchInputs(matchConcept(Concept.forID("outdoors23").withValue(true))) .and(SearchClause.matchImageURL(ClarifaiImage.of(METRO_NORTH_IMAGE_URL))) .build() ); } @Retry @Test public void t17c_searchInputsWithModel_metadata() { final List<SearchHit> hits = assertSuccess( client.searchInputs(SearchClause.matchMetadata(new JSONObjectBuilder().add("foo", "bar").build())) ).searchHits(); final ClarifaiInput hit = hits.stream() .filter(someHit -> "inputWithMetadata".equals(someHit.input().id())) .findFirst() .orElseThrow(() -> new AssertionError("")) .input(); assertEquals("inputWithMetadata", hit.id()); assertEquals(new JSONObjectBuilder().add("foo", "bar").build(), hit.metadata()); } @Retry @Test public void t17d_searchInputsWithModel_multi_language() { assertSuccess(client.searchInputs( SearchClause.matchImageURL(ClarifaiImage.of(METRO_NORTH_IMAGE_URL))).withLanguage("zh")); } @Test public void t17e_searchInputsWithModel_geo() { final String inputID = assertSuccess(client.addInputs().plus( ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL) .withGeo(PointF.at(90F, 23F)))).get(0).id(); waitForInputToDownload(client, inputID); assertSuccess( client.searchInputs(matchConcept(Concept.forID("outdoors23").withValue(true))) .and(SearchClause.matchImageURL(ClarifaiImage.of(METRO_NORTH_IMAGE_URL))) .and(SearchClause.matchGeo(PointF.at(90F, 23F), Radius.of(5, Radius.Unit.MILE))) .build() ); } @Retry @Test public void t18_testGeo() { { final List<SearchHit> hitsBeforeAdding = assertSuccess( client.searchInputs(SearchClause.matchGeo(PointF.at(59F, 29.75F), Radius.of(500, Radius.Unit.MILE))) ).searchHits(); assertEquals(0, hitsBeforeAdding.size()); } final String inputID = assertSuccess(client.addInputs().plus( ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE) .withGeo(PointF.at(60F, 29.75F)) )).get(0).id(); waitForInputToDownload(client, inputID); { final List<SearchHit> hitsAfterAdding = assertSuccess( client.searchInputs(SearchClause.matchGeo(PointF.at(59F, 29.75F), Radius.of(500, Radius.Unit.MILE))) ).searchHits(); assertEquals(1, hitsAfterAdding.size()); } { final List<SearchHit> hits = assertSuccess( client.searchInputs(SearchClause.matchGeo(PointF.at(3F, 0F), PointF.at(70, 30F))) ).searchHits(); assertEquals(1, hits.size()); } } @Retry @Test public void t19_testBatch_partialFailure() { List<ClarifaiInput> batch = new ArrayList<>(); batch.add(ClarifaiInput.forImage( FERRARI_IMAGE_URL)); batch.add(ClarifaiInput.forImage( FERRARI_IMAGE_URL2)); batch.add(ClarifaiInput.forImage("https://this_should_fail.jpg")); ClarifaiResponse<List<ClarifaiOutput<Concept>>> response = client.getDefaultModels().generalModel().predict() .withInputs(batch).executeSync(); assertMixedSuccess(response); assertNotNull(response.get()); List<ClarifaiOutput<Concept>> concepts = response.get(); assertEquals(concepts.get(2).status().statusCode(), 30002); } @Retry @Test public void t20_testDemographicsModel() { ClarifaiResponse<List<ClarifaiOutput<Region>>> faceDetects = client.getDefaultModels().demographicsModel().predict() .withInputs(ClarifaiInput.forImage(STREETBAND_IMAGE_URL)) .executeSync(); Assert.assertNotNull(faceDetects.get().get(0).data().get(0).crop()); Assert.assertNotNull(faceDetects.get().get(0).data().get(0).ageAppearances()); Assert.assertNotNull(faceDetects.get().get(0).data().get(0).genderAppearances()); Assert.assertNotNull(faceDetects.get().get(0).data().get(0).multiculturalAppearances()); } @Retry @Test public void t21_testApparelModel() { assertSuccess(client.predict(client.getDefaultModels().apparelModel().id()) .withInputs(ClarifaiInput.forImage(FAMILY_IMAGE_URL)) ); } @Retry @Test public void t22_testFocusModel() { ClarifaiResponse<List<ClarifaiOutput<Focus>>> focii = client.getDefaultModels().focusModel().predict() .withInputs(ClarifaiInput.forImage(STREETBAND_IMAGE_URL)) .executeSync(); Assert.assertNotNull(focii.get()); Assert.assertNotNull(focii.get().get(0)); Assert.assertNotNull(focii.get().get(0).data()); Assert.assertNotNull(focii.get().get(0).data().get(0)); Assert.assertNotNull(focii.get().get(0).data().get(0).crop()); } @Retry @Test public void t23_testgeneralEmbedModel() { ClarifaiResponse<List<ClarifaiOutput<Embedding>>> embeddings = client.getDefaultModels().generalEmbeddingModel() .predict() .withInputs(ClarifaiInput.forImage(STREETBAND_IMAGE_URL)) .executeSync(); Assert.assertNotNull(embeddings.get()); Assert.assertNotNull(embeddings.get().get(0)); Assert.assertNotNull(embeddings.get().get(0).data()); Assert.assertNotNull(embeddings.get().get(0).data().get(0)); Assert.assertNotNull(embeddings.get().get(0).data().get(0).embedding()); } @Retry @Test public void t24_testLogoModel() { ClarifaiResponse<List<ClarifaiOutput<Logo>>> logos = client.getDefaultModels().logoModel().predict() .withInputs(ClarifaiInput.forImage(LOGO_IMAGE_URL)) .executeSync(); Assert.assertNotNull(logos.get()); Assert.assertNotNull(logos.get().get(0)); Assert.assertNotNull(logos.get().get(0).data()); } @Retry @Test public void t25_testColorModel() { ClarifaiResponse<List<ClarifaiOutput<Color>>> colors = client.getDefaultModels().colorModel().predict() .withInputs(ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL)) .executeSync(); Assert.assertNotNull(colors.get()); Assert.assertNotNull(colors.get().get(0)); Assert.assertNotNull(colors.get().get(0).data()); Assert.assertNotNull(colors.get().get(0).data().get(0)); Assert.assertNotNull(colors.get().get(0).data().get(0).hex()); Assert.assertNotNull(colors.get().get(0).data().get(0).webSafeHex()); Assert.assertNotNull(colors.get().get(0).data().get(0).webSafeColorName()); } @Retry @Test public void t26_testGeneralVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().generalVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Retry @Test public void t27_testFoodVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().foodVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Retry @Test public void t28_testTravelVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().travelVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Retry @Test public void t29_testNSFWVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().nsfwVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Retry @Test public void t30_testWeddingVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().weddingVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Retry @Test public void t31_testApparelVideoModel() { ClarifaiResponse<List<ClarifaiOutput<Frame>>> frames = client.getDefaultModels().apparelVideoModel().predict() .withInputs(ClarifaiInput.forVideo(CONAN_GIF_URL)) .executeSync(); Assert.assertNotNull(frames.get()); Assert.assertNotNull(frames.get().get(0)); Assert.assertNotNull(frames.get().get(0).data()); Assert.assertNotNull(frames.get().get(0).data().get(0)); Assert.assertNotNull(frames.get().get(0).data().get(0).index()); Assert.assertNotNull(frames.get().get(0).data().get(0).time()); Assert.assertNotNull(frames.get().get(0).data().get(0).concepts()); } @Test public void errorsExposedToUser() { final ClarifaiResponse<ConceptModel> response = client.getDefaultModels().generalModel().modify() .withConcepts(Action.MERGE, Concept.forID("concept2")) .executeSync(); if (response.isSuccessful()) { fail("You shouldn't be able to add concepts to the built-in general model"); } logger.debug(response.getStatus().toString()); } @Retry @Test public void testDeleteBatch() { final List<ClarifaiInput> inputs = assertSuccess(client.addInputs().plus( ClarifaiInput.forImage(KOTLIN_LOGO_IMAGE_FILE).withID("kotlin"), ClarifaiInput.forImage(METRO_NORTH_IMAGE_FILE).withID("train") )); waitForInputToDownload(client, inputs.get(0).id()); waitForInputToDownload(client, inputs.get(1).id()); assertSuccess(client.deleteInputsBatch().plus("kotlin", "train")); } @Test public void testSyncNetworkExceptions() throws ExecutionException, InterruptedException { final ClarifaiResponse<List<Model<?>>> badResponse = new ClarifaiBuilder(apiKey) .baseURL(baseURL) .client(new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .writeTimeout(5, TimeUnit.SECONDS) .addInterceptor(chain -> { // Don't mess with the token request that happens behind the scenes if (chain.request().url().pathSegments().contains("token")) { return chain.proceed(chain.request()); } // Change the port on our actual requests so that we get IOExceptions return chain.proceed(chain.request().newBuilder() .url(chain.request().url().newBuilder().port(383).build()) .build() ); }) .build() ) .buildSync() .getModels() .getPage(1) .executeSync(); if (badResponse.isSuccessful()) { fail("this response used a bad port, it should not have been successful. Response: " + badResponse.get()); } final ClarifaiStatus details = badResponse.getStatus(); assertTrue(details.networkErrorOccurred()); logger.debug(details.errorDetails()); } @Test(expected = ClarifaiClientClosedException.class) public void testClosingClientWorks() { final ClarifaiClient toBeClosed = new ClarifaiBuilder(apiKey).buildSync(); toBeClosed.close(); toBeClosed.getModels().getPage(1).executeSync(); } @Retry @Test public void testCreateModel() { final String modelID = "creatingModel" + System.nanoTime(); assertSuccess(client.createModel(modelID).withOutputInfo( ConceptOutputInfo.forConcepts( Concept.forID("foo") ) )); } @Retry @Test public void testCreateModel_multi_lang() { final String modelID = "creatingModel" + System.nanoTime(); assertSuccess(client.createModel(modelID).withOutputInfo( ConceptOutputInfo.forConcepts( Concept.forID("foo") ).withLanguage("zh") )); } @Retry @Test public void testModifyModel() { final String modelID = "modifyingModel" + System.nanoTime(); assertSuccess(client.createModel(modelID).withOutputInfo( ConceptOutputInfo.forConcepts( Concept.forID("foo") ) )); assertSuccess(client.modifyModel(modelID) .withConcepts(Action.OVERWRITE, Concept.forID("bar")) ); final List<Concept> concepts = assertSuccess(client.getModelByID(modelID)).asConceptModel().outputInfo().concepts(); assertEquals(1, concepts.size()); assertEquals("bar", concepts.get(0).name()); } @Retry @Test public void testMergeMetadata() { final String inputID = assertSuccess(client.addInputs() .allowDuplicateURLs(true) .plus(ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL) ) ).get(0).id(); waitForInputToDownload(client, inputID); final JsonObject newMetadata = assertSuccess( client.addMetadataForInput( inputID, new JSONObjectBuilder() .add("foo", "bar") .build() ) ).metadata(); assertEquals(new JSONObjectBuilder().add("foo", "bar").build(), newMetadata); } @Test public void testMetadataDoesNotAllowNullDictionaryValues() { thrown.expect(IllegalArgumentException.class); client.addInputs() .allowDuplicateURLs(true) .plus(ClarifaiInput.forImage(METRO_NORTH_IMAGE_URL) // Will throw IAE because we have a null value .withMetadata(new JSONObjectBuilder().add("foo", JsonNull.INSTANCE).build()) ) .executeSync(); } }
package com.qozix.tileview.widgets; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.Scroller; import com.qozix.tileview.geom.FloatMathHelper; import com.qozix.tileview.view.TouchUpGestureDetector; import java.lang.ref.WeakReference; import java.util.HashSet; /** * ZoomPanLayout extends ViewGroup to provide support for scrolling and zooming. * Fling, drag, pinch and double-tap events are supported natively. * * Children of ZoomPanLayout are laid out to the sizes provided by setSize, * and will always be positioned at 0,0. */ public class ZoomPanLayout extends ViewGroup implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, ScaleGestureDetector.OnScaleGestureListener, TouchUpGestureDetector.OnTouchUpListener { private static final int DEFAULT_ZOOM_PAN_ANIMATION_DURATION = 400; private int mBaseWidth; private int mBaseHeight; private int mScaledWidth; private int mScaledHeight; private float mScale = 1; private float mMinScale = 0; private float mMaxScale = 1; private int mOffsetX; private int mOffsetY; private float mEffectiveMinScale = 0; private boolean mShouldLoopScale = true; private boolean mIsFlinging; private boolean mIsDragging; private boolean mIsScaling; private boolean mIsSliding; private int mAnimationDuration = DEFAULT_ZOOM_PAN_ANIMATION_DURATION; private HashSet<ZoomPanListener> mZoomPanListeners = new HashSet<ZoomPanListener>(); private Scroller mScroller; private ZoomPanAnimator mZoomPanAnimator; private ScaleGestureDetector mScaleGestureDetector; private GestureDetector mGestureDetector; private TouchUpGestureDetector mTouchUpGestureDetector; private MinimumScaleMode mMinimumScaleMode = MinimumScaleMode.FILL; /** * Constructor to use when creating a ZoomPanLayout from code. * * @param context The Context the ZoomPanLayout is running in, through which it can access the current theme, resources, etc. */ public ZoomPanLayout( Context context ) { this( context, null ); } public ZoomPanLayout( Context context, AttributeSet attrs ) { this( context, attrs, 0 ); } public ZoomPanLayout( Context context, AttributeSet attrs, int defStyleAttr ) { super( context, attrs, defStyleAttr ); setWillNotDraw( false ); setClipChildren( false ); mScroller = new Scroller( context ); mGestureDetector = new GestureDetector( context, this ); mScaleGestureDetector = new ScaleGestureDetector( context, this ); mTouchUpGestureDetector = new TouchUpGestureDetector( this ); } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { // the container's children should be the size provided by setSize // don't use measureChildren because that grabs the child's LayoutParams int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( mScaledWidth, MeasureSpec.EXACTLY ); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( mScaledHeight, MeasureSpec.EXACTLY ); for( int i = 0; i < getChildCount(); i++){ View child = getChildAt( i ); child.measure( childWidthMeasureSpec, childHeightMeasureSpec ); } // but the layout itself should report normal (on screen) dimensions int width = MeasureSpec.getSize( widthMeasureSpec ); int height = MeasureSpec.getSize( heightMeasureSpec ); width = resolveSize( width, widthMeasureSpec ); height = resolveSize( height, heightMeasureSpec ); setMeasuredDimension( width, height ); } /* ZoomPanChildren will always be laid out with the scaled dimenions - what is visible during scroll operations. Thus, a RelativeLayout added as a child that had views within it using rules like ALIGN_PARENT_RIGHT would function as expected; similarly, an ImageView would be stretched between the visible edges. If children further operate on scale values, that should be accounted for in the child's logic (see ScalingLayout). */ @Override protected void onLayout( boolean changed, int l, int t, int r, int b ) { final int width = getWidth(); final int height = getHeight(); mOffsetX = mScaledWidth >= width ? 0 : width / 2 - mScaledWidth / 2; mOffsetY = mScaledHeight >= height ? 0 : height / 2 - mScaledHeight / 2; for( int i = 0; i < getChildCount(); i++ ) { View child = getChildAt( i ); if( child.getVisibility() != GONE ) { child.layout( mOffsetX, mOffsetY, mScaledWidth + mOffsetX, mScaledHeight + mOffsetY ); } } calculateMinimumScaleToFit(); constrainScrollToLimits(); } /** * Determines whether the ZoomPanLayout should limit it's minimum scale to no less than what * would be required to fill it's container. * * @param shouldScaleToFit True to limit minimum scale, false to allow arbitrary minimum scale. */ public void setShouldScaleToFit( boolean shouldScaleToFit ) { setMinimumScaleMode(shouldScaleToFit ? MinimumScaleMode.FILL : MinimumScaleMode.NONE); } /** * Sets the minimum scale mode * * @param minimumScaleMode The minimum scale mode */ public void setMinimumScaleMode( MinimumScaleMode minimumScaleMode ) { mMinimumScaleMode = minimumScaleMode; calculateMinimumScaleToFit(); } /** * Determines whether the ZoomPanLayout should go back to minimum scale after a double-tap at * maximum scale. * * @param shouldLoopScale True to allow going back to minimum scale, false otherwise. */ public void setShouldLoopScale( boolean shouldLoopScale ) { mShouldLoopScale = shouldLoopScale; } /** * Set minimum and maximum mScale values for this ZoomPanLayout. * Note that if minimumScaleMode is set to {@link MinimumScaleMode#FIT} or {@link MinimumScaleMode#FILL}, the minimum value set here will be ignored * Default values are 0 and 1. * * @param min Minimum scale the ZoomPanLayout should accept. * @param max Maximum scale the ZoomPanLayout should accept. */ public void setScaleLimits( float min, float max ) { mMinScale = min; mMaxScale = max; setScale( mScale ); } /** * Sets the size (width and height) of the ZoomPanLayout * as it should be rendered at a scale of 1f (100%). * * @param width Width of the underlying image, not the view or viewport. * @param height Height of the underlying image, not the view or viewport. */ public void setSize( int width, int height ) { mBaseWidth = width; mBaseHeight = height; updateScaledDimensions(); calculateMinimumScaleToFit(); constrainScrollToLimits(); requestLayout(); } /** * Returns the base (not scaled) width of the underlying composite image. * * @return The base (not scaled) width of the underlying composite image. */ public int getBaseWidth() { return mBaseWidth; } /** * Returns the base (not scaled) height of the underlying composite image. * * @return The base (not scaled) height of the underlying composite image. */ public int getBaseHeight() { return mBaseHeight; } /** * Returns the scaled width of the underlying composite image. * * @return The scaled width of the underlying composite image. */ public int getScaledWidth() { return mScaledWidth; } /** * Returns the scaled height of the underlying composite image. * * @return The scaled height of the underlying composite image. */ public int getScaledHeight() { return mScaledHeight; } /** * Sets the scale (0-1) of the ZoomPanLayout. * * @param scale The new value of the ZoomPanLayout scale. */ public void setScale( float scale ) { scale = getConstrainedDestinationScale( scale ); if( mScale != scale ) { float previous = mScale; mScale = scale; updateScaledDimensions(); constrainScrollToLimits(); onScaleChanged( scale, previous ); invalidate(); } } /** * Retrieves the current scale of the ZoomPanLayout. * * @return The current scale of the ZoomPanLayout. */ public float getScale() { return mScale; } /** * Returns the horizontal distance children are offset if the content is scaled smaller than width. * * @return */ public int getOffsetX() { return mOffsetX; } /** * Return the vertical distance children are offset if the content is scaled smaller than height. * * @return */ public int getOffsetY() { return mOffsetY; } /** * Returns whether the ZoomPanLayout is currently being flung. * * @return true if the ZoomPanLayout is currently flinging, false otherwise. */ public boolean isFlinging() { return mIsFlinging; } /** * Returns whether the ZoomPanLayout is currently being dragged. * * @return true if the ZoomPanLayout is currently dragging, false otherwise. */ public boolean isDragging() { return mIsDragging; } /** * Returns whether the ZoomPanLayout is currently operating a scroll tween. * * @return True if the ZoomPanLayout is currently scrolling, false otherwise. */ public boolean isSliding() { return mIsSliding; } /** * Returns whether the ZoomPanLayout is currently operating a scale tween. * * @return True if the ZoomPanLayout is currently scaling, false otherwise. */ public boolean isScaling() { return mIsScaling; } /** * Returns the Scroller instance used to manage dragging and flinging. * * @return The Scroller instance use to manage dragging and flinging. */ public Scroller getScroller() { return mScroller; } /** * Returns the duration zoom and pan animations will use. * * @return The duration zoom and pan animations will use. */ public int getAnimationDuration() { return mAnimationDuration; } /** * Set the duration zoom and pan animation will use. * * @param animationDuration The duration animations will use. */ public void setAnimationDuration( int animationDuration ) { mAnimationDuration = animationDuration; if( mZoomPanAnimator != null ) { mZoomPanAnimator.setDuration( mAnimationDuration ); } } /** * Adds a ZoomPanListener to the ZoomPanLayout, which will receive notification of actions * relating to zoom and pan events. * * @param zoomPanListener ZoomPanListener implementation to add. * @return True when the listener set did not already contain the Listener, false otherwise. */ public boolean addZoomPanListener( ZoomPanListener zoomPanListener ) { return mZoomPanListeners.add( zoomPanListener ); } /** * Removes a ZoomPanListener from the ZoomPanLayout * * @param listener ZoomPanListener to remove. * @return True if the Listener was removed, false otherwise. */ public boolean removeZoomPanListener( ZoomPanListener listener ) { return mZoomPanListeners.remove( listener ); } /** * Scrolls and centers the ZoomPanLayout to the x and y values provided. * * @param x Horizontal destination point. * @param y Vertical destination point. */ public void scrollToAndCenter( int x, int y ) { scrollTo( x - getHalfWidth(), y - getHalfHeight() ); } /** * Set the scale of the ZoomPanLayout while maintaining the current center point. * * @param scale The new value of the ZoomPanLayout scale. */ public void setScaleFromCenter( float scale ) { setScaleFromPosition( getHalfWidth(), getHalfHeight(), scale ); } /** * Scrolls the ZoomPanLayout to the x and y values provided using scrolling animation. * * @param x Horizontal destination point. * @param y Vertical destination point. */ public void slideTo( int x, int y ) { getAnimator().animatePan( x, y ); } /** * Scrolls and centers the ZoomPanLayout to the x and y values provided using scrolling animation. * * @param x Horizontal destination point. * @param y Vertical destination point. */ public void slideToAndCenter( int x, int y ) { slideTo( x - getHalfWidth(), y - getHalfHeight() ); } /** * Animates the ZoomPanLayout to the scale provided, and centers the viewport to the position * supplied. * * @param x Horizontal destination point. * @param y Vertical destination point. * @param scale The final scale value the ZoomPanLayout should animate to. */ public void slideToAndCenterWithScale( int x, int y, float scale ) { getAnimator().animateZoomPan( x - getHalfWidth(), y - getHalfHeight(), scale ); } /** * Scales the ZoomPanLayout with animated progress, without maintaining scroll position. * * @param destination The final scale value the ZoomPanLayout should animate to. */ public void smoothScaleTo( float destination ) { getAnimator().animateZoom( destination ); } /** * Animates the ZoomPanLayout to the scale provided, while maintaining position determined by * the focal point provided. * * @param focusX The horizontal focal point to maintain, relative to the screen (as supplied by MotionEvent.getX). * @param focusY The vertical focal point to maintain, relative to the screen (as supplied by MotionEvent.getY). * @param scale The final scale value the ZoomPanLayout should animate to. */ public void smoothScaleFromFocalPoint( int focusX, int focusY, float scale ) { scale = getConstrainedDestinationScale( scale ); if( scale == mScale ) { return; } int x = getOffsetScrollXFromScale( focusX, scale, mScale ); int y = getOffsetScrollYFromScale( focusY, scale, mScale ); getAnimator().animateZoomPan( x, y, scale ); } /** * Animate the scale of the ZoomPanLayout while maintaining the current center point. * * @param scale The final scale value the ZoomPanLayout should animate to. */ public void smoothScaleFromCenter( float scale ) { smoothScaleFromFocalPoint( getHalfWidth(), getHalfHeight(), scale ); } /** * Provide this method to be overriden by subclasses, e.g., onScrollChanged. */ public void onScaleChanged( float currentScale, float previousScale ) { // noop } private float getConstrainedDestinationScale( float scale ) { scale = Math.max( scale, mEffectiveMinScale ); scale = Math.min( scale, mMaxScale ); return scale; } private void constrainScrollToLimits() { int x = getScrollX(); int y = getScrollY(); int constrainedX = getConstrainedScrollX( x ); int constrainedY = getConstrainedScrollY( y ); if( x != constrainedX || y != constrainedY ) { scrollTo( constrainedX, constrainedY ); } } private void updateScaledDimensions() { mScaledWidth = FloatMathHelper.scale( mBaseWidth, mScale ); mScaledHeight = FloatMathHelper.scale( mBaseHeight, mScale ); } protected ZoomPanAnimator getAnimator() { if( mZoomPanAnimator == null ) { mZoomPanAnimator = new ZoomPanAnimator( this ); mZoomPanAnimator.setDuration( mAnimationDuration ); } return mZoomPanAnimator; } private int getOffsetScrollXFromScale( int offsetX, float destinationScale, float currentScale ) { int scrollX = getScrollX() + offsetX; float deltaScale = destinationScale / currentScale; return (int) (scrollX * deltaScale) - offsetX; } private int getOffsetScrollYFromScale( int offsetY, float destinationScale, float currentScale ) { int scrollY = getScrollY() + offsetY; float deltaScale = destinationScale / currentScale; return (int) (scrollY * deltaScale) - offsetY; } public void setScaleFromPosition( int offsetX, int offsetY, float scale ) { scale = getConstrainedDestinationScale( scale ); if( scale == mScale ) { return; } int x = getOffsetScrollXFromScale( offsetX, scale, mScale ); int y = getOffsetScrollYFromScale( offsetY, scale, mScale ); setScale( scale ); x = getConstrainedScrollX( x ); y = getConstrainedScrollY( y ); scrollTo( x, y ); } @Override public boolean canScrollHorizontally( int direction ) { int position = getScrollX(); return direction > 0 ? position < getScrollLimitX() : direction < 0 && position > 0; } @Override public boolean onTouchEvent( MotionEvent event ) { boolean gestureIntercept = mGestureDetector.onTouchEvent( event ); boolean scaleIntercept = mScaleGestureDetector.onTouchEvent( event ); boolean touchIntercept = mTouchUpGestureDetector.onTouchEvent( event ); return gestureIntercept || scaleIntercept || touchIntercept || super.onTouchEvent( event ); } @Override public void scrollTo( int x, int y ) { x = getConstrainedScrollX( x ); y = getConstrainedScrollY( y ); super.scrollTo( x, y ); } private void calculateMinimumScaleToFit() { float minimumScaleX = getWidth() / (float) mBaseWidth; float minimumScaleY = getHeight() / (float) mBaseHeight; float recalculatedMinScale = calculatedMinScale(minimumScaleX, minimumScaleY); if( recalculatedMinScale != mEffectiveMinScale ) { mEffectiveMinScale = recalculatedMinScale; if( mScale < mEffectiveMinScale ){ setScale( mEffectiveMinScale ); } } } private float calculatedMinScale( float minimumScaleX, float minimumScaleY ) { switch( mMinimumScaleMode ) { case FILL: return Math.max( minimumScaleX, minimumScaleY ); case FIT: return Math.min( minimumScaleX, minimumScaleY ); } return mMinScale; } protected int getHalfWidth() { return FloatMathHelper.scale( getWidth(), 0.5f ); } protected int getHalfHeight() { return FloatMathHelper.scale( getHeight(), 0.5f ); } protected int getConstrainedScrollX( int x ) { return Math.max( getScrollMinX(), Math.min( x, getScrollLimitX() ) ); } protected int getConstrainedScrollY( int y ) { return Math.max( getScrollMinY(), Math.min( y, getScrollLimitY() ) ); } protected int getScrollLimitX() { return mScaledWidth - getWidth(); } protected int getScrollLimitY() { return mScaledHeight - getHeight(); } protected int getScrollMinX(){ return 0; } protected int getScrollMinY(){ return 0; } @Override public void computeScroll() { if( getScroller().computeScrollOffset() ) { int startX = getScrollX(); int startY = getScrollY(); int endX = getConstrainedScrollX( getScroller().getCurrX() ); int endY = getConstrainedScrollY( getScroller().getCurrY() ); if( startX != endX || startY != endY ) { scrollTo( endX, endY ); if( mIsFlinging ) { broadcastFlingUpdate(); } } if( getScroller().isFinished() ) { if( mIsFlinging ) { mIsFlinging = false; broadcastFlingEnd(); } } else { ViewCompat.postInvalidateOnAnimation( this ); } } } private void broadcastDragBegin() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanBegin( getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG ); } } private void broadcastDragUpdate() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanUpdate( getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG ); } } private void broadcastDragEnd() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanEnd( getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG ); } } private void broadcastFlingBegin() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanBegin( getScroller().getStartX(), getScroller().getStartY(), ZoomPanListener.Origination.FLING ); } } private void broadcastFlingUpdate() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanUpdate( getScroller().getCurrX(), getScroller().getCurrY(), ZoomPanListener.Origination.FLING ); } } private void broadcastFlingEnd() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanEnd( getScroller().getFinalX(), getScroller().getFinalY(), ZoomPanListener.Origination.FLING ); } } private void broadcastProgrammaticPanBegin() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanBegin( getScrollX(), getScrollY(), null ); } } private void broadcastProgrammaticPanUpdate() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanUpdate( getScrollX(), getScrollY(), null ); } } private void broadcastProgrammaticPanEnd() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onPanEnd( getScrollX(), getScrollY(), null ); } } private void broadcastPinchBegin() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomBegin( mScale, ZoomPanListener.Origination.PINCH ); } } private void broadcastPinchUpdate() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomUpdate( mScale, ZoomPanListener.Origination.PINCH ); } } private void broadcastPinchEnd() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomEnd( mScale, ZoomPanListener.Origination.PINCH ); } } private void broadcastProgrammaticZoomBegin() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomBegin( mScale, null ); } } private void broadcastProgrammaticZoomUpdate() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomUpdate( mScale, null ); } } private void broadcastProgrammaticZoomEnd() { for( ZoomPanListener listener : mZoomPanListeners ) { listener.onZoomEnd( mScale, null ); } } @Override public boolean onDown( MotionEvent event ) { if( mIsFlinging && !getScroller().isFinished() ) { getScroller().forceFinished( true ); mIsFlinging = false; broadcastFlingEnd(); } return true; } @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY ) { getScroller().fling( getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY, getScrollMinX(), getScrollLimitX(), getScrollMinY(), getScrollLimitY() ); mIsFlinging = true; ViewCompat.postInvalidateOnAnimation( this ); broadcastFlingBegin(); return true; } @Override public void onLongPress( MotionEvent event ) { } @Override public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) { int scrollEndX = getScrollX() + (int) distanceX; int scrollEndY = getScrollY() + (int) distanceY; scrollTo( scrollEndX, scrollEndY ); if( !mIsDragging ) { mIsDragging = true; broadcastDragBegin(); } else { broadcastDragUpdate(); } return true; } @Override public void onShowPress( MotionEvent event ) { } @Override public boolean onSingleTapUp( MotionEvent event ) { return true; } @Override public boolean onSingleTapConfirmed( MotionEvent event ) { return true; } @Override public boolean onDoubleTap( MotionEvent event ) { float destination = (float)( Math.pow( 2, Math.floor( Math.log( mScale * 2 ) / Math.log( 2 ) ) ) ); float effectiveDestination = mShouldLoopScale && mScale >= mMaxScale ? mMinScale : destination; destination = getConstrainedDestinationScale( effectiveDestination ); smoothScaleFromFocalPoint( (int) event.getX(), (int) event.getY(), destination ); return true; } @Override public boolean onDoubleTapEvent( MotionEvent event ) { return true; } @Override public boolean onTouchUp( MotionEvent event ) { if( mIsDragging ) { mIsDragging = false; if( !mIsFlinging ) { broadcastDragEnd(); } } return true; } @Override public boolean onScaleBegin( ScaleGestureDetector scaleGestureDetector ) { mIsScaling = true; broadcastPinchBegin(); return true; } @Override public void onScaleEnd( ScaleGestureDetector scaleGestureDetector ) { mIsScaling = false; broadcastPinchEnd(); } @Override public boolean onScale( ScaleGestureDetector scaleGestureDetector ) { float currentScale = mScale * mScaleGestureDetector.getScaleFactor(); setScaleFromPosition( (int) scaleGestureDetector.getFocusX(), (int) scaleGestureDetector.getFocusY(), currentScale ); broadcastPinchUpdate(); return true; } private static class ZoomPanAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener, ValueAnimator.AnimatorListener { private WeakReference<ZoomPanLayout> mZoomPanLayoutWeakReference; private ZoomPanState mStartState = new ZoomPanState(); private ZoomPanState mEndState = new ZoomPanState(); private boolean mHasPendingZoomUpdates; private boolean mHasPendingPanUpdates; public ZoomPanAnimator( ZoomPanLayout zoomPanLayout ) { super(); addUpdateListener( this ); addListener( this ); setFloatValues( 0f, 1f ); setInterpolator( new FastEaseInInterpolator() ); mZoomPanLayoutWeakReference = new WeakReference<ZoomPanLayout>( zoomPanLayout ); } private boolean setupPanAnimation( int x, int y ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { mStartState.x = zoomPanLayout.getScrollX(); mStartState.y = zoomPanLayout.getScrollY(); mEndState.x = x; mEndState.y = y; return mStartState.x != mEndState.x || mStartState.y != mEndState.y; } return false; } private boolean setupZoomAnimation( float scale ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { mStartState.scale = zoomPanLayout.getScale(); mEndState.scale = scale; return mStartState.scale != mEndState.scale; } return false; } public void animateZoomPan( int x, int y, float scale ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { mHasPendingZoomUpdates = setupZoomAnimation( scale ); mHasPendingPanUpdates = setupPanAnimation( x, y ); if( mHasPendingPanUpdates || mHasPendingZoomUpdates ) { start(); } } } public void animateZoom( float scale ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { mHasPendingZoomUpdates = setupZoomAnimation( scale ); if( mHasPendingZoomUpdates ) { start(); } } } public void animatePan( int x, int y ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { mHasPendingPanUpdates = setupPanAnimation( x, y ); if( mHasPendingPanUpdates ) { start(); } } } @Override public void onAnimationUpdate( ValueAnimator animation ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { float progress = (float) animation.getAnimatedValue(); if( mHasPendingZoomUpdates ) { float scale = mStartState.scale + (mEndState.scale - mStartState.scale) * progress; zoomPanLayout.setScale( scale ); zoomPanLayout.broadcastProgrammaticZoomUpdate(); } if( mHasPendingPanUpdates ) { int x = (int) (mStartState.x + (mEndState.x - mStartState.x) * progress); int y = (int) (mStartState.y + (mEndState.y - mStartState.y) * progress); zoomPanLayout.scrollTo( x, y ); zoomPanLayout.broadcastProgrammaticPanUpdate(); } } } @Override public void onAnimationStart( Animator animator ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { if( mHasPendingZoomUpdates ) { zoomPanLayout.mIsScaling = true; zoomPanLayout.broadcastProgrammaticZoomBegin(); } if( mHasPendingPanUpdates ) { zoomPanLayout.mIsSliding = true; zoomPanLayout.broadcastProgrammaticPanBegin(); } } } @Override public void onAnimationEnd( Animator animator ) { ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get(); if( zoomPanLayout != null ) { if( mHasPendingZoomUpdates ) { mHasPendingZoomUpdates = false; zoomPanLayout.mIsScaling = false; zoomPanLayout.broadcastProgrammaticZoomEnd(); } if( mHasPendingPanUpdates ) { mHasPendingPanUpdates = false; zoomPanLayout.mIsSliding = false; zoomPanLayout.broadcastProgrammaticPanEnd(); } } } @Override public void onAnimationCancel( Animator animator ) { onAnimationEnd( animator ); } @Override public void onAnimationRepeat( Animator animator ) { } private static class ZoomPanState { public int x; public int y; public float scale; } private static class FastEaseInInterpolator implements Interpolator { @Override public float getInterpolation( float input ) { return (float) (1 - Math.pow( 1 - input, 8 )); } } } public interface ZoomPanListener { enum Origination { DRAG, FLING, PINCH } void onPanBegin( int x, int y, Origination origin ); void onPanUpdate( int x, int y, Origination origin ); void onPanEnd( int x, int y, Origination origin ); void onZoomBegin( float scale, Origination origin ); void onZoomUpdate( float scale, Origination origin ); void onZoomEnd( float scale, Origination origin ); } public enum MinimumScaleMode { /** * Limit the minimum scale to no less than what * would be required to fill the container */ FILL, /** * Limit the minimum scale to no less than what * would be required to fit inside the container */ FIT, /** * Allow arbitrary minimum scale. */ NONE } }
package to.etc.domui.component.tbl; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.component.meta.MetaManager; import to.etc.domui.component.misc.MiniLogger; import to.etc.domui.dom.html.Checkbox; import to.etc.domui.dom.html.ClickInfo; import to.etc.domui.dom.html.ColGroup; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.IClickBase; import to.etc.domui.dom.html.IClicked; import to.etc.domui.dom.html.IClicked2; import to.etc.domui.dom.html.Img; import to.etc.domui.dom.html.NodeBase; import to.etc.domui.dom.html.Page; import to.etc.domui.dom.html.TBody; import to.etc.domui.dom.html.TD; import to.etc.domui.dom.html.TH; import to.etc.domui.dom.html.THead; import to.etc.domui.dom.html.TR; import to.etc.domui.dom.html.Table; import to.etc.domui.dom.html.TextNode; import to.etc.domui.server.RequestContextImpl; import to.etc.domui.util.DomUtil; import to.etc.domui.util.DomUtil.IPerNode; import to.etc.domui.util.JavascriptUtil; import to.etc.domui.util.Msgs; import to.etc.util.DeveloperOptions; import java.util.ArrayList; import java.util.List; import static to.etc.util.ExceptionUtil.silentThrows; final public class DataTable<T> extends PageableTabularComponentBase<T> implements ISelectionListener<T>, ISelectableTableComponent<T> { private MiniLogger m_ml = new MiniLogger(40); private Table m_table = new Table(); private IRowRenderer<T> m_rowRenderer; /** The size of the page */ private int m_pageSize; /** If a result is visible this is the data table */ private TBody m_dataBody; /** When the query has 0 results this is set to the div displaying that message. */ private Div m_errorDiv; /** The items that are currently on-screen, to prevent a reload from the model when reused. */ final private List<TableRowSet<T>> m_visibleItemList = new ArrayList<>(); /** When set, the table is in "multiselect" mode and shows checkboxes before all rows. */ private boolean m_multiSelectMode; /** When selecting, this is the last index that was used in a select click.. */ private int m_lastSelectionLocation = -1; /** When set this replaces the "no results found" message. */ @Nullable private NodeBase m_emptyMessage; /** This will control the display of readonly checkboxes, in case the items are 'not acceptable' but selection is enabled. */ private boolean m_displayReadonlySelection = true; /** When T, the header of the table is always shown, even if the list of results is empty. */ private boolean m_showHeaderAlways; /** When T, rows are not highlighted when table has no selection callbacks on rows. */ private boolean m_preventRowHighlight; @Nullable private TBody m_footerBody; @NonNull private DataTableResize m_resizeMode = DataTableResize.NONE; @NonNull final private IClicked<TH> m_headerSelectClickHandler = clickednode -> { if(isDisabled()) { return; } ISelectionModel<T> sm = getSelectionModel(); if(null == sm) return; int ct = sm.getSelectionCount(); if(0 == ct && sm.isMultiSelect()) { sm.selectAll(getModel()); } else { sm.clearSelection(); } }; public DataTable(@NonNull ITableModel<T> m, @NonNull IRowRenderer<T> r) { super(m); m_rowRenderer = r; cInit(); } public DataTable(@NonNull IRowRenderer<T> r) { m_rowRenderer = r; cInit(); } public DataTable(@NonNull ITableModel<T> m) { super(m); cInit(); } public DataTable() { cInit(); } private void cInit() { // setWidth("100%"); } protected void updateBodyClipboardSelection() { TBody dataBody = m_dataBody; if(null == dataBody) return; if(isDisableClipboardSelection()) { appendJavascript(JavascriptUtil.disableSelection(dataBody)); } } @Override public void createContent() throws Exception { if(DeveloperOptions.getBool("domui.colresizable", true) && m_resizeMode != DataTableResize.NONE) { m_table.appendCreateJS("WebUI.dataTableResults('" + m_table.getActualID() + "','" + getActualID() + "','"+ m_resizeMode.name() + "');"); } m_dataBody = null; m_errorDiv = null; addCssClass("ui-dt"); m_table.setWidth(getWidth()); //-- Do we need to render multiselect checkboxes? ISelectionModel<T> sm = getSelectionModel(); if(sm != null) { if(isShowSelectionAlways() || sm.getSelectionCount() > 0) { m_multiSelectMode = sm.isMultiSelect(); } else { m_multiSelectMode = false; } } //-- Ask the renderer for a sort order, if applicable if(m_rowRenderer == null) throw new IllegalStateException("There is no row renderer assigned to the table"); m_rowRenderer.beforeQuery(this); // ORDER!! BEFORE CALCINDICES or any other call that materializes the result. calcIndices(); // Calculate rows to show. List<T> list = getPageItems(); // Data to show if(list.size() == 0) { setNoResults(); return; } setResults(); //-- Render the rows. renderRowList(list); ml("createContent rebuilt visibleList after render"); //if(isDisableClipboardSelection()) // appendCreateJS(JavascriptUtil.disableSelection(this)); // Needed to prevent ctrl+click in IE doing clipboard-select, because preventDefault does not work there of course. } @SuppressWarnings("deprecation") private void setResults() throws Exception { if(m_errorDiv != null) { m_errorDiv.remove(); m_errorDiv = null; } if(m_dataBody != null) return; m_table.removeAllChildren(); add(m_table); //-- Render the header. ColGroup colGroup = new ColGroup(); m_table.add(colGroup); THead hd = new THead(); m_table.add(hd); hd.setKeepNode(true); HeaderContainer<T> hc = new HeaderContainer<>(this, colGroup, hd, "ui-dt-hdr"); renderHeader(hc); if(!hc.hasContent()) { hd.remove(); } m_dataBody = new TBody(); m_table.add(m_dataBody); updateBodyClipboardSelection(); TBody footerBody = m_footerBody; if(null != footerBody) m_table.add(footerBody); } /** * EXPERIMENTAL */ public TBody getFooterBody() { TBody footerBody = m_footerBody; if(null == footerBody) { m_footerBody = footerBody = new TBody(); if(m_dataBody != null) { m_table.add(footerBody); } } return footerBody; } /** * DO NOT OVERRIDE - INTERNAL ONLY - DEPRECATED FOR EXTERNAL USE!! * * Renders the table header. If we're in multi select mode the first column will be * added as a checkbox column. The rest of the columns is delegated to the row * renderer in use. * * @param hc specified header container */ @Deprecated void renderHeader(@NonNull HeaderContainer<T> hc) throws Exception { //-- Are we rendering a multi-selection? if(m_multiSelectMode) { HeaderContainer.HeaderContainerCell cell = hc.add(""); TH headerCell = cell.getTh(); headerCell.add(new Img("THEME/dspcb-on.png")); headerCell.setTestID("dt_select_all"); headerCell.setClicked(m_headerSelectClickHandler); headerCell.setCssClass("ui-clickable"); // headerCell.setWidth("1%"); //keep selection column with minimal width cell.getCol().setWidth("3em"); } m_rowRenderer.renderHeader(this, hc); } private void setNoResults() throws Exception { if(m_showHeaderAlways) setNoResultsWithHeader(); else setNoResultsWithoutHeader(); } /** * Shows an empty data table including header, followed by the no results div. */ private void setNoResultsWithHeader() throws Exception { m_visibleItemList.clear(); ml("setNoResults visibleList cleared"); if(m_errorDiv != null) return; if(m_table != null) { m_table.removeAllChildren(); } else { add(m_table = new Table()); } m_dataBody = null; //-- Render the header. if(!m_table.isAttached()) add(m_table); ColGroup colGroup = new ColGroup(); m_table.add(colGroup); THead hd = new THead(); m_table.add(hd); hd.setKeepNode(true); HeaderContainer<T> hc = new HeaderContainer<>(this, colGroup, hd, "ui-dt-hdr"); renderHeader(hc); if(!hc.hasContent()) { hd.remove(); } m_dataBody = new TBody(); m_table.add(m_dataBody); updateBodyClipboardSelection(); renderNoResultsMessage(); } private void renderNoResultsMessage() { m_errorDiv = new Div(); m_errorDiv.setCssClass("ui-dt-nores"); NodeBase emptyMessage = m_emptyMessage; if(null == emptyMessage) { m_errorDiv.setText(Msgs.uiDatatableEmpty.getString()); } else { m_errorDiv.add(emptyMessage); } add(m_errorDiv); } /** * Removes any data table, and presents the "no results found" div. */ private void setNoResultsWithoutHeader() throws Exception { m_visibleItemList.clear(); ml("setNoResults visibleList cleared"); if(m_errorDiv != null) return; if(m_table != null) { m_table.removeAllChildren(); m_table.remove(); m_dataBody = null; } renderNoResultsMessage(); } public void setEmptyMessage(@Nullable String message) { if(null != message) m_emptyMessage = new TextNode(message); else m_emptyMessage = null; } public void setEmptyMessage(@Nullable NodeBase node) { m_emptyMessage = node; } /* CODING: Row rendering & select click handling. */ /** * DO NOT OVERRIDE - DEPRECATED FOR EXTERNAL USE!! * Renders row content into specified row. */ @SuppressWarnings("deprecation") private void renderRow(@NonNull final TR tr, @NonNull ColumnContainer<T> cc, int index, @NonNull final T value) throws Exception { tr.addCssClass("ui-dt-row"); //-- Is a rowclick handler needed? ISelectionModel<T> sm = getSelectionModel(); if(m_rowRenderer.getRowClicked() != null || null != sm) { //-- Add a click handler to select or pass the rowclicked event. cc.getTR().setClicked2(new IClicked2<TR>() { @Override public void clicked(@NonNull TR b, @NonNull ClickInfo clinfo) throws Exception { handleRowClick(b, value, clinfo); } }); cc.getTR().addCssClass("ui-rowsel"); } else if(!m_preventRowHighlight) { cc.getTR().addCssClass("ui-dt-row-nosel"); } if(sm != null) { boolean issel = sm.isSelected(value); String clzName = sm.isMultiSelect() ? "mselected" : "selected"; if(issel) tr.addCssClass(clzName); else tr.removeCssClass(clzName); //-- If we're in multiselect mode show the select boxes if(m_multiSelectMode) { Checkbox cb = createSelectionCheckbox(value, sm); TD td = cc.add(cb); if(cb.isReadOnly()) { td.addCssClass("ui-cur-default"); } else { //it very annoying to target small check box, so we also allow click in cell outside to perform check/uncheck hookCheckboxClickToCellToo(td, cb); } cb.setChecked(issel); } } internalRenderRow(tr, cc, index, value); } private void hookCheckboxClickToCellToo(TD td, Checkbox cb) { td.setClicked2((IClicked2<TD>) (node, clinfo) -> { if(!cb.isDisabled()) { IClickBase<?> clickHandler = cb.getClicked(); if(null != clickHandler && clickHandler instanceof IClicked2) { cb.setChecked(!cb.isChecked()); ((IClicked2<Checkbox>) clickHandler).clicked(cb, clinfo); } } }); } /** * Must exist for CheckBoxDataTable; remove asap AND DO NOT USE AGAIN - internal interfaces should remain hidden. */ @Deprecated void internalRenderRow(@NonNull final TR tr, @NonNull ColumnContainer<T> cc, int index, @NonNull final T value) throws Exception { m_rowRenderer.renderRow(this, cc, index, value); } /** * Click handler for rows. This handles both row clicked handling and row selection handling. * * @param b * @param instance * @param clinfo * @throws Exception */ private void handleRowClick(final TR b, final T instance, final ClickInfo clinfo) throws Exception { //-- If we have a selection model: check if this is some selecting clicky. ISelectionModel<T> selectionModel = getSelectionModel(); if(selectionModel != null) { //-- Treat clicks with ctrl or shift as selection clickies if(clinfo.isControl() || clinfo.isShift()) { handleSelectClicky(instance, clinfo, null); return; // Do NOT fire on selection clickies. } else { if(!selectionModel.isMultiSelect()) { handleSelectClicky(instance, clinfo, null); } } } //-- If this has a click handler- fire it. ICellClicked<?> rowClicked = m_rowRenderer.getRowClicked(); if(null != rowClicked) ((ICellClicked<T>) rowClicked).cellClicked(instance); } /** * When checkbox itself is clicked, this handles shift stuff. * @param instance * @param checked * @param info * @throws Exception */ private void selectionCheckboxClicked(T instance, boolean checked, ClickInfo info, @NonNull Checkbox checkbox) throws Exception { handleSelectClicky(instance, info, Boolean.valueOf(checked)); ISelectionModel<T> sm = getSelectionModel(); if(null != sm) { checkbox.setChecked(sm.isSelected(instance)); } } /** * If the specified item is on-screen, this returns the row index inside TBody for that item. * It returns -1 if the thing is not found. * @param item * @return */ protected int findRowIndex(T item) { for(int i = m_visibleItemList.size(); --i >= 0; ) { if(item == m_visibleItemList.get(i)) return i; } return -1; } /** * Handle a click that is meant to select/deselect the item(s). It handles ctrl+click as "toggle selection", * and shift+click as "toggle everything between this and the last one". * @param setTo When null toggle, else set to specific. */ private void handleSelectClicky(@NonNull T instance, @NonNull ClickInfo clinfo, @Nullable Boolean setTo) throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(null == sm) throw new IllegalStateException("SelectionModel is null??"); boolean nvalue = setTo != null ? setTo.booleanValue() : !sm.isSelected(instance); if(!clinfo.isShift()) { sm.setInstanceSelected(instance, nvalue); m_lastSelectionLocation = -1; return; } int itemindex = getVisibleItemindex(instance); if(itemindex == -1) // Ignore when thingy not found return; itemindex += m_six; //-- Is a previous location set? If not: just toggle the current and retain the location. if(m_lastSelectionLocation == -1) { //-- Start of region.... m_lastSelectionLocation = itemindex; sm.setInstanceSelected(instance, !sm.isSelected(instance)); return; } //-- We have a previous location- we need to toggle all instances; int sl, el; if(m_lastSelectionLocation < itemindex) { sl = m_lastSelectionLocation + 1; // Exclusive el = itemindex + 1; } else { sl = itemindex; el = m_lastSelectionLocation; // Exclusive } //-- Now toggle all instances, in batches, to prevent loading 1000+ records that cannot be gc'd. toggleAllInstances(sm, sl, el); m_lastSelectionLocation = -1; } private void toggleAllInstances(ISelectionModel<T> sm, int sl, int el) throws Exception { for(int i = sl; i < el; ) { int ex = i + 50; if(ex > el) ex = el; List<T> sub = getModel().getItems(i, ex); i += ex; for(T item : sub) { if(item == null) throw new IllegalStateException("null item in list"); sm.setInstanceSelected(item, !sm.isSelected(item)); } } } private int getVisibleItemindex(@NonNull T instance) { //-- Toggle region. Get the current item's index. int itemindex = -1, index = 0; for(TableRowSet<T> rowSet : m_visibleItemList) { if(MetaManager.areObjectsEqual(rowSet.getInstance(), instance)) { itemindex = index; break; } index++; } return itemindex; } /* CODING: Selection UI update handling. */ /** * Updates the "selection" state of the specified local row#. * @param instance * @param tableRowSet * @param on */ private void updateSelectionChanged(T instance, TableRowSet<T> tableRowSet, boolean on) throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(sm == null) throw new IllegalStateException("No selection model!?"); TR row = tableRowSet.getPrimaryRow(); THead head = m_table.getHead(); if(null == head) throw new IllegalStateException("I've lost my head!?"); TR headerrow = (TR) head.getChild(0); if(!sm.isMultiSelect()) { //-- Single selection model. Just add/remove the "selected" class from the row. if(on) row.addCssClass("selected"); else row.removeCssClass("selected"); return; } /* * In multiselect. If the multiselect UI is not visible we check if we are switching * ON, else there we can exit. If we switch ON we add the multiselect UI if not * yet present. Then we set/reset the checkbox for the row. */ if(!m_multiSelectMode) { if(!on) // No UI yet, but this is a deselect so let it be return; //-- Render the multiselect UI: add the header cell and row cells. createMultiselectUI(headerrow); } //-- The checkbox is in cell0; get it and change it's value if (still) needed TD td = (TD) row.getChild(0); Checkbox cb = (Checkbox) td.getChild(0); if(cb.isChecked() != on) // Only change if not already correct cb.setChecked(on); if(on) row.addCssClass("mselected"); else row.removeCssClass("mselected"); } /** * Make the multiselect UI for all visible rows and the header. */ private void createMultiselectUI(TR headerrow) { if(m_multiSelectMode) return; m_multiSelectMode = true; //-- 1. Add the select TH. TD th = new TH(); th.add(new Img("THEME/dspcb-on.png")); th.setTestID("dt_select_all"); th.setWidth("1%"); headerrow.add(0, th); th.setClicked(m_headerSelectClickHandler); th.setCssClass("ui-clickable"); //-- 2. Insert a checkbox in all rows. for(int i = 0; i < m_dataBody.getChildCount(); i++) { TableRowSet<T> rowSet = m_visibleItemList.get(i); TR tr = rowSet.getPrimaryRow(); TD td = new TD(); tr.add(0, td); td.setRowspan(rowSet.rowCount()); final Checkbox cb = createSelectionCheckbox(rowSet.getInstance(), getSelectionModel()); if(cb.isReadOnly()) { td.addCssClass("ui-cur-default"); } else { //it very annoying to target small check box, so we also allow click in cell outside to perform check/uncheck hookCheckboxClickToCellToo(td, cb); } td.add(cb); cb.setChecked(false); } fireSelectionUIChanged(); } @NonNull private Checkbox createSelectionCheckbox(@NonNull final T rowInstance, @Nullable ISelectionModel<T> selectionModel) { Checkbox cb = new Checkbox(); boolean selectable = true; if(selectionModel instanceof IAcceptable) { selectable = ((IAcceptable<T>) selectionModel).acceptable(rowInstance); } if(selectable) { cb.setClicked2(new IClicked2<Checkbox>() { @Override public void clicked(@NonNull Checkbox clickednode, @NonNull ClickInfo info) throws Exception { selectionCheckboxClicked(rowInstance, clickednode.isChecked(), info, clickednode); } }); } else { cb.setReadOnly(true); } return cb; } @Override protected void createSelectionUI() throws Exception { THead head = m_table.getHead(); if(null == head) throw new IllegalStateException("I've lost my head!?"); TR headerrow = (TR) head.getChild(0); createMultiselectUI(headerrow); } /* CODING: ITableModelListener implementation */ /** * Called when there are sweeping changes to the model. It forces a complete re-render of the table. */ @Override public void modelChanged(@Nullable ITableModel<T> model) { forceRebuild(); fireModelChanged(null, model); } @Override protected void updateAllRows() throws Exception { if(! isBuilt()) return; calcIndices(); List<T> list = getPageItems(); // Data to show if(list.size() == 0) { setNoResults(); return; } //-- Render the rows. renderRowList(list); ml("createContent rebuilt visibleList updateAllRows"); } private void renderRowList(List<T> list) throws Exception { if(m_dataBody == null) return; ColumnContainer<T> cc = new ColumnContainer<>(this); m_visibleItemList.clear(); m_dataBody.removeAllChildren(); int ix = m_six; for(T o : list) { TableRowSet<T> rowSet = new TableRowSet<>(this, o); m_visibleItemList.add(rowSet); TR tr = rowSet.getPrimaryRow(); m_dataBody.add(tr); tr.setTestRepeatID("r" + ix); cc.setParent(tr); renderRow(tr, cc, ix, o); ix++; } } @Override public void rowsSorted(@NonNull ITableModel<T> model) throws Exception { updateAllRows(); } /** * Row add. Determine if the row is within the paged-in indexes. If not we ignore the * request. If it IS within the paged content we insert the new TR. Since this adds a * new row to the visible set we check if the resulting rowset is not bigger than the * page size; if it is we delete the last node. After all this the renderer will render * the correct result. * When called the actual insert has already taken place in the model. * * @see to.etc.domui.component.tbl.ITableModelListener#rowAdded(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ @Override public void rowAdded(@NonNull ITableModel<T> model, int index, @NonNull T value) throws Exception { try { if(!isBuilt()) return; calcIndices(); // Calculate visible nodes if(index < m_six || index >= m_eix) { // Outside visible bounds firePageChanged(); return; } //-- What relative row? setResults(); int rrow = index - m_six; // This is the location within the child array ml("rowAdded before anything: rrow=" + rrow + " index=" + index); ColumnContainer<T> cc = new ColumnContainer<T>(this); //-- We need a new TableRowSet. TableRowSet<T> rowSet = new TableRowSet<T>(this, value); DataTableRow<T> tr = rowSet.getPrimaryRow(); m_visibleItemList.add(rrow, rowSet); //-- Locate the insert position for this row and add it to the table before rendering int bodyIndex = calculateBodyPosition(rrow); m_dataBody.add(bodyIndex, tr); cc.setParent(tr); tr.setTestRepeatID("r" + index); renderRow(tr, cc, index, value); ml("rowAdded after adds: rrow=" + rrow + ", index=" + index + ", bodyIndex=" + bodyIndex); //-- If we exceed the page size delete the last row. if(m_pageSize > 0 && m_visibleItemList.size() > m_pageSize) { //-- Delete the last row. int lastChildIndex = m_visibleItemList.size() - 1; ml("rowAdded removing last item at " + lastChildIndex); TableRowSet<T> lastRow = m_visibleItemList.remove(lastChildIndex); for(DataTableRow<T> tableRow : lastRow) { tableRow.remove(); } ml("rowAdded after pgsz delete visibleSz=" + m_visibleItemList.size()); } if(m_pageSize > 0) { while(m_visibleItemList.size() > m_pageSize) { int lastChildIndex = m_visibleItemList.size() - 1; ml("rowAdded removing last VISIBLE row at " + lastChildIndex); m_visibleItemList.remove(lastChildIndex); } ml("rowAdded after pgsz delete visibleSz=" + m_visibleItemList.size()); } handleOddEven(rrow); firePageChanged(); } catch(Exception x) { System.err.println("Last DataTable actions:\n" + m_ml.getData()); throw x; } } /** * This calculates the starting index position inside the TBody for the data row with * the specified rowIndex. It walks all visibleItems up till the rowIndex, and adds * their rowSize to get the next index. */ private int calculateBodyPosition(int rowIndex) { int position = 0; for(int i = 0; i < rowIndex; i++) { TableRowSet<T> rowSet = m_visibleItemList.get(i); position += rowSet.rowCount(); } return position; } private void ml(String rest) { try { TBody dataBody = m_dataBody; int sz = dataBody == null ? -1 : dataBody.getChildCount(); m_ml.add(rest + ": six=" + m_six + ", eix=" + m_eix + ", visibleSz=" + m_visibleItemList.size() + ", bodySz=" + sz); } catch(Exception x) { m_ml.add("Exception adding to log stack: " + x); } } /** * Delete the row specified. If it is not visible we do nothing. If it is visible we * delete the row. This causes one less row to be shown, so we check if we have a pagesize * set; if so we add a new row at the end IF it is available. * * @see ITableModelListener#rowDeleted(ITableModel, int, Object) */ @Override public void rowDeleted(@NonNull ITableModel<T> model, int index, @NonNull T value) throws Exception { try { if(!isBuilt()) return; //-- We need the indices of the OLD data, so DO NOT RECALCULATE - the model size has changed. if(index < m_six || index >= m_eix) { // Outside visible bounds calcIndices(); // Calculate visible nodes firePageChanged(); return; } int rrow = index - m_six; // This is the location within the visible items list ml("rowDeleted before, index=" + index +", rrow=" + rrow); TableRowSet<T> rowSet = m_visibleItemList.remove(rrow); for(DataTableRow<T> tableRow : rowSet) { tableRow.remove(); } if(m_visibleItemList.size() == 0) { calcIndices(); // Calculate visible nodes setNoResults(); firePageChanged(); return; } //-- One row gone; must we add one at the end? int peix = m_six + m_pageSize - 1; // Index of last element on "page" if(m_pageSize > 0 && peix < m_eix && peix < getModel().getRows()) { ml("rowDelete grow page: peix=" + peix + ", rrow=" + rrow); T mi = getModelItem(peix); TableRowSet<T> newSet = new TableRowSet<T>(this, mi); int lastIndex = m_pageSize - 1; m_visibleItemList.add(lastIndex, newSet); ColumnContainer<T> cc = new ColumnContainer<>(this); DataTableRow<T> tr = newSet.getPrimaryRow(); cc.setParent(tr); int bodyIndex = calculateBodyPosition(lastIndex); ml("rowDelete add at body index " + lastIndex); m_dataBody.add(lastIndex, tr); renderRow(tr, cc, peix, mi); } calcIndices(); // Calculate visible nodes handleOddEven(rrow); firePageChanged(); } catch(IndexOutOfBoundsException x) { System.err.println("Last DataTable actions:\n" + m_ml.getData()); throw new RuntimeException("Bug 7153 rowDelete index error " + x.getMessage() + "\n" + m_ml.getData(), x); } catch(Exception x) { System.err.println("Last DataTable actions:\n" + m_ml.getData()); throw x; } } /** * For all VisibleItems, this marks all of their rows as odd/even, starting at the specified index * till the end of the visible range. * * @param index */ private void handleOddEven(int index) { for(int ix = index; ix < m_visibleItemList.size(); ix++) { TableRowSet<T> rowSet = m_visibleItemList.get(ix); rowSet.markEven((ix & 0x1) == 0); } } /** * Merely force a full redraw of the appropriate row. * * @see ITableModelListener#rowModified(ITableModel, int, Object) */ @Override public void rowModified(@NonNull ITableModel<T> model, int index, @NonNull T value) throws Exception { if(!isBuilt()) return; if(index < m_six || index >= m_eix) // Outside visible bounds return; try { int rrow = index - m_six; // This is the location within the child array TableRowSet<T> rowSet = m_visibleItemList.get(rrow); for(DataTableRow<T> tableRow : rowSet) { tableRow.remove(); } rowSet = new TableRowSet<T>(this, value); m_visibleItemList.set(rrow, rowSet); // Replace with new rowSet ml("rowModified: index=" + index + ", rrow=" + rrow); TR tr = rowSet.getPrimaryRow(); int bodyIndex = calculateBodyPosition(rrow); m_dataBody.add(bodyIndex, tr); ColumnContainer<T> cc = new ColumnContainer<>(this); cc.setParent(tr); renderRow(tr, cc, index, value); } catch(Exception x) { System.err.println("Last DataTable actions:\n" + m_ml.getData()); throw x; } } public void setTableWidth(@Nullable String w) { m_table.setTableWidth(w); } @NonNull public IRowRenderer<T> getRowRenderer() { return m_rowRenderer; } public void setRowRenderer(@NonNull IRowRenderer<T> rowRenderer) { if(DomUtil.isEqual(m_rowRenderer, rowRenderer)) return; m_rowRenderer = rowRenderer; forceRebuild(); } @Override protected void onForceRebuild() { m_visibleItemList.clear(); ml("onForceRebuild, visiblesz cleared"); m_lastSelectionLocation = -1; super.onForceRebuild(); } /* CODING: ISelectionListener. */ /** * Called when a selection event fires. The underlying model has already been changed. It * tries to see if the row is currently paged in, and if so asks the row renderer to update * it's selection presentation. * * @see ISelectionListener#selectionChanged(Object, boolean) */ @Override public void selectionChanged(@NonNull T row, boolean on) throws Exception { //-- Is this a visible row? for(TableRowSet<T> tableRowSet : m_visibleItemList) { if(MetaManager.areObjectsEqual(row, tableRowSet.getInstance())) { updateSelectionChanged(row, tableRowSet, on); return; } } } /* CODING: Handling selections. */ /** * Called when a selection cleared event fires. The underlying model has already been changed. It * tries to see if the row is currently paged in, and if so asks the row renderer to update * it's selection presentation. */ @Override public void selectionAllChanged() throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(sm == null) throw new IllegalStateException("Got selection changed event but selection model is empty?"); //-- Is this a visible row? for(TableRowSet<T> tableRowSet : m_visibleItemList) { updateSelectionChanged(tableRowSet.getInstance(), tableRowSet, sm.isSelected(tableRowSet.getInstance())); } } public boolean isDisplayReadonlySelection() { return m_displayReadonlySelection; } public void setDisplayReadonlySelection(boolean displayReadonlySelection) { if(m_displayReadonlySelection == displayReadonlySelection) return; m_displayReadonlySelection = displayReadonlySelection; forceRebuild(); } /** * When T, the header of the table is always shown, even if the list of results is empty. * @return */ public boolean isShowHeaderAlways() { return m_showHeaderAlways; } /** * When T, the header of the table is always shown, even if the list of results is empty. * @param showHeaderAlways */ public void setShowHeaderAlways(boolean showHeaderAlways) { m_showHeaderAlways = showHeaderAlways; } public boolean isPreventRowHighlight() { return m_preventRowHighlight; } /** * When T, rows are not highlighted when table has no selection callbacks on rows. * * @param preventRowHighlight */ public void setPreventRowHighlight(boolean preventRowHighlight) { m_preventRowHighlight = preventRowHighlight; } /** * UNSTABLE INTERFACE - UNDER CONSIDERATION. * @param dataBody */ private void setDataBody(@NonNull TBody dataBody) { m_dataBody = dataBody; updateBodyClipboardSelection(); } @NonNull private TBody getDataBody() { if(null == m_dataBody) throw new IllegalStateException("dataBody is still null"); return m_dataBody; } /** * Return the backing table for this data browser. For component extension only - DO NOT MAKE PUBLIC. * @return */ @NonNull protected Table getTable() { if(null == m_table) throw new IllegalStateException("Backing table is still null"); return m_table; } @Override public boolean isMultiSelectionVisible() { return m_multiSelectMode; } /** * Return the page size: the #of records to show. If &lt;= 0 all records are shown. */ @Override public int getPageSize() { return m_pageSize; } /** * Set the page size: the #of records to show. If &lt;= 0 all records are shown. * * @param pageSize */ public void setPageSize(int pageSize) { if(m_pageSize == pageSize) return; m_pageSize = pageSize; forceRebuild(); firePageChanged(); } private void checkVisible(TableRowSet<T> rowSet) { if(! m_visibleItemList.contains(rowSet)) throw new IllegalStateException("The row set is no longer visible"); } public boolean isVisible(TableRowSet<T> rowSet) { return m_visibleItemList.contains(rowSet); } void appendExtraRowAfter(TableRowSet<T> rowSet, DataTableRow<T> newRow, DataTableRow<T> row) { checkVisible(rowSet); row.appendAfterMe(newRow); } void appendExtraRowBefore(TableRowSet<T> rowSet, DataTableRow<T> newRow, DataTableRow<T> row) { checkVisible(rowSet); row.appendBeforeMe(newRow); } @NonNull public DataTableResize getResizeMode() { return m_resizeMode; } public void setResizeMode(@NonNull DataTableResize resize) { m_resizeMode = resize; } /** * Gets called when column widths have been altered. This retrieves all columns that were changed * and saves the widths so that a next render will reuse the sizes. */ public void webActionCOLWIDTHS(@NonNull RequestContextImpl context) throws Exception { m_rowRenderer.updateWidths(this, context); } @Override public void setHint(String hintText) { } @Override public void onRemoveFromPage(Page p) { super.onRemoveFromPage(p); silentThrows(()->{ DomUtil.walkTree(this, new IPerNode() { @Override public Object before(@NonNull NodeBase n) throws Exception { if(n != null && n.getTestID() != null) { p.dealocateTestId(n.getTestID()); } return null; } @Override public Object after(@NonNull NodeBase n) throws Exception { return null; } }); }); } }
package to.etc.domui.component.tbl; import to.etc.domui.component.meta.*; import to.etc.domui.dom.css.*; import to.etc.domui.dom.html.*; import to.etc.domui.server.*; import to.etc.domui.util.*; import javax.annotation.*; import java.util.*; final public class ScrollableDataTable<T> extends SelectableTabularComponent<T> implements ISelectionListener<T>, ISelectableTableComponent<T> { static private final boolean DEBUG = false; private IRowRenderer<T> m_rowRenderer; @Nullable private Table m_dataTable; /** If a result is visible this is the data table */ private TBody m_dataBody; /** When the query has 0 results this is set to the div displaying that message. */ private Div m_errorDiv; /** The items that are currently on-screen, to prevent a reload from the model when reused. */ final private List<T> m_visibleItemList = new ArrayList<T>(); /** When set, the table is in "multiselect" mode and shows checkboxes before all rows. */ private boolean m_multiSelectMode; /** When selecting, this is the last index that was used in a select click.. */ private int m_lastSelectionLocation = -1; /** The last index rendered. */ private int m_nextIndexToLoad; private int m_batchSize = 80; private boolean m_allRendered; @Nonnull final private IClicked<TH> m_headerSelectClickHandler = new IClicked<TH>() { @Override public void clicked(@Nonnull TH clickednode) throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(null == sm) return; int ct = sm.getSelectionCount(); if(0 == ct && sm.isMultiSelect()) { sm.selectAll(getModel()); } else { sm.clearSelection(); } } }; private boolean m_redrawn; public ScrollableDataTable(@Nonnull ITableModel<T> m, @Nonnull IRowRenderer<T> r) { super(m); m_rowRenderer = r; } public ScrollableDataTable(@Nonnull IRowRenderer<T> r) { m_rowRenderer = r; } public ScrollableDataTable(@Nonnull ITableModel<T> m) { super(m); } public ScrollableDataTable() {} @Override public void createContent() throws Exception { m_dataTable = null; m_dataBody = null; m_errorDiv = null; m_allRendered = false; addCssClass("ui-dt"); setOverflow(Overflow.AUTO); m_nextIndexToLoad = 0; //-- Do we need to render multiselect checkboxes? ISelectionModel<T> sm = getSelectionModel(); if(sm != null) { if(isShowSelectionAlways() || sm.getSelectionCount() > 0) { m_multiSelectMode = sm.isMultiSelect(); } else { m_multiSelectMode = false; } } //-- Ask the renderer for a sort order, if applicable if(m_rowRenderer == null) throw new IllegalStateException("There is no row renderer assigned to the table"); m_rowRenderer.beforeQuery(this); // ORDER!! BEFORE CALCINDICES or any other call that materializes the result. if(getModel().getRows() == 0) { setNoResults(); return; } setResults(); loadMoreData(); if(isDisableClipboardSelection()) appendCreateJS(JavascriptUtil.disableSelection(this)); // Needed to prevent ctrl+click in IE doing clipboard-select, because preventDefault does not work there of course. if(m_redrawn) { appendJavascript("WebUI.scrollableTableReset('" + getActualID() + "','" + tbl().getActualID() + "');"); } else { appendCreateJS("WebUI.initScrollableTable('" + getActualID() + "','" + tbl().getActualID() + "');"); m_redrawn = true; } } @Nonnull private Table tbl() { Table t = m_dataTable; if(null == t) throw new IllegalStateException("Access to table while unbuilt?"); return t; } private void loadMoreData() throws Exception { if(m_allRendered) { System.err.println("domui: ScrollableDataTable got unexpected loadMoreData"); return; } int rows = getModel().getRows(); if(m_nextIndexToLoad >= rows) { System.err.println("domui: ScrollableDataTable got unexpected loadMoreData and allrendered is false!?"); return; } //-- Get the next batch int six = m_nextIndexToLoad; int eix = six + m_batchSize; if(eix > rows) eix = rows; List<T> list = getModel().getItems(six, eix); //-- Render the rows. ColumnContainer<T> cc = new ColumnContainer<T>(this); int ix = six; for(T o : list) { m_visibleItemList.add(o); TR tr = new TR(); m_dataBody.add(tr); tr.setTestRepeatID("r" + ix); cc.setParent(tr); renderRow(tr, cc, ix, o); ix++; } m_nextIndexToLoad = eix; if(ix >= getModel().getRows()) { renderFinalRow(); } if(DEBUG) System.out.println("rendered till "+ m_nextIndexToLoad); } private void rerender() throws Exception { if(! isBuilt() || m_dataBody == null) return; m_nextIndexToLoad = 0; m_dataBody.removeAllChildren(); m_allRendered = false; loadMoreData(); appendJavascript("WebUI.scrollableTableReset('" + getActualID() + "','" + tbl().getActualID() + "');"); } private void renderFinalRow() { TBody dataBody = m_dataBody; if(null == dataBody) throw new IllegalStateException("No data body?"); int colspan = 1; if(dataBody.getChildCount() > 0) { TR row = dataBody.getRow(dataBody.getChildCount()-1); colspan = row.getChildCount(); if(colspan == 0) colspan = 1; } m_allRendered = true; TR row = new TR(); dataBody.add(row); TD cell = new TD(); row.add(cell); cell.setColspan(colspan); row.setSpecialAttribute("lastRow", "true"); //cell.setText("All records loaded"); } private List<T> getPageItems() throws Exception { return getModel().getItems(0, m_nextIndexToLoad); } @SuppressWarnings("deprecation") private void setResults() throws Exception { if(m_errorDiv != null) { m_errorDiv.remove(); m_errorDiv = null; } if(m_dataBody != null) return; Table dataTable = m_dataTable = new Table(); add(dataTable); dataTable.setCssClass("ui-dt-ovflw-tbl"); //-- Render the header. THead hd = new THead(); dataTable.add(hd); HeaderContainer<T> hc = new HeaderContainer<T>(this, hd, "ui-dt-hdr"); renderHeader(hc); if(!hc.hasContent()) { hd.remove(); } m_dataBody = new TBody(); dataTable.add(m_dataBody); } /** * DO NOT OVERRIDE - INTERNAL ONLY - DEPRECATED FOR EXTERNAL USE!! * * Renders the table header. If we're in multiselect mode the first column will be * added as a checkbox column. The rest of the columns is delegated to the row * renderer in use. * * @param hc specified header container * @throws Exception */ @Deprecated private void renderHeader(@Nonnull HeaderContainer<T> hc) throws Exception { //-- Are we rendering a multi-selection? if(m_multiSelectMode) { TH headerCell = hc.add(""); headerCell.add(new Img("THEME/dspcb-on.png")); headerCell.setTestID("dt_select_all"); headerCell.setWidth("1%"); //keep selection column with minimal width headerCell.setClicked(m_headerSelectClickHandler); headerCell.setCssClass("ui-clickable"); } m_rowRenderer.renderHeader(this, hc); } /** * Removes any data table, and presents the "no results found" div. */ private void setNoResults() { m_visibleItemList.clear(); if(m_errorDiv != null) return; Table dataTable = m_dataTable; if(dataTable != null) { dataTable.removeAllChildren(); dataTable.remove(); m_dataBody = null; m_dataTable = null; } m_errorDiv = new Div(); m_errorDiv.setCssClass("ui-dt-nores"); m_errorDiv.setText(Msgs.BUNDLE.getString(Msgs.UI_DATATABLE_EMPTY)); add(m_errorDiv); return; } /* CODING: Row rendering & select click handling. */ /** * DO NOT OVERRIDE - DEPRECATED FOR EXTERNAL USE!! * Renders row content into specified row. * * @param cc * @param index * @param value * @throws Exception */ @SuppressWarnings("deprecation") private void renderRow(@Nonnull final TR tr, @Nonnull ColumnContainer<T> cc, int index, @Nonnull final T value) throws Exception { //-- Is a rowclick handler needed? ISelectionModel<T> sm = getSelectionModel(); if(m_rowRenderer.getRowClicked() != null || null != sm) { //-- Add a click handler to select or pass the rowclicked event. cc.getTR().setClicked(new IClicked2<TR>() { @Override @SuppressWarnings({"synthetic-access"}) public void clicked(@Nonnull TR b, @Nonnull ClickInfo clinfo) throws Exception { handleRowClick(b, value, clinfo); } }); cc.getTR().addCssClass("ui-rowsel"); } //-- If we're in multiselect mode show the select boxes if(m_multiSelectMode && sm != null) { Checkbox cb = createSelectionCheckbox(value, sm); TD td = cc.add(cb); if(cb.isReadOnly()) { td.addCssClass("ui-cur-default"); } boolean issel = sm.isSelected(value); cb.setChecked(issel); if(issel) tr.addCssClass("mselected"); else tr.removeCssClass("mselected"); } internalRenderRow(tr, cc, index, value); } /** * Must exist for CheckBoxDataTable; remove asap AND DO NOT USE AGAIN - internal interfaces should remain hidden. * @param tr * @param cc * @param index * @param value * @throws Exception */ @Deprecated private void internalRenderRow(@Nonnull final TR tr, @Nonnull ColumnContainer<T> cc, int index, @Nonnull final T value) throws Exception { m_rowRenderer.renderRow(this, cc, index, value); } /** * Click handler for rows. This handles both row clicked handling and row selection handling. * * @param tbl * @param b * @param instance * @param clinfo * @throws Exception */ private void handleRowClick(final TR b, final T instance, final ClickInfo clinfo) throws Exception { //-- If we have a selection model: check if this is some selecting clicky. ISelectionModel<T> selectionModel = getSelectionModel(); if(selectionModel != null) { //-- Treat clicks with ctrl or shift as selection clickies if(clinfo.isControl() || clinfo.isShift()) { handleSelectClicky(instance, clinfo, null); return; // Do NOT fire on selection clickies. } else { if(! selectionModel.isMultiSelect()) { handleSelectClicky(instance, clinfo, null); } } } //-- If this has a click handler- fire it. ICellClicked< ? > rowClicked = m_rowRenderer.getRowClicked(); if(null != rowClicked) ((ICellClicked<T>) rowClicked).cellClicked(b, instance); } /** * When checkbox itself is clicked, this handles shift stuff. * @param instance * @param checked * @param info * @param clickednode * @throws Exception */ private void selectionCheckboxClicked(T instance, boolean checked, ClickInfo info, @Nonnull Checkbox checkbox) throws Exception { handleSelectClicky(instance, info, Boolean.valueOf(checked)); ISelectionModel<T> sm = getSelectionModel(); if(null != sm) { checkbox.setChecked(sm.isSelected(instance)); } } /** * Handle a click that is meant to select/deselect the item(s). It handles ctrl+click as "toggle selection", * and shift+click as "toggle everything between this and the last one". * * @param instance * @param clinfo * @param setTo When null toggle, else set to specific. */ private void handleSelectClicky(@Nonnull T instance, @Nonnull ClickInfo clinfo, @Nullable Boolean setTo) throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(null == sm) throw new IllegalStateException("SelectionModel is null??"); boolean nvalue = setTo != null ? setTo.booleanValue() : !sm.isSelected(instance); if(!clinfo.isShift()) { sm.setInstanceSelected(instance, nvalue); m_lastSelectionLocation = -1; return; } //-- Toggle region. Get the current item's index. int itemindex = -1, index = 0; for(T item : m_visibleItemList) { if(MetaManager.areObjectsEqual(item, instance)) { itemindex = index; break; } index++; } if(itemindex == -1) // Ignore when thingy not found return; //-- Is a previous location set? If not: just toggle the current and retain the location. if(m_lastSelectionLocation == -1) { //-- Start of region.... m_lastSelectionLocation = itemindex; sm.setInstanceSelected(instance, !sm.isSelected(instance)); return; } //-- We have a previous location- we need to toggle all instances; int sl, el; if(m_lastSelectionLocation < itemindex) { sl = m_lastSelectionLocation + 1; // Exclusive el = itemindex + 1; } else { sl = itemindex; el = m_lastSelectionLocation; // Exclusive } //-- Now toggle all instances, in batches, to prevent loading 1000+ records that cannot be gc'd. for(int i = sl; i < el;) { int ex = i + 50; if(ex > el) ex = el; List<T> sub = getModel().getItems(i, ex); i += ex; for(T item : sub) { if(item == null) throw new IllegalStateException("null item in list"); sm.setInstanceSelected(item, !sm.isSelected(item)); } } m_lastSelectionLocation = -1; } /* CODING: Selection UI update handling. */ /** * Updates the "selection" state of the specified local row#. * @param instance * @param i * @param on */ private void updateSelectionChanged(T instance, int lrow, boolean on) throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(sm == null) throw new IllegalStateException("No selection model!?"); TR row = (TR) m_dataBody.getChild(lrow); THead head = tbl().getHead(); if(null == head) throw new IllegalStateException("I've lost my head!?"); TR headerrow = (TR) head.getChild(0); if(!sm.isMultiSelect()) { //-- Single selection model. Just add/remove the "selected" class from the row. if(on) row.addCssClass("selected"); else row.removeCssClass("selected"); return; } /* * In multiselect. If the multiselect UI is not visible we check if we are switching * ON, else there we can exit. If we switch ON we add the multiselect UI if not * yet present. Then we set/reset the checkbox for the row. */ if(!m_multiSelectMode) { if(!on) // No UI yet, but this is a deselect so let it be return; //-- Render the multiselect UI: add the header cell and row cells. createMultiselectUI(headerrow); } //-- The checkbox is in cell0; get it and change it's value if (still) needed TD td = (TD) row.getChild(0); Checkbox cb = (Checkbox) td.getChild(0); if(cb.isChecked() != on) // Only change if not already correct cb.setChecked(on); if(on) row.addCssClass("mselected"); else row.removeCssClass("mselected"); } /** * Make the multiselect UI for all visible rows and the header. */ private void createMultiselectUI(TR headerrow) { if(m_multiSelectMode) return; m_multiSelectMode = true; //-- 1. Add the select TH. TD th = new TH(); th.add(new Img("THEME/dspcb-on.png")); th.setTestID("dt_select_all"); th.setWidth("1%"); headerrow.add(0, th); th.setClicked(m_headerSelectClickHandler); th.setCssClass("ui-clickable"); //-- 2. Insert a checkbox in all rows. for(int i = 0; i < m_dataBody.getChildCount(); i++) { final T instance = m_visibleItemList.get(i); TR tr = (TR) m_dataBody.getChild(i); TD td = new TD(); tr.add(0, td); Checkbox cb = createSelectionCheckbox(instance, getSelectionModel()); if(cb.isReadOnly()) { td.addCssClass("ui-cur-default"); } td.add(cb); cb.setChecked(false); } fireSelectionUIChanged(); } @Override protected void createSelectionUI() throws Exception { THead head = tbl().getHead(); if(null == head) throw new IllegalStateException("I've lost my head!?"); TR headerrow = (TR) head.getChild(0); createMultiselectUI(headerrow); } @Override public boolean isMultiSelectionVisible() { return m_multiSelectMode; } /* CODING: ITableModelListener implementation */ /** * Called when there are sweeping changes to the model. It forces a complete re-render of the table. */ @Override public void modelChanged(@Nullable ITableModel<T> model) throws Exception { rerender(); fireModelChanged(null, model); } /** * Row add. Determine if the row is within the paged-in indexes. If not we ignore the * request. If it IS within the paged content we insert the new TR. Since this adds a * new row to the visible set we check if the resulting rowset is not bigger than the * page size; if it is we delete the last node. After all this the renderer will render * the correct result. * When called the actual insert has already taken place in the model. * * @see to.etc.domui.component.tbl.ITableModelListener#rowAdded(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ @Override public void rowAdded(@Nonnull ITableModel<T> model, int index, @Nonnull T value) throws Exception { if(!isBuilt()) return; calcIndices(); // Calculate visible nodes if(DEBUG) System.out.println("dd: add@ "+index+", eix="+ m_nextIndexToLoad); if(index < 0 || (index >= m_nextIndexToLoad && m_nextIndexToLoad >= m_batchSize)) { // Outside visible bounds & no need to load more firePageChanged(); return; } //-- What relative row? setResults(); int rrow = index; // This is the location within the child array ColumnContainer<T> cc = new ColumnContainer<>(this); TR tr = new TR(); m_dataBody.add(rrow, tr); cc.setParent(tr); tr.setTestRepeatID("r" + index); renderRow(tr, cc, index, value); m_visibleItemList.add(rrow, value); //-- Do we need to increase the nextIndexToLoad? if(m_nextIndexToLoad < m_batchSize) { if(m_visibleItemList.size() > m_nextIndexToLoad) m_nextIndexToLoad = m_visibleItemList.size(); } else if(m_visibleItemList.size() > m_nextIndexToLoad && m_nextIndexToLoad >= m_batchSize) { //-- Delete the last row. int delindex = m_visibleItemList.size() - 1; m_visibleItemList.remove(delindex); m_dataBody.removeChild(delindex); } handleOddEven(rrow); firePageChanged(); } /** * Delete the row specified. If it is not visible we do nothing. If it is visible we * delete the row. This causes one less row to be shown, so we check if we have a pagesize * set; if so we add a new row at the end IF it is available. * * @see to.etc.domui.component.tbl.ITableModelListener#rowDeleted(to.etc.domui.component.tbl.ITableModel, int, Object) */ @Override public void rowDeleted(@Nonnull ITableModel<T> model, int index, @Nonnull T value) throws Exception { if(!isBuilt()) return; //-- We need the indices of the OLD data, so DO NOT RECALCULATE - the model size has changed. if(DEBUG) System.out.println("dd: delete index="+index+", eix="+ m_nextIndexToLoad); if(index < 0 || index >= m_nextIndexToLoad) { // Outside visible bounds calcIndices(); // Calculate visible nodes firePageChanged(); return; } int rrow = index; // This is the location within the child array m_dataBody.removeChild(rrow); // Discard this one; m_visibleItemList.remove(rrow); if(m_dataBody.getChildCount() == 0) { calcIndices(); // Calculate visible nodes setNoResults(); firePageChanged(); return; } //-- One row gone; must we add one at the end? if(index < m_nextIndexToLoad && m_nextIndexToLoad <= getModel().getRows()) { ColumnContainer<T> cc = new ColumnContainer<T>(this); TR tr = new TR(); cc.setParent(tr); T mi = getModelItem(m_nextIndexToLoad -1); // Because of delete the item to show has become "visible" in the model @ the last index if(DEBUG) System.out.println("dd: Add item#"+ m_nextIndexToLoad +" @ "+(m_nextIndexToLoad -1)); m_dataBody.add(m_nextIndexToLoad -1, tr); renderRow(tr, cc, m_nextIndexToLoad -1, mi); m_visibleItemList.add(m_nextIndexToLoad -1, mi); } if(m_nextIndexToLoad > getModel().getRows()) { m_nextIndexToLoad = getModel().getRows(); if(DEBUG) System.out.println("dd: decrement size of loaded data eix="+ m_nextIndexToLoad); } if(DEBUG) System.out.println("dd: sizes "+getModel().getRows()+" "+m_dataBody.getChildCount()+", "+m_visibleItemList.size()+", eix="+ m_nextIndexToLoad); calcIndices(); // Calculate visible nodes handleOddEven(rrow); firePageChanged(); } private void calcIndices() {} private void handleOddEven(int index) { for(int ix = index; ix < m_dataBody.getChildCount(); ix++) { TR tr = (TR) m_dataBody.getChild(ix); if((ix & 0x1) == 0) { //-- Even tr.removeCssClass("ui-odd"); tr.addCssClass("ui-even"); } else { tr.addCssClass("ui-odd"); tr.removeCssClass("ui-even"); } } } /** * Merely force a full redraw of the appropriate row. * * @see to.etc.domui.component.tbl.ITableModelListener#rowModified(to.etc.domui.component.tbl.ITableModel, int, java.lang.Object) */ @Override public void rowModified(@Nonnull ITableModel<T> model, int index, @Nonnull T value) throws Exception { if(!isBuilt()) return; if(index < 0 || index >= m_nextIndexToLoad) // Outside visible bounds return; int rrow = index; // This is the location within the child array TR tr = (TR) m_dataBody.getChild(rrow); // The visible row there tr.removeAllChildren(); // Discard current contents. m_visibleItemList.set(rrow, value); ColumnContainer<T> cc = new ColumnContainer<T>(this); cc.setParent(tr); renderRow(tr, cc, index, value); } public void setTableWidth(@Nullable String w) { tbl().setTableWidth(w); } @Nonnull public IRowRenderer<T> getRowRenderer() { return m_rowRenderer; } public void setRowRenderer(@Nonnull IRowRenderer<T> rowRenderer) { if(DomUtil.isEqual(m_rowRenderer, rowRenderer)) return; m_rowRenderer = rowRenderer; forceRebuild(); } @Override protected void onForceRebuild() { m_visibleItemList.clear(); m_lastSelectionLocation = -1; super.onForceRebuild(); } /* CODING: ISelectionListener. */ /** * Called when a selection event fires. The underlying model has already been changed. It * tries to see if the row is currently paged in, and if so asks the row renderer to update * it's selection presentation. * * @see to.etc.domui.component.tbl.ISelectionListener#selectionChanged(java.lang.Object, boolean) */ @Override public void selectionChanged(@Nonnull T row, boolean on) throws Exception { //-- Is this a visible row? for(int i = 0; i < m_visibleItemList.size(); i++) { if(MetaManager.areObjectsEqual(row, m_visibleItemList.get(i))) { updateSelectionChanged(row, i, on); return; } } } /* CODING: Handling selections. */ /** * Called when a selection cleared event fires. The underlying model has already been changed. It * tries to see if the row is currently paged in, and if so asks the row renderer to update * it's selection presentation. */ @Override public void selectionAllChanged() throws Exception { ISelectionModel<T> sm = getSelectionModel(); if(sm == null) throw new IllegalStateException("Got selection changed event but selection model is empty?"); //-- Is this a visible row? for(int i = 0; i < m_visibleItemList.size(); i++) { T item = m_visibleItemList.get(i); updateSelectionChanged(item, i, sm.isSelected(item)); } } @Nonnull private Checkbox createSelectionCheckbox(@Nonnull final T rowInstance, @Nullable ISelectionModel<T> selectionModel) { Checkbox cb = new Checkbox(); boolean selectable = true; if(selectionModel instanceof IAcceptable) { selectable = ((IAcceptable<T>) selectionModel).acceptable(rowInstance); } if(selectable) { cb.setClicked(new IClicked2<Checkbox>() { @Override public void clicked(@Nonnull Checkbox clickednode, @Nonnull ClickInfo info) throws Exception { selectionCheckboxClicked(rowInstance, clickednode.isChecked(), info, clickednode); } }); } else { cb.setReadOnly(true); } return cb; } @Override public void componentHandleWebAction(@Nonnull RequestContextImpl ctx, @Nonnull String action) throws Exception { if("LOADMORE".equals(action)) { loadMoreData(); return; } super.componentHandleWebAction(ctx, action); } /** * The number of records to load every time new data is needed. Should be enough to provide (a bit more than) an entire page of data. * @return */ public int getBatchSize() { return m_batchSize; } public void setBatchSize(int batchSize) { m_batchSize = batchSize; } }
package com.torodb.translator; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.torodb.kvdocument.conversion.mongo.MongoTypeConverter; import com.torodb.kvdocument.conversion.mongo.MongoValueConverter; import com.torodb.kvdocument.types.DocType; import com.torodb.kvdocument.types.ObjectType; import com.torodb.kvdocument.values.DocValue; import com.torodb.torod.core.exceptions.ToroImplementationException; import com.torodb.torod.core.exceptions.UserToroException; import com.torodb.torod.core.language.AttributeReference; import com.torodb.torod.core.language.querycriteria.*; import com.torodb.torod.core.language.querycriteria.utils.ConjunctionBuilder; import com.torodb.torod.core.language.querycriteria.utils.DisjunctionBuilder; import com.torodb.torod.core.language.querycriteria.utils.EqualFactory; import com.torodb.torod.core.subdocument.BasicType; import com.torodb.torod.core.subdocument.values.ArrayValue; import com.torodb.torod.core.subdocument.values.IntegerValue; import com.torodb.torod.core.subdocument.values.ValueFactory; import java.util.*; import java.util.regex.Pattern; import javax.annotation.Nonnull; import org.bson.BSONObject; public class BasicQueryTranslator { /** * Generates a basic torodb query from a mongodb query. * <p> * Given a mongodb query, its basic torodb query is the one that returns the * following subset of the original query: * <ol> * <li>All input attribute references are treated as * {@linkplain AttributeReference.ObjectKey object keys}. This doesn't mean * that all output attribute references are like object keys. Attribute * references generated as the body of an equality operation can contain * {@linkplain AttributeReferece.Arraykey array key} if the original * equality value contains an array that contains an object</li> * <li>Attribute references are strict, in other words: the semantic used by * mongodb that translate attribute references to something like <em>this * sub attribute reference points to an array that contains an object that * evaluates to true the same condition with the rest of the attribute * reference</em> is ignored</li> * </ol> * <p> * @param queryObject * @return * @throws UserToroException */ public QueryCriteria translate( BSONObject queryObject ) throws UserToroException { return translateImplicitAnd(AttributeReference.EMPTY_REFERENCE, queryObject); } private AttributeReference translateObjectAttributeReference( @Nonnull AttributeReference attRefAcum, @Nonnull String key ) { if (key.isEmpty()) { return attRefAcum; } ImmutableList.Builder<AttributeReference.Key> newKeysBuilder = ImmutableList.<AttributeReference.Key>builder(). addAll(attRefAcum.getKeys()); StringTokenizer st = new StringTokenizer(key, "."); while (st.hasMoreTokens()) { newKeysBuilder.add(new AttributeReference.ObjectKey(st.nextToken())); } return new AttributeReference(newKeysBuilder.build()); } private QueryCriteria translateImplicitAnd( @Nonnull AttributeReference attRefAcum, @Nonnull BSONObject exp ) throws UserToroException { Set<String> keys = exp.keySet(); if (keys.isEmpty()) { return TrueQueryCriteria.getInstance(); } if (keys.size() == 1) { String key = keys.iterator(). next(); Object uncastedArg = exp.get(key); return translateExp(attRefAcum, key, uncastedArg); } ConjunctionBuilder conjunctionBuilder = new ConjunctionBuilder(); //TODO: Constraint merged ands, ors, nors and subqueries and equalities for (String key : keys) { Object uncastedArg = exp.get(key); conjunctionBuilder.add(translateExp(attRefAcum, key, uncastedArg)); } return conjunctionBuilder.build(); } private QueryCriteria translateExp( @Nonnull AttributeReference attRefAcum, @Nonnull String key, @Nonnull Object uncastedArg ) throws UserToroException { switch (getExpressionType(key, uncastedArg)) { case AND_OR_NOR: { if (isAnd(key)) { return translateAndOperand(attRefAcum, uncastedArg); } if (isOr(key)) { return translateOrOperand(attRefAcum, uncastedArg); } if (isNor(key)) { return translateNorOperand(attRefAcum, uncastedArg); } throw new ToroImplementationException("Unexpected operation"); } case EQUALITY: { AttributeReference newAttRefAcum = translateObjectAttributeReference(attRefAcum, key); return translateEquality(newAttRefAcum, uncastedArg); } case SUB_EXP: { AttributeReference newAttRefAcum = translateObjectAttributeReference(attRefAcum, key); return translateSubQueries(newAttRefAcum, uncastedArg); } case INVALID: default: { throw new UserToroException("The query {" + key + ": " + uncastedArg + "} is not a valid top level expression"); } } } private ExpressionType getExpressionType( @Nonnull String key, @Nonnull Object uncastedArg ) { if (isAnd(key) || isOr(key) || isNor(key)) { return ExpressionType.AND_OR_NOR; } if (isSubQuery(key)) { return ExpressionType.INVALID; } if (!(uncastedArg instanceof BSONObject)) { return ExpressionType.EQUALITY; } Set<String> keySet = ((BSONObject) uncastedArg).keySet(); boolean oneSubQuery = false; boolean oneNoSubQuery = false; for (String subKey : keySet) { if (isSubQuery(subKey)) { oneSubQuery |= true; } else { oneNoSubQuery |= true; } } if (!oneSubQuery) { return ExpressionType.EQUALITY; } if (oneNoSubQuery) { return ExpressionType.INVALID; } return ExpressionType.SUB_EXP; } private boolean isAnd( @Nonnull String key ) { return key.equals("$and"); } private boolean isOr( @Nonnull String key ) { return key.equals("$or"); } private boolean isNor( @Nonnull String key) { return key.equals("$nor"); } private boolean isSubQuery(@Nonnull String key) { return QueryOperator.isSubQuery(key); } private boolean isSubQuery(@Nonnull Object uncastedArg) { if (!(uncastedArg instanceof BSONObject)) { return false; } Set<String> keySet = ((BSONObject) uncastedArg).keySet(); if (keySet.isEmpty()) { return false; } for (String key : keySet) { if (!isSubQuery(key)) { return false; } } return true; } private QueryCriteria translateAndOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg ) throws UserToroException { if (!(uncastedArg instanceof List)) { throw new UserToroException( "$and operand requires an array of json objects, but " + uncastedArg + " is " + "recived"); } ConjunctionBuilder buidler = new ConjunctionBuilder(); List argument = (List) uncastedArg; for (Object object : argument) { if (object == null || !(object instanceof BSONObject)) { throw new UserToroException( "$and operand requires an array of json objects, but " + argument + " contains " + object + ", that is not a json object"); } buidler.add(translateImplicitAnd(attRefAcum, (BSONObject) object)); } return buidler.build(); } private QueryCriteria translateOrOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg ) throws UserToroException { if (!(uncastedArg instanceof List)) { throw new UserToroException( "$or operand requires an array of json objects, but " + uncastedArg + " has been " + "recived"); } List argument = (List) uncastedArg; if (argument.isEmpty()) { throw new UserToroException( "$or operands requires a nonempty array, but an empty one has been recived"); } DisjunctionBuilder buidler = new DisjunctionBuilder(); for (Object object : argument) { if (object == null || !(object instanceof BSONObject)) { throw new UserToroException( "$and operand requires an array of json objects, but " + argument + " contains " + object + ", that is not a json object"); } buidler.add(translateImplicitAnd(attRefAcum, (BSONObject) object)); } return buidler.build(); } private QueryCriteria translateNorOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg ) throws UserToroException { //http://docs.mongodb.org/manual/reference/operator/query/nor/#op._S_nor if (!(uncastedArg instanceof List)) { throw new UserToroException("$nor needs an array"); } List value = (List) uncastedArg; if (value.isEmpty()) { throw new UserToroException("$nor must not be a nonempty array"); } return new NotQueryCriteria( translateOrOperand(attRefAcum, value) ); } private QueryCriteria translateEquality( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg ) { DocValue value = MongoValueConverter.translateBSON(uncastedArg); return EqualFactory.createEquality(attRefAcum, value); } private QueryCriteria translateSubQueries( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg ) throws UserToroException { if (!(uncastedArg instanceof BSONObject)) { throw new ToroImplementationException("A bson object was expected"); } BSONObject arg = (BSONObject) uncastedArg; if (arg.keySet().size() == 1) { String key = arg.keySet(). iterator(). next(); return translateSubQuery(attRefAcum, key, arg.get(key)); } else { ConjunctionBuilder cb = new ConjunctionBuilder(); for (String key : arg.keySet()) { cb.add( translateSubQuery(attRefAcum, key, arg.get(key)) ); } return cb.build(); } } private QueryCriteria translateSubQuery( @Nonnull AttributeReference attRefAcum, @Nonnull String key, @Nonnull Object uncastedArg ) throws UserToroException { switch (QueryOperator.fromKey(key)) { case GT_KEY: return translateGtOperand(attRefAcum, uncastedArg); case GTE_KEY: return translateGteOperand(attRefAcum, uncastedArg); case LT_KEY: return translateLtOperand(attRefAcum, uncastedArg); case LTE_KEY: return translateLteOperand(attRefAcum, uncastedArg); case NE_KEY: return translateNeOperand(attRefAcum, uncastedArg); case IN_KEY: return translateInOperand(attRefAcum, uncastedArg); case NIN_KEY: return translateNinOperand(attRefAcum, uncastedArg); case NOT_KEY: return translateNotOperand(attRefAcum, uncastedArg); case EXISTS_KEY: return translateExistsOperand(attRefAcum, uncastedArg); case TYPE_KEY: return translateTypeOperand(attRefAcum, uncastedArg); case MOD_KEY: return translateModOperand(attRefAcum, uncastedArg); case REGEX_KEY: return translateRegexOperand(attRefAcum, uncastedArg); case TEXT_KEY: return translateTextOperand(attRefAcum, uncastedArg); case WHERE_KEY: return translateWhereOperand(attRefAcum, uncastedArg); case ALL_KEY: return translateAllOperand(attRefAcum, uncastedArg); case ELEM_MATCH_KEY: return translateElemMatchOperand(attRefAcum, uncastedArg); case SIZE_KEY: return translateSizeOperand(attRefAcum, uncastedArg); case GEO_WITHIN_KEY: case GEO_INTERSECTS_KEY: case NEAR_KEY: case NEAR_SPHERE_KEY: default: return translateUnsupportedOperation(attRefAcum, uncastedArg); } } private QueryCriteria translateUnsupportedOperation( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { throw new UserToroException("The operation " + uncastedArg + " is not supported right now"); } private QueryCriteria translateGtOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new IsGreaterQueryCriteria( attRefAcum, ValueFactory.fromDocValue(docValue) ); } private QueryCriteria translateGteOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new IsGreaterOrEqualQueryCriteria( attRefAcum, ValueFactory.fromDocValue(docValue) ); } private QueryCriteria translateLtOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new IsLessQueryCriteria( attRefAcum, ValueFactory.fromDocValue(docValue) ); } private QueryCriteria translateLteOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new IsLessOrEqualQueryCriteria( attRefAcum, ValueFactory.fromDocValue(docValue) ); } private QueryCriteria translateNeOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new NotQueryCriteria( EqualFactory.createEquality( attRefAcum, docValue ) ); } private QueryCriteria translateInOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { if (!(uncastedArg instanceof List)) { throw new ToroImplementationException("$in needs an array"); } DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new InQueryCriteria( attRefAcum, (ArrayValue) ValueFactory.fromDocValue(docValue) ); } private QueryCriteria translateNinOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { if (!(uncastedArg instanceof List)) { throw new ToroImplementationException("$in needs an array"); } DocValue docValue = MongoValueConverter.translateBSON(uncastedArg); return new NotQueryCriteria( new InQueryCriteria( attRefAcum, (ArrayValue) ValueFactory.fromDocValue(docValue) ) ); } private QueryCriteria translateNotOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof BSONObject)) { if (uncastedArg instanceof Pattern) { throw new ToroImplementationException( "Regex are not supported right now"); } throw new UserToroException( "$not needs a regex (not supported right now) or document"); } return new NotQueryCriteria( translateSubQueries(attRefAcum, uncastedArg) ); } private QueryCriteria translateExistsOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof Boolean)) { throw new UserToroException("$exists needs a boolean"); } Boolean positive = (Boolean) uncastedArg; List<AttributeReference.Key> keys = attRefAcum.getKeys(); AttributeReference target; switch (keys.size()) { case 0: { throw new UserToroException( "$exists needs a not-empty attribute reference"); } case 1: { target = AttributeReference.EMPTY_REFERENCE; break; } default: { target = attRefAcum.subReference(0, keys.size() - 1); break; } } assert !keys.isEmpty(); AttributeReference.Key lastKey = keys.get(keys.size() - 1); if (!(lastKey instanceof AttributeReference.ObjectKey)) { throw new UserToroException( "$exists needs an object key as last attribute reference key"); } String lastKeyName = ((AttributeReference.ObjectKey) lastKey).getKey(); QueryCriteria result = new ContainsAttributesQueryCriteria( target, Collections.singleton(lastKeyName), false ); if (!positive) { return new NotQueryCriteria(result); } return result; } private QueryCriteria translateTypeOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof Integer)) { throw new UserToroException("$type needs an integer"); } Integer value = (Integer) uncastedArg; DocType dt = MongoTypeConverter.translateType(value); if (dt.equals(ObjectType.INSTANCE)) { return new IsObjectQueryCriteria(attRefAcum); } else { BasicType bt = BasicType.fromDocType(dt); return new TypeIsQueryCriteria( attRefAcum, bt ); } } private QueryCriteria translateModOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof List)) { throw new UserToroException("$mod needs an array"); } List value = (List) uncastedArg; if (value.size() != 2) { throw new UserToroException( "$mod needs an array with 2 elements but " + value.size() + " elements were found"); } if (!(value.get(0) instanceof Number)) { throw new UserToroException("$mod needs a numeric divisor but " + value.get(0) + " was found"); } if (!(value.get(1) instanceof Number)) { throw new UserToroException("$mod needs a numeric remainder but " + value.get(1) + " was found"); } Number divisor = (Number) value.get(0); Number reminder = (Number) value.get(1); if (divisor.equals(0)) { throw new UserToroException("Divisor cannot be 0"); } return new ModIsQueryCriteria( attRefAcum, ValueFactory.fromNumber(divisor), ValueFactory.fromNumber(reminder) ); } private QueryCriteria translateRegexOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private QueryCriteria translateTextOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private QueryCriteria translateWhereOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private QueryCriteria translateAllOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof List)) { throw new UserToroException("$all needs an array"); } com.torodb.kvdocument.values.ArrayValue value = MongoValueConverter. translateArray((List) uncastedArg); if (value.isEmpty()) { return FalseQueryCriteria.getInstance(); } QueryCriteria equality = null; if (value.size() == 1) { //escalar attributes are candidates equality = EqualFactory.createEquality(attRefAcum, value.get(0)); } ConjunctionBuilder builder = new ConjunctionBuilder(); for (DocValue child : value) { builder.add( new ExistsQueryCriteria( attRefAcum, EqualFactory.createEquality( AttributeReference.EMPTY_REFERENCE, child)) ); } if (equality != null) { return new OrQueryCriteria(equality, builder.build()); } else { return builder.build(); } } private QueryCriteria translateElemMatchOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { if (!(uncastedArg instanceof BSONObject)) { throw new UserToroException("$elemMatch needs an object"); } QueryCriteria body; BSONObject castedObject = (BSONObject) uncastedArg; if (isSubQuery(uncastedArg)) { body = translateSubQueries(AttributeReference.EMPTY_REFERENCE, uncastedArg); } else { body = translateImplicitAnd(AttributeReference.EMPTY_REFERENCE, castedObject); } return new ExistsQueryCriteria( attRefAcum, body ); } private QueryCriteria translateSizeOperand( @Nonnull AttributeReference attRefAcum, @Nonnull Object uncastedArg) throws UserToroException { Object uncastedValue = uncastedArg; if (!(uncastedValue instanceof Integer)) { throw new UserToroException("$size needs an integer"); } return new SizeIsQueryCriteria( attRefAcum, (IntegerValue) ValueFactory.fromNumber((Number) uncastedValue) ); } private static enum ExpressionType { EQUALITY, SUB_EXP, AND_OR_NOR, INVALID } private static enum QueryOperator { GT_KEY("$gt"), GTE_KEY("$gte"), LT_KEY("$lt"), LTE_KEY("$lte"), NE_KEY("$ne"), IN_KEY("$in"), NIN_KEY("$nin"), NOT_KEY("$not"), EXISTS_KEY("$exists"), TYPE_KEY("$type"), MOD_KEY("$mod"), REGEX_KEY("$regex"), TEXT_KEY("$text"), WHERE_KEY("$where"), GEO_WITHIN_KEY("$geoWithin"), GEO_INTERSECTS_KEY("$getIntersects"), NEAR_KEY("$near"), NEAR_SPHERE_KEY("$nearSphere"), ALL_KEY("$all"), ELEM_MATCH_KEY("$elemMatch"), SIZE_KEY("$size"); private static final Map<String, QueryOperator> operandsByKey; private final String key; static { operandsByKey = Maps.newHashMapWithExpectedSize(QueryOperator. values().length); for (QueryOperator operand : QueryOperator.values()) { operandsByKey.put(operand.key, operand); } } private QueryOperator(String key) { this.key = key; } public String getKey() { return key; } public static boolean isSubQuery(String key) { return operandsByKey.containsKey(key); } @Nonnull public static QueryOperator fromKey(String key) { QueryOperator result = operandsByKey.get(key); if (result == null) { throw new IllegalArgumentException( "There is no operand whose key is '" + key + "'"); } return result; } } }
package org.apache.xmlbeans.impl.newstore.pub.store; import javax.xml.namespace.QName; import org.w3c.dom.Node; import java.io.PrintStream; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.impl.newstore.pub.store.Dom.CharNode; import org.apache.xmlbeans.impl.newstore.Cursor; public abstract class Cur { public static final int TEMP = 0; public static final int PERM = 1; public static final int WEAK = 2; public static final int POOLED = 0; public static final int UNEMBEDDED = 1; public static final int EMBEDDED = 2; public static final int DISPOSED = 3; public static final int NONE = 0; public static final int ROOT = 1; public static final int ELEM = 2; public static final int LEAF = 3; public static final int ATTR = 4; public static final int TEXT = 5; public static final int DOMDOC = ROOT + (1 << 3); public static final int DOMFRAG = ROOT + (2 << 3); public static final int XMLNS = ATTR + (1 << 3); public static final int COMMENT = LEAF + (1 << 3); public static final int PROCINST = LEAF + (2 << 3); protected abstract int _kind ( ); protected abstract void _dispose ( ); protected abstract Locale _locale ( ); protected abstract boolean _isPositioned ( ); protected abstract void _moveToCur ( Cur c ); protected abstract void _moveToCharNode ( CharNode node ); protected abstract void _moveToDom ( Dom d ); protected abstract boolean _isSamePosition ( Cur that ); protected abstract boolean _next ( ); protected abstract void _toEnd ( ); protected abstract boolean _toParent ( boolean raw ); protected abstract boolean _toNextSibling ( ); protected abstract boolean _toFirstChild ( ); protected abstract boolean _toLastChild ( ); protected abstract boolean _toFirstAttr ( ); protected abstract void _create ( int k, QName name ); protected abstract void _createElement ( QName name, QName parentName ); protected abstract void _moveNode ( Cur to ); protected abstract void _copyNode ( Cur to ); protected abstract Object _moveChars ( Cur to, int cch ); protected abstract void _insertChars ( Object src, int off, int cch ); protected abstract QName _getName ( ); protected abstract void _setName ( QName n ); protected abstract String _getValueString ( ); protected abstract Object _getChars ( int cch ); protected abstract String _getString ( int cch ); protected abstract Dom _getDom ( ); protected abstract CharNode _getCharNodes ( ); protected abstract void _setCharNodes ( CharNode nodes ); protected abstract void _setBookmark ( Class c, Object o ); protected abstract Object _getBookmark ( Class c ); public final Locale locale ( ) { return _locale(); } public final int kind ( ) { return _kind(); } public final int type ( ) { return _kind() % 8; } public static boolean typeIsContainer ( int t ) { return t > 0 && t <= ELEM; } public final boolean isRoot ( ) { return type() == ROOT; } public final boolean isElem ( ) { return type() == ELEM; } public final boolean isAttr ( ) { return type() == ATTR; } public final boolean isLeaf ( ) { return type() == LEAF; } public final boolean isContainer ( ) { return typeIsContainer( type() ); } public final Cur tempCur ( ) { Cur c = locale().tempCur(); c.moveToCur( this ); return c; } public final Cur weakCur ( Object o ) { Cur c = locale().weakCur( o ); c.moveToCur( this ); return c; } public final boolean isPositioned ( ) { return _isPositioned(); } public final void moveToCur ( Cur c ) { _moveToCur( c ); } public final void moveToDom ( Dom d ) { assert d != null; _moveToDom( d ); } public final void moveToCharNode ( CharNode node ) { _moveToCharNode( node ); } public boolean isSamePosition ( Cur that ) { return _isSamePosition( that ); } public final boolean next ( ) { return _next(); } public final void toEnd ( ) { _toEnd(); } public final boolean toParentRaw ( ) { return _toParent( true ); } public final boolean toParent ( ) { return _toParent( false ); } public final boolean toFirstChild ( ) { return _toFirstChild(); } public final boolean toLastChild ( ) { return _toLastChild(); } public final boolean toFirstAttr ( ) { return _toFirstAttr(); } public final boolean toNextSibling ( ) { return _toNextSibling(); } public final void moveNode ( Cur to ) { _moveNode( to ); } public final void copyNode ( Cur to ) { _copyNode( to ); } public final Object moveChars ( Cur to, int cch ) { return _moveChars( to, cch ); } public final void insertChars ( Object src, int off, int cch ) { _insertChars( src, off, cch ); } public final void setName ( QName name ) { _setName( name ); } public final QName getName ( ) { return _getName(); } public final String getValueString ( ) { return _getValueString(); } public final String getString ( int cch ) { return _getString( cch ); } public final Object getChars ( int cch ) { return _getChars( cch ); } public final Dom getDom ( ) { assert isPositioned() && kind() != TEXT; return _getDom(); } public final CharNode getCharNodes ( ) { assert isPositioned(); return _getCharNodes(); } public final void setCharNodes ( CharNode nodes ) { assert isPositioned(); _setCharNodes( nodes ); } public void setBookmark ( Class c, Object o ) { _setBookmark( c, o ); } public Object getBookmark ( Class c ) { return _getBookmark( c ); } public final void createRoot ( int k ) { Locale l = _locale(); assert k == ROOT || k == DOMDOC || k == DOMFRAG; assert !isPositioned(); assert k != DOMDOC || l._ownerDoc == null; if (k == DOMDOC || (k == ROOT && l._ownerDoc == null)) _create( DOMDOC, null ); else _create( k, null ); } public final void createElement ( QName name, QName parentName ) { _createElement( name, parentName ); } public final void createElement ( QName name ) { _create( ELEM, name ); } public final void createComment ( ) { _create( COMMENT, null ); } public final void createAttr ( QName name ) { _create( ATTR, name ); } public final String namespaceForPrefix ( String prefix ) { throw new RuntimeException( "Not implemented" ); } public final String prefixForNamespace ( String ns ) { throw new RuntimeException( "Not implemented" ); } public final boolean toNearestContainer ( ) { int t = type(); switch ( t ) { case ROOT : case ELEM : return true; case TEXT : next(); break; case ATTR: if (!toParentRaw() || !toFirstChild()) return false; break; } while ( !isContainer() ) if (!toNextSibling()) return false; return true; } public final boolean toFirstChildElem ( ) { assert isContainer(); if (!toFirstChild()) return false; while ( !isElem() ) if (!toNextSibling()) return false; return true; } public final void release ( ) { assert _state != POOLED || _nextTemp == null; if (_state == POOLED || _state == DISPOSED) return; _moveToCur( null ); if (_obj instanceof Locale.Ref) ((Locale.Ref) _obj).clear(); _obj = null; _curKind = -1; _tempCurFrame = -1; assert _state == UNEMBEDDED; Locale l = _locale(); l._unembedded = listRemove( l._unembedded ); if (l._poolCount < 16) { l._pool = listInsert( l._pool, POOLED ); l._poolCount++; } else { _dispose(); _state = DISPOSED; } } public final boolean isOnList ( Cur head ) { for ( ; head != null ; head = head._next ) if (head == this) return true; return false; } public final Cur listInsert ( Cur head, int state ) { assert _next == null && _prev == null; if (head == null) head = _prev = this; else { _prev = head._prev; head._prev = head._prev._next = this; } _state = state; return head; } public final Cur listRemove ( Cur head ) { assert _prev != null && isOnList( head ); if (_prev == this) head = null; else { if (head == this) head = _next; else _prev._next = _next; if (_next == null) head._prev = _prev; else { _next._prev = _prev; _next = null; } } _prev = null; _state = -1; return head; } protected final static CharNode updateCharNodes ( Locale l, Object src, CharNode nodes, int cch ) { CharNode node = nodes; int i = 0; while ( node != null && cch > 0 ) { assert node._src == src; if (node._cch > cch) node._cch = cch; node._off = i; i += node._cch; cch -= node._cch; node = node._next; } if (cch <= 0) { for ( ; node != null ; node = node._next ) { assert node._src == src; if (node._cch != 0) node._cch = 0; node._off = i; } } else { node = l.createTextNode(); node._src = src; node._cch = cch; node._off = i; nodes = CharNode.appendNode( nodes, node ); } return nodes; } public static String kindName ( int kind ) { switch ( kind ) { case ROOT : return "ROOT"; case ELEM : return "ELEM"; case LEAF : return "LEAF"; case ATTR : return "ATTR"; case TEXT : return "TEXT"; case DOMDOC : return "DOMDOC"; case DOMFRAG : return "DOMFRAG"; case XMLNS : return "XMLNS"; case COMMENT : return "COMMENT"; case PROCINST : return "PROCINST"; default : return "<< Unknown Kind (" + kind + ") >>"; } } public static String typeName ( int type ) { switch ( type ) { case ROOT : return "ROOT"; case ELEM : return "ELEM"; case LEAF : return "LEAF"; case ATTR : return "ATTR"; case TEXT : return "TEXT"; default : return "<< Unknown type (" + type + ") >>"; } } public static void dump ( PrintStream o, Dom d ) { d.dump( o ); } public static void dump ( Dom d ) { dump( System.out, d ); } public static void dump ( XmlCursor xc ) { Cursor c = (Cursor) xc; c.dump(); } public static void dump ( Node n ) { dump( System.out, n ); } public static void dump ( PrintStream o, Node n ) { dump( o, (Dom) n ); } public void dump ( ) { dump( System.out ); } public void dump ( PrintStream o ) { o.println( "Dump not implemented" ); } public int _state; public int _curKind; public Cur _next; public Cur _prev; public Object _obj; int _tempCurFrame; Cur _nextTemp; public int _offSrc; public int _cchSrc; }
package com.khartec.waltz.data; import com.khartec.waltz.common.StringUtilities; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class SearchUtilities { public static List<String> mkTerms(String query) { if(query.length() < 3) return new ArrayList<>(); String safeQuery = query .replace("[", " ") .replace("]", " ") .replace("'", " ") .replace("\"", " ") .replace("|", " ") .replace("!", " ") .replace("%", " ") .replace("(", " ") .replace(")", " ") .replace(",", " ") .replace("~", " "); String[] terms = safeQuery.split(" "); // ensure the first term is at least 3 characters if(terms.length == 1 && terms[0].length() < 3) return new ArrayList<>(); return Stream.of(terms) .filter(StringUtilities::notEmpty) .collect(toList()); } }
package org.cmo.cancerhotspots.domain; import com.univocity.parsers.annotations.Convert; import com.univocity.parsers.annotations.Parsed; import com.univocity.parsers.annotations.Trim; import io.swagger.annotations.ApiModelProperty; import org.cmo.cancerhotspots.util.ChainMapConversion; import org.cmo.cancerhotspots.util.ListConversion; import org.cmo.cancerhotspots.util.CompositionMapConversion; import java.util.List; import java.util.Map; /** * @author Selcuk Onur Sumer */ public class HotspotMutation { @Trim @Parsed(field = "Hugo Symbol") private String hugoSymbol; @Trim @Parsed(field = "Codon") private String codon; @Trim @Parsed(field = "Cluster") private String cluster; @Trim @Convert(conversionClass = ChainMapConversion.class) @Parsed(field = "PDB chains") private Map<String, Double> pdbChains; @Trim @Parsed(field = "Class") private String classification; @Trim @Convert(conversionClass = CompositionMapConversion.class) @Parsed(field = "Variant Amino Acid") private Map<String, Integer> variantAminoAcid; @Trim @Parsed(field = "Q-value") private String qValue; @Trim @Parsed(field = "P-value") private String pValue; @Trim @Parsed(field = "Tumor Count") private Integer tumorCount; @Trim @Parsed(field = "Tumor Type Count") private Integer tumorTypeCount; @Trim @Convert(conversionClass = CompositionMapConversion.class) @Parsed(field = "Tumor Type Composition") private Map<String, Integer> tumorTypeComposition; @ApiModelProperty(value = "Hugo symbol", required = true) public String getHugoSymbol() { return hugoSymbol; } public void setHugoSymbol(String hugoSymbol) { this.hugoSymbol = hugoSymbol; } @ApiModelProperty(value = "Codon", required = true) public String getCodon() { return codon; } public void setCodon(String codon) { this.codon = codon; } @ApiModelProperty(value = "Variant Amino Acid", required = true) public Map<String, Integer> getVariantAminoAcid() { return variantAminoAcid; } public void setVariantAminoAcid(Map<String, Integer> variantAminoAcid) { this.variantAminoAcid = variantAminoAcid; } @ApiModelProperty(value = "Q-value", required = false) public String getqValue() { return qValue; } public void setqValue(String qValue) { this.qValue = qValue; } @ApiModelProperty(value = "P-value", required = false) public String getpValue() { return pValue; } public void setpValue(String pValue) { this.pValue = pValue; } @ApiModelProperty(value = "Number of Tumors", required = true) public Integer getTumorCount() { return tumorCount; } public void setTumorCount(Integer tumorCount) { this.tumorCount = tumorCount; } @ApiModelProperty(value = "Number of Distinct Tumor Types", required = false) public Integer getTumorTypeCount() { return tumorTypeCount; } public void setTumorTypeCount(Integer tumorTypeCount) { this.tumorTypeCount = tumorTypeCount; } @ApiModelProperty(value = "Tumor Type Composition", required = true) public Map<String, Integer> getTumorTypeComposition() { return tumorTypeComposition; } public void setTumorTypeComposition(Map<String, Integer> tumorTypeComposition) { this.tumorTypeComposition = tumorTypeComposition; } @ApiModelProperty(value = "Cluster No", required = false) public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } @ApiModelProperty(value = "PDB chain (with p-value)", required = false) public Map<String, Double> getPdbChains() { return pdbChains; } public void setPdbChains(Map<String, Double> pdbChains) { this.pdbChains = pdbChains; } @ApiModelProperty(value = "Hotspot Classification", required = false) public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } // @Trim // @Parsed(field = "Alt Common Codon Usage *") // private String altCommonCodonUsage; // @Trim // @Parsed(field = "Validation Level [a]") // private String validationLevel; // @ApiModelProperty(value = "Alternative Common Codon Usage", required = true) // public String getAltCommonCodonUsage() // return altCommonCodonUsage; // public void setAltCommonCodonUsage(String altCommonCodonUsage) // this.altCommonCodonUsage = altCommonCodonUsage; // @ApiModelProperty(value = "Validation Level", required = true) // public String getValidationLevel() // return validationLevel; // public void setValidationLevel(String validationLevel) // this.validationLevel = validationLevel; }
package com.box.l10n.mojito.aspect; import com.google.common.base.Stopwatch; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple aspect to log time spent in a function. * * @author jeanaurambault */ @Aspect public class StopWatchAspect { /** * logger */ static Logger logger = LoggerFactory.getLogger(StopWatchAspect.class); @Around("methods()") public Object mesureTime(ProceedingJoinPoint pjp) throws Throwable { Stopwatch stopwatch = Stopwatch.createStarted(); Object res = pjp.proceed(); stopwatch.stop(); logger.debug("{}#{} took: {}", pjp.getSignature().getDeclaringTypeName(), pjp.getSignature().getName(), stopwatch.toString()); return res; } @Pointcut("execution(@com.box.l10n.mojito.aspect.StopWatch * *(..))") private void methods() { } }
package com.hextilla.cardbook.auth; import java.io.Serializable; import java.util.*; import java.sql.*; import java.lang.reflect.*; import com.samskivert.util.StringUtil; import com.samskivert.jdbc.jora.FieldDescriptor; import com.samskivert.jdbc.jora.FieldMask; import com.samskivert.jdbc.jora.Table; import static com.hextilla.cardbook.Log.log; /** * Used to establish mapping between corteges of database tables and java classes. this class is * responsible for constructing SQL statements for extracting, updating and deleting records of * the database table. */ public class DebugTable<T> extends Table<T> { /** * Constructor for table object. Make association between Java class and * database table. * * @param clazz the class that represents a row entry. * @param tableName name of database table mapped on this Java class * @param key table's primary key. This parameter is used in UPDATE/DELETE * operations to locate record in the table. * @param mixedCaseConvert whether or not to convert mixed case field * names into underscore separated uppercase column names. */ public DebugTable (Class<T> clazz, String tableName, String key, boolean mixedCaseConvert) { super(clazz, tableName, key, mixedCaseConvert); } /** * Constructor for table object. Make association between Java class and * database table. * * @param clazz the class that represents a row entry. * @param tableName name of database table mapped on this Java class * @param key table's primary key. This parameter is used in UPDATE/DELETE * operations to locate record in the table. */ public DebugTable (Class<T> clazz, String tableName, String key) { super(clazz, tableName, key); } /** * Constructor for table object. Make association between Java class and * database table. * * @param clazz the class that represents a row entry. * @param tableName name of database table mapped on this Java class * @param keys table primary keys. This parameter is used in UPDATE/DELETE * operations to locate record in the table. */ public DebugTable (Class<T> clazz, String tableName, String[] keys) { super(clazz, tableName, keys); } /** * Constructor for table object. Make association between Java class and * database table. * * @param clazz the class that represents a row entry. * @param tableName name of database table mapped on this Java class * @param keys table primary keys. This parameter is used in UPDATE/DELETE * operations to locate record in the table. * @param mixedCaseConvert whether or not to convert mixed case field * names into underscore separated uppercase column names. */ public DebugTable (Class<T> clazz, String tableName, String[] keys, boolean mixedCaseConvert) { super(clazz, tableName, keys, mixedCaseConvert); } /** * Insert new record in the table. Values of inserted record fields are * taken from specified object. * * @param obj object specifying values of inserted record fields */ public synchronized void insert (Connection conn, T obj) throws SQLException { StringBuilder sql = new StringBuilder( "insert into " + name + " (" + listOfFields + ") values (?"); for (int i = 1; i < nColumns; i++) { sql.append(",?"); } sql.append(")"); log.info("SQL update prepared statement is: " + sql.toString()); PreparedStatement insertStmt = conn.prepareStatement(sql.toString()); bindUpdateVariables(insertStmt, obj, null, false); insertStmt.executeUpdate(); insertStmt.close(); } /** * Insert several new records in the table. Values of inserted records * fields are taken from objects of specified array. * * @param objects array with objects specifying values of inserted record * fields */ public synchronized void insert (Connection conn, T[] objects) throws SQLException { StringBuilder sql = new StringBuilder( "insert into " + name + " (" + listOfFields + ") values (?"); for (int i = 1; i < nColumns; i++) { sql.append(",?"); } sql.append(")"); log.info("SQL update prepared statement is: " + sql.toString()); PreparedStatement insertStmt = conn.prepareStatement(sql.toString()); for (int i = 0; i < objects.length; i++) { bindUpdateVariables(insertStmt, objects[i], null, false); insertStmt.addBatch(); } insertStmt.executeBatch(); insertStmt.close(); } /** * Update record in the table using table's primary key to locate record in * the table and values of fields of specified object <I>obj</I> to alter * record fields. * * @param obj object specifying value of primary key and new values of * updated record fields * * @return number of objects actually updated */ public int update (Connection conn, T obj) throws SQLException { return super.update(conn, obj, null); } /** * Update record in the table using table's primary key to locate record in * the table and values of fields of specified object <I>obj</I> to alter * record fields. Only the fields marked as modified in the supplied field * mask will be updated in the database. * * @param obj object specifying value of primary key and new values of * updated record fields * @param mask a {@link FieldMask} instance configured to indicate which of * the object's fields are modified and should be written to the database. * * @return number of objects actually updated */ public synchronized int update (Connection conn, T obj, FieldMask mask) throws SQLException { return super.delete(conn, obj, mask); } /** * Update set of records in the table using table's primary key to locate * record in the table and values of fields of objects from specified array * <I>objects</I> to alter record fields. * * @param objects array of objects specifying primary keys and and new * values of updated record fields * * @return number of objects actually updated */ public synchronized int update (Connection conn, T[] objects) throws SQLException { return super.update(conn, objects); } /** * Delete record with specified value of primary key from the table. * * @param obj object containing value of primary key. */ public synchronized int delete (Connection conn, T obj) throws SQLException { return super.delete(conn, obj); } /** * Delete records with specified primary keys from the table. * * @param objects array of objects containing values of primary key. * * @return number of objects actually deleted */ public synchronized int delete (Connection conn, T[] objects) throws SQLException { return super.delete(conn, objects); } protected int bindUpdateVariables(PreparedStatement pstmt, T obj, FieldMask mask, boolean derp) throws SQLException { return bindUpdateVariables(pstmt, obj, 0, nFields, 0, mask, derp); } protected final int bindUpdateVariables ( PreparedStatement pstmt, Object obj, int i, int end, int column, FieldMask mask, boolean derp) throws SQLException { try { while (i < end) { FieldDescriptor fd = fields[i++]; Object comp = null; // skip non-modified fields if (mask != null && !mask.isModified(i-1)) { continue; } if (!fd.isBuiltin() && (comp = fd.field.get(obj)) == null) { if (fd.isCompound()) { int nComponents = fd.outType-FieldDescriptor.tCompound; while (--nComponents >= 0) { fd = fields[i++]; if (!fd.isCompound()) { pstmt.setNull(++column, FieldDescriptor.sqlTypeMapping[fd.outType]); log.info("Setting column " + column + " to null"); } } } else { pstmt.setNull( ++column, FieldDescriptor.sqlTypeMapping[fd.outType]); log.info("Setting column " + column + " to null"); } } else { if (!fd.bindVariable(pstmt, obj, ++column)) { int nComponents = fd.outType-FieldDescriptor.tCompound; column = bindUpdateVariables( pstmt, comp, i, i+nComponents,column-1, mask); i += nComponents; } log.info("Setting column " + column + " to non-null value " + obj.toString()); } } } catch(IllegalAccessException ex) { throw new IllegalAccessError(); } return column; } /** protected String name; protected String listOfFields; protected String qualifiedListOfFields; protected String listOfAssignments; protected Class<T> _rowClass; protected boolean mixedCaseConvert = false; protected FieldDescriptor[] fields; protected FieldMask fMask; protected int nFields; // length of "fields" array protected int nColumns; // number of atomic fields in "fields" array protected String primaryKeys[]; protected int primaryKeyIndices[]; protected Constructor<T> constructor; protected static final Method setBypass = getSetBypass(); protected static final Class<Serializable> serializableClass = Serializable.class; protected static final Object[] bypassFlag = { Boolean.TRUE }; protected static final Object[] constructorArgs = {}; // used to identify byte[] fields protected static final byte[] BYTE_PROTO = new byte[0]; */ }
package org.wisdom.api.bodies; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.Charset; import org.wisdom.api.http.Context; import org.wisdom.api.http.MimeTypes; import org.wisdom.api.http.Renderable; import org.wisdom.api.http.Result; /** * A renderable object taking a String as parameter. */ public class RenderableString implements Renderable<String> { //TODO Support encoding private final String rendered; private final String type; public RenderableString(String object) { this(object, null); } public RenderableString(StringBuilder object) { this(object.toString(), null); } public RenderableString(StringBuffer object) { this(object.toString(), null); } public RenderableString(Object object) { this(object.toString(), null); } public RenderableString(Object object, String type) { this(object.toString(), type); } public RenderableString(StringWriter object) { this(object.toString(), null); } public RenderableString(String object, String type) { rendered = object; this.type = type; } @Override public InputStream render(Context context, Result result) throws Exception { byte[] bytes = null; if(result != null){ // We have a result, charset have to be provided if(result.getCharset() == null){ // No charset provided result.with(Charset.defaultCharset()); // Set the default encoding } bytes = rendered.getBytes(result.getCharset()); }else{ //No Result, use the default platform encoding bytes = rendered.getBytes(); } return new ByteArrayInputStream(bytes); } @Override public long length() { return rendered.length(); } @Override public String mimetype() { if (type == null) { return MimeTypes.HTML; } else { return type; } } @Override public String content() { return rendered; } @Override public boolean requireSerializer() { return false; } @Override public void setSerializedForm(String serialized) { // Nothing because serialization is not supported for this renderable class. } @Override public boolean mustBeChunked() { return false; } }
package org.knowm.xchange.dto.meta; import java.io.IOException; import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Describe a call rate limit as a number of calls per some time span. */ public class RateLimit { @JsonProperty("calls") public int calls = 1; @JsonProperty("time_span") public int timeSpan = 1; @JsonProperty("time_unit") @JsonDeserialize(using = TimeUnitDeserializer.class) public TimeUnit timeUnit = TimeUnit.SECONDS; /** * Constructor */ public RateLimit() { } /** * Constructor * * @param calls * @param timeSpan * @param timeUnit */ public RateLimit( @JsonProperty("calls") int calls, @JsonProperty("time_span") int timeSpan, @JsonProperty("time_unit") @JsonDeserialize(using = TimeUnitDeserializer.class) TimeUnit timeUnit ) { this.calls = calls; this.timeUnit = timeUnit; this.timeSpan = timeSpan; } /** * @return this rate limit as a number of milliseconds required between any two remote calls, assuming the client makes consecutive calls without * any bursts or breaks for an infinite period of time. */ @JsonIgnore public long getPollDelayMillis() { return timeUnit.toMillis(timeSpan) / calls; } public static class TimeUnitDeserializer extends JsonDeserializer<TimeUnit> { @Override public TimeUnit deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { return TimeUnit.valueOf(jp.getValueAsString().toUpperCase()); } } }
package com.thoughtworks.acceptance; import com.thoughtworks.xstream.core.JVM; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Tests with buffered images. * * @author J&ouml;rg Schaible */ public class BufferedImagesTest extends AbstractAcceptanceTest { public void testInBWCanBeMarshalled() throws IOException { boolean isHeadless = Boolean.valueOf(System.getProperty("java.awt.headless", "false")).booleanValue(); if (!isHeadless || JVM.is15()) { final BufferedImage image = new BufferedImage(3, 3, BufferedImage.TYPE_BYTE_BINARY); final Graphics2D graphics = image.createGraphics(); graphics.setBackground(Color.WHITE); graphics.clearRect(0, 0, 2, 2); graphics.setColor(Color.BLACK); graphics.drawLine(0, 0, 2, 2); final ByteArrayOutputStream baosOriginal = new ByteArrayOutputStream(); ImageIO.write(image, "tiff", baosOriginal); xstream.alias("image", BufferedImage.class); final String xml = xstream.toXML(image); final ByteArrayOutputStream baosSerialized = new ByteArrayOutputStream(); ImageIO.write((RenderedImage)xstream.fromXML(xml), "tiff", baosSerialized); assertArrayEquals(baosOriginal.toByteArray(), baosSerialized.toByteArray()); } } public void testInRGBACanBeMarshalled() throws IOException { boolean isHeadless = Boolean.valueOf(System.getProperty("java.awt.headless", "false")).booleanValue(); if (!isHeadless || JVM.is15()) { final BufferedImage image = new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB); final Graphics2D graphics = image.createGraphics(); graphics.setBackground(Color.WHITE); graphics.clearRect(0, 0, 2, 2); graphics.setColor(Color.RED); graphics.drawLine(0, 0, 2, 2); final ByteArrayOutputStream baosOriginal = new ByteArrayOutputStream(); ImageIO.write(image, "png", baosOriginal); xstream.alias("image", BufferedImage.class); final String xml = xstream.toXML(image); final ByteArrayOutputStream baosSerialized = new ByteArrayOutputStream(); ImageIO.write((RenderedImage)xstream.fromXML(xml), "png", baosSerialized); assertArrayEquals(baosOriginal.toByteArray(), baosSerialized.toByteArray()); } } }
package org.yamcs.web.websocket; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import org.codehaus.jackson.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.Channel; import org.yamcs.ChannelClient; import org.yamcs.ChannelException; import org.yamcs.InvalidIdentification; import org.yamcs.InvalidRequestIdentification; import org.yamcs.ParameterConsumer; import org.yamcs.ParameterRequestManager; import org.yamcs.ParameterValue; import org.yamcs.ParameterValueWithId; import org.yamcs.management.ManagementService; import org.yamcs.protobuf.Comp.ComputationDef; import org.yamcs.protobuf.Comp.ComputationDefList; import org.yamcs.protobuf.Pvalue.ParameterData; import org.yamcs.protobuf.SchemaComp; import org.yamcs.protobuf.SchemaYamcs; import org.yamcs.protobuf.Yamcs.NamedObjectId; import org.yamcs.protobuf.Yamcs.NamedObjectList; import org.yamcs.protobuf.Yamcs.ProtoDataType; import org.yamcs.protobuf.Yamcs.StringMessage; import org.yamcs.web.Computation; import org.yamcs.web.ComputationFactory; import com.dyuproject.protostuff.JsonIOUtil; /** * Provides realtime parameter subscription via web. * * TODO better deal with exceptions * * @author nm * */ public class ParameterClient implements ParameterConsumer, ChannelClient { Channel channel; Logger log; //maps subscription ids <-> addresses WebSocketServerHandler wsHandler; int subscriptionId=-1; //subscription id used for computations int compSubscriptionId=-1; final String username="unknown"; final String applicationName; final CopyOnWriteArrayList<Computation> compList=new CopyOnWriteArrayList<Computation>(); final int clientId; public ParameterClient(String yamcsInstance, WebSocketServerHandler webSocketServerHandler, String applicationName) { this.channel= Channel.getInstance(yamcsInstance, "realtime"); log=LoggerFactory.getLogger(ParameterClient.class.getName() + "[" + yamcsInstance + "]"); this.wsHandler=webSocketServerHandler; this.applicationName=applicationName; clientId=ManagementService.getInstance().registerClient(yamcsInstance, channel.getName(), this); } public void processRequest(String request, int id, JsonParser jsp, WebSocketServerHandler wssh) { log.debug("received a new request: "+request); if("subscribe".equalsIgnoreCase(request)) { subscribe(id, jsp); } else if("subscribeAll".equalsIgnoreCase(request)) { subscribeAll(id, jsp); } else if ("unsubscribe".equalsIgnoreCase(request)) { unsubscribe(id, jsp); } else if ("unsubscribeAll".equalsIgnoreCase(request)) { unsubscribeAll(id, jsp); } else if("subscribeComputations".equalsIgnoreCase(request)) { subscribeComputations(id, jsp); } else { wssh.sendException(id, "unknown request '"+request+"'"); } } private void subscribe(int id, JsonParser jsp) { List<NamedObjectId> paraList=null; NamedObjectList.Builder nolb=NamedObjectList.newBuilder(); try { JsonIOUtil.mergeFrom(jsp, nolb, SchemaYamcs.NamedObjectList.MERGE, false); paraList=nolb.getListList(); } catch (IOException e) { wsHandler.sendException(id, "error decoding message: "+e.getMessage()); log.warn("error decoding message: {}",e.toString()); return; } try { ParameterRequestManager prm=channel.getParameterRequestManager(); if(subscriptionId!=-1) { prm.addItemsToRequest(subscriptionId, paraList); } else { subscriptionId=prm.addRequest(paraList, this); System.out.println(" } wsHandler.sendReply(id, "OK", null); } catch (InvalidIdentification e) { NamedObjectList nol=NamedObjectList.newBuilder().addAllList(e.invalidParameters).build(); wsHandler.sendException(id, "InvalidIdentification", nol, org.yamcs.protobuf.SchemaYamcs.NamedObjectList.WRITE); } catch (InvalidRequestIdentification e) { log.error("got invalid subscription id", e); wsHandler.sendException(id, "internal error: "+e.toString()); } } private void unsubscribe(int id, JsonParser jsp) { List<NamedObjectId> paraList=null; try { NamedObjectList.Builder nolb=NamedObjectList.newBuilder(); JsonIOUtil.mergeFrom(jsp, nolb, SchemaYamcs.NamedObjectList.MERGE, false); paraList=nolb.getListList(); } catch (IOException e) { log.warn("Could not decode the parameter list"); return; } try { ParameterRequestManager prm=channel.getParameterRequestManager(); if(subscriptionId!=-1) { prm.removeItemsFromRequest(subscriptionId, paraList); wsHandler.sendReply(id, "OK",null); } else { wsHandler.sendException(id, "not subscribed to anything"); return; } wsHandler.sendReply(id, "OK", null); } catch (InvalidIdentification e) { wsHandler.sendException(id, e.toString()); } } private void subscribeAll(int reqId, JsonParser jsp) { String namespace=null; try { StringMessage.Builder nolb=StringMessage.newBuilder(); JsonIOUtil.mergeFrom(jsp, nolb, SchemaYamcs.StringMessage.MERGE, false); } catch (IOException e) { log.warn("Could not decode the namespace"); return; } if(subscriptionId!=-1) { wsHandler.sendException(reqId, "already subscribed for this client"); return; } ParameterRequestManager prm=channel.getParameterRequestManager(); subscriptionId=prm.subscribeAll(namespace, this); wsHandler.sendReply(reqId, "OK", null); } private void subscribeComputations(int reqId, JsonParser jsp) { List<ComputationDef> cdefList; try { ComputationDefList.Builder cdlb=ComputationDefList.newBuilder(); JsonIOUtil.mergeFrom(jsp, cdlb, SchemaComp.ComputationDefList.MERGE, false); cdefList=cdlb.getCompDefList(); } catch (IOException e) { wsHandler.sendException(reqId, "error decoding message: "+e.getMessage()); log.warn("error decoding message: {}",e.toString()); return; } List<NamedObjectId> argList=new ArrayList<NamedObjectId>(); for(ComputationDef c: cdefList) { argList.addAll(c.getArgumentList()); } try { ParameterRequestManager prm=channel.getParameterRequestManager(); if(compSubscriptionId!=-1) { prm.addItemsToRequest(compSubscriptionId, argList); } else { compSubscriptionId=prm.addRequest(argList, this); } } catch (InvalidIdentification e) { NamedObjectList nol=NamedObjectList.newBuilder().addAllList(e.invalidParameters).build(); wsHandler.sendException(reqId, "InvalidIdentification", nol, org.yamcs.protobuf.SchemaYamcs.NamedObjectList.WRITE); return; } try { for(ComputationDef cdef:cdefList) { Computation c = ComputationFactory.getComputation(cdef); compList.add(c); } } catch (Exception e) { log.warn("Cannot create computation: ",e); wsHandler.sendException(reqId, "error creating computation: "+e.toString()); return; } wsHandler.sendReply(reqId, "OK", null); } private void unsubscribeAll(int reqId, JsonParser jsp) { if(subscriptionId==-1) { wsHandler.sendException(reqId, "not subscribed"); return; } ParameterRequestManager prm=channel.getParameterRequestManager(); boolean r=prm.unsubscribeAll(subscriptionId); if(r) { wsHandler.sendReply(reqId, "OK", null); subscriptionId=-1; } else { wsHandler.sendException(reqId, "not a subscribeAll subscription for this client"); } } @Override public void updateItems(int subscrId, ArrayList<ParameterValueWithId> paramList) { if(wsHandler==null) return; if(subscrId==compSubscriptionId) { updateComputations(paramList); return; } ParameterData.Builder pd=ParameterData.newBuilder(); for(ParameterValueWithId pvwi:paramList) { ParameterValue pv=pvwi.getParameterValue(); pd.addParameter(pv.toGpb(pvwi.getId())); } try { wsHandler.sendData(ProtoDataType.PARAMETER, pd.build()); } catch (Exception e) { log.warn("got error when sending parameter updates, quitting", e); quit(); } } public void updateComputations(ArrayList<ParameterValueWithId> paramList) { Map<NamedObjectId, ParameterValue> parameters=new HashMap<NamedObjectId, ParameterValue>(); for(ParameterValueWithId pvwi:paramList) { parameters.put(pvwi.getId(), pvwi.getParameterValue()); } ParameterData.Builder pd=ParameterData.newBuilder(); for(Computation c:compList) { org.yamcs.protobuf.Pvalue.ParameterValue pv=c.evaluate(parameters); if(pv!=null) pd.addParameter(pv); } if(pd.getParameterCount()==0) return; try { wsHandler.sendData(ProtoDataType.PARAMETER, pd.build()); } catch (Exception e) { log.warn("got error when sending parameter updates, quitting", e); quit(); } } /** * called when the socket is closed * unsubscribe all parameters and the client from the managmenet interface * */ public void quit() { ParameterRequestManager prm=channel.getParameterRequestManager(); ManagementService.getInstance().unregisterClient(clientId); if(subscriptionId!=-1) prm.removeRequest(subscriptionId); if(compSubscriptionId!=-1) prm.removeRequest(compSubscriptionId); } @Override public void switchChannel(Channel c) throws ChannelException { log.info("switching channel to {}", c); ParameterRequestManager prm=channel.getParameterRequestManager(); List<NamedObjectId> paraList=prm.removeRequest(subscriptionId); List<NamedObjectId> compParaList=prm.removeRequest(compSubscriptionId); channel=c; prm=channel.getParameterRequestManager(); try { prm.addRequest(subscriptionId, paraList, this); } catch (InvalidIdentification e) { log.warn("got InvalidIdentification when resubscribing"); e.printStackTrace(); } try { prm.addRequest(compSubscriptionId, compParaList, this); } catch (InvalidIdentification e) { log.warn("got InvalidIdentification when resubscribing"); e.printStackTrace(); } } @Override public void channelQuit() { // TODO Auto-generated method stub } @Override public String getUsername() { return username; } @Override public String getApplicationName() { return applicationName; } }
package net.somethingdreadful.MAL.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Anime; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.GenericRecord; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Manga; import net.somethingdreadful.MAL.api.BaseModels.Profile; import net.somethingdreadful.MAL.api.MALApi; import java.util.ArrayList; public class DatabaseManager { SQLiteDatabase db; public DatabaseManager(Context context) { this.db = new DatabaseTest(context).getWritableDatabase(); } public void saveAnime(Anime anime) { ContentValues cv = listDetails(anime); cv.put("duration", anime.getDuration()); cv.put("episodes", anime.getEpisodes()); cv.put("youtubeId", anime.getYoutubeId()); //cv.put("listStats", anime.getListStats()); TODO: investigate what this really is if (anime.getAiring() != null) { cv.put("airingTime", anime.getAiring().getTime()); cv.put("nextEpisode", anime.getAiring().getNextEpisode()); } if (AccountService.isMAL()) { cv.put("watchedStatus", anime.getWatchedStatus()); cv.put("watchedEpisodes", anime.getWatchedEpisodes()); cv.put("watchingStart", anime.getWatchingStart()); cv.put("watchingEnd", anime.getWatchingEnd()); cv.put("fansubGroup", anime.getFansubGroup()); cv.put("storage", anime.getStorage()); cv.put("storageValue", anime.getStorageValue()); cv.put("epsDownloaded", anime.getEpsDownloaded()); cv.put("rewatching", anime.getRewatching()); cv.put("rewatchCount", anime.getRewatchCount()); cv.put("rewatchValue", anime.getRewatchValue()); } Query.newQuery(db).updateRecord(DatabaseTest.TABLE_ANIME, cv, anime.getId()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_ALTERNATIVE, anime.getId(), anime.getAlternativeVersions()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_CHARACTER, anime.getId(), anime.getCharacterAnime()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SIDE_STORY, anime.getId(), anime.getSideStories()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SPINOFF, anime.getId(), anime.getSpinOffs()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SUMMARY, anime.getId(), anime.getSummaries()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_ADAPTATION, anime.getId(), anime.getMangaAdaptations()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_PREQUEL, anime.getId(), anime.getPrequels()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SEQUEL, anime.getId(), anime.getSequels()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_PARENT_STORY, anime.getId(), anime.getParentStoryArray()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_OTHER, anime.getId(), anime.getOther()); Query.newQuery(db).updateLink(DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_ANIME_GENRES, anime.getId(), anime.getGenres(), "genre_id"); Query.newQuery(db).updateLink(DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_ANIME_TAGS, anime.getId(), anime.getTags(), "tag_id"); Query.newQuery(db).updateLink(DatabaseTest.TABLE_PRODUCER, DatabaseTest.TABLE_ANIME_PRODUCER, anime.getId(), anime.getProducers(), "producer_id"); Query.newQuery(db).updateLink(DatabaseTest.TABLE_TAGS, DatabaseTest.TABLE_ANIME_PERSONALTAGS, anime.getId(), anime.getPersonalTags(), "tag_id"); } public void saveAnimeList(ArrayList<Anime> result) { for (Anime anime : result) { saveAnimeList(anime); } } /** * Save MAL AnimeList records * * @param anime The Anime model */ public void saveAnimeList(Anime anime) { ContentValues cv = new ContentValues(); cv.put(DatabaseTest.COLUMN_ID, anime.getId()); cv.put("title", anime.getTitle()); cv.put("type", anime.getType()); cv.put("status", anime.getStatus()); cv.put("episodes", anime.getEpisodes()); cv.put("imageUrl", anime.getImageUrl()); cv.put("watchedEpisodes", anime.getWatchedEpisodes()); cv.put("score", anime.getScore()); cv.put("watchedStatus", anime.getWatchedStatus()); Query.newQuery(db).updateRecord(DatabaseTest.TABLE_ANIME, cv, anime.getId()); } public void saveManga(Manga manga) { ContentValues cv = listDetails(manga); cv.put("chapters", manga.getChapters()); cv.put("volumes", manga.getVolumes()); if (AccountService.isMAL()) { cv.put("readStatus", manga.getReadStatus()); cv.put("chaptersRead", manga.getChaptersRead()); cv.put("volumesRead", manga.getVolumesRead()); cv.put("readingStart", manga.getReadingStart()); cv.put("readingEnd", manga.getReadingEnd()); cv.put("chapDownloaded", manga.getChapDownloaded()); cv.put("rereading", manga.getRereading()); cv.put("rereadCount", manga.getRereadCount()); cv.put("rereadValue", manga.getRereadValue()); } Query.newQuery(db).updateRecord(DatabaseTest.TABLE_MANGA, cv, manga.getId()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_MANGA_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_RELATED, manga.getId(), manga.getRelatedManga()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_MANGA_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_ADAPTATION, manga.getId(), manga.getAnimeAdaptations()); Query.newQuery(db).updateRelation(DatabaseTest.TABLE_MANGA_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_ALTERNATIVE, manga.getId(), manga.getAlternativeVersions()); Query.newQuery(db).updateLink(DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_MANGA_GENRES, manga.getId(), manga.getGenres(), "genre_id"); Query.newQuery(db).updateLink(DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_MANGA_TAGS, manga.getId(), manga.getTags(), "tag_id"); Query.newQuery(db).updateLink(DatabaseTest.TABLE_TAGS, DatabaseTest.TABLE_MANGA_PERSONALTAGS, manga.getId(), manga.getPersonalTags(), "tag_id"); } public void saveMangaList(ArrayList<Manga> result) { for (Manga manga : result) { saveMangaList(manga); } } /** * Save MAL MangaList records * * @param manga The Anime model */ public void saveMangaList(Manga manga) { ContentValues cv = new ContentValues(); cv.put(DatabaseTest.COLUMN_ID, manga.getId()); cv.put("title", manga.getTitle()); cv.put("type", manga.getType()); cv.put("status", manga.getStatus()); cv.put("chapters", manga.getChapters()); cv.put("volumes", manga.getVolumes()); cv.put("imageUrl", manga.getImageUrl()); cv.put("chaptersRead", manga.getChaptersRead()); cv.put("volumesRead", manga.getVolumesRead()); cv.put("score", manga.getScore()); cv.put("readStatus", manga.getReadStatus()); Query.newQuery(db).updateRecord(DatabaseTest.TABLE_MANGA, cv, manga.getId()); } private ContentValues listDetails(GenericRecord record) { ContentValues cv = new ContentValues(); cv.put(DatabaseTest.COLUMN_ID, record.getId()); cv.put("title", record.getTitle()); cv.put("type", record.getType()); cv.put("imageUrl", record.getImageUrl()); cv.put("synopsis", record.getSynopsisString()); cv.put("status", record.getStatus()); cv.put("startDate", record.getStartDate()); cv.put("endDate", record.getEndDate()); cv.put("score", record.getScore()); cv.put("priority", record.getPriority()); cv.put("classification", record.getClassification()); cv.put("averageScore", record.getAverageScore()); cv.put("averageScoreCount", record.getAverageScoreCount()); cv.put("popularity", record.getPopularity()); cv.put("rank", record.getRank()); cv.put("notes", record.getNotes()); cv.put("favoritedCount", record.getFavoritedCount()); cv.put("dirty", record.getDirty() != null ? new Gson().toJson(record.getDirty()) : null); cv.put("createFlag", record.getCreateFlag()); cv.put("deleteFlag", record.getDeleteFlag()); return cv; } public Anime getAnime(int id) { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_ANIME).where(DatabaseTest.COLUMN_ID, String.valueOf(id)).run(); Anime result = null; if (cursor.moveToFirst()) { result = Anime.fromCursor(cursor); result.setAlternativeVersions(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_ALTERNATIVE, true)); result.setCharacterAnime(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_CHARACTER, true)); result.setSideStories(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SIDE_STORY, true)); result.setSpinOffs(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SPINOFF, true)); result.setSummaries(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SUMMARY, true)); result.setMangaAdaptations(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_ADAPTATION, false)); result.setPrequels(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_PREQUEL, true)); result.setSequels(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_SEQUEL, true)); result.setParentStoryArray(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_PARENT_STORY, true)); result.setOther(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_ANIME_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_OTHER, true)); result.setGenres(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_ANIME_GENRES, "genre_id", true)); result.setTags(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_TAGS, DatabaseTest.TABLE_ANIME_TAGS, "tag_id", true)); result.setProducers(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_PRODUCER, DatabaseTest.TABLE_ANIME_PRODUCER, "producer_id", true)); } cursor.close(); GenericRecord.setFromCursor(false); return result; } public Manga getManga(int id) { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_MANGA).where(DatabaseTest.COLUMN_ID, String.valueOf(id)).run(); Manga result = null; if (cursor.moveToFirst()) { result = Manga.fromCursor(cursor); result.setGenres(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_GENRES, DatabaseTest.TABLE_MANGA_GENRES, "genre_id", false)); result.setTags(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_TAGS, DatabaseTest.TABLE_MANGA_TAGS, "tag_id", false)); result.setPersonalTags(Query.newQuery(db).getArrayList(result.getId(), DatabaseTest.TABLE_TAGS, DatabaseTest.TABLE_MANGA_PERSONALTAGS, "tag_id", false)); result.setAlternativeVersions(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_MANGA_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_ALTERNATIVE, false)); result.setRelatedManga(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_MANGA_MANGA_RELATIONS, DatabaseTest.RELATION_TYPE_RELATED, false)); result.setAnimeAdaptations(Query.newQuery(db).getRelation(result.getId(), DatabaseTest.TABLE_MANGA_ANIME_RELATIONS, DatabaseTest.RELATION_TYPE_ADAPTATION, true)); } cursor.close(); GenericRecord.setFromCursor(false); return result; } public ArrayList<Anime> getDirtyAnimeList() { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_ANIME).isNotNull("dirty").run(); return getAnimeList(cursor); } public ArrayList<Manga> getDirtyMangaList() { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_MANGA).isNotNull("dirty").run(); return getMangaList(cursor); } public ArrayList<Anime> getAnimeList(String ListType) { Cursor cursor; Query query = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_ANIME); switch (ListType) { case "": // All cursor = query.OrderBy(1, "title").run(); break; case "rewatching": // rewatching/rereading cursor = query.whereEqGr("rewatchCount", "1").andEquals("watchedStatus", "watching").OrderBy(1, "title").run(); break; default: // normal lists cursor = query.where("watchedStatus", ListType).OrderBy(1, "title").run(); break; } return getAnimeList(cursor); } public ArrayList<Manga> getMangaList(String ListType) { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_MANGA).where("readStatus", ListType).run(); return getMangaList(cursor); } private ArrayList<Anime> getAnimeList(Cursor cursor) { ArrayList<Anime> result = new ArrayList<>(); if (cursor.moveToFirst()) { do result.add(Anime.fromCursor(cursor)); while (cursor.moveToNext()); } Crashlytics.log(Log.INFO, "MALX", "DatabaseManager.getAnimeList(): got " + String.valueOf(cursor.getCount())); cursor.close(); return result; } private ArrayList<Manga> getMangaList(Cursor cursor) { ArrayList<Manga> result = new ArrayList<>(); if (cursor.moveToFirst()) { do result.add(Manga.fromCursor(cursor)); while (cursor.moveToNext()); } cursor.close(); Crashlytics.log(Log.INFO, "MALX", "DatabaseManager.getMangaList(): got " + String.valueOf(cursor.getCount())); return result; } public void cleanupAnimeTable() { db.rawQuery("DELETE FROM " + DatabaseTest.TABLE_ANIME + " WHERE " + DatabaseTest.COLUMN_ID + " NOT IN (SELECT DISTINCT relationId FROM " + DatabaseTest.TABLE_ANIME_ANIME_RELATIONS + ") AND " + DatabaseTest.COLUMN_ID + " NOT IN (SELECT DISTINCT relationId FROM " + DatabaseTest.TABLE_MANGA_ANIME_RELATIONS + ")", null); } public void cleanupMangaTable() { db.rawQuery("DELETE FROM " + DatabaseTest.TABLE_MANGA + " WHERE " + DatabaseTest.COLUMN_ID + " NOT IN (SELECT DISTINCT relationId FROM " + DatabaseTest.TABLE_MANGA_MANGA_RELATIONS + ") AND " + DatabaseTest.COLUMN_ID + " NOT IN (SELECT DISTINCT relationId FROM " + DatabaseTest.TABLE_MANGA_ANIME_RELATIONS + ")", null); } public ArrayList<Profile> getFriendList() { ArrayList<Profile> result = new ArrayList<>(); Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_FRIENDLIST).run(); if (cursor.moveToFirst()) { do result.add(Profile.friendFromCursor(cursor)); while (cursor.moveToNext()); } cursor.close(); return result; } public void saveFriendList(ArrayList<Profile> list) { for (Profile profile : list) { ContentValues cv = new ContentValues(); cv.put("username", profile.getUsername()); cv.put("imageUrl", profile.getImageUrl()); cv.put("lastOnline", profile.getDetails().getLastOnline()); Query.newQuery(db).updateRecord(DatabaseTest.TABLE_FRIENDLIST, cv, profile.getUsername()); } } public Profile getProfile() { Cursor cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_PROFILE).run(); Profile profile = null; if (cursor.moveToFirst()) profile = Profile.fromCursor(cursor); cursor.close(); return profile; } public void saveProfile(Profile profile) { ContentValues cv = new ContentValues(); cv.put("username", profile.getUsername()); cv.put("imageUrl", profile.getImageUrl()); cv.put("imageUrlBanner", profile.getImageUrlBanner()); cv.put("notifications", profile.getNotifications()); if (AccountService.isMAL()) { cv.put("lastOnline", profile.getDetails().getLastOnline()); cv.put("status", profile.getDetails().getStatus()); cv.put("gender", profile.getDetails().getGender()); cv.put("birthday", profile.getDetails().getBirthday()); cv.put("location", profile.getDetails().getLocation()); cv.put("website", profile.getDetails().getWebsite()); cv.put("joinDate", profile.getDetails().getJoinDate()); cv.put("accessRank", profile.getDetails().getAccessRank()); cv.put("animeListViews", profile.getDetails().getAnimeListViews()); cv.put("mangaListViews", profile.getDetails().getMangaListViews()); cv.put("forumPosts", profile.getDetails().getForumPosts()); cv.put("comments", profile.getDetails().getComments()); cv.put("AnimetimeDays", profile.getAnimeStats().getTimeDays()); cv.put("Animewatching", profile.getAnimeStats().getWatching()); cv.put("Animecompleted", profile.getAnimeStats().getCompleted()); cv.put("AnimeonHold", profile.getAnimeStats().getOnHold()); cv.put("Animedropped", profile.getAnimeStats().getDropped()); cv.put("AnimeplanToWatch", profile.getAnimeStats().getPlanToWatch()); cv.put("AnimetotalEntries", profile.getAnimeStats().getTotalEntries()); cv.put("MangatimeDays", profile.getMangaStats().getTimeDays()); cv.put("Mangareading", profile.getMangaStats().getReading()); cv.put("Mangacompleted", profile.getMangaStats().getCompleted()); cv.put("MangaonHold", profile.getMangaStats().getOnHold()); cv.put("Mangadropped", profile.getMangaStats().getDropped()); cv.put("MangaplanToRead", profile.getMangaStats().getPlanToRead()); cv.put("MangatotalEntries", profile.getMangaStats().getTotalEntries()); } Query.newQuery(db).updateRecord(DatabaseTest.TABLE_PROFILE, cv, profile.getUsername()); } public void restoreLists(ArrayList<Anime> animeList, ArrayList<Manga> mangaList) { saveAnimeList(animeList); saveMangaList(mangaList); } public ArrayList<GenericRecord> getWidgetRecords() { ArrayList<GenericRecord> result = new ArrayList<>(); result.addAll(getWidgetList(MALApi.ListType.ANIME)); result.addAll(getWidgetList(MALApi.ListType.MANGA)); return result; } private ArrayList getWidgetList(MALApi.ListType type) { ArrayList result = new ArrayList<>(); Cursor cursor; if (type.equals(MALApi.ListType.ANIME)) cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_ANIME).isNotNull("widget").run(); else cursor = Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_MANGA).isNotNull("widget").run(); if (cursor.moveToFirst()) { do if (type.equals(MALApi.ListType.ANIME)) { Anime anime = Anime.fromCursor(cursor); anime.isAnime = true; result.add(anime); } else { Manga manga = Manga.fromCursor(cursor); manga.isAnime = false; result.add(manga); } while (cursor.moveToNext()); } cursor.close(); return result; } public boolean addWidgetRecord(int id, MALApi.ListType type) { if (checkWidgetID(id, type)) return false; int number = getWidgetRecords().size() + 1; ContentValues cv = new ContentValues(); cv.put("widget", number); if (type.equals(MALApi.ListType.ANIME)) db.update(DatabaseTest.TABLE_ANIME, cv, "anime_id = ?", new String[]{Integer.toString(id)}); else db.update(DatabaseTest.TABLE_MANGA, cv, "manga_id = ?", new String[]{Integer.toString(id)}); return true; } public boolean updateWidgetRecord(int oldId, MALApi.ListType oldType, int id, MALApi.ListType type) { if (checkWidgetID(id, type)) return false; // Remove old record ContentValues cv = new ContentValues(); cv.putNull("widget"); boolean anime = oldType.equals(MALApi.ListType.ANIME); db.update(DatabaseTest.TABLE_ANIME, cv, anime ? "anime_id = ?" : "manga_id = ?", new String[]{Integer.toString(oldId)}); addWidgetRecord(id, type); return true; } /** * Check if records is already a widget * * @param id The anime/manga id * @param type The List type * @return Boolean True if exists */ private boolean checkWidgetID(int id, MALApi.ListType type) { if (type.equals(MALApi.ListType.ANIME)) return Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_ANIME).where(DatabaseTest.COLUMN_ID, String.valueOf(id)).isNotNull("widget").run().getCount() > 0; else return Query.newQuery(db).selectFrom("*", DatabaseTest.TABLE_MANGA).where(DatabaseTest.COLUMN_ID, String.valueOf(id)).isNotNull("widget").run().getCount() > 0; } public void removeWidgetRecord() { int number = getWidgetRecords().size() - 1; // Remove old record ContentValues cv = new ContentValues(); cv.putNull("widget"); db.update(DatabaseTest.TABLE_ANIME, cv, "widget = ?", new String[]{Integer.toString(number)}); db.update(DatabaseTest.TABLE_MANGA, cv, "widget = ?", new String[]{Integer.toString(number)}); // Replace id of the new record ContentValues cvn = new ContentValues(); cvn.put("widget", number); db.update(DatabaseTest.TABLE_ANIME, cvn, "widget = ?", new String[]{Integer.toString(number + 1)}); db.update(DatabaseTest.TABLE_MANGA, cvn, "widget = ?", new String[]{Integer.toString(number + 1)}); } public boolean deleteAnime(int id) { boolean result = db.delete(DatabaseTest.TABLE_ANIME, "anime_id = ?", new String[]{String.valueOf(id)}) == 1; if (result) cleanupAnimeTable(); return result; } public boolean deleteManga(int id) { boolean result = db.delete(DatabaseTest.TABLE_MANGA, "manga_id = ?", new String[]{String.valueOf(id)}) == 1; if (result) cleanupMangaTable(); return result; } }
package com.almasb.fxglgames.breakout; import com.almasb.fxgl.animation.AnimatedValue; import com.almasb.fxgl.animation.Animation; import com.almasb.fxgl.animation.Interpolators; import com.almasb.fxgl.app.ApplicationMode; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.SpawnData; import com.almasb.fxgl.entity.components.IrremovableComponent; import com.almasb.fxgl.input.UserAction; import com.almasb.fxgl.physics.CollisionHandler; import com.almasb.fxgl.physics.HitBox; import com.almasb.fxglgames.breakout.components.BackgroundStarsViewComponent; import com.almasb.fxglgames.breakout.components.BallComponent; import com.almasb.fxglgames.breakout.components.BatComponent; import com.almasb.fxglgames.breakout.components.BrickComponent; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.util.Duration; import java.util.Map; import static com.almasb.fxgl.dsl.FXGL.*; import static com.almasb.fxglgames.breakout.BreakoutType.*; /** * @author Almas Baimagambetov (almaslvl@gmail.com) */ public class BreakoutApp extends GameApplication { public static final int WIDTH = 14 * 96; public static final int HEIGHT = 22 * 32; private static final int MAX_LEVEL = 5; private static final int STARTING_LEVEL = 1; @Override protected void initSettings(GameSettings settings) { settings.setTitle("FXGL Breakout"); settings.setVersion("2.0"); settings.setWidth(WIDTH); settings.setHeight(HEIGHT); settings.setFontUI("main_font.ttf"); settings.setIntroEnabled(true); settings.setProfilingEnabled(true); settings.setApplicationMode(ApplicationMode.DEVELOPER); } @Override protected void onPreInit() { getSettings().setGlobalMusicVolume(0.5); getSettings().setGlobalSoundVolume(0.5); loopBGM("BGM.mp3"); } @Override protected void initInput() { getInput().addAction(new UserAction("Move Left") { @Override protected void onAction() { getBatControl().left(); } @Override protected void onActionEnd() { getBatControl().stop(); } }, KeyCode.A); getInput().addAction(new UserAction("Move Right") { @Override protected void onAction() { getBatControl().right(); } @Override protected void onActionEnd() { getBatControl().stop(); } }, KeyCode.D); onKeyDown(KeyCode.SPACE, "Change color", () -> getBallControl().changeColorToNext()); if (!isReleaseMode()) { onKeyDown(KeyCode.L, "Next level", () -> nextLevel()); onKeyDown(KeyCode.K, "Print", () -> { byType(BACKGROUND).get(0).getComponent(BackgroundStarsViewComponent.class).onUpdate(0.016); System.out.println(); }); } } @Override protected void initGameVars(Map<String, Object> vars) { vars.put("lives", 3); vars.put("score", 0); vars.put("level", STARTING_LEVEL); } @Override protected void initGame() { getGameWorld().addEntityFactory(new BreakoutFactory()); initBackground(); setLevel(STARTING_LEVEL); } private void initBackground() { getGameScene().setBackgroundColor(Color.BLACK); spawn("background"); spawn("colorCircle", -200, getAppHeight() - 200); // we add IrremovableComponent because regardless of the level // the screen bounds stay in the game world entityBuilder() .type(WALL) .collidable() .with(new IrremovableComponent()) .buildScreenBoundsAndAttach(40); } private void nextLevel() { inc("level", +1); var levelNum = geti("level"); if (levelNum > MAX_LEVEL) { getDialogService().showMessageBox("You have completed demo!", getGameController()::exit); return; } setLevel(levelNum); } private void setLevel(int levelNum) { getGameWorld().getEntitiesCopy().forEach(e -> e.removeFromWorld()); setLevelFromMap("tmx/level" + levelNum + ".tmx"); var ball = spawn("ball", getAppWidth() / 2, getAppHeight() - 250); ball.getComponent(BallComponent.class).colorProperty().addListener((obs, old, newValue) -> { var circle = (Circle) getGameWorld().getSingleton(COLOR_CIRCLE).getViewComponent().getChildren().get(0); circle.setFill(getBallControl().getNextColor()); }); spawn("bat", getAppWidth() / 2, getAppHeight() - 180); animateCamera(() -> { getSceneService().pushSubScene(new NewLevelSubScene(levelNum)); getBallControl().release(); }); } private Animation<Double> cameraAnimation; private void animateCamera(Runnable onAnimationFinished) { AnimatedValue<Double> value = new AnimatedValue<>(getAppHeight() * 1.0, 0.0); cameraAnimation = animationBuilder() .duration(Duration.seconds(0.5)) .interpolator(Interpolators.EXPONENTIAL.EASE_OUT()) .onFinished(onAnimationFinished::run) .animate(value) .onProgress(y -> getGameScene().getViewport().setY(y)) .build(); cameraAnimation.start(); } private void playHitSound() { play("hit.wav"); } @Override protected void initPhysics() { getPhysicsWorld().setGravity(0, 0); onCollisionBegin(BALL, BRICK, (ball, brick) -> { playHitSound(); if (!getBallControl().getColor().equals(brick.getComponent(BrickComponent.class).getColor())) { return; } ball.call("onHit"); brick.call("onHit"); spawn("sparks", new SpawnData(ball.getPosition()).put("color", getBallControl().getColor())); inc("score", +50); if (FXGLMath.randomBoolean()) { spawn("powerup", brick.getPosition()); } }); onCollisionCollectible(BAT, POWERUP, powerup -> { PowerupType type = powerup.getObject("powerupType"); getBallControl().applyPowerup(type); }); onCollisionBegin(BULLET_BALL, BRICK, (ball, brick) -> { ball.removeFromWorld(); brick.call("onHit"); }); onCollisionBegin(BAT, BALL, (bat, ball) -> { playHitSound(); ball.call("applySlow"); bat.call("onHit"); }); getPhysicsWorld().addCollisionHandler(new CollisionHandler(BALL, WALL) { @Override protected void onHitBoxTrigger(Entity a, Entity b, HitBox boxA, HitBox boxB) { playHitSound(); if (boxB.getName().equals("BOT")) { inc("score", -100); } getGameScene().getViewport().shakeTranslational(1.5); } }); } @Override protected void initUI() { var textScore = getUIFactoryService().newText(getip("score").asString()); addUINode(textScore, 220, getAppHeight() - 20); var regionLeft = new Rectangle(getAppWidth() / 2, getAppHeight()); regionLeft.setOpacity(0); regionLeft.setOnMousePressed(e -> getInput().mockKeyPress(KeyCode.A)); regionLeft.setOnMouseReleased(e -> getInput().mockKeyRelease(KeyCode.A)); var regionRight = new Rectangle(getAppWidth() / 2, getAppHeight()); regionRight.setOpacity(0); regionRight.setOnMousePressed(e -> getInput().mockKeyPress(KeyCode.D)); regionRight.setOnMouseReleased(e -> getInput().mockKeyRelease(KeyCode.D)); addUINode(regionLeft); addUINode(regionRight, getAppWidth() / 2, 0); runOnce(() -> { if (isReleaseMode()) { getSceneService().pushSubScene(new TutorialSubScene()); } runOnce(() -> getBallControl().changeColorToNext(), Duration.seconds(0.016)); }, Duration.seconds(0.5)); } @Override protected void onUpdate(double tpf) { cameraAnimation.onUpdate(tpf); if (byType(BRICK).isEmpty()) { nextLevel(); } } private BatComponent getBatControl() { return getGameWorld().getSingleton(BAT).getComponent(BatComponent.class); } private BallComponent getBallControl() { return getGameWorld().getSingleton(BALL).getComponent(BallComponent.class); } public static void main(String[] args) { launch(args); } }
package edu.wm.translationengine.appium; import edu.wm.translationengine.classes.Component; import edu.wm.translationengine.classes.TestCase; import edu.wm.translationengine.trans.AbstractChecker; public class AppiumChecker extends AbstractChecker { //class used to check for the presence of the necessary parameters to do an Appium test //will primarily rely on id values, but in the event we have no id, or conflicting/general values, ALL other necessary information must be provided to create a very specific xpath //PLEASE try to create JSON files which conform to UIAutomator viewer screen grabs @Override public boolean checkAppData(TestCase tc){ if(tc.getAppName() == null || tc.getAppName().equals("")){ return false; } //check that a file named appName.apk exists in the resources folder return true; } @Override public boolean checkClick(Component c){ //if id is null we cannot do anything. if(c.getId() == null) return false; //if id is a tricky id, all the other parameters better be explicit //class text and index are musts unless we are dealing with a checkedText widget which may rotate indices else if(c.getId().contains("android:id/") || c.getId().equals("") ){ if(c.getType() == null) return false; if(c.getText() == null) return false; if(!c.getType().equals("android.widget.CheckedTextView")){ if(c.getIndex() == null) return false; } } //in any other case where we arent dealing with tricky ids, we can go ahead and use the id return true; } @Override public boolean checkLongClick(Component c){ //if id is null we cannot do anything. if(c.getId() == null) return false; //if id is a tricky id, all the other parameters better be explicit //class text and index are musts unless we are dealing with a checkedText widget which may rotate indices else if(c.getId().contains("android:id/") || c.getId().equals("") ){ if(c.getType() == null) return false; if(c.getText() == null) return false; if(!c.getType().equals("android.widget.CheckedTextView")){ if(c.getIndex() == null) return false; } } //in any other case where we arent dealing with tricky ids, we can go ahead and use the id return true; } @Override public boolean checkType(Component c){ //TODO: this will need to be redone. Im pretty sure our group is using the text parameter wrong. UIAutomator uses text to refer to text on buttons on the screen. We should have a different parameter for text that we wish to type in //if id is null we cannot do anything. if(c.getId() == null) return false; //if id is a tricky id, all the other parameters better be explicit //class text and index are musts unless we are dealing with a checkedText widget which may rotate indices else if(c.getId().contains("android:id/") || c.getId().equals("") ){ if(c.getType() == null) return false; if(c.getText() == null) return false; if(!c.getType().equals("android.widget.CheckedTextView")){ if(c.getIndex() == null) return false; } } //in any other case where we arent dealing with tricky ids, we can go ahead and use the id return true; } }
package org.jboss.as.console.spi; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Operation mode meta data for presenters. Use only for presenters which are restricted to standalone or domain. * Don't use this annotation, if the presenter is supposed to run in both standalone and domain. * * @author Harald Pehl */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface OperationMode { /** * Carries the operation mode * * @return the operation mode */ Mode value(); enum Mode { STANDALONE, DOMAIN } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import cc.arduino.packages.BoardPort; import cc.arduino.packages.MonitorFactory; import cc.arduino.packages.Uploader; import cc.arduino.packages.uploaders.SerialUploader; import cc.arduino.view.GoToLineNumber; import cc.arduino.view.StubMenuListener; import cc.arduino.view.findreplace.FindReplace; import com.jcraft.jsch.JSchException; import jssc.SerialPortException; import processing.app.debug.RunnerException; import processing.app.forms.PasswordAuthorizationDialog; import processing.app.helpers.Keys; import processing.app.helpers.OSUtils; import processing.app.helpers.PreferencesMapException; import processing.app.legacy.PApplet; import processing.app.syntax.PdeKeywords; import processing.app.tools.MenuScroller; import processing.app.tools.Tool; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.BadLocationException; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.*; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.ConnectException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.List; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static processing.app.I18n.tr; import static processing.app.Theme.scale; /** * Main editor panel for the Processing Development Environment. */ @SuppressWarnings("serial") public class Editor extends JFrame implements RunnerListener { public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000; final Platform platform; private JMenu recentSketchesMenu; private JMenu programmersMenu; private final Box upper; private ArrayList<EditorTab> tabs = new ArrayList<>(); private int currentTabIndex = -1; private static class ShouldSaveIfModified implements Predicate<SketchController> { @Override public boolean test(SketchController controller) { return PreferencesData.getBoolean("editor.save_on_verify") && controller.getSketch().isModified() && !controller.isReadOnly( BaseNoGui.librariesIndexer .getInstalledLibraries(), BaseNoGui.getExamplesPath()); } } private static class ShouldSaveReadOnly implements Predicate<SketchController> { @Override public boolean test(SketchController sketch) { return sketch.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath()); } } private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList("serial", "network"); private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(tr("Serial ports"), tr("Network ports")); final Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered private static final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ private static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; private PageFormat pageFormat; // file, sketch, and tools menus for re-inserting items private JMenu fileMenu; private JMenu toolsMenu; private int numTools = 0; public boolean avoidMultipleOperations = false; private final EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; private static JMenu portMenu; static volatile AbstractMonitor serialMonitor; static AbstractMonitor serialPlotter; final EditorHeader header; EditorStatus status; EditorConsole console; private JSplitPane splitPane; // currently opened program SketchController sketchController; Sketch sketch; EditorLineStatus lineStatus; //JEditorPane editorPane; /** Contains all EditorTabs, of which only one will be visible */ private JPanel codePanel; //Runner runtime; private JMenuItem saveMenuItem; private JMenuItem saveAsMenuItem; //boolean presenting; private boolean uploading; // undo fellers private JMenuItem undoItem; private JMenuItem redoItem; protected UndoAction undoAction; protected RedoAction redoAction; private FindReplace find; Runnable runHandler; Runnable presentHandler; private Runnable runAndSaveHandler; private Runnable presentAndSaveHandler; Runnable exportHandler; private Runnable exportAppHandler; private Runnable timeoutUploadHandler; public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception { super("Arduino"); this.base = ibase; this.platform = platform; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { base.handleActivated(Editor.this); } // added for 1.0.5 public void windowDeactivated(WindowEvent e) { fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); List<Component> toolsMenuItemsToRemove = new LinkedList<>(); for (Component menuItem : toolsMenu.getMenuComponents()) { if (menuItem instanceof JComponent) { Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation"); if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) { toolsMenuItemsToRemove.add(menuItem); } } } for (Component menuItem : toolsMenuItemsToRemove) { toolsMenu.remove(menuItem); } toolsMenu.remove(portMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); contentPain.add(pane, BorderLayout.CENTER); Box box = Box.createVerticalBox(); upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); // assemble console panel, consisting of status area and the console itself JPanel consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(); console.setName("console"); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(); consolePanel.add(lineStatus, BorderLayout.SOUTH); codePanel = new JPanel(new BorderLayout()); upper.add(codePanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // By default, the split pane binds Ctrl-Tab and Ctrl-Shift-Tab for changing // focus. Since we do not use that, but want to use these shortcuts for // switching tabs, remove the bindings from the split pane. This allows the // events to bubble up and be handled by the EditorHeader. Keys.killBinding(splitPane, Keys.ctrl(KeyEvent.VK_TAB)); Keys.killBinding(splitPane, Keys.ctrlShift(KeyEvent.VK_TAB)); splitPane.setDividerSize(scale(splitPane.getDividerSize())); // the following changed from 600, 400 for netbooks splitPane.setMinimumSize(scale(new Dimension(600, 100))); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) // listener = new EditorListener(this, textarea); pane.add(box); pane.setTransferHandler(new FileDropHandler()); // Set the minimum size for the editor window setMinimumSize(scale(new Dimension( PreferencesData.getInteger("editor.window.width.min"), PreferencesData.getInteger("editor.window.height.min")))); // Bring back the general options for the editor applyPreferences(); // Finish preparing Editor (formerly found in Base) pack(); // Set the window bounds and the divider location before setting it visible setPlacement(storedLocation, defaultLocation); // Open the document that was passed in boolean loaded = handleOpenInternal(file); if (!loaded) sketchController = null; } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ private class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> list = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (File file : list) { if (sketchController.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (String piece : pieces) { if (piece.startsWith("#")) continue; String path = null; if (piece.startsWith("file: path = piece.substring(7); } else if (piece.startsWith("file:/")) { path = piece.substring(5); } if (sketchController.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError(tr("No files were added to the sketch.")); } else if (successful == 1) { statusNotice(tr("One file added to the sketch.")); } else { statusNotice( I18n.format(tr("{0} files added to the sketch."), successful)); } return true; } } private void setPlacement(int[] storedLocation, int[] defaultLocation) { if (storedLocation.length > 5 && storedLocation[5] != 0) { setExtendedState(storedLocation[5]); setPlacement(defaultLocation); } else { setPlacement(storedLocation); } } private void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[6]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); location[5] = getExtendedState() & MAXIMIZED_BOTH; return location; } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { boolean external = PreferencesData.getBoolean("editor.external"); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); for (EditorTab tab: tabs) tab.applyPreferences(); } private void buildMenuBar() { JMenuBar menubar = new JMenuBar(); final JMenu fileMenu = buildFileMenu(); fileMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(fileMenu.getComponents()); if (!components.contains(sketchbookMenu)) { fileMenu.insert(sketchbookMenu, 3); } if (!components.contains(sketchbookMenu)) { fileMenu.insert(examplesMenu, 4); } fileMenu.revalidate(); validate(); } }); menubar.add(fileMenu); menubar.add(buildEditMenu()); final JMenu sketchMenu = new JMenu(tr("Sketch")); sketchMenu.setMnemonic(KeyEvent.VK_S); sketchMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { buildSketchMenu(sketchMenu); sketchMenu.revalidate(); validate(); } }); buildSketchMenu(sketchMenu); menubar.add(sketchMenu); final JMenu toolsMenu = buildToolsMenu(); toolsMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(toolsMenu.getComponents()); int offset = 0; for (JMenu menu : base.getBoardsCustomMenus()) { if (!components.contains(menu)) { toolsMenu.insert(menu, numTools + offset); offset++; } } if (!components.contains(portMenu)) { toolsMenu.insert(portMenu, numTools + offset); } programmersMenu.removeAll(); base.getProgrammerMenus().forEach(programmersMenu::add); toolsMenu.revalidate(); validate(); } }); menubar.add(toolsMenu); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } private JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu(tr("File")); fileMenu.setMnemonic(KeyEvent.VK_F); item = newJMenuItem(tr("New"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleNew(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); item = Editor.newJMenuItem(tr("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleOpenPrompt(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); base.rebuildRecentSketchesMenuItems(); recentSketchesMenu = new JMenu(tr("Open Recent")); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { rebuildRecentSketchesMenu(); } }); fileMenu.add(recentSketchesMenu); if (sketchbookMenu == null) { sketchbookMenu = new JMenu(tr("Sketchbook")); MenuScroller.setScrollerFor(sketchbookMenu); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu(tr("Examples")); MenuScroller.setScrollerFor(examplesMenu); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem(tr("Close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem(tr("Save"), 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift(tr("Save As..."), 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); fileMenu.addSeparator(); item = newJMenuItemShift(tr("Page Setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem(tr("Print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!OSUtils.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem(tr("Preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem(tr("Quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } public void rebuildRecentSketchesMenu() { recentSketchesMenu.removeAll(); for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) { recentSketchesMenu.add(recentSketchMenuItem); } } private void buildSketchMenu(JMenu sketchMenu) { sketchMenu.removeAll(); JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false, Editor.this.presentHandler, Editor.this.runHandler); } }); sketchMenu.add(item); item = newJMenuItem(tr("Upload"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); sketchMenu.add(item); item = newJMenuItemShift(tr("Upload Using Programmer"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(true); } }); sketchMenu.add(item); item = newJMenuItemAlt(tr("Export compiled Binary"), 'S'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (new ShouldSaveReadOnly().test(sketchController) && !handleSave(true)) { System.out.println(tr("Export canceled, changes must first be saved.")); return; } handleRun(false, new ShouldSaveReadOnly(), Editor.this.presentAndSaveHandler, Editor.this.runAndSaveHandler); } }); sketchMenu.add(item); // item = new JMenuItem("Stop"); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleStop(); // sketchMenu.add(item); sketchMenu.addSeparator(); item = newJMenuItem(tr("Show Sketch Folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); if (importMenu == null) { importMenu = new JMenu(tr("Include Library")); MenuScroller.setScrollerFor(importMenu); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = new JMenuItem(tr("Add File...")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketchController.handleAddFile(); } }); sketchMenu.add(item); } private JMenu buildToolsMenu() { toolsMenu = new JMenu(tr("Tools")); toolsMenu.setMnemonic(KeyEvent.VK_T); addInternalTools(toolsMenu); JMenuItem item = newJMenuItemShift(tr("Serial Monitor"), 'M'); item.addActionListener(e -> handleSerial()); toolsMenu.add(item); item = newJMenuItemShift(tr("Serial Plotter"), 'L'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePlotter(); } }); toolsMenu.add(item); addTools(toolsMenu, BaseNoGui.getToolsFolder()); File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools"); addTools(toolsMenu, sketchbookTools); toolsMenu.addSeparator(); numTools = toolsMenu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) base.getBoardsCustomMenus().stream().forEach(toolsMenu::add); if (portMenu == null) portMenu = new JMenu(tr("Port")); populatePortMenu(); toolsMenu.add(portMenu); item = new JMenuItem(tr("Get Board Info")); item.addActionListener(e -> handleBoardInfo()); toolsMenu.add(item); toolsMenu.addSeparator(); base.rebuildProgrammerMenu(); programmersMenu = new JMenu(tr("Programmer")); base.getProgrammerMenus().stream().forEach(programmersMenu::add); toolsMenu.add(programmersMenu); item = new JMenuItem(tr("Burn Bootloader")); item.addActionListener(e -> handleBurnBootloader()); toolsMenu.add(item); toolsMenu.addMenuListener(new StubMenuListener() { public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populatePortMenu(); for (Component c : toolsMenu.getMenuComponents()) { if ((c instanceof JMenu) && c.isVisible()) { JMenu menu = (JMenu)c; String name = menu.getText(); if (name == null) continue; String basename = name; int index = name.indexOf(':'); if (index > 0) basename = name.substring(0, index); String sel = null; int count = menu.getItemCount(); for (int i=0; i < count; i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isSelected()) { sel = item.getText(); if (sel != null) break; } } if (sel == null) { if (!name.equals(basename)) menu.setText(basename); } else { if (sel.length() > 50) sel = sel.substring(0, 50) + "..."; String newname = basename + ": \"" + sel + "\""; if (!name.equals(newname)) menu.setText(newname); } } } } }); return toolsMenu; } private void addTools(JMenu menu, File sourceFolder) { if (sourceFolder == null) return; Map<String, JMenuItem> toolItems = new HashMap<>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (File folder : folders) { File toolDirectory = new File(folder, "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (File archive : archives) { className = findClassInZipFile(folder.getName(), archive); if (className != null) break; } // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add(toolItems.get(title)); } } private String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // noop } } } return null; } public void updateKeywords(PdeKeywords keywords) { for (EditorTab tab : tabs) tab.updateKeywords(keywords); } JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } private void addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("cc.arduino.packages.formatter.AStyle"); if (item == null) { throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable"); } item.setName("menuToolsAutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); } class SerialMenuListener implements ActionListener { private final String serialPort; public SerialMenuListener(String serialPort) { this.serialPort = serialPort; } public void actionPerformed(ActionEvent e) { selectSerialPort(serialPort); base.onBoardOrPortChange(); } } private void selectSerialPort(String name) { if(portMenu == null) { System.out.println(tr("serialMenu is null")); return; } if (name == null) { System.out.println(tr("name is null")); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < portMenu.getItemCount(); i++) { JMenuItem menuItem = portMenu.getItem(i); if (!(menuItem instanceof JCheckBoxMenuItem)) { continue; } JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem); checkBoxMenuItem.setState(false); if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); BaseNoGui.selectSerialPort(name); if (serialMonitor != null) { try { serialMonitor.close(); serialMonitor.setVisible(false); } catch (Exception e) { // ignore } } if (serialPlotter != null) { try { serialPlotter.close(); serialPlotter.setVisible(false); } catch (Exception e) { // ignore } } onBoardOrPortChange(); base.onBoardOrPortChange(); //System.out.println("set to " + get("serial.port")); } private void populatePortMenu() { portMenu.removeAll(); String selectedPort = PreferencesData.get("serial.port"); List<BoardPort> ports = Base.getDiscoveryManager().discovery(); ports = platform.filterPorts(ports, PreferencesData.getBoolean("serial.ports.showall")); Collections.sort(ports, new Comparator<BoardPort>() { @Override public int compare(BoardPort o1, BoardPort o2) { return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol()); } }); String lastProtocol = null; String lastProtocolTranslated; for (BoardPort port : ports) { if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) { if (lastProtocol != null) { portMenu.addSeparator(); } lastProtocol = port.getProtocol(); if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) { lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol())); } else { lastProtocolTranslated = port.getProtocol(); } JMenuItem lastProtocolMenuItem = new JMenuItem(tr(lastProtocolTranslated)); lastProtocolMenuItem.setEnabled(false); portMenu.add(lastProtocolMenuItem); } String address = port.getAddress(); String label = port.getLabel(); JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort)); item.addActionListener(new SerialMenuListener(address)); portMenu.add(item); } portMenu.setEnabled(portMenu.getMenuComponentCount() > 0); } private JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu(tr("Help")); menu.setMnemonic(KeyEvent.VK_H); JMenuItem item; item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showArduinoGettingStarted(); } }); menu.add(item); item = new JMenuItem(tr("Environment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem(tr("Reference")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(tr("Galileo Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "ArduinoIDE_guide_galileo"); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "Guide_Troubleshooting_Galileo"); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(tr("Edison Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "ArduinoIDE_guide_edison"); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "Guide_Troubleshooting_Edison"); } }); menu.add(item); menu.addSeparator(); item = newJMenuItemShift(tr("Find in Reference"), 'F'); item.addActionListener(this::handleFindReference); menu.add(item); item = new JMenuItem(tr("Frequently Asked Questions")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem(tr("Visit Arduino.cc")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(tr("http: } }); menu.add(item); // macosx already has its own about menu if (!OSUtils.isMacOS()) { menu.addSeparator(); item = new JMenuItem(tr("About Arduino")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } private JMenu buildEditMenu() { JMenu menu = new JMenu(tr("Edit")); menu.setName("menuEdit"); menu.setMnemonic(KeyEvent.VK_E); undoItem = newJMenuItem(tr("Undo"), 'Z'); undoItem.setName("menuEditUndo"); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); if (!OSUtils.isMacOS()) { redoItem = newJMenuItem(tr("Redo"), 'Y'); } else { redoItem = newJMenuItemShift(tr("Redo"), 'Z'); } redoItem.setName("menuEditRedo"); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); JMenuItem cutItem = newJMenuItem(tr("Cut"), 'X'); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleCut(); } }); menu.add(cutItem); JMenuItem copyItem = newJMenuItem(tr("Copy"), 'C'); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().getTextArea().copy(); } }); menu.add(copyItem); JMenuItem copyForumItem = newJMenuItemShift(tr("Copy for Forum"), 'C'); copyForumItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleDiscourseCopy(); } }); menu.add(copyForumItem); JMenuItem copyHTMLItem = newJMenuItemAlt(tr("Copy as HTML"), 'C'); copyHTMLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleHTMLCopy(); } }); menu.add(copyHTMLItem); JMenuItem pasteItem = newJMenuItem(tr("Paste"), 'V'); pasteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handlePaste(); } }); menu.add(pasteItem); JMenuItem selectAllItem = newJMenuItem(tr("Select All"), 'A'); selectAllItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleSelectAll(); } }); menu.add(selectAllItem); JMenuItem gotoLine = newJMenuItem(tr("Go to line..."), 'L'); gotoLine.addActionListener(e -> { GoToLineNumber goToLineNumber = new GoToLineNumber(Editor.this); goToLineNumber.setLocationRelativeTo(Editor.this); goToLineNumber.setVisible(true); }); menu.add(gotoLine); menu.addSeparator(); JMenuItem commentItem = newJMenuItem(tr("Comment/Uncomment"), '/'); commentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleCommentUncomment(); } }); menu.add(commentItem); JMenuItem increaseIndentItem = new JMenuItem(tr("Increase Indent")); increaseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); increaseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleIndentOutdent(true); } }); menu.add(increaseIndentItem); JMenuItem decreseIndentItem = new JMenuItem(tr("Decrease Indent")); decreseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); decreseIndentItem.setName("menuDecreaseIndent"); decreseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleIndentOutdent(false); } }); menu.add(decreseIndentItem); menu.addSeparator(); JMenuItem findItem = newJMenuItem(tr("Find..."), 'F'); findItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } if (!OSUtils.isMacOS()) { find.setFindText(getCurrentTab().getSelectedText()); } find.setLocationRelativeTo(Editor.this); find.setVisible(true); } }); menu.add(findItem); JMenuItem findNextItem = newJMenuItem(tr("Find Next"), 'G'); findNextItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findNext(); } } }); menu.add(findNextItem); JMenuItem findPreviousItem = newJMenuItemShift(tr("Find Previous"), 'G'); findPreviousItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findPrevious(); } } }); menu.add(findPreviousItem); if (OSUtils.isMacOS()) { JMenuItem useSelectionForFindItem = newJMenuItem(tr("Use Selection For Find"), 'E'); useSelectionForFindItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } find.setFindText(getCurrentTab().getSelectedText()); } }); menu.add(useSelectionForFindItem); } menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { boolean enabled = getCurrentTab().getSelectedText() != null; cutItem.setEnabled(enabled); copyItem.setEnabled(enabled); } @Override public void menuDeselected(MenuEvent e) {} @Override public void menuCanceled(MenuEvent e) {} }); return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ private static JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { getCurrentTab().handleUndo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } } protected void updateUndoState() { UndoManager undo = getCurrentTab().getUndoManager(); if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText(tr("Undo")); putValue(Action.NAME, "Undo"); } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { getCurrentTab().handleRedo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } } protected void updateRedoState() { UndoManager undo = getCurrentTab().getUndoManager(); if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText(tr("Redo")); putValue(Action.NAME, "Redo"); } } } // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. private void resetHandlers() { runHandler = new BuildHandler(); presentHandler = new BuildHandler(true); runAndSaveHandler = new BuildHandler(false, true); presentAndSaveHandler = new BuildHandler(true, true); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); timeoutUploadHandler = new TimeoutUploadHandler(); } /** * Gets the current sketch controller. */ public SketchController getSketchController() { return sketchController; } /** * Gets the current sketch. */ public Sketch getSketch() { return sketch; } /** * Gets the currently displaying tab. */ public EditorTab getCurrentTab() { return tabs.get(currentTabIndex); } /** * Gets the index of the currently displaying tab. */ public int getCurrentTabIndex() { return currentTabIndex; } /** * Returns an (unmodifiable) list of currently opened tabs. */ public List<EditorTab> getTabs() { return Collections.unmodifiableList(tabs); } /** * Change the currently displayed tab. * Note that the GUI might not update immediately, since this needs * to run in the Event dispatch thread. * @param index The index of the tab to select */ public void selectTab(final int index) { currentTabIndex = index; undoAction.updateUndoState(); redoAction.updateRedoState(); updateTitle(); header.rebuild(); getCurrentTab().activated(); // This must be run in the GUI thread SwingUtilities.invokeLater(() -> { codePanel.removeAll(); codePanel.add(tabs.get(index), BorderLayout.CENTER); tabs.get(index).requestFocusInWindow(); // get the caret blinking // For some reason, these are needed. Revalidate says it should be // automatically called when components are added or removed, but without // it, the component switched to is not displayed. repaint() is needed to // clear the entire text area of any previous text. codePanel.revalidate(); codePanel.repaint(); }); } public void selectNextTab() { selectTab((currentTabIndex + 1) % tabs.size()); } public void selectPrevTab() { selectTab((currentTabIndex - 1 + tabs.size()) % tabs.size()); } public EditorTab findTab(final SketchFile file) { return tabs.get(findTabIndex(file)); } /** * Finds the index of the tab showing the given file. Matches the file against * EditorTab.getSketchFile() using ==. * * @returns The index of the tab for the given file, or -1 if no such tab was * found. */ public int findTabIndex(final SketchFile file) { for (int i = 0; i < tabs.size(); ++i) { if (tabs.get(i).getSketchFile() == file) return i; } return -1; } /** * Finds the index of the tab showing the given file. Matches the file against * EditorTab.getSketchFile().getFile() using equals. * * @returns The index of the tab for the given file, or -1 if no such tab was * found. */ public int findTabIndex(final File file) { for (int i = 0; i < tabs.size(); ++i) { if (tabs.get(i).getSketchFile().getFile().equals(file)) return i; } return -1; } /** * Create tabs for each of the current sketch's files, removing any existing * tabs. */ public void createTabs() { tabs.clear(); currentTabIndex = -1; tabs.ensureCapacity(sketch.getCodeCount()); for (SketchFile file : sketch.getFiles()) { try { addTab(file, null); } catch(IOException e) { // TODO: Improve / move error handling System.err.println(e); } } selectTab(0); } /** * Reorders tabs as per current sketch's files order */ public void reorderTabs() { Collections.sort(tabs, (x, y) -> Sketch.CODE_DOCS_COMPARATOR.compare(x.getSketchFile(), y.getSketchFile())); } /** * Add a new tab. * * @param file * The file to show in the tab. * @param contents * The contents to show in the tab, or null to load the contents from * the given file. * @throws IOException */ protected void addTab(SketchFile file, String contents) throws IOException { EditorTab tab = new EditorTab(this, file, contents); tabs.add(tab); reorderTabs(); } protected void removeTab(SketchFile file) throws IOException { int index = findTabIndex(file); tabs.remove(index); } void handleFindReference(ActionEvent e) { String text = getCurrentTab().getCurrentKeyword(); String referenceFile = base.getPdeKeywords().getReference(text); if (referenceFile == null) { statusNotice(I18n.format(tr("No reference available for \"{0}\""), text)); } else { if (referenceFile.startsWith("Serial_")) { Base.showReference("Serial/" + referenceFile.substring("Serial_".length())); } else { Base.showReference("Reference/" + referenceFile); } } } /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. * @param verboseHandler * @param nonVerboseHandler */ public void handleRun(final boolean verbose, Runnable verboseHandler, Runnable nonVerboseHandler) { handleRun(verbose, new ShouldSaveIfModified(), verboseHandler, nonVerboseHandler); } private void handleRun(final boolean verbose, Predicate<SketchController> shouldSavePredicate, Runnable verboseHandler, Runnable nonVerboseHandler) { if (shouldSavePredicate.test(sketchController)) { handleSave(true); } toolbar.activateRun(); status.progress(tr("Compiling sketch...")); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (PreferencesData.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? verboseHandler : nonVerboseHandler).start(); } class BuildHandler implements Runnable { private final boolean verbose; private final boolean saveHex; public BuildHandler() { this(false); } public BuildHandler(boolean verbose) { this(verbose, false); } public BuildHandler(boolean verbose, boolean saveHex) { this.verbose = verbose; this.saveHex = saveHex; } @Override public void run() { try { removeAllLineHighlights(); sketchController.build(verbose, saveHex); statusNotice(tr("Done compiling.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while compiling: missing '{0}' configuration parameter"), e.getMessage())); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivateRun(); avoidMultipleOperations = false; } } public void removeAllLineHighlights() { for (EditorTab tab : tabs) tab.getTextArea().removeAllLineHighlights(); } public void addLineHighlight(int line) throws BadLocationException { getCurrentTab().getTextArea().addLineHighlight(line, new Color(1, 0, 0, 0.2f)); getCurrentTab().getTextArea().setCaretPosition(getCurrentTab().getTextArea().getLineStartOffset(line)); } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ private void handleStop() { // called by menu or buttons // toolbar.activate(EditorToolbar.STOP); toolbar.deactivateRun(); // toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. toFront(); String prompt = I18n.format(tr("Save changes to \"{0}\"? "), sketch.getName()); if (!OSUtils.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, tr("Close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (result) { case JOptionPane.YES_OPTION: return handleSave(true); case JOptionPane.NO_OPTION: return true; // ok to continue case JOptionPane.CANCEL_OPTION: case JOptionPane.CLOSED_OPTION: // Escape key pressed return false; default: throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. JOptionPane pane = new JOptionPane(tr("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost."), JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { tr("Save"), tr("Cancel"), tr("Don't Save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else { return result == options[2]; } } } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(File sketchFile) { // check to make sure that this .pde file is // in a folder of the same name String fileName = sketchFile.getName(); File file = Sketch.checkSketchFile(sketchFile); if (file == null) { if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) { Base.showWarning(tr("Bad file selected"), tr("Arduino can only open its own sketches\n" + "and other files ending in .ino or .pde"), null); return false; } else { String properParent = fileName.substring(0, fileName.length() - 4); Object[] options = {tr("OK"), tr("Cancel")}; String prompt = I18n.format(tr("The file \"{0}\" needs to be inside\n" + "a sketch folder named \"{1}\".\n" + "Create this folder, move the file, and continue?"), fileName, properParent); int result = JOptionPane.showOptionDialog(this, prompt, tr("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result != JOptionPane.YES_OPTION) { return false; } // create properly named folder File properFolder = new File(sketchFile.getParent(), properParent); if (properFolder.exists()) { Base.showWarning(tr("Error"), I18n.format(tr("A folder named \"{0}\" already exists. " + "Can't open sketch."), properParent), null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning(tr("Error"), tr("Could not create the sketch folder."), null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, sketchFile.getName()); try { Base.copyFile(sketchFile, properPdeFile); } catch (IOException e) { Base.showWarning(tr("Error"), tr("Could not copy to a proper location."), e); return false; } // remove the original file, so user doesn't get confused sketchFile.delete(); // update with the new path file = properPdeFile; } } try { sketch = new Sketch(file); } catch (IOException e) { Base.showWarning(tr("Error"), tr("Could not create the sketch."), e); return false; } sketchController = new SketchController(this, sketch); createTabs(); // Disable untitled setting from previous document, if any untitled = false; // opening was successful return true; } private void updateTitle() { if (sketchController == null) { return; } SketchFile current = getCurrentTab().getSketchFile(); if (current.isPrimary()) { setTitle(I18n.format(tr("{0} | Arduino {1}"), sketch.getName(), BaseNoGui.VERSION_NAME_LONG)); } else { setTitle(I18n.format(tr("{0} - {1} | Arduino {2}"), sketch.getName(), current.getFileName(), BaseNoGui.VERSION_NAME_LONG)); } } public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 removeAllLineHighlights(); if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { return handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } private boolean handleSave2() { toolbar.activateSave(); statusNotice(tr("Saving...")); boolean saved = false; try { boolean wasReadOnly = sketchController.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath()); String previousMainFilePath = sketch.getMainFilePath(); saved = sketchController.save(); if (saved) { statusNotice(tr("Done Saving.")); if (wasReadOnly) { base.removeRecentSketchPath(previousMainFilePath); } base.storeRecentSketches(sketchController); base.rebuildRecentSketchesMenuItems(); } else { statusEmpty(); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivateSave(); return saved; } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activateSave(); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice(tr("Saving...")); try { if (sketchController.saveAs()) { base.storeRecentSketches(sketchController); base.rebuildRecentSketchesMenuItems(); statusNotice(tr("Done Saving.")); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice(tr("Save Canceled.")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivateSave(); // Update editor window title in case of "Save as..." updateTitle(); header.rebuild(); } return true; } private boolean serialPrompt() { int count = portMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = portMenu.getItem(i).getText(); } String result = (String) JOptionPane.showInputDialog(this, I18n.format( tr("Serial port {0} not found.\n" + "Retry the upload with another serial port?"), PreferencesData.get("serial.port") ), "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); base.onBoardOrPortChange(); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean usingProgrammer) { if (PreferencesData.getBoolean("editor.save_on_verify")) { if (sketch.isModified() && !sketchController.isReadOnly( BaseNoGui.librariesIndexer .getInstalledLibraries(), BaseNoGui.getExamplesPath())) { handleSave(true); } } toolbar.activateExport(); console.clear(); status.progress(tr("Uploading to I/O Board...")); new Thread(timeoutUploadHandler).start(); new Thread(usingProgrammer ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { removeAllLineHighlights(); if (serialMonitor != null) { serialMonitor.suspend(); } if (serialPlotter != null) { serialPlotter.suspend(); } uploading = true; boolean success = sketchController.exportApplet(false); if (success) { statusNotice(tr("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(tr("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { populatePortMenu(); avoidMultipleOperations = false; } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivateExport(); resumeOrCloseSerialMonitor(); resumeOrCloseSerialPlotter(); base.onBoardOrPortChange(); } } private void resumeOrCloseSerialMonitor() { // Return the serial monitor window to its initial state if (serialMonitor != null) { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); long sleptFor = 0; while (boardPort == null && sleptFor < MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR) { try { Thread.sleep(100); sleptFor += 100; boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); } catch (InterruptedException e) { // noop } } try { if (serialMonitor != null) { serialMonitor.resume(boardPort); if (boardPort == null) { serialMonitor.close(); handleSerial(); } else { serialMonitor.resume(boardPort); } } } catch (Exception e) { statusError(e); } } } private void resumeOrCloseSerialPlotter() { // Return the serial plotter window to its initial state if (serialPlotter != null) { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); try { if (serialPlotter != null) serialPlotter.resume(boardPort); if (boardPort == null) { serialPlotter.close(); handlePlotter(); } else { serialPlotter.resume(boardPort); } } catch (Exception e) { statusError(e); } } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { if (serialMonitor != null) { serialMonitor.suspend(); } if (serialPlotter != null) { serialPlotter.suspend(); } uploading = true; boolean success = sketchController.exportApplet(true); if (success) { statusNotice(tr("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(tr("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { avoidMultipleOperations = false; populatePortMenu(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivateExport(); resumeOrCloseSerialMonitor(); resumeOrCloseSerialPlotter(); base.onBoardOrPortChange(); } } class TimeoutUploadHandler implements Runnable { public void run() { try { //10 seconds, than reactivate upload functionality and let the programmer pid being killed Thread.sleep(1000 * 10); if (uploading) { avoidMultipleOperations = false; } } catch (InterruptedException e) { // noop } } } public void handleSerial() { if(serialPlotter != null) { if(serialPlotter.isClosed()) { serialPlotter = null; } else { statusError(tr("Serial monitor not available while plotter is open")); return; } } if (serialMonitor != null) { // The serial monitor already exists if (serialMonitor.isClosed()) { serialMonitor.dispose(); // If it's closed, clear the refrence to the existing // monitor and create a new one serialMonitor = null; } else { // If it's not closed, give it the focus try { serialMonitor.toFront(); serialMonitor.requestFocus(); return; } catch (Exception e) { // noop } } } BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (port == null) { statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port"))); return; } serialMonitor = new MonitorFactory().newMonitor(port); Base.setIcon(serialMonitor); // If currently uploading, disable the monitor (it will be later // enabled when done uploading) if (uploading || avoidMultipleOperations) { try { serialMonitor.suspend(); } catch (Exception e) { statusError(e); } } boolean success = false; do { if (serialMonitor.requiresAuthorization() && !PreferencesData.has(serialMonitor.getAuthorizationKey())) { PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console")); dialog.setLocationRelativeTo(this); dialog.setVisible(true); if (dialog.isCancelled()) { statusNotice(tr("Unable to open serial monitor")); return; } PreferencesData.set(serialMonitor.getAuthorizationKey(), dialog.getPassword()); } try { serialMonitor.setVisible(true); if (!avoidMultipleOperations) { serialMonitor.open(); } success = true; } catch (ConnectException e) { statusError(tr("Unable to connect: is the sketch using the bridge?")); } catch (JSchException e) { statusError(tr("Unable to connect: wrong password?")); } catch (SerialException e) { String errorMessage = e.getMessage(); if (e.getCause() != null && e.getCause() instanceof SerialPortException) { errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")"; } statusError(errorMessage); try { serialMonitor.close(); } catch (Exception e1) { // noop } } catch (Exception e) { statusError(e); } finally { if (serialMonitor.requiresAuthorization() && !success) { PreferencesData.remove(serialMonitor.getAuthorizationKey()); } } } while (serialMonitor.requiresAuthorization() && !success); } public void handlePlotter() { if(serialMonitor != null) { if(serialMonitor.isClosed()) { serialMonitor = null; } else { statusError(tr("Plotter not available while serial monitor is open")); return; } } if (serialPlotter != null) { // The serial plotter already exists if (serialPlotter.isClosed()) { // If it's closed, clear the refrence to the existing // plotter and create a new one serialPlotter = null; } else { // If it's not closed, give it the focus try { serialPlotter.toFront(); serialPlotter.requestFocus(); return; } catch (Exception e) { // noop } } } BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (port == null) { statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port"))); return; } serialPlotter = new SerialPlotter(port); Base.setIcon(serialPlotter); // If currently uploading, disable the plotter (it will be later // enabled when done uploading) if (uploading) { try { serialPlotter.suspend(); } catch (Exception e) { statusError(e); } } boolean success = false; do { if (serialPlotter.requiresAuthorization() && !PreferencesData.has(serialPlotter.getAuthorizationKey())) { PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console")); dialog.setLocationRelativeTo(this); dialog.setVisible(true); if (dialog.isCancelled()) { statusNotice(tr("Unable to open serial plotter")); return; } PreferencesData.set(serialPlotter.getAuthorizationKey(), dialog.getPassword()); } try { serialPlotter.open(); serialPlotter.setVisible(true); success = true; } catch (ConnectException e) { statusError(tr("Unable to connect: is the sketch using the bridge?")); } catch (JSchException e) { statusError(tr("Unable to connect: wrong password?")); } catch (SerialException e) { String errorMessage = e.getMessage(); if (e.getCause() != null && e.getCause() instanceof SerialPortException) { errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")"; } statusError(errorMessage); } catch (Exception e) { statusError(e); } finally { if (serialPlotter.requiresAuthorization() && !success) { PreferencesData.remove(serialPlotter.getAuthorizationKey()); } } } while (serialPlotter.requiresAuthorization() && !success); } private void handleBurnBootloader() { console.clear(); statusNotice(tr("Burning bootloader to I/O Board (this may take a minute)...")); new Thread(() -> { try { Uploader uploader = new SerialUploader(); if (uploader.burnBootloader()) { SwingUtilities.invokeLater(() -> statusNotice(tr("Done burning bootloader."))); } else { SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader."))); // error message will already be visible } } catch (PreferencesMapException e) { SwingUtilities.invokeLater(() -> { statusError(I18n.format( tr("Error while burning bootloader: missing '{0}' configuration parameter"), e.getMessage())); }); } catch (RunnerException e) { SwingUtilities.invokeLater(() -> statusError(e.getMessage())); } catch (Exception e) { SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader."))); e.printStackTrace(); } }).start(); } private void handleBoardInfo() { console.clear(); String selectedPort = PreferencesData.get("serial.port"); List<BoardPort> ports = Base.getDiscoveryManager().discovery(); String label = ""; String vid = ""; String pid = ""; String iserial = ""; String protocol = ""; boolean found = false; for (BoardPort port : ports) { if (port.getAddress().equals(selectedPort)) { label = port.getBoardName(); vid = port.getVID(); pid = port.getPID(); iserial = port.getISerial(); protocol = port.getProtocol(); found = true; break; } } if (!found) { statusNotice(tr("Please select a port to obtain board info")); return; } if (protocol.equals("network")) { statusNotice(tr("Network port, can't obtain info")); return; } if (vid == null || vid.equals("") || vid.equals("0000")) { statusNotice(tr("Native serial port, can't obtain info")); return; } if (iserial == null || iserial.equals("")) { iserial = tr("Upload any sketch to obtain it"); } if (label == null) { label = tr("Unknown board"); } String infos = I18n.format("BN: {0}\nVID: {1}\nPID: {2}\nSN: {3}", label, vid, pid, iserial); JTextArea textArea = new JTextArea(infos); JOptionPane.showMessageDialog(this, textArea, tr("Board Info"), JOptionPane.PLAIN_MESSAGE); } /** * Handler for File &rarr; Page Setup. */ private void handlePageSetup() { PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); } /** * Handler for File &rarr; Print. */ private void handlePrint() { statusNotice(tr("Printing...")); //printerJob = null; PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(getCurrentTab().getTextArea(), pageFormat); } else { printerJob.setPrintable(getCurrentTab().getTextArea()); } // set the name of the job to the code name printerJob.setJobName(getCurrentTab().getSketchFile().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(tr("Done printing.")); } catch (PrinterException pe) { statusError(tr("Error while printing.")); pe.printStackTrace(); } } else { statusNotice(tr("Printing canceled.")); } //printerJob = null; // clear this out? } /** * Show an error int the status bar. */ public void statusError(String what) { System.err.println(what); status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivateRun(); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeFile()) { selectTab(findTabIndex(re.getCodeFile())); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= getCurrentTab().getTextArea().getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = getCurrentTab().getTextArea().getLineCount() - 1; if (getCurrentTab().getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line } } if (line < 0 || line >= getCurrentTab().getTextArea().getLineCount()) { System.err.println(I18n.format(tr("Bad error line: {0}"), line)); } else { try { addLineHighlight(line); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ private void statusEmpty() { statusNotice(EMPTY); } protected void onBoardOrPortChange() { Map<String, String> boardPreferences = BaseNoGui.getBoardPreferences(); if (boardPreferences != null) lineStatus.setBoardName(boardPreferences.get("name")); else lineStatus.setBoardName("-"); lineStatus.setSerialPort(PreferencesData.get("serial.port")); lineStatus.repaint(); } }
package com.opencms.util; import com.opencms.file.*; import com.opencms.core.*; import java.util.*; import java.io.*; /** * This is a general helper class. * * @author Andreas Schouten * @author Alexander Lucas <alexander.lucas@framfab.de> * @author Stefan Marx <Stefan.Marx@framfab.de> */ public class Utils implements I_CmsConstants,I_CmsLogChannels { /** Constant for sorting files upward by name */ public static final int C_SORT_NAME_UP = 1; /** Constant for sorting files downward by name */ public static final int C_SORT_NAME_DOWN = 2; /** Constant for sorting files upward by lastmodified date */ public static final int C_SORT_LASTMODIFIED_UP = 3; /** Constant for sorting files downward by lastmodified date */ public static final int C_SORT_LASTMODIFIED_DOWN = 4; /** Constant for sorting files downward by publishing date */ public static final int C_SORT_PUBLISHED_DOWN = 5; /** * This method makes the sorting desicion for the creation of index and archive pages, * depending on the sorting method to be used. * @param cms Cms Object for accessign files. * @param sorting The sorting method to be used. * @param fileA One of the two CmsFile objects to be compared. * @param fileB The second of the two CmsFile objects to be compared. * @return <code>true</code> or <code>false</code>, depending if the two file objects have to be sorted. * @exception CmsException Is thrown when file access failed. * */ private static boolean compare(CmsObject cms, int sorting, CmsFile fileA, CmsFile fileB) throws CmsException { boolean cmp = false; String titleA = fileA.getName(); String titleB = fileB.getName(); long lastModifiedA = fileA.getDateLastModified(); long lastModifiedB = fileB.getDateLastModified(); CmsProject projectA = cms.readProject(fileA); CmsProject projectB = cms.readProject(fileB); switch(sorting) { case C_SORT_NAME_UP: cmp = (titleA.compareTo(titleB) > 0); break; case C_SORT_NAME_DOWN: cmp = (titleB.compareTo(titleA) > 0); break; case C_SORT_LASTMODIFIED_UP: cmp = (lastModifiedA > lastModifiedB); break; case C_SORT_LASTMODIFIED_DOWN: cmp = (lastModifiedA < lastModifiedB); break; case C_SORT_PUBLISHED_DOWN: cmp = (projectA.getPublishingDate() < projectB.getPublishingDate()); break; default: cmp = false; } return cmp; } /** * Returns a string representation of the full name of a user. * @param user The user to get the full name from * @return a string representation of the user fullname. */ public static String getFullName(CmsUser user) { String retValue = ""; if(user != null) { retValue += user.getFirstname() + " "; retValue += user.getLastname() + " ("; retValue += user.getName() + ")"; } return retValue; } /** * Gets a formated time string form a long time value. * @param time The time value as a long. * @return Formated time string. */ public static String getNiceDate(long time) { StringBuffer niceTime = new StringBuffer(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(time)); String day = "0" + new Integer(cal.get(Calendar.DAY_OF_MONTH)).intValue(); String month = "0" + new Integer(cal.get(Calendar.MONTH) + 1).intValue(); String year = new Integer(cal.get(Calendar.YEAR)).toString(); String hour = "0" + new Integer(cal.get(Calendar.HOUR) + 12 * cal.get(Calendar.AM_PM)).intValue(); String minute = "0" + new Integer(cal.get(Calendar.MINUTE)); if(day.length() == 3) { day = day.substring(1, 3); } if(month.length() == 3) { month = month.substring(1, 3); } if(hour.length() == 3) { hour = hour.substring(1, 3); } if(minute.length() == 3) { minute = minute.substring(1, 3); } niceTime.append(day + "."); niceTime.append(month + "."); niceTime.append(year + " "); niceTime.append(hour + ":"); niceTime.append(minute); return niceTime.toString(); } /** * Gets a formated time string form a long time value. * @param time The time value as a long. * @return Formated time string. */ public static String getNiceShortDate(long time) { StringBuffer niceTime = new StringBuffer(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(time)); String day = "0" + new Integer(cal.get(Calendar.DAY_OF_MONTH)).intValue(); String month = "0" + new Integer(cal.get(Calendar.MONTH) + 1).intValue(); String year = new Integer(cal.get(Calendar.YEAR)).toString(); if(day.length() == 3) { day = day.substring(1, 3); } if(month.length() == 3) { month = month.substring(1, 3); } niceTime.append(day + "."); niceTime.append(month + "."); niceTime.append(year); return niceTime.toString(); } /** * Gets the stack-trace of a exception, and returns it as a string. * @param e The exception to get the stackTrace from. * @return the stackTrace of the exception. */ public static String getStackTrace(Exception e) { // print the stack-trace into a writer, to get its content StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); e.printStackTrace(writer); if(e instanceof CmsException) { CmsException cmsException = (CmsException)e; if(cmsException.getException() != null) { cmsException.getException().printStackTrace(writer); } } try { writer.close(); stringWriter.close(); } catch(Exception err) { // ignore } return stringWriter.toString(); } /** * Replaces all line breaks in a given string object by * white spaces. All lines will be <code>trim</code>ed to * delete all unnecessary white spaces. * @param s Input string * @return Output String * @exception CmsException */ public static String removeLineBreaks(String s) throws CmsException { StringBuffer result = new StringBuffer(); BufferedReader br = new BufferedReader(new StringReader(s)); String lineStr = null; try { while((lineStr = br.readLine()) != null) { result.append(lineStr.trim()); result.append(" "); } } catch(IOException e) { throw new CmsException("Error while reading input stream in com.opencms.util.Utils.removeLineBreaks: " + e); } return result.toString(); } /** * Sorts a Vector of CmsFile objects according to an included sorting method. * @param cms Cms Object for accessign files. * @param unsortedFiles Vector containing a list of unsorted files * @param sorting The sorting method to be used. * @return Vector of sorted CmsFile objects */ public static Vector sort(CmsObject cms, Vector unsortedFiles, int sorting) { Vector v = new Vector(); Enumeration enu = unsortedFiles.elements(); CmsFile[] field = new CmsFile[unsortedFiles.size()]; CmsFile file; String docloader; int max = 0; try { // create an array with all unsorted files in it. This arre is later sorted in with // the sorting algorithem. while(enu.hasMoreElements()) { file = (CmsFile)enu.nextElement(); field[max] = file; max++; } // Sorting algorithm // This method uses an insertion sort algorithem int in, out; int nElem = max; for(out = 1;out < nElem;out++) { CmsFile temp = field[out]; in = out; while(in > 0 && compare(cms, sorting, field[in - 1], temp)) { field[in] = field[in - 1]; --in; } field[in] = temp; } // take sorted array and create a new vector of files out of it for(int i = 0;i < max;i++) { v.addElement(field[i]); } } catch(Exception e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, "[Utils] :" + e.toString()); } } return v; } /** * This method splits a overgiven string into substrings. * * @param toSplit the String to split. * @param at the delimeter. * * @return an Array of Strings. */ public static final String[] split(String toSplit, String at) { Vector parts = new Vector(); int index = 0; int nextIndex = toSplit.indexOf(at); while(nextIndex != -1) { parts.addElement((Object)toSplit.substring(index, nextIndex)); index = nextIndex + at.length(); nextIndex = toSplit.indexOf(at, index); } parts.addElement((Object)toSplit.substring(index)); String partsArray[] = new String[parts.size()]; parts.copyInto((Object[])partsArray); return (partsArray); } /** * Converts date string to a long value. * @param dateString The date as a string. * @return long value of date. */ public static long splitDate(String dateString) { long result = 0; if(dateString != null && !"".equals(dateString)) { String splittetDate[] = Utils.split(dateString, "."); GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(splittetDate[2]), Integer.parseInt(splittetDate[1]) - 1, Integer.parseInt(splittetDate[0]), 0, 0, 0); result = cal.getTime().getTime(); } return result; } public static boolean checkEmail(String address) { boolean result = true; try { javax.mail.internet.InternetAddress IPAdd = new javax.mail.internet.InternetAddress(address); } catch(javax.mail.internet.AddressException e) { result = false; } return result; } }
package com.puzzblocks; import com.puzzblocks.obj.WorldCanvas; import com.utilis.game.obj.CollisionGroup.Collision; public class Physics { protected static boolean movingLeft = false; protected static boolean movingRight = false; protected static float jumpCompleteness = 0F; protected static long lastFrameTime = 0L; protected static long currentTime = 0L; public static void doPhysics(WorldCanvas wc){ long deltaTime; //Time between frames, in milliseconds. long deltaSeconds; int gravDistance; int rightDistance; int leftDistance; //Sets currentTime. currentTime = System.currentTimeMillis(); //Checks if lastFrameTime is set, and if not, sets it to current time. if(lastFrameTime == 0L){ lastFrameTime = System.currentTimeMillis(); } //Calculates deltaTime. deltaTime = currentTime - lastFrameTime; deltaSeconds = deltaTime/1000; //Apply gravity. gravDistance = (int) (GameConstants.GRAVITY * deltaSeconds); //distance = speed * delta; wc.getPlayer().moveDown(gravDistance); //Check collisions. Collision gravCollision = wc.getCollisionGroup().checkCollision(); if(gravCollision.hasCollided()){ wc.getPlayer().moveUp(gravDistance); } //Move right. if(movingRight){ rightDistance = (int) (GameConstants.CHARACTER_MOVEMENT * deltaSeconds); //distance = speed * delta; wc.getPlayer().moveRight(rightDistance); //Check collisions. Collision rightCollision = wc.getCollisionGroup().checkCollision(); if(rightCollision.hasCollided()){ wc.getPlayer().moveLeft(gravDistance); } } //Move left. if(movingLeft){ leftDistance = (int) (GameConstants.CHARACTER_MOVEMENT * deltaSeconds); //distance = speed * delta; wc.getPlayer().moveLeft(leftDistance); //Check collisions. Collision leftCollision = wc.getCollisionGroup().checkCollision(); if(leftCollision.hasCollided()){ wc.getPlayer().moveRight(gravDistance); } } //Sets time of lastFrame. lastFrameTime = System.currentTimeMillis(); } public static void setMovingLeft(boolean movingLeft) { Physics.movingLeft = movingLeft; } public static void setMovingRight(boolean movingRight) { Physics.movingRight = movingRight; } }
package com.tvpower.kz; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.AdapterView; import android.content.Intent; //jsoup import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class tvpower extends Activity{ /** Called when the activity is first created. */ private Element chanel; private Elements canales; private TextView text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView)findViewById(R.id.textOne); final GridView grid = (GridView)findViewById(R.id.GridOpciones); String url = "http: Document doc = null; try{//sin esto no funciona esta mauser doc = Jsoup.connect(url).userAgent("Mozilla").get(); }catch(Exception e){ //not create text.setText("no se obtuvo nada"); return; } //Elements canales = doc.select("[href^=/canal/");//3 que no van: canales = doc.select(".canalimg"); /*va sin las comillas va sin las comillas de dentro en jQuery("[href^='/canal/ae']")*/ text.setText(doc.title() + " selector:-> " + canales.size()); grid.setAdapter(new ItemChanels(this, canales)); grid.setOnItemClickListener( new AdapterView.OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, android.view.View v, int position, long id){ Intent intent = new Intent(tvpower.this,Chanel.class); Bundle bundle = new Bundle(); chanel = canales.get(position); //todos los programas //Elements programs = chanel.parent().parent().select("td a"); bundle.putString("name",chanel.parent().text()); bundle.putString("html",chanel.parent().parent().parent().select("td").toString()); intent.putExtras(bundle); startActivity(intent); } } ); } }
package com.xrtb.pojo; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.xrtb.common.ForensiqLog; import com.xrtb.common.HttpPostGet; import com.xrtb.common.URIEncoder; /** * A Class that implements the Forenciq.com anti-fraud bid checking system. * @author Ben M. Faul * */ public class Forensiq { /** Endpoint of the forensiq api */ public String endpoint = "http://api.forensiq.com/check"; /** Your Forensiq key */ public String ck = "yourkeygoeshere"; /** Default threshhold for non bidding */ public int threshhold = 64; /** If the forensiq site throws an error or is not available, bid anyway? */ public boolean bidOnError = false; /** The precompiled preamble */ @JsonIgnore transient String preamble; /** The object mapper for converting the return from forensiq */ @JsonIgnore transient ObjectMapper mapper = new ObjectMapper(); /** A queue of HTTP get objects we can reuse */ @JsonIgnore transient Queue<HttpPostGet> httpQueue = new ConcurrentLinkedQueue<HttpPostGet>(); /** * Default constructor */ public Forensiq() { preamble = endpoint + "?" + "ck=" + ck + "&output=JSON&sub=s&"; } public Forensiq(String ck) { this.ck = ck; preamble = endpoint + "?" + "ck=" + ck + "&output=JSON&sub=s&"; } /** * Should I bid, or not? * @param rt String. The type, always "display". * @param ip String. The IP address of the user. * @param url String. The URL of the publisher. * @param ua String. The user agent. * @param seller String. The seller's domain. * @param crid String. The creative id * @return boolean. If it returns true, good to bid. Or, false if it fails the confidence test. * @throws Exception on missing rwquired fields - seller and IP. */ public ForensiqLog bid(String rt, String ip, String url, String ua, String seller, String crid) throws Exception { StringBuilder sb = new StringBuilder(preamble); JsonNode rootNode = null; if (seller == null || ip == null) { if (seller == null) throw new Exception("Required field seller is missing"); else throw new Exception("Required field ip is missing"); } String sellerE = URIEncoder.encodeURI(seller); sb.append("rt="); sb.append(rt); sb.append("&"); sb.append("ip="); sb.append(ip); sb.append("&"); sb.append("seller="); sb.append(seller); if (url != null) { sb.append("&"); sb.append("url="); sb.append(url); } if (ua != null) { sb.append("&"); sb.append("ua="); sb.append(ua); } if (crid != null) { sb.append("&"); sb.append("cmp="); sb.append(crid); } sb.append("&sub=s"); HttpPostGet http = null; if (httpQueue.isEmpty()) http = new HttpPostGet(); else http = httpQueue.remove(); try { long xtime = System.currentTimeMillis(); String content = http.sendGet(sb.toString()); xtime = System.currentTimeMillis() - xtime; rootNode = mapper.readTree(content); int risk = rootNode.get("riskScore").asInt(); int time = rootNode.get("timeMs").asInt(); if (risk > threshhold) { ForensiqLog m = new ForensiqLog(); m.ip = ip; m.url = url; m.ua = ua; m.seller = seller; m.risk = risk; return m; } return null; } catch (Exception e) { e.printStackTrace(); } finally { httpQueue.add(http); } ForensiqLog m = new ForensiqLog(); m.ip = ip; m.url = url; m.ua = ua; m.seller = seller; return m; } }
package cc.arduino; import cc.arduino.i18n.I18NAwareMessageConsumer; import cc.arduino.packages.BoardPort; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.lang3.StringUtils; import processing.app.*; import processing.app.debug.*; import processing.app.helpers.PreferencesMap; import processing.app.helpers.PreferencesMapException; import processing.app.helpers.ProcessUtils; import processing.app.helpers.StringReplacer; import processing.app.legacy.PApplet; import processing.app.tools.DoubleQuotedArgumentsOnWindowsCommandLine; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import static processing.app.I18n.tr; public class Compiler implements MessageConsumer { //used by transifex integration static { tr("'arch' folder is no longer supported! See http://goo.gl/gfFJzU for more information"); tr("Archiving built core (caching) in: {0}"); tr("Board {0} (platform {1}, package {2}) is unknown"); tr("Bootloader file specified but missing: {0}"); tr("Build options changed, rebuilding all"); tr("Unable to find {0} in {1}"); tr("Invalid quoting: no closing [{0}] char found."); tr("(legacy)"); tr("Multiple libraries were found for \"{0}\""); tr(" Not used: {0}"); tr(" Used: {0}"); tr("Library can't use both 'src' and 'utility' folders. Double check {0}"); tr("WARNING: library {0} claims to run on {1} architecture(s) and may be incompatible with your current board which runs on {2} architecture(s)."); tr("Looking for recipes like {0}*{1}"); tr("Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}"); tr("Selected board depends on '{0}' core (not installed)."); tr("{0} must be a folder"); tr("{0}: Unknown package"); tr("{0} pattern is missing"); tr("Platform {0} (package {1}) is unknown"); tr("Progress {0}"); tr("Missing '{0}' from library in {1}"); tr("Running: {0}"); tr("Running recipe: {0}"); tr("Setting build path to {0}"); tr("Unhandled type {0} in context key {1}"); tr("Unknown sketch file extension: {0}"); tr("Using library {0} at version {1} in folder: {2} {3}"); tr("Using library {0} in folder: {1} {2}"); tr("Using previously compiled file: {0}"); tr("WARNING: Category '{0}' in library {1} is not valid. Setting to '{2}'"); tr("Warning: platform.txt from core '{0}' misses property '{1}', using default value '{2}'. Consider upgrading this core."); tr("Warning: platform.txt from core '{0}' contains deprecated {1}, automatically converted to {2}. Consider upgrading this core."); tr("WARNING: Spurious {0} folder in '{1}' library"); tr("Sketch uses {0} bytes ({2}%%) of program storage space. Maximum is {1} bytes."); tr("Couldn't determine program size: {0}"); tr("Global variables use {0} bytes ({2}%%) of dynamic memory, leaving {3} bytes for local variables. Maximum is {1} bytes."); tr("Global variables use {0} bytes of dynamic memory."); tr("Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it."); tr("Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint."); tr("Low memory available, stability problems may occur."); tr("An error occurred while verifying the sketch"); tr("An error occurred while verifying/uploading the sketch"); tr("Can't find the sketch in the specified path"); tr("Done compiling"); tr("Done uploading"); tr("Error while uploading"); tr("Error while verifying"); tr("Error while verifying/uploading"); tr("Mode not supported"); tr("Multiple files not supported"); tr("No command line parameters found"); tr("No parameters"); tr("No sketch"); tr("No sketchbook"); tr("Only --verify, --upload or --get-pref are supported"); tr("Sketchbook path not defined"); tr("The --upload option supports only one file at a time"); tr("Verifying and uploading..."); } enum BuilderAction { COMPILE("-compile"), DUMP_PREFS("-dump-prefs"); final String value; BuilderAction(String value) { this.value = value; } } private static final Pattern ERROR_FORMAT = Pattern.compile("(.+\\.\\w+):(\\d+)(:\\d+)*:\\s*error:\\s*(.*)\\s*", Pattern.MULTILINE | Pattern.DOTALL); private final File pathToSketch; private final Sketch sketch; private String buildPath; private File buildCache; private final boolean verbose; private RunnerException exception; public Compiler(Sketch data) { this(data.getPrimaryFile().getFile(), data); } public Compiler(File pathToSketch, Sketch sketch) { this.pathToSketch = pathToSketch; this.sketch = sketch; this.verbose = PreferencesData.getBoolean("build.verbose"); } public String build(CompilerProgressListener progListener, boolean exportHex) throws RunnerException, PreferencesMapException, IOException { ArrayList<CompilerProgressListener> listeners = new ArrayList<>(); listeners.add(progListener); return this.build(listeners, exportHex); } public String build(ArrayList<CompilerProgressListener> progListeners, boolean exportHex) throws RunnerException, PreferencesMapException, IOException { this.buildPath = sketch.getBuildPath().getAbsolutePath(); this.buildCache = BaseNoGui.getCachePath(); TargetBoard board = BaseNoGui.getTargetBoard(); if (board == null) { throw new RunnerException("Board is not selected"); } TargetPlatform platform = board.getContainerPlatform(); TargetPackage aPackage = platform.getContainerPackage(); String vidpid = VIDPID(); PreferencesMap prefs = loadPreferences(board, platform, aPackage, vidpid); MessageConsumerOutputStream out = new MessageConsumerOutputStream(new ProgressAwareMessageConsumer(new I18NAwareMessageConsumer(System.out, System.err), progListeners), "\n"); MessageConsumerOutputStream err = new MessageConsumerOutputStream(new I18NAwareMessageConsumer(System.err, Compiler.this), "\n"); callArduinoBuilder(board, platform, aPackage, vidpid, BuilderAction.COMPILE, out, err); out.flush(); err.flush(); if (exportHex) { runActions("hooks.savehex.presavehex", prefs); saveHex(prefs); runActions("hooks.savehex.postsavehex", prefs); } return sketch.getPrimaryFile().getFileName(); } private String VIDPID() { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (boardPort == null) { return ""; } String vid = boardPort.getPrefs().get("vid"); String pid = boardPort.getPrefs().get("pid"); if (StringUtils.isEmpty(vid) || StringUtils.isEmpty(pid)) { return ""; } return vid.toUpperCase() + "_" + pid.toUpperCase(); } private PreferencesMap loadPreferences(TargetBoard board, TargetPlatform platform, TargetPackage aPackage, String vidpid) throws RunnerException, IOException { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); MessageConsumerOutputStream err = new MessageConsumerOutputStream(new I18NAwareMessageConsumer(new PrintStream(stderr), Compiler.this), "\n"); try { callArduinoBuilder(board, platform, aPackage, vidpid, BuilderAction.DUMP_PREFS, stdout, err); } catch (RunnerException e) { System.err.println(new String(stderr.toByteArray())); throw e; } PreferencesMap prefs = new PreferencesMap(); prefs.load(new ByteArrayInputStream(stdout.toByteArray())); return prefs; } private void addPathFlagIfPathExists(List<String> cmd, String flag, File folder) { if (folder.exists()) { cmd.add(flag); cmd.add(folder.getAbsolutePath()); } } private void callArduinoBuilder(TargetBoard board, TargetPlatform platform, TargetPackage aPackage, String vidpid, BuilderAction action, OutputStream outStream, OutputStream errStream) throws RunnerException { List<String> cmd = new ArrayList<>(); cmd.add(BaseNoGui.getContentFile("arduino-builder").getAbsolutePath()); cmd.add(action.value); cmd.add("-logger=machine"); File installedPackagesFolder = new File(BaseNoGui.getSettingsFolder(), "packages"); addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getHardwareFolder()); addPathFlagIfPathExists(cmd, "-hardware", installedPackagesFolder); addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getSketchbookHardwareFolder()); addPathFlagIfPathExists(cmd, "-tools", BaseNoGui.getContentFile("tools-builder")); addPathFlagIfPathExists(cmd, "-tools", Paths.get(BaseNoGui.getHardwarePath(), "tools", "avr").toFile()); addPathFlagIfPathExists(cmd, "-tools", installedPackagesFolder); addPathFlagIfPathExists(cmd, "-built-in-libraries", BaseNoGui.getContentFile("libraries")); addPathFlagIfPathExists(cmd, "-libraries", BaseNoGui.getSketchbookLibrariesFolder()); String fqbn = Stream.of(aPackage.getId(), platform.getId(), board.getId(), boardOptions(board)).filter(s -> !s.isEmpty()).collect(Collectors.joining(":")); cmd.add("-fqbn=" + fqbn); if (!"".equals(vidpid)) { cmd.add("-vid-pid=" + vidpid); } cmd.add("-ide-version=" + BaseNoGui.REVISION); cmd.add("-build-path"); cmd.add(buildPath); cmd.add("-warnings=" + PreferencesData.get("compiler.warning_level")); if (PreferencesData.getBoolean("compiler.cache_core") == true && buildCache != null) { cmd.add("-build-cache"); cmd.add(buildCache.getAbsolutePath()); } PreferencesData.getMap() .subTree("runtime.build_properties_custom") .entrySet() .stream() .forEach(kv -> cmd.add("-prefs=" + kv.getKey() + "=" + kv.getValue())); cmd.add("-prefs=build.warn_data_percentage=" + PreferencesData.get("build.warn_data_percentage")); for (Map.Entry<String, String> entry : BaseNoGui.getBoardPreferences().entrySet()) { if (entry.getKey().startsWith("runtime.tools")) { cmd.add("-prefs=" + entry.getKey() + "=" + entry.getValue()); } } //commandLine.addArgument("-debug-level=10", false); if (verbose) { cmd.add("-verbose"); } cmd.add(pathToSketch.getAbsolutePath()); if (verbose) { System.out.println(StringUtils.join(cmd, ' ')); } int result; try { Process proc = ProcessUtils.exec(cmd.toArray(new String[0])); MessageSiphon in = new MessageSiphon(proc.getInputStream(), (msg) -> { try { outStream.write(msg.getBytes()); } catch (Exception e) { exception = new RunnerException(e); } }); MessageSiphon err = new MessageSiphon(proc.getErrorStream(), (msg) -> { try { errStream.write(msg.getBytes()); } catch (Exception e) { exception = new RunnerException(e); } }); in.join(); err.join(); result = proc.waitFor(); } catch (Exception e) { throw new RunnerException(e); } if (exception != null) throw exception; if (result > 1) { System.err.println(I18n.format(tr("{0} returned {1}"), cmd.get(0), result)); } if (result != 0) { RunnerException re = new RunnerException(I18n.format(tr("Error compiling for board {0}."), board.getName())); re.hideStackTrace(); throw re; } } private void saveHex(PreferencesMap prefs) throws RunnerException { List<String> compiledSketches = new ArrayList<>(prefs.subTree("recipe.output.tmp_file", 1).values()); List<String> copyOfCompiledSketches = new ArrayList<>(prefs.subTree("recipe.output.save_file", 1).values()); if (isExportCompiledSketchSupported(compiledSketches, copyOfCompiledSketches, prefs)) { System.err.println(tr("Warning: This core does not support exporting sketches. Please consider upgrading it or contacting its author")); return; } PreferencesMap dict = new PreferencesMap(prefs); dict.put("ide_version", "" + BaseNoGui.REVISION); PreferencesMap withBootloaderDict = new PreferencesMap(dict); dict.put("build.project_name", dict.get("build.project_name") + ".with_bootloader"); if (!compiledSketches.isEmpty()) { for (int i = 0; i < compiledSketches.size(); i++) { saveHex(compiledSketches.get(i), copyOfCompiledSketches.get(i), dict); saveHex(compiledSketches.get(i), copyOfCompiledSketches.get(i), withBootloaderDict); } } else { try { saveHex(prefs.getOrExcept("recipe.output.tmp_file"), prefs.getOrExcept("recipe.output.save_file"), dict); saveHex(prefs.getOrExcept("recipe.output.tmp_file"), prefs.getOrExcept("recipe.output.save_file"), withBootloaderDict); } catch (PreferencesMapException e) { throw new RunnerException(e); } } } private void saveHex(String compiledSketch, String copyOfCompiledSketch, PreferencesMap prefs) throws RunnerException { try { compiledSketch = StringReplacer.replaceFromMapping(compiledSketch, prefs); copyOfCompiledSketch = StringReplacer.replaceFromMapping(copyOfCompiledSketch, prefs); copyOfCompiledSketch = copyOfCompiledSketch.replaceAll(":", "_"); Path compiledSketchPath; Path compiledSketchPathInSubfolder = Paths.get(prefs.get("build.path"), "sketch", compiledSketch); Path compiledSketchPathInBuildPath = Paths.get(prefs.get("build.path"), compiledSketch); if (Files.exists(compiledSketchPathInSubfolder)) { compiledSketchPath = compiledSketchPathInSubfolder; } else if (Files.exists(compiledSketchPathInBuildPath)) { compiledSketchPath = compiledSketchPathInBuildPath; } else { return; } Path copyOfCompiledSketchFilePath = Paths.get(this.sketch.getFolder().getAbsolutePath(), copyOfCompiledSketch); Files.copy(compiledSketchPath, copyOfCompiledSketchFilePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RunnerException(e); } } private boolean isExportCompiledSketchSupported(List<String> compiledSketches, List<String> copyOfCompiledSketches, PreferencesMap prefs) { return (compiledSketches.isEmpty() || copyOfCompiledSketches.isEmpty() || copyOfCompiledSketches.size() < compiledSketches.size()) && (!prefs.containsKey("recipe.output.tmp_file") || !prefs.containsKey("recipe.output.save_file")); } private void runActions(String recipeClass, PreferencesMap prefs) throws RunnerException, PreferencesMapException { List<String> patterns = prefs.keySet().stream().filter(key -> key.startsWith("recipe." + recipeClass) && key.endsWith(".pattern")).collect(Collectors.toList()); Collections.sort(patterns); for (String recipe : patterns) { runRecipe(recipe, prefs); } } private void runRecipe(String recipe, PreferencesMap prefs) throws RunnerException, PreferencesMapException { PreferencesMap dict = new PreferencesMap(prefs); dict.put("ide_version", "" + BaseNoGui.REVISION); dict.put("sketch_path", sketch.getFolder().getAbsolutePath()); String[] cmdArray; String cmd = prefs.getOrExcept(recipe); try { cmdArray = StringReplacer.formatAndSplit(cmd, dict, true); } catch (Exception e) { throw new RunnerException(e); } exec(cmdArray); } private void exec(String[] command) throws RunnerException { // eliminate any empty array entries List<String> stringList = new ArrayList<>(); for (String string : command) { string = string.trim(); if (string.length() != 0) stringList.add(string); } command = stringList.toArray(new String[stringList.size()]); if (command.length == 0) return; if (verbose) { for (String c : command) System.out.print(c + " "); System.out.println(); } DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler() { @Override protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) { final Thread result = new Thread(new MyStreamPumper(is, Compiler.this)); result.setName("MyStreamPumper Thread"); result.setDaemon(true); return result; } }); CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]); for (int i = 1; i < command.length; i++) { commandLine.addArgument(command[i], false); } int result; executor.setExitValues(null); try { result = executor.execute(commandLine); } catch (IOException e) { RunnerException re = new RunnerException(e.getMessage()); re.hideStackTrace(); throw re; } executor.setExitValues(new int[0]); // an error was queued up by message(), barf this back to compile(), // which will barf it back to Editor. if you're having trouble // discerning the imagery, consider how cows regurgitate their food // to digest it, and the fact that they have five stomaches. //System.out.println("throwing up " + exception); if (exception != null) throw exception; if (result > 1) { // a failure in the tool (e.g. unable to locate a sub-executable) System.err .println(I18n.format(tr("{0} returned {1}"), command[0], result)); } if (result != 0) { RunnerException re = new RunnerException(tr("Error compiling.")); re.hideStackTrace(); throw re; } } private String boardOptions(TargetBoard board) { return board.getMenuIds().stream() .filter(board::hasMenu) .filter(menuId -> { String entry = PreferencesData.get("custom_" + menuId); return entry != null && entry.startsWith(board.getId()); }) .map(menuId -> { String entry = PreferencesData.get("custom_" + menuId); String selectionId = entry.substring(board.getId().length() + 1); return menuId + "=" + selectionId; }) .collect(Collectors.joining(",")); } /** * Part of the MessageConsumer interface, this is called * whenever a piece (usually a line) of error message is spewed * out from the compiler. The errors are parsed for their contents * and line number, which is then reported back to Editor. */ @Override public void message(String s) { int i; if (!verbose) { while ((i = s.indexOf(buildPath + File.separator)) != -1) { s = s.substring(0, i) + s.substring(i + (buildPath + File.separator).length()); } } String[] pieces = PApplet.match(s, ERROR_FORMAT); if (pieces != null) { String error = pieces[pieces.length - 1], msg = ""; if (error.trim().equals("SPI.h: No such file or directory")) { error = tr("Please import the SPI library from the Sketch > Import Library menu."); msg = tr("\nAs of Arduino 0019, the Ethernet library depends on the SPI library." + "\nYou appear to be using it or another library that depends on the SPI library.\n\n"); } if (error.trim().equals("'BYTE' was not declared in this scope")) { error = tr("The 'BYTE' keyword is no longer supported."); msg = tr("\nAs of Arduino 1.0, the 'BYTE' keyword is no longer supported." + "\nPlease use Serial.write() instead.\n\n"); } if (error.trim().equals("no matching function for call to 'Server::Server(int)'")) { error = tr("The Server class has been renamed EthernetServer."); msg = tr("\nAs of Arduino 1.0, the Server class in the Ethernet library " + "has been renamed to EthernetServer.\n\n"); } if (error.trim().equals("no matching function for call to 'Client::Client(byte [4], int)'")) { error = tr("The Client class has been renamed EthernetClient."); msg = tr("\nAs of Arduino 1.0, the Client class in the Ethernet library " + "has been renamed to EthernetClient.\n\n"); } if (error.trim().equals("'Udp' was not declared in this scope")) { error = tr("The Udp class has been renamed EthernetUdp."); msg = tr("\nAs of Arduino 1.0, the Udp class in the Ethernet library " + "has been renamed to EthernetUdp.\n\n"); } if (error.trim().equals("'class TwoWire' has no member named 'send'")) { error = tr("Wire.send() has been renamed Wire.write()."); msg = tr("\nAs of Arduino 1.0, the Wire.send() function was renamed " + "to Wire.write() for consistency with other libraries.\n\n"); } if (error.trim().equals("'class TwoWire' has no member named 'receive'")) { error = tr("Wire.receive() has been renamed Wire.read()."); msg = tr("\nAs of Arduino 1.0, the Wire.receive() function was renamed " + "to Wire.read() for consistency with other libraries.\n\n"); } if (error.trim().equals("'Mouse' was not declared in this scope")) { error = tr("'Mouse' not found. Does your sketch include the line '#include <Mouse.h>'?"); //msg = _("\nThe 'Mouse' class is only supported on the Arduino Leonardo.\n\n"); } if (error.trim().equals("'Keyboard' was not declared in this scope")) { error = tr("'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?"); //msg = _("\nThe 'Keyboard' class is only supported on the Arduino Leonardo.\n\n"); } RunnerException ex = placeException(error, pieces[1], PApplet.parseInt(pieces[2]) - 1); if (ex != null) { String fileName = ex.getCodeFile().getPrettyName(); int lineNum = ex.getCodeLine() + 1; s = fileName + ":" + lineNum + ": error: " + error + msg; } if (ex != null) { if (exception == null || exception.getMessage().equals(ex.getMessage())) { exception = ex; exception.hideStackTrace(); } } } if (s.contains("undefined reference to `SPIClass::begin()'") && s.contains("libraries/Robot_Control")) { String error = tr("Please import the SPI library from the Sketch > Import Library menu."); exception = new RunnerException(error); } if (s.contains("undefined reference to `Wire'") && s.contains("libraries/Robot_Control")) { String error = tr("Please import the Wire library from the Sketch > Import Library menu."); exception = new RunnerException(error); } System.err.println(s); } private RunnerException placeException(String message, String fileName, int line) { for (SketchFile file : sketch.getFiles()) { if (new File(fileName).getName().equals(file.getFileName())) { return new RunnerException(message, file, line); } } return null; } }
package authoringEnvironment.editors; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javafx.geometry.Dimension2D; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Group; import javafx.scene.control.Button; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; import authoringEnvironment.objects.FlowView; import authoringEnvironment.objects.UnitView; /** * Creates the Wave Editor that allows the user to create and edit waves made * out of units or other waves. * * @author Megan Gutter * */ public class WaveEditor extends MainEditor { private Dimension2D myDimensions; private Group myRoot; private Map<String, ArrayList<FlowView>> myWaves; public WaveEditor(Dimension2D dim, Stage s) { super(dim, s); myWaves = new HashMap<String, ArrayList<FlowView>>(); myDimensions = dim; } @Override public Node configureUI() { myRoot = new Group(); StackPane editor = new StackPane(); HBox newWavePanel = new HBox(10); VBox contents = new VBox(10); ScrollPane contentScrollPane = new ScrollPane(); contentScrollPane.setHbarPolicy(ScrollBarPolicy.NEVER); contentScrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS); contentScrollPane.setMaxHeight(myDimensions.getHeight()); contentScrollPane.setMaxWidth(myDimensions.getWidth()); Button makeNewWave = new Button("Create New Wave"); makeNewWave.setOnAction(e -> { promptNewWaveName(editor, contents); // makeNewWave(contents); }); newWavePanel.getChildren().add(makeNewWave); contents.getChildren().add(newWavePanel); contentScrollPane.setContent(contents); editor.getChildren().add(contentScrollPane); myRoot.getChildren().add(editor); return myRoot; } private void promptNewWaveName(StackPane editor, VBox contents) { StackPane promptDisplay = new StackPane(); Rectangle promptBackground = new Rectangle(300, 400); promptBackground.setOpacity(0.8); VBox promptContent = new VBox(20); promptContent.setAlignment(Pos.CENTER); Text prompt = new Text("Creating a new wave..."); prompt.setFill(Color.WHITE); TextField promptField = new TextField(); promptField.setMaxWidth(225); promptField.setPromptText("Enter a name..."); HBox buttons = new HBox(10); Button create = new Button("Create"); create.setOnAction((e) -> { makeNewWave(contents, promptField.getText()); myWaves.put(promptField.getText(), new ArrayList<FlowView>()); editor.getChildren().remove(promptDisplay); }); Button cancel = new Button("Cancel"); cancel.setOnAction((e) -> { editor.getChildren().remove(promptDisplay); }); buttons.setAlignment(Pos.CENTER); buttons.getChildren().addAll(create, cancel); promptContent.getChildren().addAll(prompt, promptField, buttons); promptDisplay.getChildren().addAll(promptBackground, promptContent); editor.getChildren().add(promptDisplay); } private void makeNewWave(VBox contents, String waveName) { ScrollPane newWave = new ScrollPane(); newWave.setHbarPolicy(ScrollBarPolicy.ALWAYS); newWave.setVbarPolicy(ScrollBarPolicy.NEVER); newWave.setMaxWidth(myDimensions.getWidth()); HBox waveContent = new HBox(10); Button addUnit = new Button("Add Unit"); addUnit.setOnAction(e -> { addUnitToWave(waveContent, waveName); }); Button save = new Button("Save"); save.setOnAction(e -> { ArrayList<String> partFileNames = new ArrayList<String>(); ArrayList<Double> delays = new ArrayList<Double>(); for (FlowView unit : myWaves.get(waveName)) { partFileNames.add(unit.getFileName()); // System.out.println(unit.getFileName()); delays.add(unit.getDelay()); } ArrayList<Object> data = new ArrayList<Object>(); data.add(partFileNames); data.add(delays); //addPartToGame("wave", waveName, params, data); }); VBox buttons = new VBox(10); buttons.getChildren().add(addUnit); buttons.getChildren().add(save); waveContent.getChildren().add(buttons); newWave.setContent(waveContent); contents.getChildren().add(newWave); // return newWave; } private void addUnitToWave(HBox wave, String waveName) { FlowView unit = new FlowView(100, 100); wave.getChildren().add(unit); myWaves.get(waveName).add(unit); } public ArrayList<UnitView> getWaves() { return new ArrayList<>(); } @Override protected void createMap() { } @Override protected void update() { // TODO Auto-generated method stub } }
package org.neo4j.impl.shell.apps; import java.lang.reflect.Array; import java.rmi.RemoteException; import java.util.regex.Pattern; import org.neo4j.api.core.Direction; import org.neo4j.api.core.Node; import org.neo4j.api.core.NotFoundException; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.Transaction; import org.neo4j.impl.shell.NeoShellServer; import org.neo4j.impl.shell.NodeOrRelationship; import org.neo4j.impl.shell.TypedId; import org.neo4j.util.shell.AbstractApp; import org.neo4j.util.shell.AbstractClient; import org.neo4j.util.shell.AppCommandParser; import org.neo4j.util.shell.Output; import org.neo4j.util.shell.Session; import org.neo4j.util.shell.ShellException; /** * An implementation of {@link App} which has common methods and functionality * to use with neo. */ public abstract class NeoApp extends AbstractApp { private static final String CURRENT_KEY = "CURRENT_DIR"; public static NodeOrRelationship getCurrent( NeoShellServer server, Session session ) throws ShellException { String currentThing = ( String ) safeGet( session, CURRENT_KEY ); NodeOrRelationship result = null; if ( currentThing == null ) { result = NodeOrRelationship.wrap( server.getNeo().getReferenceNode() ); setCurrent( session, result ); } else { TypedId typedId = new TypedId( currentThing ); result = getThingById( server, typedId ); } return result; } protected NodeOrRelationship getCurrent( Session session ) throws ShellException { return getCurrent( getNeoServer(), session ); } protected static void setCurrent( Session session, NodeOrRelationship current ) { safeSet( session, CURRENT_KEY, current.getTypedId().toString() ); } protected void assertCurrentIsNode( Session session ) throws ShellException { NodeOrRelationship current = getCurrent( session ); if ( !current.isNode() ) { throw new ShellException( "You must stand on a node to be able to do this" ); } } protected NeoShellServer getNeoServer() { return ( NeoShellServer ) this.getServer(); } protected RelationshipType getRelationshipType( String name ) { return new NeoAppRelationshipType( name ); } protected Direction getDirection( String direction ) throws ShellException { return getDirection( direction, Direction.OUTGOING ); } protected Direction getDirection( String direction, Direction defaultDirection ) throws ShellException { return ( Direction ) parseEnum( Direction.class, direction, defaultDirection ); } protected static NodeOrRelationship getThingById( NeoShellServer server, TypedId typedId ) throws ShellException { NodeOrRelationship result = null; if ( typedId.isNode() ) { try { result = NodeOrRelationship.wrap( server.getNeo().getNodeById( typedId.getId() ) ); } catch ( NotFoundException e ) { throw new ShellException( "Node " + typedId.getId() + " not found" ); } } else { try { result = NodeOrRelationship.wrap( server.getNeo().getRelationshipById( typedId.getId() ) ); } catch ( NotFoundException e ) { throw new ShellException( "Relationship " + typedId.getId() + " not found" ); } } return result; } protected NodeOrRelationship getThingById( TypedId typedId ) throws ShellException { return getThingById( getNeoServer(), typedId ); } protected Node getNodeById( long id ) { return this.getNeoServer().getNeo().getNodeById( id ); } public final String execute( AppCommandParser parser, Session session, Output out ) throws ShellException { Transaction tx = getNeoServer().getNeo().beginTx(); try { String result = this.exec( parser, session, out ); tx.success(); return result; } catch ( RemoteException e ) { throw new ShellException( e ); } finally { tx.finish(); } } protected String directionAlternatives() { return "OUTGOING, INCOMING, o, i"; } protected abstract String exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException; protected String getDisplayNameForCurrent( Session session ) throws ShellException { NodeOrRelationship current = getCurrent( session ); return current.isNode() ? "(me)" : "<me>"; } /** * @param thing the thing to get the name-representation for. * @return the display name for a {@link Node}. */ public static String getDisplayName( NeoShellServer server, Session session, NodeOrRelationship thing ) { if ( thing.isNode() ) { return getDisplayName( server, session, thing.asNode() ); } else { return getDisplayName( server, session, thing.asRelationship(), true ); } } public static String getDisplayName( NeoShellServer server, Session session, TypedId typedId ) throws ShellException { return getDisplayName( server, session, getThingById( server, typedId ) ); } public static String getDisplayName( NeoShellServer server, Session session, Node node ) { StringBuffer result = new StringBuffer( // "(" + node.getId() + ")" ); "(" + node.getId() ); String title = findTitle( server, session, node ); if ( title != null ) { // result.append( " " + title ); result.append( ", " + title ); } result.append( ")" ); return result.toString(); } private static String findTitle( NeoShellServer server, Session session, Node node ) { String keys = ( String ) safeGet( session, AbstractClient.TITLE_KEYS_KEY ); if ( keys == null ) { return null; } String[] titleKeys = keys.split( Pattern.quote( "," ) ); Pattern[] patterns = new Pattern[ titleKeys.length ]; for ( int i = 0; i < titleKeys.length; i++ ) { patterns[ i ] = Pattern.compile( titleKeys[ i ] ); } for ( Pattern pattern : patterns ) { for ( String nodeKey : node.getPropertyKeys() ) { if ( matches( pattern, nodeKey, false, false ) ) { return trimLength( session, format( node.getProperty( nodeKey ), false ) ); } } } return null; } private static String trimLength( Session session, String string ) { String maxLengthString = ( String ) safeGet( session, AbstractClient.TITLE_MAX_LENGTH ); int maxLength = maxLengthString != null ? Integer.parseInt( maxLengthString ) : Integer.MAX_VALUE; if ( string.length() > maxLength ) { string = string.substring( 0, maxLength ) + "..."; } return string; } public static String getDisplayName( NeoShellServer server, Session session, Relationship relationship, boolean verbose ) { StringBuffer result = new StringBuffer( "<" ); if ( verbose ) { result.append( relationship.getId() + ", " ); } result.append( relationship.getType().name() + ">" ); return result.toString(); } protected static String fixCaseSensitivity( String string, boolean caseInsensitive ) { return caseInsensitive ? string.toLowerCase() : string; } protected static Pattern newPattern( String pattern, boolean caseInsensitive ) { return pattern == null ? null : Pattern.compile( fixCaseSensitivity( pattern, caseInsensitive ) ); } protected static boolean matches( Pattern patternOrNull, String value, boolean caseInsensitive, boolean loose ) { if ( patternOrNull == null ) { return true; } value = fixCaseSensitivity( value, caseInsensitive ); return loose ? patternOrNull.matcher( value ).find() : patternOrNull.matcher( value ).matches(); } protected static <T extends Enum<T>> Enum<T> parseEnum( Class<T> enumClass, String name, Enum<T> defaultValue ) { if ( name == null ) { return defaultValue; } name = name.toLowerCase(); for ( T enumConstant : enumClass.getEnumConstants() ) { if ( enumConstant.name().equalsIgnoreCase( name ) ) { return enumConstant; } } for ( T enumConstant : enumClass.getEnumConstants() ) { if ( enumConstant.name().toLowerCase().startsWith( name ) ) { return enumConstant; } } throw new IllegalArgumentException( "No '" + name + "' or '" + name + ".*' in " + enumClass ); } protected static String frame( String string, boolean frame ) { return frame ? "[" + string + "]" : string; } protected static String format( Object value, boolean includeFraming ) { String result = null; if ( value.getClass().isArray() ) { StringBuffer buffer = new StringBuffer(); int length = Array.getLength( value ); for ( int i = 0; i < length; i++ ) { Object singleValue = Array.get( value, i ); if ( i > 0 ) { buffer.append( "," ); } buffer.append( frame( singleValue.toString(), includeFraming ) ); } result = buffer.toString(); } else { result = frame( value.toString(), includeFraming ); } return result; } private static class NeoAppRelationshipType implements RelationshipType { private String name; private NeoAppRelationshipType( String name ) { this.name = name; } public String name() { return this.name; } @Override public String toString() { return name(); } } }
package org.anyline.net; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; import org.anyline.util.BasicUtil; import org.anyline.util.ConfigTable; import org.anyline.util.DateUtil; import org.anyline.util.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; import com.jcraft.jsch.SftpProgressMonitor; public class SFTPUtil { private final Logger log = LoggerFactory.getLogger(SFTPUtil.class); private static Map<String,SFTPUtil> instances = new HashMap<String,SFTPUtil>(); private String host; private int port=22; private String user; private String password; private ChannelSftp client; private Session session; public SFTPUtil() throws Exception{ } public SFTPUtil(String host, int port, String user, String password) throws Exception{ this(host, user, password, 22); } public SFTPUtil(String host, String user, String password) throws Exception{ this(host, user, password, 22); } public SFTPUtil(String host, String user, String password, int port) throws Exception{ this.host = host; this.user = user; this.password = password; Channel channel = null; JSch jsch = new JSch(); session = jsch.getSession(this.user, this.host, this.port); if(BasicUtil.isNotEmpty(this.password)){ session.setPassword(this.password); } Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sshConfig); session.connect(); channel = session.openChannel("sftp"); channel.connect(); client = (ChannelSftp) channel; } public static SFTPUtil getInstance (String host, String account, String password, int port){ String key = "host:"+host+",account:"+account+",password:"+password+",port:"+port; SFTPUtil util = instances.get(key); if(null == util){ try { util = new SFTPUtil(host, account, password, port); } catch (Exception e) { e.printStackTrace(); } } return util; } public static SFTPUtil getInstance(String host, String account, String password){ return getInstance(host, account, password, 22); } /** * -sftp. * @param remote * @param local * @throws Exception */ public void download(String remote, String local) throws Exception { FileOutputStream os = null; File localFile = new File(local); try { if (!localFile.exists()) { File parentFile = localFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } localFile.createNewFile(); } os = new FileOutputStream(localFile); List<String> list = FTPUtil.formatPath(remote); long fr = System.currentTimeMillis(); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[][file:{}]",list.get(0) + list.get(1)); } String remotePath = list.get(0) + list.get(1); SftpATTRS attr = client.stat(remotePath); long length = attr.getSize(); SFTPProgressMonitor process = new SFTPProgressMonitor(remotePath,local, length); client.get(remotePath, os, process); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[][:{}][file:{}]",System.currentTimeMillis()-fr,list.get(0) + list.get(1)); } } catch (Exception e) { throw e; } finally { os.close(); } } /** * * @return return */ public boolean disconnect(){ if (session != null) { if (session.isConnected()) { session.disconnect(); } } if (client != null) { if (client.isConnected()) { client.disconnect(); } client.exit(); } return true; } public int fileSize(String remoteDir){ int size = 0; try { Vector<?> files = client.ls(remoteDir); size = files.size(); } catch (Exception e) { if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[][result:fail][msg:{}]", e.getMessage()); } } return size; } /** * -sftp. * @param path * @throws SftpException */ public void deleteFile(String path) throws SftpException { List<String> list = FTPUtil.formatPath(path); String dir = list.get(0); String file = list.get(1); if (dirExist(dir + file)) { client.rm(list.get(0) + list.get(1)); } } /** * -sftp.. * @param path * @throws SftpException SftpException */ public void deleteDir(String path) throws SftpException { @SuppressWarnings("unchecked") Vector<LsEntry> vector = client.ls(path); if (vector.size() == 1) { client.rm(path); } else if (vector.size() == 2) { client.rmdir(path); } else { String fileName = ""; for (LsEntry en : vector) { fileName = en.getFilename(); if (".".equals(fileName) || "..".equals(fileName)) { continue; } else { deleteDir(path + "/" + fileName); } } client.rmdir(path); } } /** * -sftp. * @param localFile * @param remoteDir * @param remoteFile * @throws SftpException */ public void uploadFile(String localFile, String remoteDir, String remoteFile) throws SftpException { long fr = System.currentTimeMillis(); mkdir(remoteDir); client.cd(remoteDir); client.put(localFile, remoteFile); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[][:{}][local:{}][remote:{}]",DateUtil.conversion(System.currentTimeMillis()-fr),localFile,remoteDir+"/"+remoteFile); } } public void uploadFile(File localFile, String remoteDir, String remoteFile) throws SftpException { uploadFile(localFile.getAbsolutePath(), remoteDir, remoteFile); } /** * -sftp. * @param localFile /xxx/xx.yy x:/xxx/xxx.yy * @return * @throws SftpException */ public boolean uploadFile(String localFile) throws SftpException { File file = new File(localFile); if (file.exists()) { List<String> list = FTPUtil.formatPath(localFile); uploadFile(localFile, list.get(0), list.get(1)); return true; } return false; } /** * . * @param dir /xxx/xxx/ / * @return return * @throws SftpException */ public boolean mkdir(String dir) throws SftpException { if (BasicUtil.isEmpty(dir)){ return false; } String md = dir.replaceAll("\\\\", "/"); if (md.indexOf("/") != 0 || md.length() == 1) return false; return mkdirs(md); } /** * . * @param dir * @return * @throws SftpException */ public boolean mkdirs(String dir) throws SftpException { String[] dirArr = dir.split("/"); String base = ""; for (String d : dirArr) { if(BasicUtil.isEmpty(d)){ continue; } base += "/" + d; if (dirExist(base + "/")) { continue; } else { client.mkdir(base + "/"); } } return true; } /** * . * @param dir /xxx/xxx/ * @return */ public boolean dirExist(String dir) { try { Vector<?> vector = client.ls(dir); if (null == vector) return false; else return true; } catch (SftpException e) { return false; } } @SuppressWarnings("unchecked") public List<String> files(String dir){ List<String> list = new ArrayList<>(); try { Vector<LsEntry> files = client.ls(dir); for(LsEntry file:files){ // int t = file.getAttrs().getATime(); // String s= file.getAttrs().getAtimeString(); // int t1 = file.getAttrs().getMTime(); // String s1= file.getAttrs().getMtimeString(); String nm = file.getFilename(); if(".".equals(nm) || "..".equals(nm)){ continue; } list.add(nm); } } catch (Exception e) { log.warn("[scan dir error][dir:{}][error:{}]",dir,e.getMessage()); } if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[scan dir][dir:{}][file size:{}]",dir,list.size()); } return list; } public boolean fileExists(String dir, String file){ List<String> files = files(dir); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[check file exists][dir:{}][file:{}]",dir,file); } for(String item:files){ if(item.equals(file)){ return true; } } return false; } public boolean fileExists(String path){ List<String> list = FTPUtil.formatPath(path); String dir = list.get(0); String file = list.get(1); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[check file exists][path:"+path+"]"); } return fileExists(dir, file); } } class SFTPProgressMonitor implements SftpProgressMonitor { private final Logger log = LoggerFactory.getLogger(SFTPProgressMonitor.class); private String remote = ""; private String local = ""; private long length; private long transfered; private double displayRate; private long startTime = 0; private long displayTime; public SFTPProgressMonitor(String remote, long length){ this.remote = remote; this.length = length; this.startTime = System.currentTimeMillis(); } public SFTPProgressMonitor(String remote, String local, long length){ this.remote = remote; this.local = local; this.length = length; this.startTime = System.currentTimeMillis(); } public SFTPProgressMonitor(long length){ this.length = length; this.startTime = System.currentTimeMillis(); } @Override public boolean count(long count) { double curRate = (transfered+count)/length * 100; if(curRate - displayRate >= 0.5 || System.currentTimeMillis() - displayTime > 1000 * 5 || curRate == 100){ displayRate = curRate; displayTime = System.currentTimeMillis(); long delay = System.currentTimeMillis()-startTime; double expect = 0; if(delay>0 && transfered>0){ expect = length / (transfered/delay); String total_title = "[][:" + FileUtil.progress(length, transfered) +"][:"+DateUtil.conversion(delay)+"/"+DateUtil.conversion(expect)+"("+FileUtil.length(transfered*1000/delay)+"/s)]"; if(null != local){ total_title = "[local:"+local+"]" + total_title; } if(null != remote){ total_title = "[remote:"+remote+"]" + total_title; } log.warn(total_title); } } transfered = transfered + count; return true; } @Override public void end() { log.warn("."); } @Override public void init(int op, String src, String dest, long max) { log.warn("."); } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } }
package com.gh4a.fragment; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.design.widget.CoordinatorLayout; import android.support.v4.content.Loader; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.gh4a.BaseActivity; import com.gh4a.Gh4Application; import com.gh4a.ProgressDialogTask; import com.gh4a.R; import com.gh4a.activities.EditIssueCommentActivity; import com.gh4a.activities.EditPullRequestCommentActivity; import com.gh4a.adapter.RootAdapter; import com.gh4a.adapter.timeline.TimelineItemAdapter; import com.gh4a.loader.LoaderResult; import com.gh4a.loader.ReviewTimelineLoader; import com.gh4a.loader.TimelineItem; import com.gh4a.utils.IntentUtils; import com.gh4a.widget.EditorBottomSheet; import org.eclipse.egit.github.core.Comment; import org.eclipse.egit.github.core.CommitComment; import org.eclipse.egit.github.core.Reaction; import org.eclipse.egit.github.core.RepositoryId; import org.eclipse.egit.github.core.Review; import org.eclipse.egit.github.core.service.IssueService; import org.eclipse.egit.github.core.service.PullRequestService; import java.io.IOException; import java.util.List; public class ReviewFragment extends ListDataBaseFragment<TimelineItem> implements TimelineItemAdapter.OnCommentAction, EditorBottomSheet.Callback, EditorBottomSheet.Listener { private static final int REQUEST_EDIT = 1000; private static final String EXTRA_SELECTED_REPLY_COMMENT_ID = "selected_reply_comment_id"; @Nullable private TimelineItemAdapter mAdapter; private EditorBottomSheet mBottomSheet; public static ReviewFragment newInstance(String repoOwner, String repoName, int issueNumber, Review review, IntentUtils.InitialCommentMarker mInitialComment) { ReviewFragment f = new ReviewFragment(); Bundle args = new Bundle(); args.putString("repo_owner", repoOwner); args.putString("repo_name", repoName); args.putInt("issue_number", issueNumber); args.putSerializable("review", review); args.putParcelable("initial_comment", mInitialComment); f.setArguments(args); return f; } private String mRepoOwner; private String mRepoName; private int mIssueNumber; private Review mReview; private IntentUtils.InitialCommentMarker mInitialComment; private long mSelectedReplyCommentId; private @StringRes int mCommentEditorHintResId = R.string.review_reply_hint; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mRepoOwner = args.getString("repo_owner"); mRepoName = args.getString("repo_name"); mIssueNumber = args.getInt("issue_number"); mReview = (Review) args.getSerializable("review"); mInitialComment = args.getParcelable("initial_comment"); args.remove("initial_comment"); if (savedInstanceState != null) { mSelectedReplyCommentId = savedInstanceState.getLong(EXTRA_SELECTED_REPLY_COMMENT_ID); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View listContent = super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.comment_list, container, false); FrameLayout listContainer = v.findViewById(R.id.list_container); listContainer.addView(listContent); mBottomSheet = v.findViewById(R.id.bottom_sheet); mBottomSheet.setCallback(this); mBottomSheet.setResizingView(listContainer); mBottomSheet.setListener(this); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getBaseActivity().addAppBarOffsetListener(mBottomSheet); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(EXTRA_SELECTED_REPLY_COMMENT_ID, mSelectedReplyCommentId); } @Override public void onDestroyView() { super.onDestroyView(); getBaseActivity().removeAppBarOffsetListener(mBottomSheet); } @Override public boolean onBackPressed() { if (mBottomSheet != null && mBottomSheet.isInAdvancedMode()) { mBottomSheet.setAdvancedMode(false); return true; } return false; } @Override public boolean canChildScrollUp() { return (mBottomSheet != null && mBottomSheet.isExpanded()) || super.canChildScrollUp(); } @Override protected void setHighlightColors(int colorAttrId, int statusBarColorAttrId) { super.setHighlightColors(colorAttrId, statusBarColorAttrId); mBottomSheet.setHighlightColor(colorAttrId); } @Override protected Loader<LoaderResult<List<TimelineItem>>> onCreateLoader() { return new ReviewTimelineLoader(getActivity(), mRepoOwner, mRepoName, mIssueNumber, mReview.getId()); } @Override protected RootAdapter<TimelineItem, ? extends RecyclerView.ViewHolder> onCreateAdapter() { mAdapter = new TimelineItemAdapter(getActivity(), mRepoOwner, mRepoName, mIssueNumber, true, false, this); return mAdapter; } @Override protected void onAddData(RootAdapter<TimelineItem, ?> adapter, List<TimelineItem> data) { selectAndRemoveFirstReply(data); // Lock the bottom sheet if there is no selected reply group mBottomSheet.setLocked(mSelectedReplyCommentId <= 0, R.string.no_reply_group_selected_hint); mCommentEditorHintResId = R.string.reply; for (TimelineItem item : data) { if (item instanceof TimelineItem.Reply) { mCommentEditorHintResId = R.string.review_reply_hint; break; } } mBottomSheet.updateHint(); super.onAddData(adapter, data); if (mInitialComment != null) { highlightInitialComment(data); } } private void selectAndRemoveFirstReply(List<TimelineItem> data) { int replyItemCount = 0; TimelineItem.Reply firstReplyItem = null; for (TimelineItem timelineItem : data) { if (timelineItem instanceof TimelineItem.Reply) { replyItemCount += 1; if (replyItemCount > 1) { return; } if (firstReplyItem == null) { firstReplyItem = (TimelineItem.Reply) timelineItem; } } } if (firstReplyItem != null) { mSelectedReplyCommentId = firstReplyItem.timelineComment.comment.getId(); // When there is only one reply item we don't need to display it data.remove(firstReplyItem); } } private void highlightInitialComment(List<TimelineItem> data) { for (int i = 0; i < data.size(); i++) { TimelineItem item = data.get(i); if (item instanceof TimelineItem.TimelineComment) { TimelineItem.TimelineComment comment = (TimelineItem.TimelineComment) item; if (mInitialComment.matches(comment.comment.getId(), comment.getCreatedAt())) { scrollToAndHighlightPosition(i); break; } } } mInitialComment = null; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_EDIT) { if (resultCode == Activity.RESULT_OK) { reloadComments(true); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void reloadComments( boolean alsoClearCaches) { if (mAdapter != null && !alsoClearCaches) { // Don't clear adapter's cache, we're only interested in the new event mAdapter.suppressCacheClearOnNextClear(); } onRefresh(); } @Override protected int getEmptyTextResId() { return 0; } @Override public void editComment(Comment comment) { Intent intent; if (comment instanceof CommitComment) { intent = EditPullRequestCommentActivity.makeIntent(getActivity(), mRepoOwner, mRepoName, mIssueNumber, 0L, (CommitComment) comment, 0); } else { intent = EditIssueCommentActivity.makeIntent(getActivity(), mRepoOwner, mRepoName, mIssueNumber, comment, 0); } startActivityForResult(intent, REQUEST_EDIT); } @Override public void deleteComment(final Comment comment) { new AlertDialog.Builder(getActivity()) .setMessage(R.string.delete_comment_message) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new DeleteCommentTask(getBaseActivity(), comment).schedule(); } }) .setNegativeButton(R.string.cancel, null) .show(); } @Override public void onToggleAdvancedMode(boolean advancedMode) { getBaseActivity().collapseAppBar(); getBaseActivity().setAppBarLocked(advancedMode); mBottomSheet.resetPeekHeight(0); } @Override public void onScrollingInBasicEditor(boolean scrolling) { getBaseActivity().setAppBarLocked(scrolling); } @Override public void quoteText(CharSequence text) { mBottomSheet.addQuote(text); } @Override public void onReplyCommentSelected(long replyToId) { mSelectedReplyCommentId = replyToId; mBottomSheet.setLocked(false, 0); } @Override public long getSelectedReplyCommentId() { return mSelectedReplyCommentId; } @Override public String getShareSubject(Comment comment) { return null; } @Override public void addText(CharSequence text) { } @Override public List<Reaction> loadReactionDetailsInBackground(Comment comment) throws IOException { RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName); Gh4Application app = Gh4Application.get(); if (comment instanceof CommitComment) { PullRequestService pullService = (PullRequestService) app.getService(Gh4Application.PULL_SERVICE); return pullService.getCommentReactions(repoId, comment.getId()); } else { IssueService issueService = (IssueService) app.getService(Gh4Application.ISSUE_SERVICE); return issueService.getCommentReactions(repoId, comment.getId()); } } @Override public Reaction addReactionInBackground(Comment comment, String content) throws IOException { RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName); Gh4Application app = Gh4Application.get(); if (comment instanceof CommitComment) { PullRequestService pullService = (PullRequestService) app.getService(Gh4Application.PULL_SERVICE); return pullService.addCommentReaction(repoId, comment.getId(), content); } else { IssueService issueService = (IssueService) app.getService(Gh4Application.ISSUE_SERVICE); return issueService.addCommentReaction(repoId, comment.getId(), content); } } @Override public int getCommentEditorHintResId() { return mCommentEditorHintResId; } @Override public int getEditorErrorMessageResId() { return R.string.issue_error_comment; } @Override public void onEditorSendInBackground(String comment) throws IOException { Gh4Application app = Gh4Application.get(); PullRequestService pullService = (PullRequestService) app.getService(Gh4Application.PULL_SERVICE); RepositoryId repositoryId = new RepositoryId(mRepoOwner, mRepoName); pullService.replyToComment(repositoryId, mIssueNumber, mSelectedReplyCommentId, comment); } @Override public void onEditorTextSent() { onRefresh(); } @Override public CoordinatorLayout getRootLayout() { return getBaseActivity().getRootLayout(); } private class DeleteCommentTask extends ProgressDialogTask<Void> { private final Comment mComment; public DeleteCommentTask(BaseActivity activity, Comment comment) { super(activity, R.string.deleting_msg); mComment = comment; } @Override protected ProgressDialogTask<Void> clone() { return new DeleteCommentTask(getBaseActivity(), mComment); } @Override protected Void run() throws Exception { RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName); Gh4Application app = Gh4Application.get(); if (mComment instanceof CommitComment) { PullRequestService pullService = (PullRequestService) app.getService(Gh4Application.PULL_SERVICE); pullService.deleteComment(repoId, mComment.getId()); } else { IssueService issueService = (IssueService) app.getService(Gh4Application.ISSUE_SERVICE); issueService.deleteComment(repoId, mComment.getId()); } return null; } @Override protected void onSuccess(Void result) { reloadComments(false); } @Override protected String getErrorMessage() { return getContext().getString(R.string.error_delete_comment); } } }
package com.noprestige.kanaquiz; import android.arch.persistence.room.Room; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v4.widget.TextViewCompat; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.noprestige.kanaquiz.logs.LogDatabase; import com.noprestige.kanaquiz.logs.LogView; import com.noprestige.kanaquiz.options.KanaSelection; import com.noprestige.kanaquiz.options.OptionsControl; import com.noprestige.kanaquiz.options.OptionsScreen; import com.noprestige.kanaquiz.questions.KanaQuestionBank; import com.noprestige.kanaquiz.questions.NoQuestionsException; import com.noprestige.kanaquiz.questions.QuestionManagement; import com.noprestige.kanaquiz.reference.ReferenceScreen; import java.text.DecimalFormat; import static android.graphics.Typeface.BOLD; import static android.graphics.Typeface.NORMAL; import static android.os.Build.VERSION.SDK_INT; import static android.util.TypedValue.COMPLEX_UNIT_SP; public class MainQuiz extends AppCompatActivity { private int totalQuestions; private float totalCorrect; private boolean canSubmit; private KanaQuestionBank questionBank; private TextView lblResponse; private EditText txtAnswer; private TextView lblDisplayKana; private MultipleChoicePad btnMultipleChoice; private int oldTextColour; private static final DecimalFormat PERCENT_FORMATTER = new DecimalFormat(" private static final DecimalFormat SCORE_FORMATTER = new DecimalFormat(" private Handler delayHandler = new Handler(); private int retryCount = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_quiz); lblResponse = findViewById(R.id.lblResponse); txtAnswer = findViewById(R.id.txtAnswer); lblDisplayKana = findViewById(R.id.lblDisplayKana); btnMultipleChoice = findViewById(R.id.btnMultipleChoice); oldTextColour = lblResponse.getCurrentTextColor(); // TODO: replace kludge for reverting text colour if (SDK_INT < 26) TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(lblDisplayKana, 12, 144, 2, COMPLEX_UNIT_SP); onConfigurationChanged(getResources().getConfiguration()); OptionsControl.initialize(getApplicationContext()); QuestionManagement.initialize(getApplicationContext()); //TODO: Figure out how to run the database on a different thread. if (LogDatabase.DAO == null) LogDatabase.DAO = Room.databaseBuilder(getApplicationContext(), LogDatabase.class, "user-logs").allowMainThreadQueries().build().logDao(); txtAnswer.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { String answer = v.getText().toString().trim(); if ((actionId == EditorInfo.IME_ACTION_GO) || (actionId == EditorInfo.IME_NULL)) checkAnswer(answer); return true; } } ); resetQuiz(); nextQuestion(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.keyboard == Configuration.KEYBOARD_NOKEYS && newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) txtAnswer.setHint(R.string.answer_hint_touch); else txtAnswer.setHint(R.string.answer_hint_hardware); } private void resetQuiz() { totalQuestions = 0; totalCorrect = 0; lblDisplayKana.setText(""); lblResponse.setText(""); if (!OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_default)) lblResponse.setMinLines(2); questionBank = QuestionManagement.getFullQuestionBank(); txtAnswer.setEnabled(true); //TODO: Fix spacing when txtAnswer is rendered invisible if (OptionsControl.getBoolean(R.string.prefid_multiple_choice)) { txtAnswer.setVisibility(View.INVISIBLE); txtAnswer.setHeight(0); btnMultipleChoice.setVisibility(View.VISIBLE); } else { txtAnswer.setVisibility(View.VISIBLE); txtAnswer.setLines(1); btnMultipleChoice.setVisibility(View.INVISIBLE); } } private void nextQuestion() { try { questionBank.newQuestion(); lblDisplayKana.setText(questionBank.getCurrentKana()); retryCount = 0; if (OptionsControl.getBoolean(R.string.prefid_multiple_choice)) btnMultipleChoice.setChoices(questionBank.getPossibleAnswers()); ReadyForAnswer(); } catch (NoQuestionsException ex) { lblDisplayKana.setText(""); lblResponse.setText(R.string.no_questions); canSubmit = false; lblResponse.setTypeface(null, NORMAL); lblResponse.setTextColor(oldTextColour); // TODO: replace kludge for reverting text colours if (OptionsControl.getBoolean(R.string.prefid_multiple_choice)) btnMultipleChoice.deleteChoices(); else { txtAnswer.setEnabled(false); txtAnswer.setText(""); } } TextView lblScore = findViewById(R.id.lblScore); if (totalQuestions > 0) { lblScore.setText(R.string.score_label); lblScore.append(": "); lblScore.append(PERCENT_FORMATTER.format(totalCorrect / (float) totalQuestions)); lblScore.append(System.getProperty("line.separator")); lblScore.append(SCORE_FORMATTER.format(totalCorrect)); lblScore.append(" / "); lblScore.append(Integer.toString(totalQuestions)); } else lblScore.setText(""); } public void checkAnswer(String answer) { if (canSubmit && !answer.isEmpty()) { boolean isGetNewQuestion = true; canSubmit = false; if (questionBank.checkCurrentAnswer(answer)) { lblResponse.setText(R.string.correct_answer); lblResponse.setTypeface(null, BOLD); lblResponse.setTextColor(ContextCompat.getColor(this, R.color.correct)); if (retryCount == 0) { totalCorrect++; LogDatabase.DAO.reportCorrectAnswer(lblDisplayKana.getText().toString()); } else if (retryCount <= 4) //anything over 4 retrys gets no score at all totalCorrect += Math.pow(0.5f, retryCount); } else { lblResponse.setText(R.string.incorrect_answer); lblResponse.setTypeface(null, BOLD); lblResponse.setTextColor(ContextCompat.getColor(this, R.color.incorrect)); if (retryCount == 0) LogDatabase.DAO.reportIncorrectAnswer(lblDisplayKana.getText().toString(), answer); else LogDatabase.DAO.reportIncorrectRetry(lblDisplayKana.getText().toString(), answer); if (OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_show_answer)) { lblResponse.append(System.getProperty("line.separator")); lblResponse.append(getResources().getText(R.string.show_correct_answer)); lblResponse.append(": "); lblResponse.append(questionBank.fetchCorrectAnswer()); } else if (OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_retry)) { lblResponse.append(System.getProperty("line.separator")); lblResponse.append(getResources().getText(R.string.try_again)); retryCount++; isGetNewQuestion = false; delayHandler.postDelayed( new Runnable() { public void run() { ReadyForAnswer(); btnMultipleChoice.enableButtons(); } }, 1000 ); } } if (isGetNewQuestion) { totalQuestions++; //txtAnswer.setEnabled(false); //TODO: Find a way to disable a textbox without closing the touch keyboard delayHandler.postDelayed( new Runnable() { public void run() { nextQuestion(); } }, 1000 ); } } } private void ReadyForAnswer() { if (OptionsControl.getBoolean(R.string.prefid_multiple_choice)) lblResponse.setText(R.string.request_multiple_choice); else { lblResponse.setText(R.string.request_text_input); txtAnswer.requestFocus(); txtAnswer.setText(""); } canSubmit = true; lblResponse.setTypeface(null, NORMAL); lblResponse.setTextColor(oldTextColour); // TODO: replace kludge for reverting text colours } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Class destination; int result = 0; switch (item.getItemId()) { case R.id.mnuSelection: destination = KanaSelection.class; result = 1; break; case R.id.mnuReference: destination = ReferenceScreen.class; break; case R.id.mnuOptions: destination = OptionsScreen.class; result = 1; break; case R.id.mnuLogs: destination = LogView.class; break; case R.id.mnuAbout: destination = AboutScreen.class; break; default: return super.onOptionsItemSelected(item); } startActivityForResult(new Intent(MainQuiz.this, destination), result); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { resetQuiz(); nextQuestion(); } } }
// associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // furnished to do so, subject to the following conditions: // substantial portions of the Software. // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.onefishtwo.bbqtimer; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioAttributes; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.SystemClock; import android.text.Spanned; import android.text.SpannedString; import android.view.View; import android.widget.RemoteViews; import com.onefishtwo.bbqtimer.state.ApplicationState; import androidx.annotation.DrawableRes; import androidx.annotation.IdRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.RawRes; import androidx.annotation.StringRes; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; import androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle; import androidx.media.app.NotificationCompat.MediaStyle; /** * Manages the app's Android Notifications. */ public class Notifier { private static final int NOTIFICATION_ID = 7; /** * Construct a custom notification for this API level and higher. The custom notification really * helps on Android 12 where MediaStyle's collapsed notification hides the Chronometer and the * lock screen interferes with expanding the notification. * * API 24 is required for a count-down Chronometer and for * NotificationCompat.DecoratedMediaCustomViewStyle to do more than MediaStyle. */ private static final int CUSTOM_NOTIFICATION_API_LEVEL = 24; private static final SpannedString EMPTY_SPAN = new SpannedString(""); // Vibration pattern: ms off, on, off, ... // Match the notification sound to the degree feasible. // Workaround: Start with a tiny pulse for when Android drops the initial "off" interval. private static final long[] VIBRATE_PATTERN = {0, 1, 280, 40, 220, 80, 440, 45, 265, 55}; private static final int[][] ACTION_INDICES = {{}, {0}, {0, 1}, {0, 1, 2}}; static final String ALARM_NOTIFICATION_CHANNEL_ID = "alarmChannel"; // Was in release "2.5" (v15) and will remain immutable on devices while the app is installed: // static final String CONTROLS_NOTIFICATION_CHANNEL_ID = "controlsChannel"; private static final int RUNNING_FLIPPER_CHILD = 0; private static final int PAUSED_FLIPPER_CHILD = 1; private static boolean builtNotificationChannels = false; @NonNull private final Context context; @NonNull private final NotificationManager notificationManager; @NonNull private final NotificationManagerCompat notificationManagerCompat; private final int notificationLightColor; private Bitmap largeIcon; // only for API < 24 private boolean soundAlarm = false; // whether the next notification should sound an alarm private int numActions; // the number of action buttons added to the notification being built public Notifier(@NonNull Context _context) { this.context = _context; notificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManagerCompat = NotificationManagerCompat.from(_context); notificationLightColor = ContextCompat.getColor(_context, R.color.notification_light_color); } /** * Builder-style setter: Whether to make the next notification sound an alarm, vibrate, and * flash the device LED. Initially set to false. */ @NonNull public Notifier setAlarm(boolean _soundAlarm) { this.soundAlarm = _soundAlarm; return this; } private Uri getSoundUri(@RawRes int soundId) { return Uri.parse("android.resource://" + context.getPackageName() + "/" + soundId); } /** Constructs a PendingIntent to use as a Notification Action. */ private PendingIntent makeActionIntent(String action) { return TimerAppWidgetProvider.makeActionIntent(context, action); } /** * Adds an action button to the given NotificationBuilder and to the * {@link #setMediaStyleActionsInCompactView} list. */ private void addAction(@NonNull NotificationCompat.Builder builder, @DrawableRes int iconId, @StringRes int titleId, PendingIntent intent) { builder.addAction(iconId, context.getString(titleId), intent); ++numActions; } /** * Makes the first 3 added {@link #addAction} actions appear in a MediaStyle notification * view. The Media template should fit 3 actions in its collapsed view, 6 actions in expanded * view, or 5 actions in expanded view with a large image but I haven't tested that. *<p/> * Calls builder.setColor() on some versions of Android to cope with OS vagaries. */ private void setMediaStyleActionsInCompactView(@NonNull NotificationCompat.Builder builder) { int num = Math.min(numActions, ACTION_INDICES.length - 1); if (num < 1) { return; } MediaStyle style; if (Build.VERSION.SDK_INT >= CUSTOM_NOTIFICATION_API_LEVEL) { style = new DecoratedMediaCustomViewStyle(); } else { style = new MediaStyle(); } style.setShowActionsInCompactView(ACTION_INDICES[num]); builder.setStyle(style); // API 21 L - 22 L1: colors the notification area background needlessly. By default, // * Heads-up notifications: Medium gray text on light white background. // * Pull-down notifications: Light white text on dark gray background. // API 23 M: colors the notification area background; needed to work around low contrast: // * Heads-up notifications: Medium gray text. // * Pull-down notifications: Light white text on the SAME background. // The color setting carries over from a notification to its replacement so there's no // way to get consistently different background colors for the two cases. // API 24 N - API 27 O1: colors the small icon, action button, and app title color. Garish. // API 28 P - API 30 R: colors the small icon and action button. Garish. // API 31 S: See below. // setColorized(false) didn't change any of these results. if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) { int workaroundColor = context.getColor(R.color.m_notification_background); builder.setColor(workaroundColor); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12, S, API 31: setColor() colors the small icon's circular background. int iconBackgroundColor = context.getColor(R.color.dark_orange_red); builder.setColor(iconBackgroundColor); } } /** * Returns a localized description of the timer's run state: "Running", "Paused 00:12.3" * (optionally including the time value), or "Stopped". */ @NonNull String timerRunState(@NonNull TimeCounter timer, boolean includeTime) { if (timer.isRunning()) { return context.getString(R.string.timer_running); } else if (timer.isPaused()) { Spanned pauseTime = includeTime ? timer.formatHhMmSsFraction() : EMPTY_SPAN; return context.getString(R.string.timer_paused, pauseTime); } else { return context.getString(R.string.timer_stopped); } } /** * Returns a localized description of the periodic alarms. * * @param state the ApplicationState. * @return a localized string like "Alarm every 2 minutes", or "" for no periodic alarms. */ @NonNull String describePeriodicAlarms(@NonNull ApplicationState state) { // Synthesize a "quantity" to select the right pluralization rule. String intervalMmSs = state.formatIntervalTimeHhMmSs(); return state.isEnableReminders() ? context.getResources().getString(R.string.notification_body, intervalMmSs) : ""; } /** * <em>(Re)Opens</em> this app's notification with content depending on {@code state} and * {@link #setAlarm(boolean)}, * <em>or cancels</em> the app's notification if there's nothing to show or sound. * * @param state the ApplicationState state to display. */ public void openOrCancel(@NonNull ApplicationState state) { TimeCounter timer = state.getTimeCounter(); if (!timer.isStopped() || soundAlarm) { Notification notification = buildNotification(state); notificationManagerCompat.notify(NOTIFICATION_ID, notification); } else { cancelAll(); } } /** * Returns true if the Alarm channel is configured On with enough Importance to hear alarms. * After createNotificationChannelV26() creates the channels, the user can reconfigure them and * the app can only set their names and descriptions. If users configure the Alarm channel to be * silent but request Periodic Alarms, they'll think the app is broken. */ boolean isAlarmChannelOK() { if (Build.VERSION.SDK_INT >= 26) { NotificationChannel channel = notificationManager.getNotificationChannel( ALARM_NOTIFICATION_CHANNEL_ID); if (channel == null) { // The channel hasn't been created so it can't be broken. return true; } int importance = channel.getImportance(); return importance >= NotificationManager.IMPORTANCE_DEFAULT; } return true; } /** * Creates a notification channel that matches the parameters #buildNotification() uses. The * "Alarm" channel sounds an alarm at heads-up High importance. */ @TargetApi(26) private void createNotificationChannelV26() { String name = context.getString(R.string.notification_alarm_channel_name); String description = context.getString(R.string.notification_alarm_channel_description); NotificationChannel channel = new NotificationChannel( ALARM_NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(description); channel.enableLights(true); channel.setLightColor(notificationLightColor); channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); channel.enableVibration(true); channel.setVibrationPattern(VIBRATE_PATTERN); { AudioAttributes audioAttributes = new AudioAttributes.Builder() //.setLegacyStreamType(AudioManager.STREAM_ALARM) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_ALARM) .build(); channel.setSound(getSoundUri(R.raw.cowbell4), audioAttributes); } channel.setShowBadge(false); // Did not setBypassDnd(), setGroup(). notificationManager.createNotificationChannel(channel); // goofy naming } /** Creates notification channel(s) lazily (or updates the text) on Android O+. */ private void createNotificationChannels() { if (Build.VERSION.SDK_INT < 26 || builtNotificationChannels) { return; } createNotificationChannelV26(); builtNotificationChannels = true; } /** Update state (e.g. notification channel text) for a UI Locale change. */ void onLocaleChange() { if (Build.VERSION.SDK_INT >= 26) { NotificationChannel channel = notificationManager.getNotificationChannel( ALARM_NOTIFICATION_CHANNEL_ID); //noinspection VariableNotUsedInsideIf if (channel != null) { builtNotificationChannels = false; createNotificationChannels(); } } } /** * Make and initialize the RemoteViews for a Custom Notification. *<p/> * Workaround: A paused Chronometer doesn't show a stable value, e.g. switching light/dark theme * can change it, and it ignores its format string thus ruling out some workarounds. * *SO* when the timer is paused, flip to a TextView. * * @param layoutId the layout resource ID for the RemoteViews. * @param state the ApplicationState to show. * @param countUpMessage the message to show next to the count-up (stopwatch) Chronometer. This * Chronometer and its message are GONE if there are no periodic alarms. * @param countDownMessage the message to show next to the count-down (timer) Chronometer. * @return RemoteViews */ @NonNull @TargetApi(24) private RemoteViews makeRemoteViews( @LayoutRes int layoutId, @NonNull ApplicationState state, @NonNull String countUpMessage, @NonNull String countDownMessage) { TimeCounter timer = state.getTimeCounter(); long elapsedTime = timer.getElapsedTime(); boolean isRunning = timer.isRunning(); long rt = SystemClock.elapsedRealtime(); long countUpBase = rt - elapsedTime; @IdRes int childId = isRunning ? RUNNING_FLIPPER_CHILD : PAUSED_FLIPPER_CHILD; RemoteViews remoteViews = new RemoteViews(context.getPackageName(), layoutId); // Count-up time and status if (!isRunning) { remoteViews.setTextViewText(R.id.pausedCountUp, timer.formatHhMmSs()); } remoteViews.setDisplayedChild(R.id.countUpViewFlipper, childId); remoteViews.setChronometer( R.id.countUpChronometer, countUpBase, null, isRunning); remoteViews.setTextViewText(R.id.countUpMessage, countUpMessage); // Count-down time and status if (state.isEnableReminders()) { long countdownToNextAlarm = state.getMillisecondsToNextAlarm(); long countdownBase = rt + countdownToNextAlarm; if (!isRunning) { remoteViews.setTextViewText( R.id.pausedCountdown, TimeCounter.formatHhMmSs(countdownToNextAlarm)); } remoteViews.setDisplayedChild(R.id.countdownViewFlipper, childId); remoteViews.setChronometer( R.id.countdownChronometer, countdownBase, null, isRunning); remoteViews.setTextViewText(R.id.countdownMessage, countDownMessage); } else { remoteViews.setChronometer( R.id.countdownChronometer, 0, null, false); remoteViews.setViewVisibility(R.id.countdownChronometer, View.GONE); remoteViews.setViewVisibility(R.id.countdownMessage, View.GONE); } return remoteViews; } /** * Builds a notification. Its alarm sound, vibration, and LED light flashing are switched on/off * by {@link #setAlarm(boolean)}. */ @NonNull protected Notification buildNotification(@NonNull ApplicationState state) { createNotificationChannels(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID) .setPriority(NotificationCompat.PRIORITY_MAX) .setCategory(NotificationCompat.CATEGORY_ALARM) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); { // Construct the visible notification contents. TimeCounter timer = state.getTimeCounter(); boolean isRunning = timer.isRunning(); builder.setSmallIcon(R.drawable.notification_icon) .setContentTitle(context.getString(R.string.app_name)); // Android API < 24 stretches the small icon into a fuzzy large icon, so add a large // icon. On API 24+, adopt the UI guideline, thus making the notification fit more in // the compact form, which could help when the lock screen is set to // "Show sensitive content only when unlocked". if (Build.VERSION.SDK_INT < 24) { if (largeIcon == null) { largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_large_notification); } builder.setLargeIcon(largeIcon); } if (Build.VERSION.SDK_INT < CUSTOM_NOTIFICATION_API_LEVEL && isRunning) { builder.setWhen(System.currentTimeMillis() - timer.getElapsedTime()) .setUsesChronometer(true); } else { // Hide the "when" field, which isn't useful while Paused, so it doesn't take space // in the compact view along with 3 action buttons (Reset, Start, Stop). builder.setShowWhen(false); } String alarmEvery = describePeriodicAlarms(state); if (isRunning && state.isEnableReminders()) { builder.setContentText(alarmEvery); } else { String runPauseStop = timerRunState(timer, true); // Running/Paused 00:12.3/Stopped builder.setContentText(runPauseStop); if (timer.isPaused()) { builder.setSubText(context.getString(R.string.dismiss_tip)); } else if (isRunning) { builder.setSubText(context.getString(R.string.no_reminders_tip)); } } if (Build.VERSION.SDK_INT >= CUSTOM_NOTIFICATION_API_LEVEL) { String countUpMessage = timerRunState(timer, false); // Running/Paused/Stopped RemoteViews notificationView = makeRemoteViews( R.layout.custom_notification, state, countUpMessage, alarmEvery); builder.setCustomContentView(notificationView); builder.setCustomHeadsUpContentView(notificationView); builder.setCustomBigContentView(notificationView); } numActions = 0; { PendingIntent activityPendingIntent = MainActivity.makePendingIntent(context); builder.setContentIntent(activityPendingIntent); // Action button to reset the timer. if (timer.isPaused() && !timer.isPausedAt0()) { PendingIntent resetIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_RESET); addAction(builder, R.drawable.ic_action_replay, R.string.reset, resetIntent); } // Action button to run (start) the timer. if (!isRunning) { PendingIntent runIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_RUN); addAction(builder, R.drawable.ic_action_play, R.string.start, runIntent); } // Action button to pause the timer. if (!timer.isPaused()) { PendingIntent pauseIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_PAUSE); addAction(builder, R.drawable.ic_action_pause, R.string.pause, pauseIntent); } // Action button to stop the timer. PendingIntent stopIntent = makeActionIntent(TimerAppWidgetProvider.ACTION_STOP); if (!timer.isStopped()) { addAction(builder, R.drawable.ic_action_stop, R.string.stop, stopIntent); } // Allow stopping via dismissing the notification (unless it's "ongoing"). builder.setDeleteIntent(stopIntent); setMediaStyleActionsInCompactView(builder); } if (isRunning) { builder.setOngoing(true); } } if (soundAlarm) { builder.setSound(getSoundUri(R.raw.cowbell4), AudioManager.STREAM_ALARM); builder.setVibrate(VIBRATE_PATTERN); builder.setLights(notificationLightColor, 1000, 2000); } else { builder.setSilent(true); } return builder.build(); } /** Cancels all of this app's notifications. */ public void cancelAll() { notificationManagerCompat.cancelAll(); } }
package com.samourai.wallet.util; import android.content.Context; import android.util.Log; //import android.util.Log; import com.samourai.wallet.R; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.NameValuePair; import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.message.BasicNameValuePair; import info.guardianproject.netcipher.client.StrongHttpsClient; public class WebUtil { public static final String BLOCKCHAIN_DOMAIN = "https://blockchain.info/"; public static final String SAMOURAI_API = "https://api.samouraiwallet.com/"; public static final String SAMOURAI_API_CHECK = "https://api.samourai.io/v1/status"; public static final String LBC_EXCHANGE_URL = "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/"; public static final String BTCe_EXCHANGE_URL = "https://btc-e.com/api/3/ticker/"; public static final String BFX_EXCHANGE_URL = "https://api.bitfinex.com/v1/pubticker/btcusd"; public static final String AVG_EXCHANGE_URL = "https://api.bitcoinaverage.com/ticker/global/all"; public static final String VALIDATE_SSL_URL = SAMOURAI_API; public static final String DYNAMIC_FEE_URL = "https://bitcoinfees.21.co/api/v1/fees/recommended"; public static final String BTCX_FEE_URL = "http://bitcoinexchangerate.org/fees"; public static final String CHAINSO_TX_PREV_OUT_URL = "https://chain.so/api/v2/tx/BTC/"; public static final String CHAINSO_PUSHTX_URL = "https://chain.so/api/v2/send_tx/BTC/"; public static final String RECOMMENDED_BIP47_URL = "http://samouraiwallet.com/api/v1/get-pcodes"; private static final int DefaultRequestRetry = 2; private static final int DefaultRequestTimeout = 60000; private static final String strProxyType = StrongHttpsClient.TYPE_SOCKS; private static final String strProxyIP = "127.0.0.1"; private static final int proxyPort = 9050; /* HTTP Proxy: private static final String strProxyType = StrongHttpsClient.TYPE_HTTP; private static final String strProxyIP = "127.0.0.1"; private static final int strProxyPort = 8118; */ private static WebUtil instance = null; private static Context context = null; private WebUtil() { ; } public static WebUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new WebUtil(); } return instance; } public String postURL(String request, String urlParameters) throws Exception { if(context == null) { return postURL(null, request, urlParameters); } else { Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast()); if(TorUtil.getInstance(context).statusFromBroadcast()) { if(urlParameters.startsWith("tx=")) { return tor_postURL(request, urlParameters.substring(3)); } else { return tor_postURL(request + urlParameters); } } else { return postURL(null, request, urlParameters); } } } public String postURL(String contentType, String request, String urlParameters) throws Exception { String error = null; for (int ii = 0; ii < DefaultRequestRetry; ++ii) { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", contentType == null ? "application/x-www-form-urlencoded" : contentType); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); connection.setUseCaches (false); connection.setConnectTimeout(DefaultRequestTimeout); connection.setReadTimeout(DefaultRequestTimeout); connection.connect(); DataOutputStream wr = new DataOutputStream(connection.getOutputStream ()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); connection.setInstanceFollowRedirects(false); if (connection.getResponseCode() == 200) { // System.out.println("postURL:return code 200"); return IOUtils.toString(connection.getInputStream(), "UTF-8"); } else { error = IOUtils.toString(connection.getErrorStream(), "UTF-8"); // System.out.println("postURL:return code " + error); } Thread.sleep(5000); } finally { connection.disconnect(); } } throw new Exception("Invalid Response " + error); } public String getURL(String URL) throws Exception { if(context == null) { return _getURL(URL); } else { //if(TorUtil.getInstance(context).orbotIsRunning()) { Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast()); if(TorUtil.getInstance(context).statusFromBroadcast()) { return tor_getURL(URL); } else { return _getURL(URL); } } } private String _getURL(String URL) throws Exception { URL url = new URL(URL); String error = null; for (int ii = 0; ii < DefaultRequestRetry; ++ii) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); connection.setConnectTimeout(DefaultRequestTimeout); connection.setReadTimeout(DefaultRequestTimeout); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() == 200) return IOUtils.toString(connection.getInputStream(), "UTF-8"); else error = IOUtils.toString(connection.getErrorStream(), "UTF-8"); Thread.sleep(5000); } finally { connection.disconnect(); } } return error; } private String tor_getURL(String URL) throws Exception { StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts); httpclient.useProxy(true, strProxyType, strProxyIP, proxyPort); HttpGet httpget = new HttpGet(URL); HttpResponse response = httpclient.execute(httpget); StringBuffer sb = new StringBuffer(); sb.append(response.getStatusLine()).append("\n\n"); InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } httpclient.close(); String result = sb.toString(); // Log.d("WebUtil", "GET result via Tor:" + result); int idx = result.indexOf("{"); if(idx != -1) { return result.substring(idx); } else { return result; } } private String tor_postURL(String URL) throws Exception { Log.d("WebUtil", URL); StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts); httpclient.useProxy(true, strProxyType, strProxyIP, proxyPort); HttpPost httppost = new HttpPost(new URI(URL)); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setHeader("charset", "utf-8"); httppost.setHeader("Accept", "application/json"); // httppost.setHeader("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); httppost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); HttpResponse response = httpclient.execute(httppost); StringBuffer sb = new StringBuffer(); sb.append(response.getStatusLine()).append("\n\n"); InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } httpclient.close(); String result = sb.toString(); // Log.d("WebUtil", "POST result via Tor:" + result); int idx = result.indexOf("{"); if(idx != -1) { return result.substring(idx); } else { return result; } } private String tor_postURL(String URL, String tx) throws Exception { Log.d("WebUtil", URL); StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts); httpclient.useProxy(true, strProxyType, strProxyIP, proxyPort); HttpPost httppost = new HttpPost(new URI(URL)); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setHeader("charset", "utf-8"); httppost.setHeader("Accept", "application/json"); // httppost.setHeader("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); httppost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("tx", tx)); httppost.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse response = httpclient.execute(httppost); StringBuffer sb = new StringBuffer(); sb.append(response.getStatusLine()).append("\n\n"); InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } httpclient.close(); String result = sb.toString(); // Log.d("WebUtil", "POST result via Tor:" + result); int idx = result.indexOf("{"); if(idx != -1) { return result.substring(idx); } else { return result; } } }
package com.snatik.matches.common; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.Log; import java.util.Map; import static android.R.attr.id; import static android.R.id.edit; import static android.content.Context.MODE_PRIVATE; public class Memory { private static final String SHARED_PREFERENCES_NAME = "com.snatik.matches"; private static String highStartKey = "theme_%d_difficulty_%d"; private static String bestTimeKey = "themeTime_%d_difficultyTime_%d"; public static void save(int theme, int difficulty, int stars) { Log.i("In save()",""); int highStars = getHighStars(theme, difficulty); if (stars > highStars) { Log.i("New best stars",""); SharedPreferences sharedPreferences = Shared.context.getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE); SharedPreferences.Editor edit = sharedPreferences.edit(); String key = String.format(highStartKey, theme, difficulty); edit.putInt(key, stars).commit(); } } public static void saveTime(int theme,int difficulty,int passedSecs) { int bestTime = getBestTime(theme,difficulty); if(passedSecs<bestTime && bestTime != -1) { SharedPreferences sharedPreferences = Shared.context.getSharedPreferences(SHARED_PREFERENCES_NAME,MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); String timeKey = String.format(bestTimeKey, theme, difficulty); editor.putInt(timeKey,passedSecs); editor.commit(); } if( bestTime == -1) { SharedPreferences sharedPreferences = Shared.context.getSharedPreferences(SHARED_PREFERENCES_NAME,MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); String timeKey = String.format(bestTimeKey, theme, difficulty); editor.putInt(timeKey,passedSecs); editor.commit(); } } public static int getHighStars(int theme, int difficulty) { SharedPreferences sharedPreferences = Shared.context.getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE); String key = String.format(highStartKey, theme, difficulty); return sharedPreferences.getInt(key, 0); } public static int getBestTime(int theme,int difficulty) { SharedPreferences sharedPreferences = Shared.context.getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE); String key = String.format(bestTimeKey, theme, difficulty); return sharedPreferences.getInt(key, -1); } public static String getBestTimeForStage(int theme,int difficulty) { int bestTime = getBestTime(theme,difficulty); if(bestTime != -1) { Log.i("Best time for diff", ""+bestTime); int minutes = (bestTime % 3600) / 60; int seconds = (bestTime) % 60; String result = String.format("BEST : %02d:%02d", minutes, seconds); return result; } else { String result = "BEST : -"; return result; } } }
package cz.tmapy.android.trex; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Location; import android.os.Bundle; import android.os.PowerManager; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import java.text.SimpleDateFormat; public class MainScreen extends ActionBarActivity { private static final String TAG = "MainScreen"; private String mTargetServerURL; private String mDeviceId; private Boolean mKeepScreenOn = false; private PowerManager.WakeLock mWakeLock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_screen); final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggle_start); //sets toggle state before listener is attached toggle.setChecked(getIntent().getBooleanExtra(Constants.EXTRAS_LOCALIZATION_IS_RUNNING, false)); toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (!startSending()) //cancel toggle switch when service' start is not successful { toggle.setChecked(false); } } else { stopSending(); } } }); //Registrace broadcastreceiveru komunikaci se sluzbou (musi byt tady, aby fungoval i po nove inicializaci aplikace z notifikace // The filter's action is BROADCAST_ACTION IntentFilter mIntentFilter = new IntentFilter(Constants.LOCATION_BROADCAST); // Instantiates a new mPositionReceiver NewPositionReceiver mPositionReceiver = new NewPositionReceiver(); // Registers the mPositionReceiver and its intent filters LocalBroadcastManager.getInstance(this).registerReceiver(mPositionReceiver, mIntentFilter); //ACRA.getErrorReporter().putCustomData("myKey", "myValue"); //ACRA.getErrorReporter().handleException(new Exception("Test exception")); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_screen, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, Settings.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * Start localizing and sending */ public Boolean startSending(){ //Check screen on/off settings SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); mDeviceId = sharedPref.getString("pref_id",""); mTargetServerURL =sharedPref.getString("pref_targetUrl", ""); if (!mTargetServerURL.isEmpty()) { if (!mDeviceId.isEmpty()) { if (!isServiceRunning(BackgroundLocationService.class)) { //Keep CPU on PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TRexWakelockTag"); mWakeLock.acquire(); mKeepScreenOn = sharedPref.getBoolean("pref_screen_on", false); if (mKeepScreenOn) getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //Nastartovani sluzby ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName()); ComponentName service = getApplicationContext().startService(new Intent().setComponent(comp)); if (null == service) { // something really wrong here Toast.makeText(this, R.string.localiz_could_not_start, Toast.LENGTH_SHORT).show(); if (Constants.LOG_BASIC) Log.e(TAG, "Could not start localization service " + comp.toString()); return false; } else return true; } else { Toast.makeText(this, R.string.localiz_run, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "Set device identifier", Toast.LENGTH_SHORT).show(); if (Constants.LOG_BASIC) Log.e(TAG, "Device identifier is not setted"); } } else { Toast.makeText(this, "Set target server URL", Toast.LENGTH_SHORT).show(); if (Constants.LOG_BASIC) Log.e(TAG, "Target server URL is not setted"); } return false; } /** * Switch off sending */ public void stopSending() { if (isServiceRunning(BackgroundLocationService.class)) { ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName()); getApplicationContext().stopService(new Intent().setComponent(comp)); TextView dateText = (TextView) findViewById(R.id.text_position_date); dateText.setText(null); TextView latText = (TextView) findViewById(R.id.text_position_lat); latText.setText(null); TextView lonText = (TextView) findViewById(R.id.text_position_lon); lonText.setText(null); TextView altText = (TextView) findViewById(R.id.text_position_alt); altText.setText(null); TextView speedText = (TextView) findViewById(R.id.text_position_speed); speedText.setText(null); TextView speedBearing = (TextView) findViewById(R.id.text_position_bearing); speedBearing.setText(null); TextView respText = (TextView) findViewById(R.id.text_http_response); respText.setText(null); //remove flag, if any getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } else Toast.makeText(this, R.string.localiz_not_run, Toast.LENGTH_SHORT).show(); } private boolean isServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } /** * This class uses the BroadcastReceiver framework to detect and handle new postition messages from * the service */ private class NewPositionReceiver extends BroadcastReceiver { // prevents instantiation by other packages. private NewPositionReceiver(){} /** * This method is called by the system when a broadcast Intent is matched by this class' * intent filters * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { Location location = (Location)intent.getExtras().get(Constants.EXTRAS_POSITION_DATA); String serverResponse = intent.getStringExtra(Constants.EXTRAS_SERVER_RESPONSE); if (location != null || serverResponse != null) { UpdateGUI(location,serverResponse); } } } private void UpdateGUI(Location location, String serverResponse) { if (location != null) { //2014-06-28T15:07:59 String mLastUpdateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(location.getTime()); String lat = Double.toString(location.getLatitude()); String lon = Double.toString(location.getLongitude()); String alt = String.valueOf(location.getAltitude()); String speed = String.valueOf(location.getSpeed()); String bearing = String.valueOf(location.getBearing()); TextView dateText = (TextView) findViewById(R.id.text_position_date); dateText.setText(mLastUpdateTime); TextView latText = (TextView) findViewById(R.id.text_position_lat); latText.setText(lat); TextView lonText = (TextView) findViewById(R.id.text_position_lon); lonText.setText(lon); TextView altText = (TextView) findViewById(R.id.text_position_alt); altText.setText(alt); TextView speedText = (TextView) findViewById(R.id.text_position_speed); speedText.setText(speed); TextView speedBearing = (TextView) findViewById(R.id.text_position_bearing); speedBearing.setText(bearing); } if (serverResponse != null) { TextView httpRespText = (TextView) findViewById(R.id.text_http_response); httpRespText.setText(serverResponse); } } }
package org.mozilla.focus.utils; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helpful tools for dealing with other browsers. */ public class Browsers { public enum KnownBrowser { FIREFOX("org.mozilla.firefox"), FIREFOX_BETA("org.mozilla.firefox_beta"), FIREFOX_AURORA("org.mozilla.fennec_aurora"), FIREFOX_NIGHTLY("org.mozilla.fennec"), CHROME("com.android.chrome"), CHROME_BETA("com.chrome.beta"), CHROME_DEV("com.chrome.dev"), CHROME_CANARY("com.chrome.canary"), OPERA("com.opera.browser"), OPERA_BETA("com.opera.browser.beta"), OPERA_MINI("com.opera.mini.native"), OPERA_MINI_BETA("com.opera.mini.native.beta"), UC_BROWSER("com.UCMobile.intl"), UC_BROWSER_MINI("com.uc.browser.en"), ANDROID_STOCK_BROWSER("com.android.browser"), SAMSUNG_INTERNET("com.sec.android.app.sbrowser"), DOLPHIN_BROWSER("mobi.mgeek.TunnyBrowser"), BRAVE_BROWSER("com.brave.browser"), LINK_BUBBLE("com.linkbubble.playstore"), ADBLOCK_BROWSER("org.adblockplus.browser"), CHROMER("arun.com.chromer"), FLYNX("com.flynx"), GHOSTERY_BROWSER("com.ghostery.android.ghostery"); public final String packageName; KnownBrowser(String packageName) { this.packageName = packageName; } } private final Map<String, ActivityInfo> browsers; private ActivityInfo defaultBrowser; public Browsers(Context context, String url) { final PackageManager packageManager = context.getPackageManager(); final Map<String, ActivityInfo> browsers = resolveBrowsers(packageManager, url); // If there's a default browser set then modern Android systems won't return other browsers // anymore when using queryIntentActivities(). That's annoying and our only option is // to go through a list of known browsers and see if anyone of them is installed and // wants to handle our URL. findKnownBrowsers(packageManager, browsers, url); this.browsers = browsers; this.defaultBrowser = findDefault(packageManager, url); } private Map<String, ActivityInfo> resolveBrowsers(PackageManager packageManager, String url) { final Map<String, ActivityInfo> browsers = new HashMap<>(); final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); final List<ResolveInfo> infos = packageManager.queryIntentActivities(intent, 0); for (ResolveInfo info : infos) { browsers.put(info.activityInfo.packageName, info.activityInfo); } return browsers; } private void findKnownBrowsers(PackageManager packageManager, Map<String, ActivityInfo> browsers, String url) { for (KnownBrowser browser : KnownBrowser.values()) { if (browsers.containsKey(browser.packageName)) { continue; } final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); intent.setPackage(browser.packageName); final ResolveInfo info = packageManager.resolveActivity(intent, 0); if (info == null || info.activityInfo == null) { continue; } browsers.put(info.activityInfo.packageName, info.activityInfo); } } private ActivityInfo findDefault(PackageManager packageManager, String url) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); final ResolveInfo resolveInfo = packageManager.resolveActivity(intent, 0); if (resolveInfo == null || resolveInfo.activityInfo == null) { return null; } if ("android".equals(resolveInfo.activityInfo.packageName)) { // If there's actually no default then Android might return a system activity that we // are not interested in. return null; } return resolveInfo.activityInfo; } /** * Does this user have a default browser that is not Firefox (release) or Focus (this build). */ public boolean hasThirdPartyDefaultBrowser(Context context) { return defaultBrowser != null && !defaultBrowser.packageName.equals(KnownBrowser.FIREFOX.packageName) && !defaultBrowser.packageName.equals(context.getPackageName()); } public ActivityInfo getDefaultBrowser() { return defaultBrowser; } /** * Does this user have browsers installed that are not Focus, Firefox or the default browser? */ public boolean hasMultipleThirdPartyBrowsers(Context context) { if (browsers.size() > 2) { // There are more than us and Firefox. return true; } for (ActivityInfo info : browsers.values()) { if (info != defaultBrowser && !info.packageName.equals(KnownBrowser.FIREFOX.packageName) && !info.packageName.equals(context.getPackageName())) { // There's at least one browser that is not Focus or Firefox and also not the // default browser. return true; } } return false; } public boolean isInstalled(KnownBrowser browser) { return browsers.containsKey(browser.packageName); } public ActivityInfo[] getInstalledBrowsers() { final Collection<ActivityInfo> collection = browsers.values(); return collection.toArray(new ActivityInfo[collection.size()]); } }
package org.commcare.view; import java.util.Vector; import org.commcare.util.CommCareSense; import org.commcare.util.MultimediaListener; import org.javarosa.formmanager.view.CustomChoiceGroup; import org.javarosa.utilities.media.MediaUtils; import de.enough.polish.ui.ChoiceGroup; import de.enough.polish.ui.Command; import de.enough.polish.ui.CommandListener; import de.enough.polish.ui.Displayable; import de.enough.polish.ui.List; /** * @author ctsims * */ public class CommCareListView extends List implements MultimediaListener { private Vector<String> audioLocations = new Vector<String>(); public CommCareListView(String title) { this(title, CommCareSense.formEntryQuick(), !CommCareSense.formEntryQuick()); } public CommCareListView(String title, boolean autoSelect, boolean numericNavigation) { super(title, List.IMPLICIT); this.choiceGroup = new CustomChoiceGroup(null, ChoiceGroup.IMPLICIT, autoSelect, numericNavigation) { public void playAudio(int index) { if(audioLocations.size() > index && audioLocations.elementAt(index) != null) { MediaUtils.playOrPauseAudio(audioLocations.elementAt(index), String.valueOf(index)); } } }; this.choiceGroup.isFocused = true; this.container = this.choiceGroup; } public void registerAudioTrigger(int index, String audioURI) { if(audioLocations.size() < index+1) { audioLocations.setSize(index+1); } audioLocations.setElementAt(audioURI, index); } protected CommandListener wrapped; public void setCommandListener(CommandListener cl) { wrapped = cl; super.setCommandListener(new CommandListener(){ public void commandAction(Command c, Displayable d) { if(d == CommCareListView.this && c.equals(CommCareListView.this.SELECT_COMMAND)) { if(!((CustomChoiceGroup)CommCareListView.this.choiceGroup).isFireable()) { return; } } //All list view actions should stop any currently playing audio MediaUtils.stopAudio(); //otherwise wrapped.commandAction(c, d); } }); } }
package br.com.caelum.iogi.reflection; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import net.vidageek.mirror.dsl.Mirror; import net.vidageek.mirror.list.dsl.Matcher; import br.com.caelum.iogi.Instantiator; import br.com.caelum.iogi.parameters.Parameters; public class NewObject { public static NewObject nullNewObject() { return new NewObject(null, null, null) { @Override public Object value() { return null; } @Override public Object valueWithPropertiesSet() { return null; } }; } private final Instantiator<?> propertiesInstantiator; private final Parameters parameters; private final Object object; public NewObject(final Instantiator<?> propertiesInstantiator, final Parameters parameters, final Object newObjectValue) { this.propertiesInstantiator = propertiesInstantiator; this.parameters = parameters; this.object = newObjectValue; } public Object valueWithPropertiesSet() { populateProperties(); return value(); } public Object value() { return object; } private void populateProperties() { for (final Setter setter : Setter.settersIn(object)) { setProperty(setter); } } private void setProperty(final Setter setter) { if (parameters.hasRelatedTo(setter.asTarget())) { final Object propertyValue = propertiesInstantiator.instantiate(setter.asTarget(), parameters); setter.set(propertyValue); } } private static abstract class Setter { private static Collection<Setter> settersIn(final Object object) { final ArrayList<Setter> setters = new ArrayList<Setter>(); for (final Method setterMethod: JavaSetter.settersOf(object)) { setters.add(new JavaSetter(setterMethod, object)); } for (final Method setterMethod: ScalaSetter.settersOf(object)) { setters.add(new ScalaSetter(setterMethod, object)); } return Collections.unmodifiableList(setters); } protected final Method setter; private final Object object; public Setter(final Method setter, final Object object) { this.setter = setter; this.object = object; } public void set(final Object argument) { new Mirror().on(object).invoke().method(setter).withArgs(argument); } private Target<Object> asTarget() { return new Target<Object>(type(), propertyName()); } protected abstract String propertyName(); private Type type() { return setter.getGenericParameterTypes()[0]; } @Override public String toString() { return "Setter(" + propertyName() +")"; } } private static class JavaSetter extends Setter { public JavaSetter(Method setter, Object object) { super(setter, object); } @Override protected String propertyName() { final String capitalizedPropertyName = setter.getName().substring(3); final String propertyName = capitalizedPropertyName.substring(0, 1).toLowerCase() + capitalizedPropertyName.substring(1); return propertyName; } static List<Method> settersOf(Object object) { return new Mirror().on(object.getClass()).reflectAll().methods().matching(new Matcher<Method>() { public boolean accepts(final Method method) { return !method.isBridge() && !method.isSynthetic() && !Modifier.isAbstract(method.getModifiers()) && method.getName().startsWith("set"); } }); } } private static class ScalaSetter extends Setter { public ScalaSetter(Method setter, Object object) { super(setter, object); } @Override protected String propertyName() { return setter.getName().replace("_$eq", ""); } static List<Method> settersOf(Object object) { return new Mirror().on(object.getClass()).reflectAll().methods().matching(new Matcher<Method>() { public boolean accepts(final Method method) { return method.getName().endsWith("_$eq"); } }); } } }
package ca.team3161.lib.utils.controls; import edu.wpi.first.wpilibj.GenericHID; /** * A thin wrapper over the FRC Joystick class, with built-in Y-axis inversion * and deadzone */ public class Joystick { private JoystickMode mode; private float inversion; private final float DEADZONE; private final GenericHID backingHID; /** * @param port which USB port this is plugged into, as reported by the Driver Station */ public Joystick(final int port) { this(port, 0.0f); } /** * @param port which USB port this is plugged into, as reported by the Driver Station * @param deadzone Axis values less than this in absolute value will be ignored */ public Joystick(final int port, final float deadzone) { this(port, deadzone, new LinearJoystickMode()); } /** * @param port which USB port this is plugged into, as reported by the Driver Station * @param deadzone Axis values less than this in absolute value will be ignored * @param mode the joystick input scaling mode */ public Joystick(final int port, final float deadzone, final JoystickMode mode) { this.backingHID = new edu.wpi.first.wpilibj.Joystick(port); this.inversion = 1.0f; this.DEADZONE = deadzone; this.mode = mode; } /** * Invert the Y-Axis of this Joystick * @param inverted if the Y-Axis should be inverted */ public void setInverted(final boolean inverted) { if (inverted) { inversion = -1.0f; } else { inversion = 1.0f; } } /** * Set the JoystickMode after the Joystick has already been constructed * @param mode */ public void setMode(final JoystickMode mode) { this.mode = mode; } /** * Get the X-axis reading from this Joystick * @return the value */ public double getX() { if (Math.abs(backingHID.getX()) < DEADZONE) { return 0.0; } return mode.adjust(backingHID.getX()); } /** * Get the Y-axis reading from this Joystick * @return the value */ public double getY() { if (Math.abs(backingHID.getY()) < DEADZONE) { return 0.0; } return inversion * mode.adjust(backingHID.getY()); } /** * Check if a button is pressed * @param button identifier for the button to check * @return the button's pressed state */ public boolean getButton(final int button) { return backingHID.getRawButton(button); } /** * Get an arbitrary axis reading from this Joystick * @param axis identifier for the axis to check * @return the value */ public double getRawAxis(final int axis) { return backingHID.getRawAxis(axis); } }
package codechicken.lib.render; import codechicken.lib.colour.ColourRGBA; public class ColourMultiplier implements CCRenderState.IVertexOperation { private static ColourMultiplier instance = new ColourMultiplier(-1); public static ColourMultiplier instance(int colour) { instance.colour = colour; return instance; } public static final int operationIndex = CCRenderState.registerOperation(); public int colour; public ColourMultiplier(int colour) { this.colour = colour; } @Override public boolean load() { if(colour == -1) { CCRenderState.setColour(-1); return false; } CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); return true; } @Override public void operate() { CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colour)); } @Override public int operationID() { return operationIndex; } }
package com.akjava.gwt.three.client.js.math; import com.akjava.gwt.three.client.gwt.core.Intersect; import com.akjava.gwt.three.client.js.core.Object3D; import com.akjava.gwt.three.client.js.scenes.Scene; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; public class Ray extends JavaScriptObject{ protected Ray(){} public final native Vector3 getOrigin()/*-{ return this.origin; }-*/; public final native Vector3 getDirection()/*-{ return this.direction; }-*/; public final native Ray set(Vector3 origin,Vector3 direction)/*-{ return this.set(origin,direction); }-*/; public final native Ray copy(Ray ray)/*-{ return this.copy(ray); }-*/; public final native Vector3 at(double t,Vector3 optionalTarget)/*-{ return this.at(t,optionalTarget); }-*/; public final native Ray recast(double t)/*-{ return this.recast(); }-*/; public final native Vector3 closestPointToPoint(Vector3 point,Vector3 optionalTarget)/*-{ return this.closestPointToPoint(point,optionalTarget); }-*/; public final native double distanceToPoint(Vector3 point)/*-{ return this.distanceToPoint(point); }-*/; public final native double distanceSqToSegment(Vector3 v0,Vector3 v1,Vector3 optionalPointOnRay,Vector3 optionalPointOnSegment)/*-{ return this.distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment); }-*/; public final native boolean isIntersectionSphere(Sphere sphere)/*-{ return this.isIntersectionSphere(sphere); }-*/; public final native boolean isIntersectionPlane(Plane plane)/*-{ return this.isIntersectionPlane(plane); }-*/; public final native Double distanceToPlane(Plane plane)/*-{ return this.distanceToPlane(plane); }-*/; public final native Vector3 intersectPlane(Plane plane,Vector3 optionalTarget)/*-{ return this.intersectPlane(plane,optionalTarget); }-*/; public final native boolean isIntersectionBox(Box3 box)/*-{ return this.isIntersectionBox(box); }-*/; public final native Vector3 intersectBox(Box3 box,Vector3 optionalTarget)/*-{ return this.intersectBox(box,optionalTarget); }-*/; public final native Vector3 intersectTriangle(Vector3 a,Vector3 b,Vector3 c,boolean backfaceCulling,Vector3 optionalTarget)/*-{ return this.intersectTriangle(); }-*/; public final native Ray applyMatrix4(Matrix4 matrix4)/*-{ return this.applyMatrix4(matrix4); }-*/; public final native boolean equals(Ray ray)/*-{ return this.equals(ray); }-*/; /** * @deprecated? */ public final native JsArray<Intersect> intersectScene(Scene scene)/*-{ return this.intersectScene( scene ); }-*/; /** * @deprecated? */ public final native JsArray<Intersect> intersectObjects(JsArray<Object3D> objects)/*-{ return this.intersectObjects( objects ); }-*/; /** * @deprecated? */ public final native JsArray<Intersect> intersectObject(Object3D object)/*-{ return this.intersectObject( object ); }-*/; public final native Vector3 intersectSphere (Sphere sphere,Vector3 optionalTarget)/*-{ return this.intersectSphere(sphere,optionalTarget); }-*/; public final native Ray clone()/*-{ return this.clone(); }-*/; public final native double distanceSqToPoint(Vector3 point)/*-{ return this.distanceSqToPoint(point); }-*/; }