answer
stringlengths
17
10.2M
package br.com.dbsoft.task; import br.com.dbsoft.error.DBSIOException; public interface IDBSTaskEventsListener { public void initializeTask(DBSTaskEvent pEvent); public void finalizeTask(DBSTaskEvent pEvent); public void beforeRun(DBSTaskEvent pEvent) throws DBSIOException; public void afterRun(DBSTaskEvent pEvent) throws DBSIOException; public void interrupted(DBSTaskEvent pEvent) throws DBSIOException; public void step(DBSTaskEvent pEvent) throws DBSIOException; public void taskUpdated(DBSTaskEvent pEvent) throws DBSIOException; public void taskStateChanged(DBSTaskEvent pEvent) throws DBSIOException; // public void scheduleEnabledChanged(DBSTaskEvent pEvent); public void runStatusChanged(DBSTaskEvent pEvent) throws DBSIOException; }
package org.xins.common.collections; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.xins.common.MandatoryArgumentChecker; /** * Implementation of a list that can only be modified using the secret key * passed to the constructor. * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>) * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.1.0 */ public final class ProtectedList extends AbstractList implements Cloneable { // Class fields // Class functions // Constructors public ProtectedList(Object secretKey, int initialCapacity) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("secretKey", secretKey); _secretKey = secretKey; _list = new ArrayList(initialCapacity); } public ProtectedList(Object secretKey) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("secretKey", secretKey); _secretKey = secretKey; _list = new ArrayList(); } public ProtectedList(Object secretKey, Collection c) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("secretKey", secretKey, "c", c); _secretKey = secretKey; _list = new ArrayList(c); } // Fields /** * The secret key. */ private final Object _secretKey; /** * The list containing the objects. */ private ArrayList _list; // Methods public Object get(int index) { return _list.get(index); } public int size() { return _list.size(); } public void add(Object secretKey, Object element) throws IllegalArgumentException { // Check preconditions if (secretKey != _secretKey) { throw new IllegalArgumentException("Invalid key."); } // Store the value _list.add(element); } public void remove(Object secretKey, int index) throws IllegalArgumentException { // Check preconditions if (secretKey != _secretKey) { throw new IllegalArgumentException("Invalid key."); } // Remove the element _list.remove(index); } /** * Clones this list. The cloned list will only be ediatable by using the * same secret key. * * @return * a new clone of this object, never <code>null</code>. */ public Object clone() { ProtectedList clone = new ProtectedList(_secretKey); clone._list = (ArrayList)_list.clone(); return clone; } }
package com.mpdeimos.foodbot; import com.mpdeimos.foodscraper.Retriever; import com.mpdeimos.foodscraper.data.IBistro; import com.mpdeimos.foodscraper.data.IDish; import com.mpdeimos.foodscraper.data.IMenu; import com.mpdeimos.webscraper.ScraperException; import com.mpdeimos.webscraper.util.Strings; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map.Entry; import spark.Request; import spark.Response; import spark.Spark; public class Server { public final Config config = new Config(); public final Slack slack = new Slack(config); public Server() { Spark.port(config.PORT); Spark.before( (request, response) -> response.type( "text/plain; charset=UTF-8")); Spark.get("/", this::getHome); Spark.get("/slack/bistro", slack::sendBistro); Spark.get("/config", (req, res) -> new Config(), new JsonTransformer()); } public Object getHome(Request req, Response res) { StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); Retriever retriever = new Retriever(); try { retriever.retrieve(); } catch (ScraperException e) { writer.println("Error: " + e.getMessage()); writer.println(Strings.EMPTY); } Iterable<Entry<IBistro, IMenu>> menu = retriever.getTodaysMenu(); for (Entry<IBistro, IMenu> entry : menu) { try { writer.println("## " + entry.getKey().getName() + " ##"); writer.println(Strings.EMPTY); for (IDish dish : entry.getValue().getDishes()) { writer.println(" " + dish.getName()); writer.println( " " + config.PRICE_FORMAT.format(dish.getPrice())); writer.println(Strings.EMPTY); } } catch (Exception e) { } } return out.getBuffer().toString(); } public Object getSlackBistro(Request req, Response res) { return new Config(); } public static void main(String[] args) { new Server(); } }
package com.psddev.dari.util; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.Collection; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** Writer implementation that adds basic HTML formatting. */ public class HtmlWriter extends Writer { private final Writer writer; private final Map<Class<?>, HtmlFormatter<Object>> defaultFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Map<Class<?>, HtmlFormatter<Object>> overrideFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Deque<String> tags = new ArrayDeque<String>(); /** Creates an instance that writes to the given {@code writer}. */ public HtmlWriter(Writer writer) { this.writer = writer; } @SuppressWarnings("unchecked") public <T> void putDefault(Class<T> objectClass, HtmlFormatter<? super T> formatter) { defaultFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } @SuppressWarnings("unchecked") public <T> void putOverride(Class<T> objectClass, HtmlFormatter<? super T> formatter) { overrideFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } public void putAllStandardDefaults() { putDefault(null, HtmlFormatter.NULL); putDefault(Class.class, HtmlFormatter.CLASS); putDefault(Collection.class, HtmlFormatter.COLLECTION); putDefault(Date.class, HtmlFormatter.DATE); putDefault(Double.class, HtmlFormatter.FLOATING_POINT); putDefault(Enum.class, HtmlFormatter.ENUM); putDefault(Float.class, HtmlFormatter.FLOATING_POINT); putDefault(Map.class, HtmlFormatter.MAP); putDefault(Number.class, HtmlFormatter.NUMBER); putDefault(PaginatedResult.class, HtmlFormatter.PAGINATED_RESULT); putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT); putDefault(Throwable.class, HtmlFormatter.THROWABLE); // Optional. if (HtmlFormatter.JASPER_EXCEPTION_CLASS != null) { putDefault(HtmlFormatter.JASPER_EXCEPTION_CLASS, HtmlFormatter.JASPER_EXCEPTION); } } public void removeDefault(Class<?> objectClass) { defaultFormatters.remove(objectClass); } public void removeOverride(Class<?> objectClass) { overrideFormatters.remove(objectClass); } /** * Escapes the given {@code string} so that it's safe to use in * an HTML page. */ protected String escapeHtml(String string) { return StringUtils.escapeHtml(string); } private void writeAttribute(Object name, Object value) throws IOException { if (!(ObjectUtils.isBlank(name) || value == null)) { writer.write(' '); writer.write(escapeHtml(name.toString())); writer.write("=\""); writer.write(escapeHtml(value.toString())); writer.write('"'); } } /** * Writes the given {@code tag} with the given {@code attributes}. * * <p>This method doesn't keep state, so it should be used with doctype * declaration and self-closing tags like {@code img}.</p> */ public HtmlWriter tag(String tag, Object... attributes) throws IOException { if (tag == null) { throw new IllegalArgumentException("Tag can't be null!"); } writer.write('<'); writer.write(tag); if (attributes != null) { for (int i = 0, length = attributes.length; i < length; ++ i) { Object name = attributes[i]; if (name instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) name).entrySet()) { writeAttribute(entry.getKey(), entry.getValue()); } } else { ++ i; Object value = i < length ? attributes[i] : null; writeAttribute(name, value); } } } writer.write('>'); return this; } /** * Writes the given start {@code tag} with the given {@code attributes}. * * <p>This method keeps state, so there should be a matching {@link #end} * call afterwards.</p> */ public HtmlWriter start(String tag, Object... attributes) throws IOException { tag(tag, attributes); tags.addFirst(tag); return this; } /** Writes the end tag previously started with {@link #start}. */ public HtmlWriter end() throws IOException { String tag = tags.removeFirst(); if (tag == null) { throw new IllegalStateException("No more tags!"); } writer.write("</"); writer.write(tag); writer.write('>'); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, the given {@code defaultUnescapedHtml}. */ public HtmlWriter htmlOrDefault(Object unescapedHtml, String defaultUnescapedHtml) throws IOException { writer.write(escapeHtml(unescapedHtml == null ? defaultUnescapedHtml : unescapedHtml.toString())); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, nothing. */ public HtmlWriter html(Object unescapedHtml) throws IOException { htmlOrDefault(unescapedHtml, ""); return this; } /** Formats and writes the given {@code object}. */ public HtmlWriter object(Object object) throws IOException { HtmlFormatter<Object> formatter; if (object == null) { formatter = overrideFormatters.get(null); if (formatter == null) { formatter = defaultFormatters.get(null); } if (formatter != null) { formatter.format(this, null); return this; } } else { if (formatWithMap(overrideFormatters, object)) { return this; } if (object instanceof HtmlObject) { ((HtmlObject) object).format(this); return this; } if (formatWithMap(defaultFormatters, object)) { return this; } } if (object != null && object.getClass().isArray()) { start("ul"); for (int i = 0, length = Array.getLength(object); i < length; ++ i) { start("li").object(Array.get(object, i)).end(); } end(); return this; } return html(object); } private boolean formatWithMap( Map<Class<?>, HtmlFormatter<Object>> formatters, Object object) throws IOException { HtmlFormatter<Object> formatter; for (Class<?> objectClass = object.getClass(); objectClass != null; objectClass = objectClass.getSuperclass()) { formatter = formatters.get(objectClass); if (formatter != null) { formatter.format(this, object); return true; } for (Class<?> interfaceClass : objectClass.getInterfaces()) { formatter = formatters.get(interfaceClass); if (formatter != null) { formatter.format(this, object); return true; } } } return false; } /** Returns a CSS string based on the given {@code properties}. */ public String cssString(Object... properties) { return Static.cssString(properties); } /** Writes a CSS rule based on the given parameters. */ public HtmlWriter css(String selector, Object... properties) throws IOException { write(selector); write('{'); write(cssString(properties)); write('}'); return this; } public HtmlWriter grid(Object object, HtmlGrid grid) throws IOException { Map<String, Area> areas = createAreas(grid); if (areas == null || areas.isEmpty()) { if (object instanceof Map) { object = ((Map<?, ?>) object).values(); } if (object instanceof Iterable) { for (Object item : (Iterable<?>) object) { object(item); } } else { object(object); } } else { if (object == null) { object = areas; } start("div", "style", cssString( "float", "left", "width", "100%")); for (Map.Entry<String, Area> entry : areas.entrySet()) { String name = entry.getKey(); Area area = entry.getValue(); Object value = CollectionUtils.getByPath(object, name); write(area.htmlBefore); start("div", "class", "cms-grid-area", "data-grid-area", name); object(value); end(); write(area.htmlAfter); } end(); start("div", "style", cssString("clear", "left")); end(); } return this; } private Map<String, Area> createAreas(HtmlGrid grid) { if (grid == null) { return null; } List<CssUnit> columns = grid.getColumns(); List<CssUnit> rows = grid.getRows(); List<List<String>> template = grid.getTemplate(); Map<String, Area> areaInstances = new LinkedHashMap<String, Area>(); int clearAt = -1; for (int rowStart = 0, rowSize = rows.size(); rowStart < rowSize; ++ rowStart) { List<String> areas = template.get(rowStart); for (int columnStart = 0, columnSize = columns.size(); columnStart < columnSize; ++ columnStart) { String area = areas.get(columnStart); if (!(area == null || ".".equals(area))) { int rowStop = rowStart + 1; int columnStop = columnStart + 1; for (; columnStop < columnSize; ++ columnStop) { if (!ObjectUtils.equals(areas.get(columnStop), area)) { break; } else { areas.set(columnStop, null); } } for (; rowStop < rowSize; ++ rowStop) { if (columnStart < template.get(rowStop).size() && !ObjectUtils.equals(template.get(rowStop).get(columnStart), area)) { break; } else { for (int i = columnStart; i < columnStop; ++ i) { if (i < template.get(rowStop).size()) { template.get(rowStop).set(i, null); } } } } StringBuilder htmlBefore = new StringBuilder(); StringBuilder htmlAfter = new StringBuilder(); double frMax; double frBefore; double frAfter; double frBeforeRatio; double frAfterRatio; frMax = 0; frBefore = 0; frAfter = 0; for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); if ("fr".equals(column.getUnit())) { double fr = column.getNumber(); frMax += fr; if (i < columnStart) { frBefore += fr; } else if (i >= columnStop) { frAfter += fr; } } } frBeforeRatio = frMax > 0 ? frBefore / frMax : 0.0; frAfterRatio = frMax > 0 ? frAfter / frMax : 0.0; htmlBefore.append("<div style=\"margin-left:-30000px;margin-right:30000px;\">"); htmlAfter.insert(0, "</div>"); htmlBefore.append("<div style=\"float:left;margin:0 -100% 0 "); htmlBefore.append(frBeforeRatio * 100.0); htmlBefore.append("%;width:"); htmlBefore.append(frMax > 0 ? ((frMax - frBefore - frAfter) * 100.0 / frMax) + "%" : "auto"); htmlBefore.append(";\">"); htmlAfter.insert(0, "</div>"); Map<String, Adjustment> adjustments = new HashMap<String, Adjustment>(); for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); String columnUnit = column.getUnit(); if (!"fr".equals(columnUnit)) { double columnNumber = column.getNumber(); double left = columnNumber * ((i < columnStart ? 1 : 0) - frBeforeRatio); double right = columnNumber * ((i >= columnStop ? 1 : 0) - frAfterRatio); if (left != 0.0 || right != 0.0) { Adjustment adjustment = adjustments.get(columnUnit); if (adjustment == null) { adjustment = new Adjustment(); adjustments.put(columnUnit, adjustment); } adjustment.left += left; adjustment.right += right; } } } frMax = 0; frBefore = 0; for (int i = rowSize - 1; i >= 0; CssUnit row = rows.get(i); if (i < rowStart && "auto".equals(row.getUnit())) { break; } else if ("fr".equals(row.getUnit())) { double fr = row.getNumber(); frMax += fr; if (i < rowStart) { frBefore += fr; } } } frBeforeRatio = frMax > 0 ? frBefore / frMax : 0.0; for (int i = rowSize - 1; i >= 0; CssUnit row = rows.get(i); String rowUnit = row.getUnit(); if (i < rowStart && "auto".equals(rowUnit)) { break; } else if (!"fr".equals(rowUnit)) { double top = row.getNumber() * ((i < rowStart ? 1 : 0) - frBeforeRatio); if (top != 0.0) { Adjustment adjustment = adjustments.get(rowUnit); if (adjustment == null) { adjustment = new Adjustment(); adjustments.put(rowUnit, adjustment); } adjustment.top += top; } } } for (Map.Entry<String, Adjustment> entry : adjustments.entrySet()) { String unit = entry.getKey(); Adjustment adjustment = entry.getValue(); htmlBefore.append("<div style=\"margin:"); htmlBefore.append(new CssUnit(adjustment.top - 1, unit)); htmlBefore.append(" "); htmlBefore.append(new CssUnit(adjustment.right - 1, unit)); htmlBefore.append(" -1px "); htmlBefore.append(new CssUnit(adjustment.left - 1, unit)); htmlBefore.append(";padding:"); htmlBefore.append(new CssUnit(1, unit)); htmlBefore.append(" "); htmlBefore.append(new CssUnit(1, unit)); htmlBefore.append(" 1px "); htmlBefore.append(new CssUnit(1, unit)); htmlBefore.append(";\">"); htmlAfter.insert(0, "</div>"); } htmlBefore.append("<div style=\"margin-left:30000px;margin-right:-30000px;\">"); htmlAfter.insert(0, "</div>"); // Area size. boolean autoHeight = false; for (int i = rowStart; i < rowStop; ++ i) { if ("auto".equals(rows.get(i).getUnit())) { autoHeight = true; break; } } htmlBefore.append("<div class=\"cms-grid-areaWrapper\" style=\"height:100%;width:100%;\">"); // Minimum width. for (int i = columnStart; i < columnStop; ++ i) { CssUnit column = columns.get(i); if (!"fr".equals(column.getUnit())) { htmlBefore.append("<div style=\"padding-left:"); htmlBefore.append(column); htmlBefore.append(";height:0;\">"); } } for (int i = columnStart; i < columnStop; ++ i) { if (!"fr".equals(columns.get(i).getUnit())) { htmlBefore.append("</div>"); } } // Minimum height. if (!autoHeight) { htmlBefore.append("<div style=\"float:left;width:0;\">"); for (int i = rowStart; i < rowStop; ++ i) { CssUnit row = rows.get(i); htmlBefore.append("<div style=\"padding-top:"); htmlBefore.append(row); htmlBefore.append(";width:0;\">"); } for (int i = rowStart; i < rowStop; ++ i) { htmlBefore.append("</div>"); } htmlBefore.append("</div>"); htmlBefore.append("<div style=\"height:0;width:100%;\">"); htmlAfter.insert(0, "</div>"); htmlAfter.insert(0, "<div style=\"clear:left;\"></div>"); } htmlAfter.insert(0, "</div>"); if (clearAt >= 0 && clearAt <= rowStart) { clearAt = -1; htmlBefore.insert(0, "<div style=\"clear:left;\"></div>"); } if (autoHeight && rowStop > clearAt) { clearAt = rowStop; } areaInstances.put(area, new Area( area, htmlBefore.toString(), htmlAfter.toString())); } } } return areaInstances; } /** * Writes the given {@code object} and positions it according to the * grid rules as specified by the given parameters. * * @see #grid(Object, HtmlGrid) */ public HtmlWriter grid(Object object, String columns, String rows, String... template) throws IOException { return grid(object, new HtmlGrid(columns, rows, template)); } public static class Area { private final String name; protected final String htmlBefore; protected final String htmlAfter; public Area(String name, String htmlBefore, String htmlAfter) { this.name = name; this.htmlBefore = htmlBefore; this.htmlAfter = htmlAfter; } public String getName() { return name; } } private static class Adjustment { public double left; public double right; public double top; } @Override public Writer append(char letter) throws IOException { writer.write(letter); return this; } @Override public Writer append(CharSequence text) throws IOException { writer.append(text); return this; } @Override public Writer append(CharSequence text, int start, int end) throws IOException { writer.append(text, start, end); return this; } @Override public void close() throws IOException { writer.close(); } @Override public void flush() throws IOException { writer.flush(); } @Override public void write(char[] buffer) throws IOException { writer.write(buffer); } @Override public void write(char[] buffer, int offset, int length) throws IOException { writer.write(buffer, offset, length); } @Override public void write(int letter) throws IOException { writer.write(letter); } @Override public void write(String text) throws IOException { writer.write(text); } @Override public void write(String text, int offset, int length) throws IOException { writer.write(text, offset, length); } /** {@link HtmlWriter} utility methods. */ public static final class Static { /** Returns a CSS string based on the given {@code properties}. */ public static String cssString(Object... properties) { StringBuilder css = new StringBuilder(); if (properties != null) { for (int i = 1, length = properties.length; i < length; i += 2) { Object property = properties[i - 1]; if (property != null) { Object value = properties[i]; if (value != null) { css.append(property); css.append(':'); css.append(value); css.append(';'); } } } } return css.toString(); } } /** @deprecated Use {@link #htmlOrDefault} instead. */ @Deprecated public HtmlWriter stringOrDefault(Object string, String defaultString) throws IOException { return htmlOrDefault(string, defaultString); } /** @deprecated Use {@link #html} instead. */ @Deprecated public HtmlWriter string(Object string) throws IOException { return html(string); } }
package no.priv.garshol.duke.test; import java.util.List; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.io.IOException; import org.junit.Test; import org.junit.Before; import org.junit.Ignore; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertEquals; import no.priv.garshol.duke.Record; import no.priv.garshol.duke.Property; import no.priv.garshol.duke.Database; import no.priv.garshol.duke.Configuration; import no.priv.garshol.duke.DatabaseProperties; import no.priv.garshol.duke.comparators.ExactComparator; public abstract class DatabaseTest { private Database db; private Configuration config; @Before public void setup() throws IOException { ExactComparator comp = new ExactComparator(); List<Property> props = new ArrayList(); props.add(new Property("ID")); props.add(new Property("NAME", comp, 0.3, 0.8)); props.add(new Property("EMAIL", comp, 0.3, 0.8)); config = new Configuration(); config.setProperties(props); config.setThreshold(0.85); config.setMaybeThreshold(0.8); db = createDatabase(config); } // overridden to create specific databases public abstract Database createDatabase(Configuration config); @Test public void testTrivial() throws IOException { Record record = TestUtils.makeRecord("ID", "1", "NAME", "AND", "EMAIL", "BBBBB"); db.index(record); db.commit(); record = db.findRecordById("1"); assertTrue("no record found", record != null); assertEquals("wrong ID", "1", record.getValue("ID")); } @Test public void testBackslash() throws IOException { String name = "\"Lastname, Firstname \\(external\\)\""; Record record = TestUtils.makeRecord("ID", "1", "NAME", name, "EMAIL", "BBBBB"); db.index(record); db.commit(); Record record2 = TestUtils.makeRecord("NAME", "\"lastname, firstname \\(external\\)\""); db.findCandidateMatches(record2); } @Test public void testBNode() throws IOException { Record record = TestUtils.makeRecord("ID", "_:RHUKdfPM299", "NAME", "AND", "EMAIL", "BBBBB"); db.index(record); db.commit(); record = db.findRecordById("_:RHUKdfPM299"); assertTrue("no record found", record != null); assertEquals("wrong ID", "_:RHUKdfPM299", record.getValue("ID")); } @Test public void testURI() throws IOException { Record record = TestUtils.makeRecord("ID", "http://norman.walsh.name/knows/who/robin-berjon", "NAME", "AND", "EMAIL", "BBBBB"); db.index(record); db.commit(); record = db.findRecordById("http://norman.walsh.name/knows/who/robin-berjon"); assertTrue("no record found", record != null); assertEquals("wrong ID", "http://norman.walsh.name/knows/who/robin-berjon", record.getValue("ID")); } @Test public void testTrivialFind() throws IOException { Record record = TestUtils.makeRecord("ID", "1", "NAME", "AND", "EMAIL", "BBBBB"); db.index(record); db.commit(); Collection<Record> cands = db.findCandidateMatches(record); assertEquals("no record found", 1, cands.size()); assertEquals("wrong ID", "1", cands.iterator().next().getValue("ID")); } }
package liquibase.migrator.change; import liquibase.database.Database; import liquibase.database.MSSQLDatabase; import liquibase.database.OracleDatabase; import liquibase.database.PostgresDatabase; import liquibase.migrator.UnsupportedChangeException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Makes an existing column into an auto-increment column. * This change is only valid for databases with auto-increment/identity columns. * The current version does not support MS-SQL. */ public class AddAutoIncrementChange extends AbstractChange { private String tableName; private String columnName; private String columnDataType; public AddAutoIncrementChange() { super("addAutoIncrement", "Set Column as Auto-Increment"); } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getColumnDataType() { return columnDataType; } public void setColumnDataType(String columnDataType) { this.columnDataType = columnDataType; } public String[] generateStatements(Database database) throws UnsupportedChangeException { if (database instanceof OracleDatabase) { throw new UnsupportedChangeException("Oracle does not support auto-increment columns"); } else if (database instanceof MSSQLDatabase) { throw new UnsupportedChangeException("MS SQL Server does not support auto-increment columns"); } else if (database instanceof PostgresDatabase) { throw new UnsupportedChangeException("PostgreSQL does not support auto-increment columns"); } return new String[]{ "ALTER TABLE " + getTableName() + " MODIFY " + getColumnName() + " " + getColumnDataType() + " AUTO_INCREMENT", }; } public String getConfirmationMessage() { return "Column Set as Auto-Increment"; } public Element createNode(Document currentChangeLogFileDOM) { Element node = currentChangeLogFileDOM.createElement("addAutoIncrement"); node.setAttribute("tableName", getTableName()); node.setAttribute("columnName", getColumnName()); return node; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; /** * Provides utility routines to simplify obtaining randomized values. * * <p>Each instance of Randoms contains an underlying {@link java.util.Random} instance and is * only as thread-safe as that is. If you wish to have a private stream of pseudorandom numbers, * use the {@link #with} factory. */ public class Randoms { /** A default Randoms that is thread-safe and can be safely shared by any caller. */ public static final Randoms RAND = with(new Random()); /** * A factory to create a new Randoms object. */ public static Randoms with (Random rand) { return new Randoms(rand); } /** * Get a thread-local Randoms instance that will not contend with any other thread * for random number generation. * * <p><b>Note:</b> This method will return a Randoms instance that is not thread-safe. * It can generate random values with less overhead, however it may be dangerous to share * the reference. Instead you should probably always use it immediately as in the following * example: * <pre style="code"> * Puppy pick = Randoms.threadLocal().pick(Puppy.LITTER, null); * </pre> */ public static Randoms threadLocal () { return _localRandoms.get(); } public int getInt (int high) { return _r.nextInt(high); } public int getInRange (int low, int high) { return low + _r.nextInt(high - low); } /** * Returns a pseudorandom, uniformly distributed <code>float</code> value between * <code>0.0</code> (inclusive) and the <code>high</code> (exclusive). * * @param high the high value limiting the random number sought. */ public float getFloat (float high) { return _r.nextFloat() * high; } /** * Returns a pseudorandom, uniformly distributed <code>float</code> value between * <code>low</code> (inclusive) and <code>high</code> (exclusive). */ public float getInRange (float low, float high) { return low + (_r.nextFloat() * (high - low)); } public boolean getChance (int n) { return (0 == _r.nextInt(n)); } /** * Has a probability <code>p</code> of returning true. */ public boolean getProbability (float p) { return _r.nextFloat() < p; } /** * Returns <code>true</code> or <code>false</code> with approximately even probability. */ public boolean getBoolean () { return _r.nextBoolean(); } /** * Returns a pseudorandom, normally distributed <code>float</code> value around the * <code>mean</code> with the standard deviation <code>dev</code>. */ public float getNormal (float mean, float dev) { return (float)_r.nextGaussian() * dev + mean; } /** * Pick a random element from the specified Iterator, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> because the total size of the Iterator is not known, * the random number generator is queried after the second element and every element * thereafter. * * @throws NullPointerException if the iterator is null. */ public <T> T pick (Iterator<? extends T> iterator, T ifEmpty) { if (!iterator.hasNext()) { return ifEmpty; } T pick = iterator.next(); for (int count = 2; iterator.hasNext(); count++) { T next = iterator.next(); if (0 == _r.nextInt(count)) { pick = next; } } return pick; } /** * Pick a random element from the specified Iterable, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> optimized implementations are used if the Iterable * is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator, Object)} * with the Iterable's Iterator. * * @throws NullPointerException if the iterable is null. */ public <T> T pick (Iterable<? extends T> iterable, T ifEmpty) { return pickPluck(iterable, ifEmpty, false); } public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty) { T pick = ifEmpty; double total = 0.0; for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) { double weight = entry.getValue().doubleValue(); if (weight > 0.0) { total += weight; if ((total == weight) || ((_r.nextDouble() * total) < weight)) { pick = entry.getKey(); } } else if (weight < 0.0) { throw new IllegalArgumentException("Weight less than 0: " + entry); } // else: weight == 0.0 is OK } return pick; } /** * Pluck (remove) a random element from the specified Iterable, or return <code>ifEmpty</code> * if it is empty. * * <p><b>Implementation note:</b> optimized implementations are used if the Iterable * is a List or Collection. Otherwise, two Iterators are created from the Iterable * and a random number is generated after the second element and all beyond. * * @throws NullPointerException if the iterable is null. * @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator * does not support {@link Iterator#remove()}. */ public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty) { return pickPluck(iterable, ifEmpty, true); } /** * Construct a Randoms. */ protected Randoms (Random rand) { _r = rand; } /** * Shared code for pick and pluck. */ protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) { if (iterable instanceof Collection) { // optimized path for Collection @SuppressWarnings("unchecked") Collection<? extends T> coll = (Collection<? extends T>)iterable; int size = coll.size(); if (size == 0) { return ifEmpty; } if (coll instanceof List) { // extra-special optimized path for Lists @SuppressWarnings("unchecked") List<? extends T> list = (List<? extends T>)coll; int idx = _r.nextInt(size); if (remove) { // ternary conditional causes warning here with javac 1.6, :( return list.remove(idx); } return list.get(idx); } // for other Collections, we must iterate Iterator<? extends T> it = coll.iterator(); for (int idx = _r.nextInt(size); idx > 0; idx it.next(); } try { return it.next(); } finally { if (remove) { it.remove(); } } } if (!remove) { return pick(iterable.iterator(), ifEmpty); } // from here on out, we're doing a pluck with a complicated two-iterator solution Iterator<? extends T> it = iterable.iterator(); if (!it.hasNext()) { return ifEmpty; } Iterator<? extends T> lagIt = iterable.iterator(); T pick = it.next(); lagIt.next(); for (int count = 2, lag = 1; it.hasNext(); count++, lag++) { T next = it.next(); if (0 == _r.nextInt(count)) { pick = next; // catch up lagIt so that it has just returned 'pick' as well for ( ; lag > 0; lag lagIt.next(); } } } lagIt.remove(); // remove 'pick' from the lagging iterator return pick; } /** The random number generator. */ protected final Random _r; /** A ThreadLocal for accessing a thread-local version of Randoms. */ protected static final ThreadLocal<Randoms> _localRandoms = new ThreadLocal<Randoms>() { @Override public Randoms initialValue () { return with(new ThreadLocalRandom()); } }; protected static class ThreadLocalRandom extends Random { // same constants as Random, but must be redeclared because private private final static long multiplier = 0x5DEECE66DL; private final static long addend = 0xBL; private final static long mask = (1L << 48) - 1; /** * The random seed. We can't use super.seed. */ private long rnd; /** * Initialization flag to permit calls to setSeed to succeed only * while executing the Random constructor. We can't allow others * since it would cause setting seed in one part of a program to * unintentionally impact other usages by the thread. */ boolean initialized; // Padding to help avoid memory contention among seed updates in // different TLRs in the common case that they are located near // each other. @SuppressWarnings("unused") private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; /** * Constructor called only by localRandom.initialValue. */ ThreadLocalRandom() { super(); initialized = true; } /** * Throws {@code UnsupportedOperationException}. Setting seeds in * this generator is not supported. * * @throws UnsupportedOperationException always */ @Override public void setSeed(long seed) { if (initialized) throw new UnsupportedOperationException(); rnd = (seed ^ multiplier) & mask; } @Override protected int next(int bits) { rnd = (rnd * multiplier + addend) & mask; return (int) (rnd >>> (48-bits)); } // as of JDK 1.6, this method does not exist in java.util.Random // public int nextInt(int least, int bound) { // if (least >= bound) // return nextInt(bound - least) + least; public long nextLong(long n) { if (n <= 0) throw new IllegalArgumentException("n must be positive"); // Divide n by two until small enough for nextInt. On each // iteration (at most 31 of them but usually much less), // randomly choose both whether to include high bit in result // (offset) and whether to continue with the lower vs upper // half (which makes a difference only if odd). long offset = 0; while (n >= Integer.MAX_VALUE) { int bits = next(2); long half = n >>> 1; long nextn = ((bits & 2) == 0) ? half : n - half; if ((bits & 1) == 0) offset += n - nextn; n = nextn; } return offset + nextInt((int) n); } public long nextLong(long least, long bound) { if (least >= bound) throw new IllegalArgumentException(); return nextLong(bound - least) + least; } public double nextDouble(double n) { if (n <= 0) throw new IllegalArgumentException("n must be positive"); return nextDouble() * n; } public double nextDouble(double least, double bound) { if (least >= bound) throw new IllegalArgumentException(); return nextDouble() * (bound - least) + least; } private static final long serialVersionUID = -5851777807851030925L; } }
package edu.jhu.hlt.optimize; import java.util.ArrayList; import java.util.List; import org.junit.Test; /** * Basic test class -- should be replaced with something more flexible. * * @author Nicholas Andrews */ public class OptimizeTester { public List<TestFunction> getTestFunctions() { List<TestFunction> fs = new ArrayList<TestFunction>(); fs.add(new TestFunction(new XSquared(+1d), 0d, 1e-4, new double[] {0d}, 1e-3)); fs.add(new TestFunction(new XSquared(-1d), 0d, 1e-4, new double[] {0d}, 1e-3)); return fs; } @Test public void testStochasticGradientDescent() { List<TestFunction> fs = getTestFunctions(); for(TestFunction f : fs) { StochasticGradientDescent sgd = new StochasticGradientDescent((DifferentiableRealScalarFunction) f.getFunction(), 1); f.checkValue(sgd.val()); f.checkParam(sgd.getFunction().get()); } } }
package org.stepic.droid.analytic; import android.os.Bundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface Analytic { interface Registration { String ERROR = "registration_error"; String TAP_ON_FIELDS = "tap_on_fields_registration"; String TYPING_TEXT_FIELDS = "typing_text_fields_registration"; String CLICK_WITH_INTERACTION_TYPE = "click_registration_with_interaction_type"; String CLICK_SEND_IME = "click_registration_send_ime"; } interface Login { String FAIL_LOGIN = "fail_login"; String REQUEST_LOGIN_WITH_INTERACTION_TYPE = "click_sign_in_with_interaction_type"; String TAP_ON_FIELDS = "tap_on_fields_login"; String TYPING_TEXT_FIELDS = "typing_text_fields_login"; } interface System { String BOOT_COMPLETED = "boot_completed"; java.lang.String FIRST_LAUNCH_AFTER_INSTALL = "first_launch_after_install"; } interface Preferences { String VIDEO_QUALITY = "video quality was chosen"; } interface Interaction { String CLICK_SIGN_IN = "click sign in on launch screen"; String CLICK_SIGN_UP = "click sign up"; String CLICK_SIGN_IN_ON_SIGN_IN_SCREEN = "click sign in on sign in on sign-in screen"; String CLICK_SIGN_IN_NEXT_ON_SIGN_IN_SCREEN = "click_sign_in_next_sign_in_screen"; String CLICK_DELETE_SECTION = "Click delete section from cache"; String CLICK_CACHE_SECTION = "Click cache section"; String CLICK_CACHE_LESSON = "Click cache unit"; String CLICK_DELETE_LESSON = "Click delete unit from cache"; String CLICK_LOGOUT = "Click logout"; String CLICK_CLEAR_CACHE = "Click clear cache button"; String CLICK_YES_LOGOUT = "Click accept logout"; String CANCEL_VIDEO_QUALITY = "Cancel video quality dialog"; String CANCEL_VIDEO_QUALITY_DETAILED = "cancel_detailed_video"; String YES_CLEAR_VIDEOS = "clear videos from downloads"; String DELETE_COMMENT_TRIAL = "comment: delete comment trial"; String UPDATING_MESSAGE_IS_APPROVED = "updating approved"; String PULL_TO_REFRESH_COURSE = "Pull from top to refreshWhenOnConnectionProblem course"; String COURSE_USER_TRY_FAIL = "course: user open failed for him course"; String JOIN_COURSE_NULL = "course is null when join, detail"; String CANCEL_CHOOSE_STORE_CLICK = "storage: cancel choice"; String AUTH_FROM_DIALOG_FOR_UNAUTHORIZED_USER = "Auth: yes from auth dialog"; String TRANSFER_DATA_YES = "storage: transfer data"; String CLICK_CANCEL_SECTION = "click cancel section"; String CLICK_CANCEL_LESSON = "click cancel unit"; String UPDATING_MESSAGE_IS_SHOWN = "updating shown"; String REFRESH_UNIT = "Pull from top to refreshWhenOnConnectionProblem section unit"; String REFRESH_SECTION = "Pull from top to refreshWhenOnConnectionProblem section"; String SUCCESS_LOGIN = "success login"; String SHOW_DETAILED_INFO_CLICK = "Show detailed info click from context menu of course"; String LONG_TAP_COURSE = "Long tap on course"; String CLICK_REGISTER_BUTTON = "click_register_register_screen"; String CLICK_SEND_SUBMISSION = "click_send_submission"; String SHARE_COURSE = "share_course_detail"; String SHARE_COURSE_SECTION = "share_course_from_section"; String CLICK_FIND_COURSE_EMPTY_SCREEN = "click_find_courses_empty_screen"; String CLICK_NEXT_LESSON_IN_STEPS = "click_next_lesson_in_steps"; String CLICK_PREVIOUS_LESSON_IN_STEPS = "click_previous_lesson_in_steps"; String CLICK_SIGN_IN_SOCIAL = "social_login"; String CLICK_ACCEPT_FILTER_BUTTON = "click_accept_filter_btn"; String CLICK_AUTH_FROM_STEPS = "click_auth_from_steps"; String SHARE_STEP_CLICK = "share_step_click"; String CLICK_TRY_STEP_AGAIN = "step_try_again"; String NO_DISCOUNTING_DIALOG = "discounting_dialog_no"; String YES_DISCOUNTING_DIALOG = "discounting_dialog_yes"; String CLICK_SETTINGS_FROM_NOTIFICATION = "click_settings_from_notification"; String START_SPLASH = "user_start_splash_new"; String START_SPLASH_EXPERT = "user_start_splash_expert"; String CLICK_CHOOSE_NOTIFICATION_INTERVAL = "click_choose_notification_interval"; String CLICK_PRIVACY_POLICY = "click_privacy_policy"; String CLICK_TERMS_OF_SERVICE = "click_terms_of_service"; String POSITIVE_MATERIAL_DIALOG_INVITATION = "material_dialog_invite_positive"; String NEGATIVE_MATERIAL_DIALOG_INVITATION = "material_dialog_invite_negative"; String SHOW_MATERIAL_DIALOG_INVITATION = "materdial_dialog_invite_shown"; String INVITATION_PREVENTED = "invite_prevented"; String CLICK_CONTINUE_COURSE = "click_continue_course"; String CLICK_COURSE = "click_course"; String CLICK_PROFILE_BEFORE_LOADING = "click_profile_before_loading"; String JOIN_COURSE = "click_join_course"; String CLICK_FIND_COURSE_LAUNCH = "click_find_courses_launch"; String USER_OPEN_IMAGE = "user_open_image"; String SCREENSHOT = "screenshot"; String GOOGLE_SOCIAL_IS_NOT_ENABLED = "google_social_is_not_enabled"; String ACCEPT_DELETING_UNIT = "click_delete_unit_dialog"; String ACCEPT_DELETING_SECTION = "click_delete_section_dialog"; String CLICK_STREAK_DRAWER = "click_streak_drawer"; String SHOW_LAUNCH_SCREEN_AFTER_LOGOUT = "show_launch_screen_after_logout"; } interface Screens { String SHOW_LAUNCH = "Screen manager: show launch screen"; String SHOW_REGISTRATION = "Screen manager: show registration"; String SHOW_LOGIN = "Screen manager: show login"; String SHOW_MAIN_FEED = "Screen manager: show main feed"; String SHOW_COURSE_DESCRIPTION = "Screen manager: show course description"; String SHOW_TEXT_FEEDBACK = "show text feedback"; String OPEN_STORE = "Open google play, estimation"; String TRY_OPEN_VIDEO = "video is tried to show"; String SHOW_SETTINGS = "show settings"; String SHOW_STORAGE_MANAGEMENT = "show storage management"; String OPEN_COMMENT_NOT_AVAILABLE = "comment: not available"; String OPEN_COMMENT = "comments: open oldList"; String OPEN_WRITE_COMMENT = "comments: open write form"; String SHOW_SECTIONS = "Screen manager: show section"; String SHOW_UNITS = "Screen manager: show units-lessons screen"; String SHOW_STEP = "Screen manager: show steps of lesson"; String OPEN_STEP_IN_WEB = "Screen manager: open Step in Web"; String REMIND_PASSWORD = "Screen manager: remind password"; String OPEN_LINK_IN_WEB = "open_link"; String USER_OPEN_MY_COURSES = "main_choice_my_courses"; String USER_OPEN_FIND_COURSES = "main_choice_find_courses"; String USER_OPEN_DOWNLOADS = "main_choice_downloads"; String USER_OPEN_CERTIFICATES = "main_choice_certificates"; String USER_OPEN_FEEDBACK = "main_choice_feedback"; String USER_OPEN_NOTIFICATIONS = "main_choice_notifications"; String USER_OPEN_SETTINGS = "main_choice_settings"; String USER_LOGOUT = "main_choice_logout"; String USER_OPEN_ABOUT_APP = "main_choice_about"; String SHOW_SECTIONS_JOINED = "show_sections_joined"; String USER_OPEN_PROFILE = "main_choice_profile"; } interface Video { String OPEN_EXTERNAL = "video open external"; String OPEN_NATIVE = "video open native"; String NOT_COMPATIBLE = "video is not compatible"; String VLC_HARDWARE_ERROR = "video player: vlc error hardware"; String INVALID_SURFACE_SIZE = "video player: Invalid surface size"; String SHOW_CHOOSE_RATE = "video player: showChooseRateMenu"; String JUMP_FORWARD = "video player: onJumpForward"; String JUMP_BACKWARD = "video player: onJumpBackward"; String START_LOADING = "video player: startLoading"; String STOP_LOADING = "video player: stopLoading"; String QUALITY_NOT_DETERMINATED = "video_quality_failed"; } interface AppIndexing { String COURSE_DETAIL = "appindexing_course_detail"; String COURSE_SYLLABUS = "appindexing_course_syllabus"; String STEP = "appindexing_step"; } interface Error { String CALLBACK_SOCIAL = "callback_from_social_login"; String NOT_PLAYER = "NotPlayer"; String VIDEO_RESOLVER_FAILED = "video resolver is failed"; String CANT_UPDATE_TOKEN = "cant update token"; String AUTH_ERROR = "retrofitAuth"; String ERROR_CREATING_PLAYER = "video player: Error creating player"; String INIT_PHONE_STATE = "initPhoneStateListener"; String REMOVE_PHONE_STATE = "removePhoneStateCallbacks"; String NOTIFICATION_ERROR_PARSE = "notification error parse"; String DELETE_SERVICE_ERROR = "DeleteService nullptr"; String ERROR_UPDATE_CHECK_APP = "update check failed"; String UPDATE_FROM_APK_FAILED = "update apk is failed"; String CANT_RESOLVE_VIDEO = "can't Resolve video"; String FAIL_TO_MOVE = "storage: fail to move"; String REGISTRATION_IMPORTANT_ERROR = "registration important error"; String NOTIFICATION_NOT_POSTED_ON_CLICK = "notification is not posted"; String NULL_SECTION = "Null section is not expected"; String LESSON_IN_STORE_STATE_NULL = "lesson was null in store state manager"; String UNIT_IN_STORE_STATE_NULL = "unit was null in store state manager"; String LOAD_SERVICE = "Load Service"; String PUSH_STATE_EXCEPTION = "Push state exception"; String CANT_CREATE_NOMEDIA = "can't create .nomedia"; String ILLEGAL_STATE_NEXT_LESSON = "cant_show_next_lesson"; String ILLEGAL_STATE_PREVIOUS_LESSON = "cant_show_previous_lesson"; String FAIL_PUSH_STEP_VIEW = "fail_push_step_view"; String NO_INTERNET_EXISTING_ATTEMPTS = "no_internet_existing_attempts"; String DOWNLOAD_ID_NEGATIVE = "download_id_negative"; String STREAK_ON_STEP_SOLVED = "streak_on_step_solved"; String GOOGLE_SERVICES_TOO_OLD = "google_services_too_old"; String VIDEO_PATH_WAS_NULL_WITH_INTERNET = "video_path_was_null_internet_enabled"; String FAIL_REFRESH_TOKEN_ONLINE = "fail_refresh_token_online"; String FAIL_REFRESH_TOKEN_ONLINE_EXTENDED = "fail_refresh_token_online_extended"; String COOKIE_MANAGER_ERROR = "cookie_manager_error"; String FAIL_REFRESH_TOKEN_INLINE_GETTING = "fail_refresh_token_online_get"; String COOKIE_WAS_EMPTY = "cookie_was_empty"; String FAIL_LOGOUT_WHEN_REFRESH = "refresh_fail_logout_social"; String UNITS_LOADING_FAIL = "units_loading_fail"; String UNPREDICTABLE_LOGIN_RESULT = "login_successful_was_not_correct"; String LESSON_ACCESS_DENIED = "lesson_access_denied"; String SEARCH_COURSE_NO_INTERNET = "search_course_no_internet"; String SEARCH_COURSE_UNSUCCESSFUL = "search_course_unsuccessful"; } interface Web { String UPDATE_TOKEN_FAILED = "update is failed"; String AUTH_LOGIN_PASSWORD = "Api:auth with login password"; String AUTH_SOCIAL = "Api:auth with social account"; String TRY_REGISTER = "Api: try register"; String TRY_JOIN_COURSE = "Api:try join to course"; String DROP_COURSE = "Api: drop course"; String DROP_COURSE_SUCCESSFUL = "drop course successful"; String DROP_COURSE_FAIL = "drop course fail"; } interface Notification { String DISABLED_BY_USER = "Notification is disabled by user in app"; String ACTION_NOT_SUPPORT = "notification action is not support"; String HTML_WAS_NULL = "notification_html_was_null"; String WAS_MUTED = "notification_was_muted"; String NOT_SUPPORT_TYPE = "notification_type_is_not_support";//After checking action String CANT_PARSE_COURSE_ID = "notification, cant parse courseId"; String TOKEN_UPDATED = "notification gcm token is updated"; String TOKEN_UPDATE_FAILED = "notification gcm token is not updated"; String OPEN_NOTIFICATION = "notification_opened"; String OPEN_NOTIFICATION_SYLLABUS = "notification_opened_syllabus"; String ID_WAS_NULL = "notification_id_was_null"; String NOTIFICATION_NULL_POINTER = "notification_unpredicatable_null"; String NOTIFICATION_CLICKED_IN_CENTER = "notification_clicked_in_center"; String NOTIFICATION_CENTER_OPENED = "notification_center_opened"; String OPEN_COMMENT_NOTIFICATION_LINK = "notification_open_comment_link"; String OPEN_LESSON_NOTIFICATION_LINK = "notification_open_lesson_link"; String NOTIFICATION_NOT_OPENABLE = "notification_not_openable"; String GCM_TOKEN_NOT_OK = "notification_gsm_token_not_ok"; String NOTIFICATION_SHOWN = "notification_shown"; String DISCARD = "notification_discarded"; String CANT_PARSE_NOTIFICATION = "notification_parse_fail"; String OPEN_TEACH_CENTER = "notification_open_teach_link"; String PERSISTENT_KEY_NULL = "notification_key_null"; String MARK_ALL_AS_READ = "notification_mark_all"; String REMIND_HIDDEN = "remind_hidden"; String REMIND_SHOWN = "remind_shown"; String REMIND_SCHEDULED = "remind_scheduled"; String REMIND_OPEN = "remind_opened"; String REMIND_ENROLL = "remind_success_user_enroll"; String REMINDER_SWIPE_TO_CANCEL = "remind_swipe_to_cancel"; String STREAK_SWIPE_TO_CANCEL = "streak_swipe_to_cancel"; String NIGHT_WITHOUT_SOUND_AND_VIBRATE = "notification_night_without_sound_and_vibrate"; } interface Feedback { String FAILED_ON_SERVER = "Feedback is failed due to server"; String INTERNET_FAIL = "Feedback internet fail"; } interface Comments { String CLICK_SEND_COMMENTS = "comments: click send comment"; String COMMENTS_SENT_SUCCESSFULLY = "comments: comment was sent successfully"; String DELETE_COMMENT_CONFIRMATION = "comment: delete comment confirmed"; String ORDER_TREND = "order_trend"; String SHOW_CONFIRM_DISCARD_TEXT_DIALOG = "comment_discard_dialog_show"; String SHOW_CONFIRM_DISCARD_TEXT_DIALOG_SUCCESS = "comment_discard_ok"; String OPEN_FROM_OPTION_MENU = "comment_open_from_option_menu"; String OPEN_FROM_STEP_UI = "comment_open_from_step_ui"; } interface Steps { String CORRECT_SUBMISSION_FILL = "submission_correct_fill"; // it can be existing submission, use in chain. String WRONG_SUBMISSION_FILL = "submission_wrong_fill"; String SHARE_OPEN_IN_BROWSER = "step_share_open_in_browser"; String COPY_LINK = "step_share_copy"; String SHARE_ALL = "steps_share_all"; String SHOW_KEEP_ON_SCREEN = "steps_show_keep_on_screen"; String SHOW_KEEP_OFF_SCREEN = "steps_show_keep_off_screen"; String STEP_OPENED = "step_opened"; String CLICK_SEND_SUBMISSION_STEP_TYPE = "step_click_send"; } interface Calendar { String USER_CLICK_ADD_WIDGET = "calendar_click_add_widget"; String USER_CLICK_ADD_MENU = "calendar_click_add_menu"; String CALENDAR_ADDED_SUCCESSFULLY = "calendar_added_successfully"; String CALENDAR_ADDED_FAIL = "calendar_added_fail"; String SHOW_CALENDAR_AS_WIDGET = "calendar_shown_as_widget"; String SHOW_CALENDAR = "calendar_shown"; // course with deadlines in future //// FIXME: 13.01.17 this metric has doubled number of events String HIDE_WIDGET_FROM_PREFS = "widget_hidden_from_prefs"; //// FIXME: 13.01.17 this metric has doubled number of events String USER_CLICK_NOT_NOW = "calendar_click_not_now"; } interface DeepLink { String USER_OPEN_LINK_GENERAL = "open_deep_link"; String USER_OPEN_SYLLABUS_LINK = "open_syllabus_by_link"; String USER_OPEN_COURSE_DETAIL_LINK = "open_detail_course_link"; String USER_OPEN_STEPS_LINK = "open_step_link"; String ANONYMOUS_OPEN_STEPS_LINK = "open_step_link_anonymous"; } interface Certificate { String COPY_LINK_CERTIFICATE = "certificate_copy_link"; String SHARE_LINK_CERTIFICATE = "certificate_share"; String ADD_LINKEDIN = "certificate_add_linkeding"; String OPEN_IN_BROWSER = "certificate_open_browser"; String CLICK_SHARE_MAIN = "certificate_click_share_main"; String OPEN_CERTIFICATE_FROM_NOTIFICATION_CENTER = "certificate_notification_center"; } interface Filters { String FILTERS_CANCELED = "filters_canceled"; String FILTERS_NEED_UPDATE = "filters_need_update"; String FILTER_APPLIED_IN_INTERFACE_WITH_PARAMS = "filters_params"; } interface Exam { String START_EXAM = "exam_start"; String SHOW_EXAM = "exam_shown_on_bind_view"; } interface Profile { String CLICK_INSTRUCTOR = "profile_click_instructor"; String CLICK_USER_IN_COMMENT = "profile_click_in_comment"; String CLICK_OPEN_MY_PROFILE_IMAGE = "profile_click_open_my"; //click on image String SHOW_LOCAL = "profile_show_my"; String OPEN_NO_INTERNET = "profile_no_internet"; String STREAK_NO_INTERNET = "profile_no_internet_streak"; String OPEN_BY_LINK = "profile_open_by_link"; String CLICK_IMAGE = "profile_click_avatar"; String CLICK_STREAK_VALUE = "profile_click_streak"; String CLICK_FULL_NAME = "profile_click_full_name"; String OPEN_SCREEN_OVERALL = "profile_open_screen_overall"; String CLICK_FULL_NAME_DRAWER = "profile_click_fill_name_drawer"; } interface Streak { String SWITCH_NOTIFICATION_IN_MENU = "streak_switch_notification_state"; String CHOOSE_INTERVAL_PROFILE = "streak_choose_interval_profile"; String CHOOSE_INTERVAL_CANCELED_PROFILE = "streak_choose_interval_canceled_profile"; String CHOOSE_INTERVAL_CANCELED = "streak_choose_interval_canceled"; String CHOOSE_INTERVAL = "streak_choose_interval"; String CAN_SHOW_DIALOG = "streak_can_show_dialog"; String SHOW_DIALOG_UNDEFINED_STREAKS = "streak_show_dialog_undefined"; String SHOW_DIALOG_POSITIVE_STREAKS = "streak_show_dialog_positive"; String STREAK_NOTIFICATION_OPENED = "streak_notification_opened"; String NEGATIVE_MATERIAL_DIALOG = "streak_material_dialog_negative"; String POSITIVE_MATERIAL_DIALOG = "streak_material_dialog_positive"; String SHOWN_MATERIAL_DIALOG = "streak_material_dialog_shown"; String GET_NON_ZERO_STREAK_NOTIFICATION = "streak_get_non_zero_notification"; String GET_ZERO_STREAK_NOTIFICATION = "streak_get_zero_notification"; String GET_NO_INTERNET_NOTIFICATION = " streak_get_no_internet_notification"; } interface Shortcut { String OPEN_PROFILE = "shortcut_open_profile"; String FIND_COURSES = "shortcut_find_courses"; } interface Anonymous { String JOIN_COURSE = "click_join_course_anonymous"; String BROWSE_COURSES_CENTER = "click_anonymous_browse_courses_center"; String AUTH_CENTER = "click_anonymous_auth_center"; String BROWSE_COURSES_DRAWER = "click_anonymous_auth_center"; String AUTH_DRAWER = "click_anonymous_auth_drawer"; String SUCCESS_LOGIN_AND_ENROLL = "success_login_insta_enroll"; } interface DownloadManager { String DOWNLOAD_MANAGER_IS_NOT_ENABLED = "download_manager_is_not_enabled"; } interface SmartLock { String READ_CREDENTIAL_WITHOUT_INTERACTION = "smartlock_read_without_interaction"; String DISABLED_LOGIN = "smartlock_disabled_login"; String DISABLED_REGISTRATION = "smartlock_disabled_registration"; String SHOW_SAVE_LOGIN = "smartlock_show_save_login"; String LOGIN_SAVED = "smartlock_login_saved"; String LOGIN_NOT_SAVED = "smartlock_login_not_saved"; String SHOW_SAVE_REGISTRATION = "smartlock_show_save_registration"; String REGISTRATION_SAVED = "smartlock_registration_saved"; String REGISTRATION_NOT_SAVED = "smartlock_registration_not_saved"; String PROMPT_TO_CHOOSE_CREDENTIALS = "smartlock_prompt_to_choose_credentials"; String LAUNCH_CREDENTIAL_RETRIEVED_PROMPT = "smartlock_launch_credential_retrieved_prompt"; String LAUNCH_CREDENTIAL_CANCELED_PROMPT = "smartlock_launch_credential_canceled_prompt"; String CREDENTIAL_DELETED_FAIL = "smartlock_credential_deleted_fail"; String CREDENTIAL_DELETED_SUCCESSFUL = "smartlock_credential_deleted_successful"; } interface RemoteConfig { String FETCHED_SUCCESSFUL = "remote_fetched_successful"; String FETCHED_UNSUCCESSFUL = "remote_fetched_unsuccessful"; } interface ContinueExperiment { String CONTINUE_OLD = "experiment_continue_old"; String CONTINUE_NEW = "experiment_continue_new"; String COURSE_OLD = "experiment_continue_course_old";// click whole course (only for enrolled) String COURSE_NEW = "experiment_continue_course_new";// click whole course (only for enrolled) } interface CourseDetailScreen { String ANONYMOUS = "course_detail_anonymous"; String ENROLLED = "course_detail_enrolled"; String NOT_ENROLLED = "course_detail_not_enrolled"; } void reportEvent(String eventName, Bundle bundle); void reportEvent(String eventName, String id); void reportEventWithIdName(String eventName, String id, @Nullable String name); void reportEventWithName(String eventName, @Nullable String name); void reportEvent(String eventName); void reportError(String message, @NotNull Throwable throwable); void setUserId(@NotNull String userId); void reportEventValue(String eventName, long value); }
package com.alexrnl.subtitlecorrector; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.alexrnl.commons.translation.Translator; import com.alexrnl.subtitlecorrector.correctionstrategy.FixPunctuation; import com.alexrnl.subtitlecorrector.correctionstrategy.LetterReplacement; import com.alexrnl.subtitlecorrector.correctionstrategy.Strategy; import com.alexrnl.subtitlecorrector.io.SubtitleFormatManager; import com.alexrnl.subtitlecorrector.io.subrip.SubRip; import com.alexrnl.subtitlecorrector.service.DictionaryManager; import com.alexrnl.subtitlecorrector.service.SessionManager; import com.alexrnl.subtitlecorrector.service.UserPrompt; /** * Abstract subtitle correction application.<br /> * Allows to factorise initialization code between console and GUI application. * @author Alex */ public abstract class AbstractApp { /** The translator to use in the application */ private final Translator translator; /** The session manager to use */ private final SessionManager sessionManager; /** The dictionary manager */ private final DictionaryManager dictionariesManager; /** The available strategies */ private final Map<String, Strategy> strategies; /** The subtitle format manager */ private final SubtitleFormatManager subtitleFormatManager; /** * Default constructor.<br /> * Initialize default behavior: * <ul> * <li>Translator</li> * <li>Dictionary manager</li> * <li>Strategies</li> * <li>Subtitle format manager</li> * </ul> * @param userPrompt * the user prompt to use for initializing strategies. * @throws IOException * if a resource cannot be loaded. * @throws URISyntaxException * if there is an error while building a Path. */ public AbstractApp (final UserPrompt userPrompt) throws IOException, URISyntaxException { super(); translator = new Translator(Paths.get(AbstractApp.class.getResource("/locale/en.xml").toURI())); userPrompt.setTranslator(translator); sessionManager = new SessionManager(); sessionManager.addSessionListener(userPrompt); // Load services TODO load custom dictionaries from configuration dictionariesManager = new DictionaryManager(Paths.get(AbstractApp.class.getResource("/dictionary").toURI()), Paths.get(AbstractApp.class.getResource("/locale").toURI())); sessionManager.addSessionListener(dictionariesManager); strategies = new HashMap<>(); addStrategy(new LetterReplacement(dictionariesManager, userPrompt)); addStrategy(new FixPunctuation(Paths.get(AbstractApp.class.getResource("/punctuation").toURI()))); subtitleFormatManager = new SubtitleFormatManager(); subtitleFormatManager.registerFormat(new SubRip()); } /** * Return the attribute translator. * @return the attribute translator. */ protected Translator getTranslator () { return translator; } /** * Return the attribute sessionManager. * @return the attribute sessionManager. */ protected SessionManager getSessionManager () { return sessionManager; } /** * Return the attribute dictionariesManager. * @return the attribute dictionariesManager. */ protected DictionaryManager getDictionariesManager () { return dictionariesManager; } /** * Return the attribute strategies. * @return the attribute strategies. */ protected Map<String, Strategy> getStrategies () { return Collections.unmodifiableMap(strategies); } /** * Add a strategy to the map.<br /> * Also add the new strategy to the session manager, and remove the previously installed one. * @param strategy * the strategy to add. * @return <code>true</code> if there was a previous strategy registered with the same * translation. */ protected boolean addStrategy (final Strategy strategy) { final String name = getTranslator().get(strategy.getName()); final Strategy previousStrategy = strategies.put(name, strategy); getSessionManager().removeSessionListener(previousStrategy); return previousStrategy != null; } /** * Return the attribute subtitleFormatManager. * @return the attribute subtitleFormatManager. */ protected SubtitleFormatManager getSubtitleFormatManager () { return subtitleFormatManager; } /** * Launch the application.<br /> * @return <code>true</code> if the application has been launched successfully. */ public abstract boolean launch (); }
package com.surmize.snaporm; import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class BaseDAO<T> { protected final DataSourceManager dsMan; protected final ResultSetMapper mapper; protected final PreparedStatementGenerator statementGenerator; public BaseDAO() { dsMan = DataSourceManager.getInstance(); mapper = new ResultSetMapper(); statementGenerator = new PreparedStatementGenerator(); } public List<T> executeSelect(String query) throws SQLException { return executeSelect(query, null); } public List<T> executeSelect(String query, List params) throws SQLException { List<T> results = new ArrayList<>(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = dsMan.getConnection(); stmt = statementGenerator.getStatement(con, query, params); rs = stmt.executeQuery(); while (rs.next()) { T entity = instantiateEntity(); mapper.mapResults(rs, entity); results.add(entity); } } finally { dsMan.closeAll(rs, stmt, con); } return results; } public int executeUpdate(String update, List params) throws SQLException { Connection con = null; PreparedStatement stmt = null; int result; try { con = dsMan.getConnection(); stmt = statementGenerator.getStatement(con, update, params); result = stmt.executeUpdate(); } finally { dsMan.closeStatement(stmt); dsMan.closeConnection(con); } return result; } public T findEntityById(Object id) throws SQLException { T result = null; Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = dsMan.getConnection(); stmt = statementGenerator.getFindByIdStatement(con, instantiateEntity(), id); rs = stmt.executeQuery(); if (rs.next()) { result = instantiateEntity(); mapper.mapResults(rs, result); } } finally { dsMan.closeAll(rs, stmt, con); } return result; } public int insertOrUpdateEntity(T entity) throws SQLException { if( exists(entity) ){ return updateEntity(entity); } else { try{ return insertEntity(entity); } catch(MySQLIntegrityConstraintViolationException | SQLIntegrityConstraintViolationException ex){ Logger.getLogger(BaseDAO.class.getName()).log(Level.INFO, null, ex); return updateEntity(entity); } } } public int insertEntity(T entity) throws SQLException { Connection con = null; PreparedStatement stmt = null; int result; try { con = dsMan.getConnection(); stmt = statementGenerator.getInsertStatement(con, entity); result = stmt.executeUpdate(); } finally { dsMan.closeStatement(stmt); dsMan.closeConnection(con); } return result; } public int insertEntityReturnId(T entity) throws SQLException { Connection con = null; PreparedStatement stmt = null; PreparedStatement getIdStmt = null; ResultSet rs = null; int pkId = 0; try { con = dsMan.getConnection(); stmt = statementGenerator.getInsertStatement(con, entity); stmt.executeUpdate(); getIdStmt = con.prepareStatement("select LAST_INSERT_ID()"); rs = getIdStmt.executeQuery(); if (rs.next()) { pkId = rs.getInt(1); } } finally { dsMan.closeResultSet(rs); dsMan.closeStatement(stmt); dsMan.closeStatement(getIdStmt); dsMan.closeConnection(con); } return pkId; } public int updateEntity(T entity) throws SQLException { Connection con = null; PreparedStatement stmt = null; int result; try { con = dsMan.getConnection(); stmt = statementGenerator.getUpdateStatement(con, entity); result = stmt.executeUpdate(); } finally { dsMan.closeStatement(stmt); dsMan.closeConnection(con); } return result; } public int deleteByPrimaryKey(T entity) throws SQLException { Connection con = null; PreparedStatement stmt = null; int result; try { con = dsMan.getConnection(); stmt = statementGenerator.getDeleteStatement(con, entity); result = stmt.executeUpdate(); } finally { dsMan.closeStatement(stmt); dsMan.closeConnection(con); } return result; } public boolean exists(T entity) throws SQLException { AbstractMap.SimpleEntry keyValueMap = statementGenerator.getPrimaryKeyNameAndValue(entity); if (keyValueMap == null) { return false; } else { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = dsMan.getConnection(); stmt = statementGenerator.getExistsStatement(con, entity); rs = stmt.executeQuery(); if (rs.next()) { if(rs.getInt("TOTAL") > 0){ return true; } } } finally { dsMan.closeAll(rs, stmt, con); } return false; } } public T instantiateEntity() throws SQLException{ try { return (T)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); throw new SQLException("Invalid object type"); } } }
package org.miabis.converter; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations={"/spring/batch/config/database.xml", "/spring/batch/jobs/job-csv-db.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class JobFilesDBTabTest { private static final String DIRECTORY = "data/input/"; private static final String DIRECTORY_OUT = "data/output/"; @Autowired private JobLauncher jobLauncher; @Autowired private Job job; @Test public void testSimpleProperties() throws Exception { assertNotNull(jobLauncher); } @Test public void testLaunchJob() throws Exception { JobParametersBuilder pb = new JobParametersBuilder(); pb.addString("contactInfo", DIRECTORY + "contactInfo.txt"); pb.addString("biobank", DIRECTORY + "biobank.txt"); pb.addString("sampleCollection", DIRECTORY + "sampleCollection.txt"); pb.addString("study", DIRECTORY + "study.txt"); pb.addString("sample", DIRECTORY + "sample.txt"); pb.addString("tab.output",DIRECTORY_OUT + "db.out.tab"); jobLauncher.run(job, pb.toJobParameters()); } }
package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; /** * <p>Provides utilities for manipulating and examining * <code>Throwable</code> objects.</p> * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @author Dmitri Plotnikov * @author Stephen Colebourne * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @since 1.0 * @version $Id: ExceptionUtils.java,v 1.30 2003/07/26 14:22:21 scolebourne Exp $ */ public class ExceptionUtils { /** * <p>Used when printing stack frames to denote the start of a * wrapped exception.</p> * * <p>Package private for accessibility by test suite.</p> */ static final String WRAPPED_MARKER = " [wrapped] "; /** * <p>The names of methods commonly used to access a wrapped exception.</p> */ private static String[] CAUSE_METHOD_NAMES = { "getCause", "getNextException", "getTargetException", "getException", "getSourceException", "getRootCause", "getCausedByException", "getNested" }; /** * <p>The Method object for JDK1.4 getCause.</p> */ private static final Method THROWABLE_CAUSE_METHOD; static { Method getCauseMethod; try { getCauseMethod = Throwable.class.getMethod("getCause", null); } catch (Exception e) { getCauseMethod = null; } THROWABLE_CAUSE_METHOD = getCauseMethod; } /** * <p>Public constructor allows an instance of <code>ExceptionUtils</code> * to be created, although that is not normally necessary.</p> */ public ExceptionUtils() { } /** * <p>Adds to the list of method names used in the search for <code>Throwable</code> * objects.</p> * * @param methodName the methodName to add to the list, <code>null</code> * and empty strings are ignored */ public static void addCauseMethodName(String methodName) { if (StringUtils.isNotEmpty(methodName)) { List list = new ArrayList(Arrays.asList(CAUSE_METHOD_NAMES)); list.add(methodName); CAUSE_METHOD_NAMES = (String[]) list.toArray(new String[list.size()]); } } /** * <p>Introspects the <code>Throwable</code> to obtain the cause.</p> * * <p>The method searches for methods with specific names that return a * <code>Throwable</code> object. This will pick up most wrapping exceptions, * including those from JDK 1.4, and * {@link org.apache.commons.lang.exception.NestableException NestableException}. * The method names can be added to using {@link #addCauseMethodName(String)}.</p> * * <p>The default list searched for are:</p> * <ul> * <li><code>getCause()</code></li> * <li><code>getNextException()</code></li> * <li><code>getTargetException()</code></li> * <li><code>getException()</code></li> * <li><code>getSourceException()</code></li> * <li><code>getRootCause()</code></li> * <li><code>getCausedByException()</code></li> * <li><code>getNested()</code></li> * </ul> * * <p>In the absence of any such method, the object is inspected for a * <code>detail</code> field assignable to a <code>Throwable</code>.</p> * * <p>If none of the above is found, returns <code>null</code>.</p> * * @param throwable the throwable to introspect for a cause, may be null * @return the cause of the <code>Throwable</code>, * <code>null</code> if none found or null throwable input */ public static Throwable getCause(Throwable throwable) { return getCause(throwable, CAUSE_METHOD_NAMES); } /** * <p>Introspects the <code>Throwable</code> to obtain the cause.</p> * * <ol> * <li>Try known exception types.</p> * <li>Try the supplied array of method names.</p> * <li>Try the field 'detail'.</p> * </ol> * * <p>A <code>null</code> set of method names means use the default set. * A <code>null</code> in the set of method names will be ignored.</p> * * @param throwable the throwable to introspect for a cause, may be null * @param methodNames the method names, null treated as default set * @return the cause of the <code>Throwable</code>, * <code>null</code> if none found or null throwable input */ public static Throwable getCause(Throwable throwable, String[] methodNames) { if (throwable == null) { return null; } Throwable cause = getCauseUsingWellKnownTypes(throwable); if (cause == null) { if (methodNames == null) { methodNames = CAUSE_METHOD_NAMES; } for (int i = 0; i < methodNames.length; i++) { String methodName = methodNames[i]; if (methodName != null) { cause = getCauseUsingMethodName(throwable, methodName); if (cause != null) { break; } } } if (cause == null) { cause = getCauseUsingFieldName(throwable, "detail"); } } return cause; } /** * <p>Introspects the <code>Throwable</code> to obtain the root cause.</p> * * <p>This method walks through the exception chain to the last element, * "root" of the tree, using {@link #getCause(Throwable)}, and * returns that exception.</p> * * @param throwable the throwable to get the root cause for, may be null * @return the root cause of the <code>Throwable</code>, * <code>null</code> if none found or null throwable input */ public static Throwable getRootCause(Throwable throwable) { Throwable cause = getCause(throwable); if (cause != null) { throwable = cause; while ((throwable = getCause(throwable)) != null) { cause = throwable; } } return cause; } /** * <p>Finds a <code>Throwable</code> for known types.</p> * * <p>Uses <code>instanceof</code> checks to examine the exception, * looking for well known types which could contain chained or * wrapped exceptions.</p> * * @param throwable the exception to examine * @return the wrapped exception, or <code>null</code> if not found */ private static Throwable getCauseUsingWellKnownTypes(Throwable throwable) { if (throwable instanceof Nestable) { return ((Nestable) throwable).getCause(); } else if (throwable instanceof SQLException) { return ((SQLException) throwable).getNextException(); } else if (throwable instanceof InvocationTargetException) { return ((InvocationTargetException) throwable).getTargetException(); } else { return null; } } /** * <p>Finds a <code>Throwable</code> by method name.</p> * * @param throwable the exception to examine * @param methodName the name of the method to find and invoke * @return the wrapped exception, or <code>null</code> if not found */ private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) { Method method = null; try { method = throwable.getClass().getMethod(methodName, null); } catch (NoSuchMethodException ignored) { } catch (SecurityException ignored) { } if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { try { return (Throwable) method.invoke(throwable, ArrayUtils.EMPTY_OBJECT_ARRAY); } catch (IllegalAccessException ignored) { } catch (IllegalArgumentException ignored) { } catch (InvocationTargetException ignored) { } } return null; } /** * <p>Finds a <code>Throwable</code> by field name.</p> * * @param throwable the exception to examine * @param fieldName the name of the attribute to examine * @return the wrapped exception, or <code>null</code> if not found */ private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) { Field field = null; try { field = throwable.getClass().getField(fieldName); } catch (NoSuchFieldException ignored) { } catch (SecurityException ignored) { } if (field != null && Throwable.class.isAssignableFrom(field.getType())) { try { return (Throwable) field.get(throwable); } catch (IllegalAccessException ignored) { } catch (IllegalArgumentException ignored) { } } return null; } /** * <p>Checks if the Throwable class has a <code>getCause</code> method.</p> * * <p>This is true for JDK 1.4 and above.</p> * * @return true if Throwable is nestable */ public static boolean isThrowableNested() { return (THROWABLE_CAUSE_METHOD != null); } /** * <p>Checks whether this <code>Throwable</code> class can store a cause.</p> * * <p>This method does <b>not</b> check whether it actually does store a cause.<p> * * @param throwable the <code>Throwable</code> to examine, may be null * @return boolean <code>true</code> if nested otherwise <code>false</code> */ public static boolean isNestedThrowable(Throwable throwable) { if (throwable == null) { return false; } if (throwable instanceof Nestable) { return true; } else if (throwable instanceof SQLException) { return true; } else if (throwable instanceof InvocationTargetException) { return true; } else if (isThrowableNested()) { return true; } Class cls = throwable.getClass(); for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) { try { Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], null); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { return true; } } catch (NoSuchMethodException ignored) { } catch (SecurityException ignored) { } } try { Field field = cls.getField("detail"); if (field != null) { return true; } } catch (NoSuchFieldException ignored) { } catch (SecurityException ignored) { } return false; } /** * <p>Counts the number of <code>Throwable</code> objects in the * exception chain.</p> * * <p>A throwable without cause will return <code>1</code>. * A throwable with one cause will return <code>2</code> and so on. * A <code>null</code> throwable will return <code>0</code>.</p> * * @param throwable the throwable to inspect, may be null * @return the count of throwables, zero if null input */ public static int getThrowableCount(Throwable throwable) { int count = 0; while (throwable != null) { count++; throwable = ExceptionUtils.getCause(throwable); } return count; } /** * <p>Returns the list of <code>Throwable</code> objects in the * exception chain.</p> * * <p>A throwable without cause will return an array containing * one element - the input throwable. * A throwable with one cause will return an array containing * two elements. - the input throwable and the cause throwable. * A <code>null</code> throwable will return an array size zero.</p> * * @param throwable the throwable to inspect, may be null * @return the array of throwables, never null */ public static Throwable[] getThrowables(Throwable throwable) { List list = new ArrayList(); while (throwable != null) { list.add(throwable); throwable = ExceptionUtils.getCause(throwable); } return (Throwable[]) list.toArray(new Throwable[list.size()]); } /** * <p>Returns the (zero based) index of the first <code>Throwable</code> * that matches the specified type in the exception chain.</p> * * <p>A <code>null</code> throwable returns <code>-1</code>. * A <code>null</code> type returns <code>-1</code>. * No match in the chain returns <code>-1</code>.</p> * * @param throwable the throwable to inspect, may be null * @param type the type to search for * @return the index into the throwable chain, -1 if no match or null input */ public static int indexOfThrowable(Throwable throwable, Class type) { return indexOfThrowable(throwable, type, 0); } /** * <p>Returns the (zero based) index of the first <code>Throwable</code> * that matches the specified type in the exception chain from * a specified index.</p> * * <p>A <code>null</code> throwable returns <code>-1</code>. * A <code>null</code> type returns <code>-1</code>. * No match in the chain returns <code>-1</code>. * A negative start index is treated as zero. * A start index greater than the number of throwables returns <code>-1</code>.</p> * * @param throwable the throwable to inspect, may be null * @param type the type to search for * @param fromIndex the (zero based) index of the starting position, * negative treated as zero, larger than chain size returns -1 * @return the index into the throwable chain, -1 if no match or null input */ public static int indexOfThrowable(Throwable throwable, Class type, int fromIndex) { if (throwable == null) { return -1; } if (fromIndex < 0) { fromIndex = 0; } Throwable[] throwables = ExceptionUtils.getThrowables(throwable); if (fromIndex >= throwables.length) { return -1; } for (int i = fromIndex; i < throwables.length; i++) { if (throwables[i].getClass().equals(type)) { return i; } } return -1; } /** * <p>Prints a compact stack trace for the root cause of a throwable * to <code>System.err</code>.</p> * * <p>The compact stack trace starts with the root cause and prints * stack frames up to the place where it was caught and wrapped. * Then it prints the wrapped exception and continues with stack frames * until the wrapper exception is caught and wrapped again, etc.</p> * * <p>The method is equivalent to <code>printStackTrace</code> for throwables * that don't have nested causes.</p> * * @param throwable the throwable to output */ public static void printRootCauseStackTrace(Throwable throwable) { printRootCauseStackTrace(throwable, System.err); } public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) { if (throwable == null) { return; } if (stream == null) { throw new NullArgumentException("PrintStream"); } String trace[] = getRootCauseStackTrace(throwable); for (int i = 0; i < trace.length; i++) { stream.println(trace[i]); } stream.flush(); } public static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer) { if (throwable == null) { return; } if (writer == null) { throw new NullArgumentException("PrintWriter"); } String trace[] = getRootCauseStackTrace(throwable); for (int i = 0; i < trace.length; i++) { writer.println(trace[i]); } writer.flush(); } /** * <p>Creates a compact stack trace for the root cause of the supplied * <code>Throwable</code>.</p> * * @param throwable the throwable to examine, may be null * @return an array of stack trace frames, never null */ public static String[] getRootCauseStackTrace(Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } Throwable throwables[] = getThrowables(throwable); int count = throwables.length; ArrayList frames = new ArrayList(); List nextTrace = getStackFrameList(throwables[count - 1]); for (int i = count; --i >= 0;) { List trace = nextTrace; if (i != 0) { nextTrace = getStackFrameList(throwables[i - 1]); removeCommonFrames(trace, nextTrace); } if (i == count - 1) { frames.add(throwables[i].toString()); } else { frames.add(WRAPPED_MARKER + throwables[i].toString()); } for (int j = 0; j < trace.size(); j++) { frames.add(trace.get(j)); } } return (String[]) frames.toArray(new String[0]); } public static void removeCommonFrames(List causeFrames, List wrapperFrames) { if (causeFrames == null || wrapperFrames == null) { throw new NullArgumentException("List"); } int causeFrameIndex = causeFrames.size() - 1; int wrapperFrameIndex = wrapperFrames.size() - 1; while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) { // Remove the frame from the cause trace if it is the same // as in the wrapper trace String causeFrame = (String) causeFrames.get(causeFrameIndex); String wrapperFrame = (String) wrapperFrames.get(wrapperFrameIndex); if (causeFrame.equals(wrapperFrame)) { causeFrames.remove(causeFrameIndex); } causeFrameIndex wrapperFrameIndex } } /** * <p>Gets the stack trace from a Throwable as a String.</p> * * @param throwable the <code>Throwable</code> to be examined * @return the stack trace as generated by the exception's * <code>printStackTrace(PrintWriter)</code> method */ public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.getBuffer().toString(); } /** * <p>A way to get the entire nested stack-trace of an throwable.</p> * * @param throwable the <code>Throwable</code> to be examined * @return the nested stack trace, with the root cause first */ public static String getFullStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); Throwable[] ts = getThrowables(throwable); for (int i = 0; i < ts.length; i++) { ts[i].printStackTrace(pw); if (isNestedThrowable(ts[i])) { break; } } return sw.getBuffer().toString(); } /** * <p>Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of * stack frames.</p> * * @param throwable the <code>Throwable</code> to exaamine, may be null * @return an array of strings describing each stack frame, never null */ public static String[] getStackFrames(Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } return getStackFrames(getStackTrace(throwable)); } /** * <p>Functionality shared between the * <code>getStackFrames(Throwable)</code> methods of this and the * {@link org.apache.commons.lang.exception.NestableDelegate} * classes.</p> */ static String[] getStackFrames(String stackTrace) { String linebreak = SystemUtils.LINE_SEPARATOR; StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new LinkedList(); while (frames.hasMoreTokens()) { list.add(frames.nextToken()); } return (String[]) list.toArray(new String[list.size()]); } /** * <p>Produces a <code>List</code> of stack frames - the message * is not included.</p> * * <p>This works in most cases - it will only fail if the exception * message contains a line that starts with: * <code>&quot;&nbsp;&nbsp;&nbsp;at&quot;.</code></p> * * @param t is any throwable * @return List of stack frames */ static List getStackFrameList(Throwable t) { String stackTrace = getStackTrace(t); String linebreak = SystemUtils.LINE_SEPARATOR; StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new LinkedList(); boolean traceStarted = false; while (frames.hasMoreTokens()) { String token = frames.nextToken(); // Determine if the line starts with <whitespace>at int at = token.indexOf("at"); if (at != -1 && token.substring(0, at).trim().length() == 0) { traceStarted = true; list.add(token); } else if (traceStarted) { break; } } return list; } }
package org.notificationengine.mail; import java.util.Properties; import org.junit.Before; import org.junit.Test; import org.notificationengine.mail.Mailer; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import static org.junit.Assert.assertTrue; public class TestMailer { private Mailer mailer; @Before public void init() { SimpleMailMessage templateMessage = new SimpleMailMessage(); templateMessage.setFrom("mduclos@sqli.com"); templateMessage.setSubject("Notification Engine Test Mail"); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername("mduclos@sqli.com"); mailSender.setPassword("*******"); Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.timeout", "8500"); mailSender.setJavaMailProperties(properties); this.mailer = new Mailer(); this.mailer.setMailSender(mailSender); this.mailer.setTemplateMessage(templateMessage); } @Test public void testSendMail() { assertTrue(this.mailer.sendMail("mduclos@sqli.com", "Default Test Mail Content.")); } @Test public void testSendMailWithSubject() { assertTrue(this.mailer.sendMail("mduclos@sqli.com", "Mail with a different subject", "NotificationEngine Test with custom subject")); } @Test public void testSendMailWithSubjectAndFromField() { // TODO : this test is not failing but "from" field is the admin one. assertTrue(this.mailer.sendMail("mduclos@sqli.com", "Mail with a different subject and from field", "Notification Engine - Custom subject and from fields", "notification@engine.com")); } }
package annis.gui.exporter; import annis.CommonHelper; import annis.libgui.Helper; import annis.model.AnnisConstants; import annis.model.Annotation; import annis.model.RelannisNodeFeature; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.Map; import annis.service.objects.SubgraphFilter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import net.xeoh.plugins.base.annotations.PluginImplementation; import org.apache.commons.lang3.StringUtils; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.core.SAnnotation; import org.corpus_tools.salt.core.SNode; /** * @author barteld */ @PluginImplementation public class CSVMultiTokExporter extends SaltBasedExporter { @Override public String getHelpMessage() { return "The CSV MultiTok Exporter exports only the " + "values of the elements searched for by the user, ignoring the context " + "around search results. The values for all annotations of each of the " + "found nodes is given in a comma-separated table (CSV). <br/><br/>" + "This exporter will take more time than the normal CSV Exporter " + "but it is able to export the underlying text for spans " + "if the corpus contains multiple tokenizations. <br/><br/>" + "Parameters: <br/>" + "<em>metakeys</em> - comma seperated list of all meta data to include in the result (e.g. " + "<code>metakeys=title,documentname</code>)"; } @Override public SubgraphFilter getSubgraphFilter() { return SubgraphFilter.all; } @Override public String getFileEnding() { return "csv"; } private Set<String> metakeys; @Override public void convertText(SDocumentGraph graph, List<String> annoKeys, Map<String, String> args, int matchNumber, Writer out) throws IOException { // first match - collect some data if (matchNumber == -1) { // get list of metakeys to export metakeys = new HashSet<>(); if (args.containsKey("metakeys")) { for (String meta: args.get("metakeys").split(",")) metakeys.add(meta); } } // first match - output header // TODO should iterate over all matches to compute the header if (matchNumber == -1) { List<String> headerLine = new ArrayList<>(); int i = 1; for(String matchid: graph .getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_MATCHEDIDS) .getValue_STEXT().split(",")) { headerLine.add(String.valueOf(i) + "_id"); headerLine.add(String.valueOf(i) + "_span"); List<SAnnotation> annots = new ArrayList<>(graph.getNode(matchid).getAnnotations()); java.util.Collections.sort(annots, new Comparator<SAnnotation>() { @Override public int compare(SAnnotation a, SAnnotation b) { return a.getName().compareTo(b.getName()); } }); for (SAnnotation annot: annots) { headerLine.add(String.valueOf(i) + "_anno_" + annot.getNamespace() + "::" + annot.getName()); } i++; } for (String key: metakeys) { headerLine.add("meta_" + key); } out.append(StringUtils.join(headerLine, "\t")); out.append("\n"); } // output nodes in the order of the matches List<String> contentLine = new ArrayList<>(); for(String matchid: graph .getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_MATCHEDIDS) .getValue_STEXT().split(",")) { SNode node = graph.getNode(matchid); // export id RelannisNodeFeature feats = RelannisNodeFeature.extract(node); contentLine.add(String.valueOf(feats.getInternalID())); // export spanned text String span = graph.getText(node); if (span != null) contentLine.add(graph.getText(node)); else contentLine.add(""); // export annotations List<SAnnotation> annots = new ArrayList<>(node.getAnnotations()); java.util.Collections.sort(annots, new Comparator<SAnnotation>() { @Override public int compare(SAnnotation a, SAnnotation b) { return a.getName().compareTo(b.getName()); } }); for (SAnnotation annot: annots) { contentLine.add(annot.getValue_STEXT()); } } // export Metadata // TODO cache the metadata if(!metakeys.isEmpty()) { // TODO is this the best way to get the corpus name? String corpus_name = CommonHelper.getCorpusPath(java.net.URI.create(graph.getDocument().getId())).get(0); List<Annotation> asList = Helper.getMetaData(corpus_name, graph.getDocument().getName()); for(Annotation anno : asList) { if (metakeys.contains(anno.getName())) contentLine.add(anno.getValue()); } } out.append(StringUtils.join(contentLine, "\t")); out.append("\n"); } }
package seedu.address.commons.core; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.todo.commons.core.Version; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class VersionTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void versionParsing_acceptableVersionString_parsedVersionCorrectly() { verifyVersionParsedCorrectly("V0.0.0ea", 0, 0, 0, true); verifyVersionParsedCorrectly("V3.10.2", 3, 10, 2, false); verifyVersionParsedCorrectly("V100.100.100ea", 100, 100, 100, true); } @Test public void versionParsing_wrongVersionString_throwIllegalArgumentException() { thrown.expect(IllegalArgumentException.class); Version.fromString("This is not a version string"); } @Test public void versionConstructor_correctParameter_valueAsExpected() { Version version = new Version(19, 10, 20, true); assertEquals(19, version.getMajor()); assertEquals(10, version.getMinor()); assertEquals(20, version.getPatch()); assertEquals(true, version.isEarlyAccess()); } @Test public void versionToString_validVersion_correctStringRepresentation() { // boundary at 0 Version version = new Version(0, 0, 0, true); assertEquals("V0.0.0ea", version.toString()); // normal values version = new Version(4, 10, 5, false); assertEquals("V4.10.5", version.toString()); // big numbers version = new Version(100, 100, 100, true); assertEquals("V100.100.100ea", version.toString()); } @Test public void versionComparable_validVersion_compareToIsCorrect() { Version one; Version another; // Tests equality one = new Version(0, 0, 0, true); another = new Version(0, 0, 0, true); assertTrue(one.compareTo(another) == 0); one = new Version(11, 12, 13, false); another = new Version(11, 12, 13, false); assertTrue(one.compareTo(another) == 0); // Tests different patch one = new Version(0, 0, 5, false); another = new Version(0, 0, 0, false); assertTrue(one.compareTo(another) > 0); // Tests different minor one = new Version(0, 0, 0, false); another = new Version(0, 5, 0, false); assertTrue(one.compareTo(another) < 0); // Tests different major one = new Version(10, 0, 0, true); another = new Version(0, 0, 0, true); assertTrue(one.compareTo(another) > 0); // Tests high major vs low minor one = new Version(10, 0, 0, true); another = new Version(0, 1, 0, true); assertTrue(one.compareTo(another) > 0); // Tests high patch vs low minor one = new Version(0, 0, 10, false); another = new Version(0, 1, 0, false); assertTrue(one.compareTo(another) < 0); // Tests same major minor different patch one = new Version(2, 15, 0, false); another = new Version(2, 15, 5, false); assertTrue(one.compareTo(another) < 0); // Tests early access vs not early access on same version number one = new Version(2, 15, 0, true); another = new Version(2, 15, 0, false); assertTrue(one.compareTo(another) < 0); // Tests early access lower version vs not early access higher version compare by version number first one = new Version(2, 15, 0, true); another = new Version(2, 15, 5, false); assertTrue(one.compareTo(another) < 0); // Tests early access higher version vs not early access lower version compare by version number first one = new Version(2, 15, 0, false); another = new Version(2, 15, 5, true); assertTrue(one.compareTo(another) < 0); } @Test public void versionComparable_validVersion_hashCodeIsCorrect() { Version version = new Version(100, 100, 100, true); assertEquals(100100100, version.hashCode()); version = new Version(10, 10, 10, false); assertEquals(1010010010, version.hashCode()); } @Test public void versionComparable_validVersion_equalIsCorrect() { Version one; Version another; one = new Version(0, 0, 0, false); another = new Version(0, 0, 0, false); assertTrue(one.equals(another)); one = new Version(100, 191, 275, true); another = new Version(100, 191, 275, true); assertTrue(one.equals(another)); } private void verifyVersionParsedCorrectly(String versionString, int major, int minor, int patch, boolean isEarlyAccess) { assertEquals(new Version(major, minor, patch, isEarlyAccess), Version.fromString(versionString)); } }
package com.bourke.glimmr.fragments; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockDialogFragment; import com.bourke.glimmr.activities.MainActivity; import com.bourke.glimmr.common.Constants; import com.bourke.glimmr.common.TextUtils; import com.bourke.glimmr.event.Events.IAccessTokenReadyListener; import com.bourke.glimmr.event.Events.IRequestTokenReadyListener; import com.bourke.glimmr.fragments.base.BaseFragment; import com.bourke.glimmr.R; import com.bourke.glimmr.tasks.GetRequestToken; import com.googlecode.flickrjandroid.oauth.OAuth; import com.googlecode.flickrjandroid.oauth.OAuthToken; import com.googlecode.flickrjandroid.people.User; public final class LoginFragment extends BaseFragment implements IRequestTokenReadyListener, IAccessTokenReadyListener { private static final String TAG = "Glimmr/LoginFragment"; private IOnNotNowClicked mNotNowListener; public static LoginFragment newInstance() { if (Constants.DEBUG) Log.d(TAG, "newInstance"); return new LoginFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Constants.DEBUG) Log.d(TAG, "onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (Constants.DEBUG) Log.d(getLogTag(), "onCreateView"); mLayout = (RelativeLayout) inflater.inflate( R.layout.login_fragment, container, false); setupTextViews(); return mLayout; } @Override public void onRequestTokenReady(String authUri, Exception e) { if (e != null) { /* Usually down to a bad clock / timezone on device */ if (e.getMessage().equals("No authentication challenges found") || e.getMessage().equals("Received authentication " + "challenge is null")) { FragmentManager fm = mActivity.getSupportFragmentManager(); LoginErrorTipDialog d = new LoginErrorTipDialog(); d.show(fm, "LoginErrorTipDialog"); } } else if (authUri != null && !authUri.startsWith("error")) { mActivity.startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse(authUri))); } } @Override public void onAccessTokenReady(OAuth accessToken) { persistAccessToken(accessToken); if (Constants.DEBUG) { Log.d(TAG, "Got token, saved to disk, good to start MainActivity"); } Toast.makeText(mActivity, getString(R.string.logged_in), Toast.LENGTH_SHORT).show(); mActivity.startActivity(new Intent(mActivity, MainActivity.class)); /* Prevent the user pressing back to get to the unauthed activity */ mActivity.finish(); } private void persistAccessToken(OAuth oauth) { SharedPreferences sp = mActivity.getSharedPreferences( Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); OAuthToken token = oauth.getToken(); User user = oauth.getUser(); editor.putString(Constants.KEY_OAUTH_TOKEN, token.getOauthToken()); editor.putString(Constants.KEY_TOKEN_SECRET, token .getOauthTokenSecret()); editor.putString(Constants.KEY_ACCOUNT_USER_NAME, user.getUsername()); editor.putString(Constants.KEY_ACCOUNT_USER_ID, user.getId()); editor.commit(); } private void setupTextViews() { /* Set fonts */ mTextUtils.setFont((TextView) mLayout.findViewById(R.id.textWelcome), TextUtils.FONT_ROBOTOTHIN); mTextUtils.setFont((TextView) mLayout.findViewById(R.id.textTo), TextUtils.FONT_ROBOTOTHIN); mTextUtils.setFont((TextView) mLayout.findViewById(R.id.textGlimmr), TextUtils.FONT_ROBOTOREGULAR); mTextUtils.setFont((TextView) mLayout.findViewById(R.id.textNotNow), TextUtils.FONT_ROBOTOTHIN); Button buttonLogin = (Button) mLayout.findViewById(R.id.btnLogin); buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new GetRequestToken(LoginFragment.this, mActivity).execute(); } }); final TextView tvNotNow = (TextView) mLayout.findViewById( R.id.textNotNow); mTextUtils.colorTextViewSpan(tvNotNow, tvNotNow.getText().toString(), mActivity.getString(R.string.browse), mActivity.getResources().getColor( R.color.abs__holo_blue_light)); tvNotNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mNotNowListener.onNotNowClicked(); } }); tvNotNow.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mTextUtils.colorTextViewSpan(tvNotNow, tvNotNow.getText().toString(), mActivity.getString(R.string.browse), mActivity.getResources().getColor( R.color.flickr_pink)); } else { mTextUtils.colorTextViewSpan(tvNotNow, tvNotNow.getText().toString(), mActivity.getString(R.string.browse), mActivity.getResources().getColor( R.color.abs__holo_blue_light)); } return false; } }); } @Override protected String getLogTag() { return TAG; } public void setNotNowListener(IOnNotNowClicked listener) { mNotNowListener = listener; } public interface IOnNotNowClicked { public void onNotNowClicked(); } class LoginErrorTipDialog extends SherlockDialogFragment { public LoginErrorTipDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setTitle(R.string.login_problem) .setMessage(R.string.timezone_message) .setIcon(R.drawable.alerts_and_states_error_dark) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dismiss(); } }); return builder.create(); } } }
package ikube.action; import ikube.IntegrationTest; import ikube.cluster.IClusterManager; import ikube.database.IDataBase; import ikube.model.Action; import ikube.model.Url; import ikube.toolkit.ObjectToolkit; import mockit.Deencapsulation; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Michael Couck * @version 01.00 * @since 21-11-2010 */ @SuppressWarnings("SpringJavaAutowiringInspection") public class ResetIntegration extends IntegrationTest { private Reset reset; @Autowired private IDataBase dataBase; private IClusterManager clusterManager; @Before public void before() { reset = new Reset(); clusterManager = mock(IClusterManager.class); Deencapsulation.setField(reset, dataBase); Deencapsulation.setField(reset, clusterManager); } @After public void after() { delete(dataBase, Url.class); } @Test public void execute() throws Exception { Action action = mock(Action.class); when(clusterManager.startWorking(anyString(), anyString(), anyString())).thenReturn(action); delete(dataBase, Url.class); List<Url> urls = dataBase.find(Url.class, 0, Integer.MAX_VALUE); assertEquals("There should be no urls in the database : ", 0, urls.size()); Url url = ObjectToolkit.populateFields(new Url(), Boolean.TRUE, 3, "id"); url.setName("indexContext"); dataBase.persist(url); urls = dataBase.find(Url.class, 0, Integer.MAX_VALUE); assertEquals("There should be one url in the database : ", 1, urls.size()); boolean result = reset.execute(monitorService.getIndexContext("indexContext")); assertTrue(result); urls = dataBase.find(Url.class, 0, Integer.MAX_VALUE); assertEquals("There should be no urls in the database : ", 0, urls.size()); } }
package com.v5analytics.webster; import com.v5analytics.webster.parameterProviders.ParameterProviderFactory; import com.v5analytics.webster.resultWriters.DefaultResultWriterFactory; import com.v5analytics.webster.resultWriters.ResultWriterFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class App { private static final Logger ACCESS_LOGGER = LoggerFactory.getLogger(App.class.getName() + ".ACCESS_LOG"); public static final String WEBSTER_APP_ATTRIBUTE_NAME = "websterApp"; private static final ResultWriterFactory DEFAULT_RESULT_WRITER_FACTORY = new DefaultResultWriterFactory(); private Router router; private Map<String, Object> config; public App(final ServletContext servletContext) { router = new Router(servletContext); config = new HashMap<>(); } public void get(String path, Handler... handlers) { router.addRoute(Route.Method.GET, path, wrapNonRequestResponseHandlers(handlers)); } public void get(String path, Class<? extends Handler>... classes) { try { Handler[] handlers = instantiateHandlers(classes); get(path, handlers); } catch (Exception e) { throw new WebsterException("Could not execute get method on path " + path, e); } } public void post(String path, Handler... handlers) { router.addRoute(Route.Method.POST, path, wrapNonRequestResponseHandlers(handlers)); } public void post(String path, Class<? extends Handler>... classes) { try { Handler[] handlers = instantiateHandlers(classes); post(path, handlers); } catch (Exception e) { throw new WebsterException("Could not execute post method on path " + path, e); } } public void put(String path, Handler... handlers) { router.addRoute(Route.Method.PUT, path, wrapNonRequestResponseHandlers(handlers)); } public void put(String path, Class<? extends Handler>... classes) { try { Handler[] handlers = instantiateHandlers(classes); put(path, handlers); } catch (Exception e) { throw new WebsterException("Could not execute put method on path " + path, e); } } public void delete(String path, Handler... handlers) { router.addRoute(Route.Method.DELETE, path, wrapNonRequestResponseHandlers(handlers)); } public void delete(String path, Class<? extends Handler>... classes) { try { Handler[] handlers = instantiateHandlers(classes); delete(path, handlers); } catch (Exception e) { throw new WebsterException("Could not execute delete method on path " + path, e); } } public void onException(Class<? extends Exception> exceptionClass, Handler... handlers) { router.addExceptionHandler(exceptionClass, wrapNonRequestResponseHandlers(handlers)); } public void onException(Class<? extends Exception> exceptionClass, Class<? extends Handler>... classes) { try { Handler[] handlers = instantiateHandlers(classes); onException(exceptionClass, handlers); } catch (Exception e) { throw new WebsterException(e); } } public Object get(String name) { return config.get(name); } public void set(String name, Object value) { config.put(name, value); } public void enable(String name) { config.put(name, true); } public void disable(String name) { config.put(name, false); } public boolean isEnabled(String name) { Object value = config.get(name); if (value != null && value instanceof Boolean) { return (Boolean) value; } return false; } public boolean isDisabled(String name) { return !isEnabled(name); } public Router getRouter() { return router; } public static App getApp(HttpServletRequest request) { return (App) request.getAttribute(WEBSTER_APP_ATTRIBUTE_NAME); } public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception { long startTime = System.currentTimeMillis(); try { request.setAttribute(WEBSTER_APP_ATTRIBUTE_NAME, this); router.route(request, response); } finally { if (ACCESS_LOGGER.isDebugEnabled()) { long endTime = System.currentTimeMillis(); long timeMs = endTime - startTime; ACCESS_LOGGER.debug(request.getMethod() + " " + request.getRequestURI() + " " + timeMs + "ms"); } } } protected Handler[] instantiateHandlers(Class<? extends Handler>[] handlerClasses) throws Exception { Handler[] handlers = new Handler[handlerClasses.length]; for (int i = 0; i < handlerClasses.length; i++) { handlers[i] = handlerClasses[i].newInstance(); } return handlers; } private RequestResponseHandler[] wrapNonRequestResponseHandlers(Handler[] handlers) { RequestResponseHandler[] results = new RequestResponseHandler[handlers.length]; for (int i = 0; i < handlers.length; i++) { if (handlers[i] instanceof RequestResponseHandler) { results[i] = (RequestResponseHandler) handlers[i]; } else if (handlers[i] instanceof ParameterizedHandler) { results[i] = new RequestResponseHandlerParameterizedHandlerWrapper(this, (ParameterizedHandler) handlers[i]); } else { throw new WebsterException("Unhandled handler type: " + handlers[i].getClass().getName()); } } return results; } public static <T> void registeredParameterProviderFactory(ParameterProviderFactory<T> parameterProviderFactory) { RequestResponseHandlerParameterizedHandlerWrapper.registeredParameterProviderFactory(parameterProviderFactory); } public static <T> void registerParameterValueConverter(Class<T> clazz, DefaultParameterValueConverter.Converter<T> converter) { DefaultParameterValueConverter.registerValueConverter(clazz, converter); } ResultWriterFactory internalGetResultWriterFactory(Method handleMethod) { return getResultWriterFactory(handleMethod); } protected ResultWriterFactory getResultWriterFactory(Method handleMethod) { return DEFAULT_RESULT_WRITER_FACTORY; } }
package org.sana.android.content; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import org.sana.net.Response; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * @author Sana Development * */ public final class ModelEntity { public static class NamedContentValues{ public final Uri uri; public final ContentValues values; public NamedContentValues(Uri uri, ContentValues values){ this.uri = uri; this.values = values; } } ContentValues values; Uri uri; public ModelEntity(Uri uri, ContentValues values){ this.uri = uri; this.values = new ContentValues(values); } public ContentValues getEntityValues(){ return values; } public Uri getUri(){ return uri; } public static Map<String, String> toMap(Bundle form){ Map<String, String> data = new HashMap<String, String>(); // Should have at least one field that need to be updated if(form != null){ Iterator<String> keys = form.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); data.put(key, form.getString(key)); } } return data; } }
package com.carlosefonseca.common.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.location.LocationManager; import android.os.*; import android.provider.Settings; import android.text.InputType; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.*; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.carlosefonseca.common.CFApp; import android.support.annotation.Nullable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; import java.util.regex.Pattern; import static java.lang.Runtime.getRuntime; public final class CodeUtils { // public static final Pattern packageNameRegex = Pattern.compile(".+\\.([^.]+\\.).+"); public static final Pattern packageNameRegex = Pattern.compile("\\."); private static final String TAG = CodeUtils.getTag(CodeUtils.class); public static final String SIDE_T = ""; public static final String LONG_L = ""; private CodeUtils() {} public static void hideKeyboard(View input) { //noinspection ConstantConditions InputMethodManager imm = (InputMethodManager) input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); } public static void recreateActivity(Activity a) { Log.d(TAG, "Recreating Activity."); if (Build.VERSION.SDK_INT >= 11) { a.recreate(); } else { Intent intent = a.getIntent(); a.finish(); a.startActivity(intent); } } public static String getTag(Class clazz) { return packageNameRegex.split(clazz.getName(), 3)[1] + "." + clazz.getSimpleName(); } public static boolean isMainThread() { return Looper.getMainLooper() == Looper.myLooper(); } public static String separator(final String text) {return " " + text + " ";} public static void sleep(int i) { try { Thread.sleep(i); } catch (InterruptedException e) { Log.e(TAG, "" + e.getMessage(), e); } } public static int hashCode(int seed, Object... objects) { if (objects == null) return seed; int hashCode = seed; for (Object element : objects) { hashCode = 31 * hashCode + (element == null ? 0 : element.hashCode()); } return hashCode; } @SuppressLint("SetJavaScriptEnabled") public static void setupWebView(WebView webView) { final Context context = webView.getContext(); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { webSettings.setDatabasePath(context.getFilesDir() + "/databases/"); } webSettings.setAppCacheEnabled(true); webSettings.setUseWideViewPort(true); webSettings.setGeolocationEnabled(true); webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) webSettings.setDisplayZoomControls(false); webView.zoomOut(); webSettings.setGeolocationDatabasePath(context.getFilesDir() + "/databases/"); // Force links and redirects to open in the WebView instead of in a browser webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("http")) { view.loadUrl(url); } else { UrlUtils.tryStartIntentForUrl(context, url); } return true; } }); webView.setWebChromeClient(new WebChromeClient() { @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } }); } static DecimalFormat formatter; static { formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US); DecimalFormatSymbols decimalFormatSymbols = formatter.getDecimalFormatSymbols(); decimalFormatSymbols.setGroupingSeparator(' '); formatter.setDecimalFormatSymbols(decimalFormatSymbols); } public static String getKB(long bytes) { return formatter.format(bytes / 1024); } protected static long getFreeMem() { Runtime r = getRuntime(); long freeMem = r.maxMemory() - r.totalMemory() + r.freeMemory(); long freeMemLess = Math.max(0, freeMem - (2 * 1024 * 1024)); Log.d(TAG, "getFreeMem: Memory usage: %s ( %s / %s ) kB. Reporting only: %s kB", getKB(freeMem), getKB(r.totalMemory() - r.freeMemory()), getKB(r.maxMemory()), getKB(freeMemLess)); return freeMemLess; } public static String getTimespan(long uptimeMillisOnStart) { double secs = (SystemClock.uptimeMillis() - uptimeMillisOnStart) / 1000d; if (secs < 10) { return String.format("%.03fs", secs); } else if (secs < 60) { return String.valueOf((int) secs) + "s"; } else { return "" + (secs / 60) + "m " + (secs % 60) + "s"; } } public interface RunnableWithView<T extends View> { void run(T view); } public static <T extends View> void runOnGlobalLayout(final T view, final RunnableWithView<T> runnable) { try { assert view.getViewTreeObserver() != null; if (view.getViewTreeObserver().isAlive()) { view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") // We check which build version we are using. @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } runnable.run(view); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public static void runOnGlobalLayout(final View view, final Runnable runnable) { try { assert view.getViewTreeObserver() != null; if (view.getViewTreeObserver().isAlive()) { view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") // We check which build version we are using. @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } runnable.run(); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public static void setupNumericEditText(final AlertDialog dialog, final EditText editText, @Nullable final DialogInterface.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(dialog, 0); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final DialogInterface.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(null, 0); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final View.OnClickListener onDone) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (onDone != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. onDone.onClick(editText); return true; // consume. } return false; // pass on to other listeners. } }); } @SuppressLint("InlinedApi") public static void setupNumericEditText(final EditText editText, @Nullable final Runnable runnable) { editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setInputType(InputType.TYPE_CLASS_PHONE | InputType.TYPE_NUMBER_VARIATION_PASSWORD); editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (runnable != null && (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { // the user is done typing. runnable.run(); return true; // consume. } return false; // pass on to other listeners. } }); } public static boolean isGpsOn() { return Settings.Secure.isLocationProviderEnabled(CFApp.getContext().getContentResolver(), LocationManager.GPS_PROVIDER); } /** * Creates a TouchListener that repeats a specified action as long as the view is being pressed. * * @param runnable The code to be repeated. * @param delayMillis The interval between repetitions. * @return A new OnTouchListener setup to handle long press to repeat. */ public static View.OnTouchListener getRepeatActionListener(final Runnable runnable, final int delayMillis) { return getRepeatActionListener(runnable, delayMillis, null); } /** * Creates a TouchListener that repeats a specified action as long as the view is being pressed. * * @param runnable The code to be repeated. * @param delayMillis The interval between repetitions. * @param onUpRunnable Code to run when the button is no longer being pressed. * @return A new OnTouchListener setup to handle long press to repeat. */ public static View.OnTouchListener getRepeatActionListener(final Runnable runnable, final int delayMillis, @Nullable final Runnable onUpRunnable) { final Handler mHandler = new Handler(); final Runnable repeatRunnable = new Runnable() { @Override public void run() { runnable.run(); mHandler.postDelayed(this, delayMillis); } }; return new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { int action = motionEvent.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: mHandler.removeCallbacks(repeatRunnable); runnable.run(); mHandler.postDelayed(repeatRunnable, 200); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mHandler.removeCallbacks(repeatRunnable); if (onUpRunnable != null) onUpRunnable.run(); break; } return false; } }; } /** * Computes the md5 hex hash for the specified string * * @param s The string to hash. * @return The hexadecimal hash. */ public static String md5(final String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { String h = Integer.toHexString(0xFF & aMessageDigest); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { Log.e(TAG, e); } return ""; } private static String versionName; public static String getAppVersionName() { if (versionName == null) { versionName = ""; try { //noinspection ConstantConditions PackageInfo pInfo = CFApp.getContext() .getPackageManager() .getPackageInfo(CFApp.getContext().getPackageName(), 0); versionName = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception", e); } } return versionName; } private static int versionCode = -1; public static int getAppVersionCode() { if (versionCode == -1) { try { //noinspection ConstantConditions PackageInfo pInfo = CFApp.getContext() .getPackageManager() .getPackageInfo(CFApp.getContext().getPackageName(), 0); versionCode = pInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception", e); } } return versionCode; } public static void runOnBackground(final Runnable runnable) { new AsyncTask<Void, Void, Void>() { @Nullable @Override protected Void doInBackground(Void... params) { runnable.run(); return null; } }.execute(); } public static void pauseRunningAppForDebugPurposesDontLeaveThisHangingAround() { if (CFApp.isTestDevice()) { Log.w(TAG, " try { boolean block = true; //noinspection ConstantConditions while (block) { Thread.sleep(1000); } } catch (InterruptedException e) { Log.e(TAG, "" + e.getMessage(), e); } } } public static void toast(final String message) { runOnUIThread(new Runnable() { @Override public void run() { Toast.makeText(CFApp.getContext(), message, Toast.LENGTH_SHORT).show(); } }); } /** * Null-safe equivalent of {@code a.equals(b)}. */ public static boolean equals(@Nullable Object a, @Nullable Object b) { return (a == null) ? (b == null) : a.equals(b); } public static void runOnUIThread(Runnable runnable) { if (isMainThread()) { runnable.run(); } else { new Handler(Looper.getMainLooper()).post(runnable); } } public static void setVisibility(int visibility, View...views) { for (View view : views) { view.setVisibility(visibility); } } }
package org.dellroad.stuff.vaadin; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.util.AbstractContainer; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; /** * Support superclass for read-only {@link Container} implementations where each {@link Item} in the container * is backed by a Java object, and the Java objects are accessed via a query returning an ordered "query list". * The container's {@link Item} ID's are simply the index of the corresponding objects in this list. * * <p> * This class invokes {@link #query} to generate the query list. The query list is then cached, but this class will invoke * {@link #validate validate()} prior to each subsequent use to ensure it is still usable. * If not, {@link #query} is invoked to regenerate it. * * <p> * Note that the query list being invalid is an orthogonal concept from the contents of the list having changed; * however, the latter implies the former (but not vice-versa). Therefore, after any change to the list content, * first {@link #invalidate} and then {@link #fireItemSetChange} should be invoked. On the other hand, the list can * become invalid without the content changing if e.g., the list contains JPA entities and the corresponding * {@link javax.persistence.EntityManager} is closed. * * <p> * The subclass may forcibly invalidate the current query list via {@link #invalidate}, e.g., after change to the * list content. * * @param <T> the type of the Java objects that back each {@link Item} in the container */ @SuppressWarnings("serial") public abstract class AbstractQueryContainer<T> extends AbstractContainer implements Container.Ordered, Container.Indexed, Container.PropertySetChangeNotifier, Container.ItemSetChangeNotifier { private final HashMap<String, PropertyDef<?>> propertyMap = new HashMap<String, PropertyDef<?>>(); private PropertyExtractor<? super T> propertyExtractor; private List<T> currentList; // Constructors protected AbstractQueryContainer(PropertyExtractor<? super T> propertyExtractor) { this.setPropertyExtractor(propertyExtractor); } protected AbstractQueryContainer(PropertyExtractor<? super T> propertyExtractor, Collection<? extends PropertyDef<?>> propertyDefs) { this(propertyExtractor); this.setProperties(propertyDefs); } // Public methods /** * Get the configured {@link PropertyExtractor} for this container. */ public PropertyExtractor<? super T> getPropertyExtractor() { return this.propertyExtractor; } public void setPropertyExtractor(PropertyExtractor<? super T> propertyExtractor) { if (propertyExtractor == null) throw new IllegalArgumentException("null extractor"); this.propertyExtractor = propertyExtractor; } public void setProperties(Collection<? extends PropertyDef<?>> propertyDefs) { if (propertyDefs == null) throw new IllegalArgumentException("null propertyDefs"); this.propertyMap.clear(); for (PropertyDef<?> propertyDef : propertyDefs) { if (this.propertyMap.put(propertyDef.getName(), propertyDef) != null) throw new IllegalArgumentException("duplicate property name `" + propertyDef.getName() + "'"); } this.fireContainerPropertySetChange(); } // Subclass hooks and methods /** * Perform a query to generate the list of Java objects that back this container. */ protected abstract List<T> query(); /** * Determine if the given list can still be used or not. */ protected abstract boolean validate(List<T> list); /** * Invalidate the current query list, if any. */ protected void invalidate() { this.currentList = null; } // Internal methods /** * Get the Java backing object at the given index in the list. * * @return backing object, or null if {@code index} is out of range */ protected T getJavaObject(int index) { List<T> list = this.getList(); if (index < 0 || index >= list.size()) return null; return list.get(index); } /** * Get the query list, validating it and regenerating if necessary. */ protected List<T> getList() { if (this.currentList == null || !this.validate(this.currentList)) this.currentList = this.query(); return this.currentList; } // Container @Override public SimpleItem<T> getItem(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); T obj = this.getJavaObject(index); if (obj == null) return null; return new SimpleItem<T>(obj, this.propertyMap, this.propertyExtractor); } @Override public Collection<Integer> getItemIds() { return new IntList(this.getList().size()); } @Override public Set<String> getContainerPropertyIds() { return Collections.unmodifiableSet(this.propertyMap.keySet()); } @Override public Property getContainerProperty(Object itemId, Object propertyId) { SimpleItem<T> item = this.getItem(itemId); return item != null ? item.getItemProperty(propertyId) : null; } @Override public Class<?> getType(Object propertyId) { PropertyDef<?> propertyDef = this.propertyMap.get(propertyId); return propertyDef != null ? propertyDef.getType() : null; } @Override public int size() { return this.getList().size(); } @Override public boolean containsId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return index >= 0 && index < this.getList().size(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItem(Object itemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItem() { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeItem(Object itemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeContainerProperty(Object propertyId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeAllItems() { throw new UnsupportedOperationException(); } // Container.Indexed /** * @throws UnsupportedOperationException always */ @Override public Object addItemAt(int index) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAt(int index, Object newItemId) { throw new UnsupportedOperationException(); } @Override public Integer getIdByIndex(int index) { return index; } @Override public int indexOfId(Object itemId) { if (!(itemId instanceof Integer)) return -1; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index < 0 || index >= list.size()) return -1; return index; } // Container.Ordered @Override public Integer nextItemId(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index < 0 || index + 1 >= list.size()) return null; return index + 1; } @Override public Integer prevItemId(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index - 1 < 0 || index >= list.size()) return null; return index - 1; } @Override public Integer firstItemId() { return this.getList().isEmpty() ? null : 0; } @Override public Integer lastItemId() { List<T> list = this.getList(); return list.isEmpty() ? null : list.size() - 1; } @Override public boolean isFirstId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return !this.getList().isEmpty() && index == 0; } @Override public boolean isLastId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return index == this.getList().size() - 1; } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAfter(Object previousItemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAfter(Object previousItemId, Object newItemId) { throw new UnsupportedOperationException(); } // Container.PropertySetChangeNotifier @Override public void addListener(Container.PropertySetChangeListener listener) { super.addListener(listener); } @Override public void removeListener(Container.PropertySetChangeListener listener) { super.removeListener(listener); } // Container.ItemSetChangeNotifier @Override public void addListener(Container.ItemSetChangeListener listener) { super.addListener(listener); } @Override public void removeListener(Container.ItemSetChangeListener listener) { super.removeListener(listener); } // IntList private static class IntList extends AbstractList<Integer> { private final int max; public IntList(int max) { if (max < 0) throw new IllegalArgumentException("max < 0"); this.max = max; } @Override public int size() { return this.max; } @Override public Integer get(int index) { if (index < 0 || index >= this.max) throw new IndexOutOfBoundsException(); return index; } } }
package com.vokal.db; import android.content.*; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import java.lang.reflect.Field; import java.util.*; public class DatabaseHelper extends SQLiteOpenHelper { protected static final ArrayList<String> TABLE_NAMES = new ArrayList<String>(); protected static final HashMap<Class, String> TABLE_MAP = new HashMap<Class, String>(); protected static final HashMap<String, Class> CLASS_MAP = new HashMap<String, Class>(); protected static final HashMap<Class, Uri> CONTENT_URI_MAP = new HashMap<Class, Uri>(); private static boolean isOpen; public DatabaseHelper(Context aContext, String aName, int aVersion) { super(aContext, aName, null, aVersion); } /* * registers a table with authority, uses lowercase class name as table name(s) */ @SafeVarargs public static void registerModel(Context aContext, Class<?>... aModelClass) { if (aModelClass != null) { for (Class<?> clazz : aModelClass) { registerModel(aContext, clazz, clazz.getSimpleName().toLowerCase(Locale.getDefault())); } } } /* * registers a table with provider with authority using specified table name */ public static void registerModel(Context aContext, Class<?> aModelClass, String aTableName) { if (!TABLE_NAMES.contains(aTableName)) { int matcher_index = TABLE_NAMES.size(); TABLE_NAMES.add(aTableName); TABLE_MAP.put(aModelClass, aTableName); CLASS_MAP.put(aTableName, aModelClass); String authority = SimpleContentProvider.getContentAuthority(aContext); Uri contentUri = Uri.parse(String.format("content://%s/%s", authority, aTableName)); CONTENT_URI_MAP.put(aModelClass, contentUri); SimpleContentProvider.URI_MATCHER.addURI(authority, aTableName, matcher_index); SimpleContentProvider.URI_ID_MATCHER.addURI(authority, aTableName, matcher_index); } } public static Uri getContentUri(Class<?> aTableName) { return CONTENT_URI_MAP.get(aTableName); } public static Uri getJoinedContentUri(Class<?> aTable1, String aColumn1, Class<?> aTable2, String aColumn2) { return getJoinedContentUri(aTable1, aColumn1, aTable2, aColumn2, null); } public static Uri getJoinedContentUri(Class<?> aTable1, String aColumn1, Class<?> aTable2, String aColumn2, Map<String, String> aProjMap) { String auth = SimpleContentProvider.sContentAuthority; if (auth == null) throw new IllegalStateException("Register tables with registerModel(..) methods first."); String tblName1 = TABLE_MAP.get(aTable1); if (tblName1 == null) throw new IllegalStateException("call registerModel() first for table " + aTable1); String tblName2 = TABLE_MAP.get(aTable2); if (tblName2 == null) throw new IllegalStateException("call registerModel() first for table " + aTable2); String path = tblName1 + "_" + tblName2; Uri contentUri = Uri.parse(String.format("content://%s/%s", auth, path)); int exists = SimpleContentProvider.URI_JOIN_MATCHER.match(contentUri); if (exists != UriMatcher.NO_MATCH) { return contentUri; } String table = String.format("%s LEFT OUTER JOIN %s ON (%s.%s = %s.%s)", tblName1, tblName2, tblName1, aColumn1, tblName2, aColumn2); int nextIndex = SimpleContentProvider.JOIN_TABLES.size(); SimpleContentProvider.JOIN_TABLES.add(table); SimpleContentProvider.URI_JOIN_MATCHER.addURI(auth, path, nextIndex); SimpleContentProvider.PROJECTION_MAPS.put(contentUri, aProjMap); SimpleContentProvider.JOIN_DETAILS.add(new SimpleContentProvider.Join(contentUri, tblName1, aColumn1, tblName2, aColumn2)); return contentUri; } public static void setProjectionMap(Uri aContentUri, Map<String, String> aProjectionMap) { SimpleContentProvider.PROJECTION_MAPS.put(aContentUri, aProjectionMap); } @Override public void onCreate(SQLiteDatabase db) { for (Map.Entry<Class, String> entry : TABLE_MAP.entrySet()) { SQLiteTable.TableCreator creator = getTableCreator(entry.getKey()); if (creator != null) { SQLiteTable.Builder builder = new SQLiteTable.Builder(entry.getValue()); SQLiteTable table = creator.buildTableSchema(builder); if (table != null) { db.execSQL(table.getCreateSQL()); if (table.getIndicesSQL() != null) { for (String indexSQL : table.getIndicesSQL()) { db.execSQL(indexSQL); } } if (table.getSeedValues() != null) { for (ContentValues values : table.getSeedValues()) { db.insert(table.getTableName(), table.getNullHack(), values); } } } } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Cursor tables = db.query("sqlite_master", null, "type='table'", null, null, null, null); ArrayList<String> tableNames = new ArrayList<String>(); if (tables != null) { for (int i = 0; i < tables.getCount(); i++) { tables.moveToPosition(i); tableNames.add(tables.getString(tables.getColumnIndex("name"))); } } for (Map.Entry<Class, String> entry : TABLE_MAP.entrySet()) { SQLiteTable.TableCreator creator = getTableCreator(entry.getKey()); if (creator == null) continue; SQLiteTable table = null; String tableName = entry.getValue(); if (!tableNames.contains(tableName)) { SQLiteTable.Builder builder = new SQLiteTable.Builder(tableName); table = creator.buildTableSchema(builder); if (table != null) { db.execSQL(table.getCreateSQL()); } } else { SQLiteTable.Updater updater = new SQLiteTable.Updater(tableName); table = creator.updateTableSchema(updater, oldVersion); if (table != null) { String[] updates = table.getUpdateSQL(); for (String updateSQL : updates) { db.execSQL(updateSQL); } } } if (table != null) { if (table.getIndicesSQL() != null) { for (String indexSQL : table.getIndicesSQL()) { db.execSQL(indexSQL); } } if (table.getSeedValues() != null) { for (ContentValues values : table.getSeedValues()) { db.insert(table.getTableName(), table.getNullHack(), values); } } } } } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); isOpen = true; } static SQLiteTable.TableCreator getTableCreator(Class aModelClass) { String className = aModelClass.getSimpleName(); SQLiteTable.TableCreator creator = null; try { Field f = aModelClass.getField("TABLE_CREATOR"); creator = (SQLiteTable.TableCreator) f.get(null); } catch (ClassCastException e) { throw new IllegalStateException("ADHD protocol requires the object called TABLE_CREATOR " + "on class " + className + " to be a SQLiteTable.TableCreator"); } catch (NoSuchFieldException e) { throw new IllegalStateException("ADHD protocol requires a SQLiteTable.TableCreator " + "object called TABLE_CREATOR on class " + className); } catch (IllegalAccessException e) { throw new IllegalStateException("ADHD protocol requires the TABLE_CREATOR object " + "to be accessible on class " + className); } catch (NullPointerException e) { throw new IllegalStateException("ADHD protocol requires the TABLE_CREATOR " + "object to be static on class " + className); } return creator; } static List<String> getTableColumns(SQLiteDatabase aDatabase, String aTableName) { List<String> columns = new ArrayList<String>(); if (isOpen && aDatabase != null) { Cursor c = aDatabase.rawQuery(String.format("PRAGMA table_info(%s)", aTableName), null); if (c.moveToFirst()) { do { columns.add(c.getString(1)); } while (c.moveToNext()); } } else { Class tableClass = CLASS_MAP.get(aTableName); if (tableClass != null) { SQLiteTable.TableCreator creator = getTableCreator(tableClass); SQLiteTable create = creator.buildTableSchema(new SQLiteTable.Builder(aTableName)); for (SQLiteTable.Column col : create.getColumns()) { columns.add(col.name); } SQLiteTable upgrade = creator.updateTableSchema(new SQLiteTable.Updater(aTableName), SimpleContentProvider.sDatabaseVersion); for (SQLiteTable.Column col : upgrade.getColumns()) { columns.add(col.name); } } } return columns; } static Map<String,String> buildDefaultJoinMap(SimpleContentProvider.Join aJoin, SQLiteDatabase aDb) { Map<String, String> projection = new HashMap<String, String>(); List<String> columns1 = getTableColumns(aDb, aJoin.table_1); List<String> columns2 = getTableColumns(aDb, aJoin.table_2); projection.put("_id", aJoin.table_1.concat("._id as _id")); for (String col : columns1) { projection.put(String.format("%s_%s", aJoin.table_1, col), String.format("%s.%s AS %s_%s", aJoin.table_1, col, aJoin.table_1, col)); } for (String col : columns2) { projection.put(String.format("%s_%s", aJoin.table_2, col), String.format("%s.%s AS %s_%s", aJoin.table_2, col, aJoin.table_2, col)); } return projection; } public static void wipeDatabase(Context aContext) { for (Uri uri : CONTENT_URI_MAP.values()) { aContext.getContentResolver().delete(uri, null, null); } } }
package org.neo4j.starter; import org.junit.Ignore; import org.junit.Test; import org.neo4j.test.server.CypherExecutor; import org.neo4j.test.server.HTTP; import org.neo4j.test.server.ManagedServerBuilders; import org.neo4j.test.server.ServerControls; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; import static org.junit.Assert.assertEquals; /** * @author mh * @since 30.11.15 */ public class Neo4jStarterTest2 { @Test @Ignore public void testMyExtension() throws Exception { // Given try (ServerControls server = ManagedServerBuilders.newManagedBuilder() .withExtension("/myExtension", MyUnmanagedExtension.class) .newServer("2.2.5")) { // When HTTP.Response response = HTTP.GET(server.httpURI().resolve("myExtension").toString()); // Then assertEquals(200, response.status()); } } @Test public void testServerWithFunctionFixture() throws Exception { // Given try (ServerControls server = ManagedServerBuilders.newManagedBuilder() .withFixture("CREATE (:User)") .newServer("2.2.5")) { // When Iterable result = server.execute("MATCH (n:User) return n"); // Then assertEquals(true, result.iterator().hasNext()); } } @Test public void testServerWithHttps() throws Exception { // Given configureJDKWithFakeTrustManager(); try (ServerControls server = ManagedServerBuilders.newManagedBuilder() .withFixture("CREATE (:User)") .withHttps() .newServer("2.2.5")) { // When CypherExecutor cypherExecutor = new CypherExecutor(server.httpsURI()); Iterable<Map<String, Object>> result = cypherExecutor.execute("MATCH (n:User) return n", null); // Then assertEquals(true, result.iterator().hasNext()); } } /** * apply a {@link TrustManager} to the JDK that simply accepts all certificates. Doing this prevents exceptions * when dealing e.g. with self-signed certificates * @throws NoSuchAlgorithmException * @throws KeyManagementException */ private void configureJDKWithFakeTrustManager() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] managers = new TrustManager[] {new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }}; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, managers, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } @Test public void testServerWithAuth() throws Exception { // Given try (ServerControls server = ManagedServerBuilders.newManagedBuilder() .withAuth() .withFixture("CREATE (:User)") .newServer("2.2.5")) { // When CypherExecutor cypherExecutor = new CypherExecutor(server.httpURI()); Iterable<Map<String, Object>> result = cypherExecutor.execute("MATCH (n:User) return n", null); // Then assertEquals(true, result.iterator().hasNext()); } } static class MyUnmanagedExtension { } }
package org.apache.poi.benchmark.suite; import com.google.common.base.Preconditions; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.ExecuteException; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.dstadler.commons.arrays.ArrayUtils; import org.dstadler.commons.exec.BufferingLogOutputStream; import org.dstadler.commons.exec.ExecutionHelper; import org.dstadler.commons.logging.jdk.DefaultFormatter; import org.dstadler.commons.logging.jdk.LoggerFactory; import org.openjdk.jmh.annotations.*; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Thread) @Fork(value = 0, warmups = 0) public abstract class BaseBenchmark { static { try { LoggerFactory.sendCommonsLogToJDKLog(); try (InputStream resource = new FileInputStream("src/jmh/resources/logging.properties")) { // apply configuration try { LogManager.getLogManager().readConfiguration(resource); } finally { resource.close(); } // apply a default format to the log handlers here before throwing an exception further down Logger log = Logger.getLogger(""); // NOSONAR - local logger used on purpose here for (Handler handler : log.getHandlers()) { handler.setFormatter(new DefaultFormatter()); } } } catch (IOException e) { throw new IllegalStateException("Current directory: " + new File(".").getAbsolutePath(), e); } } private static final Logger log = LoggerFactory.make(); protected final File srcDir = new File("sources"); @Setup public final void baseSetUp() throws IOException { // ensure directories if(!srcDir.exists()) { Preconditions.checkState(srcDir.mkdir(), "Could not create directory " + srcDir.getAbsolutePath()); } if(new File(srcDir, ".svn").exists()) { svnCleanup(); } svnCheckout(); svnStatus(); } private void svnCleanup() throws IOException { runSVN("cleanup", 60000); } private void svnCheckout() throws IOException { // svn checkout/update try (OutputStream out = new BufferingLogOutputStream()) { CommandLine cmd = new CommandLine("svn"); if(new File(srcDir, ".svn").exists()) { cmd.addArgument("up"); ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, 60000, out); } else { cmd.addArgument("co"); cmd.addArgument("https://svn.apache.org/repos/asf/poi/trunk"); cmd.addArgument(srcDir.getName()); ExecutionHelper.getCommandResultIntoStream(cmd, srcDir.getParentFile(), 0, 60000, out); } } } private void svnStatus() throws IOException { runSVN("status", TimeUnit.MINUTES.toMillis(1)); } protected void clean() throws IOException { runAntTarget("clean", TimeUnit.MINUTES.toMillis(10)); } protected void compileAll() throws IOException { runAntTarget("compile", TimeUnit.HOURS.toMillis(1)); } protected void testMain() throws IOException { runAntTarget("test-main", TimeUnit.HOURS.toMillis(1)); } protected void testScratchpad() throws IOException { runAntTarget("test-scratchpad", TimeUnit.HOURS.toMillis(1)); } protected void testOOXML() throws IOException { runAntTarget("test-ooxml", TimeUnit.HOURS.toMillis(1)); } protected void testOOXMLLite() throws IOException { // need to clean one file here to avoid not doing anything if the code // was already compiled before final File testfile = new File(srcDir, "build/ooxml-lite-testokfile.txt"); if(testfile.exists()) { if(!testfile.delete()) { throw new IOException("Could not delete file " + testfile); } } runAntTarget("test-ooxml-lite", TimeUnit.HOURS.toMillis(1)); } protected void testExcelant() throws IOException { runAntTarget("test-excelant", TimeUnit.HOURS.toMillis(1)); } protected void testIntegration() throws IOException { runAntTarget("test-integration", TimeUnit.HOURS.toMillis(2)/*, "-Dorg.apache.poi.util.POILogger=org.apache.poi.util.SystemOutLogger"*/); } private void runAntTarget(String target, long timeout, String... args) throws IOException { try (OutputStream out = new BufferingLogOutputStream()) { CommandLine cmd = new CommandLine("ant"); cmd.addArgument(target); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, timeout, out); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run Ant with target " + target + " and args: " + Arrays.toString(args), e); throw e; } } } private void runSVN(String command, long timeout, String... args) throws IOException { try (OutputStream out = new BufferingLogOutputStream()) { CommandLine cmd = new CommandLine("svn"); cmd.addArgument(command); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, timeout, out); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run SVN with command " + command + " and args: " + Arrays.toString(args), e); throw e; } } } protected void runPOIApplication(@SuppressWarnings("SameParameterValue") String clazz, long timeout, String... args) throws IOException { List<String> jars = new ArrayList<>(); addJarsFromDir(jars, "lib"); addJarsFromDir(jars, "compile-lib"); addJarsFromDir(jars, "ooxml-lib"); addClassesDir(jars, "build"); try (OutputStream out = new BufferingLogOutputStream()) { CommandLine cmd = new CommandLine("java"); cmd.addArgument("-cp"); cmd.addArgument(ArrayUtils.toString(jars.toArray(), ":", "", "")); cmd.addArgument(clazz); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, timeout, out); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run POI application " + clazz + "" + " and args: " + Arrays.toString(args), e); throw e; } } } @SuppressWarnings("SameParameterValue") private void addClassesDir(List<String> jars, String dir) { File[] files = new File(srcDir, dir).listFiles((FileFilter) new SuffixFileFilter("classes")); Preconditions.checkNotNull(files, "Directory %s does not exist", srcDir.getAbsolutePath()); for(File file : files) { jars.add(file.getAbsolutePath()); } } private void addJarsFromDir(List<String> jars, String dir) { File[] files = new File(srcDir, dir).listFiles((FileFilter) new AndFileFilter( new SuffixFileFilter(".jar"), new NotFileFilter(new AndFileFilter( new SuffixFileFilter("-sources.jar"), new SuffixFileFilter("xmlbeans-2.3.0.jar"))))); Preconditions.checkNotNull(files, "Directory %s does not exist", srcDir.getAbsolutePath()); for(File file : files) { jars.add(file.getAbsolutePath()); } } }
package com.worldnet.automerger; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * AutoMerger App. * */ public class App { static final Logger logger = LogManager.getLogger(); /** * URL to a Team Drive document published in the web (publicly available) which define branches * to be merged. */ public static final String BRANCHES_URL = "<document URL here>"; public static void main( String[] args ) throws Exception { Merger merger = new Merger(); String[] branches = readBranches().split(System.getProperty("line.separator")); //skip first line in the iteration for (int i = 1; i < branches.length; i++) { String[] mergeArgs = StringUtils.split(branches[i], ","); if(mergeArgs.length != 3){ logger.error("Incorrect branches configuration: {}", branches[i]); logger.error("A valid entry must be: <SOURCE_BRANCH>,<TARGET_BRANCH>,<REDMINE_TICKET>"); System.exit(0); } try { merger.performMerge(mergeArgs[0].trim(), mergeArgs[1].trim(), mergeArgs[2].trim()); } catch (Exception e) { logger.error(e); } } System.exit(0); } /** * Read the branches configuration to execute the automerger. * The document location is "Team Drive > Development > Projects > Automerger > Branches" * @return the branches configuration */ public static String readBranches() throws Exception{ URL url = new URL(App.BRANCHES_URL); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } in.close(); return sb.toString(); } }
package com.clivern.racter.receivers; import com.clivern.racter.receivers.webhook.*; import java.util.HashMap; import java.util.Map; import com.clivern.racter.utils.Config; import com.clivern.racter.utils.Log; import org.json.JSONObject; import org.json.JSONArray; /** * Base Receiver Class */ public class BaseReceiver { protected String message_string; protected JSONObject message_object; protected Map<String, MessageReceivedWebhook> message_received_webhook = new HashMap<String, MessageReceivedWebhook>(); protected Map<String, MessageDeliveredWebhook> message_delivered_webhook = new HashMap<String, MessageDeliveredWebhook>(); protected Map<String, MessageEchoWebhook> message_echo_webhook = new HashMap<String, MessageEchoWebhook>(); protected Map<String, MessageReadWebhook> message_read_webhook = new HashMap<String, MessageReadWebhook>(); protected Map<String, PostbackWebhook> postback_webhook = new HashMap<String, PostbackWebhook>(); protected Config configs; protected Log log; /** * Class Constructor * * @param configs * @param log */ public BaseReceiver(Config configs, Log log) { this.configs = configs; this.log = log; } /** * Set Incoming Message * * @param message_string * @return BaseReceiver */ public BaseReceiver set(String message_string) { this.message_string = message_string; this.message_object = new JSONObject(message_string); return this; } /** * Parse Incoming Message * * @return BaseReceiver */ public BaseReceiver parse() { int i; int z = 1; if( !this.message_object.has("object") || !this.message_object.getString("object").equals("page") ){ return this; } if( !this.message_object.has("entry") ){ return this; } JSONArray entry = this.message_object.getJSONArray("entry"); for ( i = 0; i < entry.length(); i++ ) { JSONObject entry_obj = entry.getJSONObject(i); if( entry_obj.has("id") ){ String page_id = entry_obj.getString("id"); } if( entry_obj.has("time") ){ Long time = entry_obj.getLong("time"); } if( entry_obj.has("messaging") ){ for ( i = 0; i < entry_obj.getJSONArray("messaging").length(); i++ ) { JSONObject messaging_item = entry_obj.getJSONArray("messaging").getJSONObject(i); // Get Sender ID String sender_id = null; if( messaging_item.has("sender") ){ JSONObject sender = messaging_item.getJSONObject("sender"); sender_id = (sender.has("id")) ? sender.getString("id") : null; } // Get Recipient ID or Page ID String recipient_id = null; if( messaging_item.has("recipient") ){ JSONObject recipient = messaging_item.getJSONObject("recipient"); recipient_id = (recipient.has("id")) ? recipient.getString("id") : null; } // Get Timestamp Long timestamp = null; if( messaging_item.has("timestamp") ){ timestamp = messaging_item.getLong("timestamp"); } // Incoming Message if( messaging_item.has("message") ){ JSONObject message = messaging_item.getJSONObject("message"); if( message.has("is_echo") ){ // Message Echo }else{ z += 1; // Message this.message_received_webhook.put("message." + z, new MessageReceivedWebhook()); this.message_received_webhook.get("message." + z).setUserId(sender_id); this.message_received_webhook.get("message." + z).setPageId(recipient_id); this.message_received_webhook.get("message." + z).setTimestamp(timestamp); String mid = (message.has("mid")) ? message.getString("mid") : null; this.message_received_webhook.get("message." + z).setMessageId(mid); if ( message.has("text") ){ String text = message.getString("text"); this.message_received_webhook.get("message." + z).setMessageText(text); } if ( message.has("quick_reply") ){ JSONObject quick_reply = message.getJSONObject("quick_reply"); String payload = (quick_reply.has("payload")) ? quick_reply.getString("payload") : null; this.message_received_webhook.get("message." + z).setQuickReplyPayload(payload); } if ( message.has("attachments") ){ JSONArray attachments = message.getJSONArray("attachments"); for ( i = 0; i < attachments.length(); i++ ) { JSONObject attachment = attachments.getJSONObject(i); String type = (attachment.has("type")) ? attachment.getString("type") : null; if( type.equals("audio") ){ if( attachment.has("payload") ){ JSONObject attachment_payload = attachment.getJSONObject("payload"); String url = (attachment_payload.has("url")) ? attachment_payload.getString("url") : null; this.message_received_webhook.get("message." + z).setAttachment("audio", url); } // Unknown right now // }else if( type.equals("fallback") ){ }else if( type.equals("file") ){ if( attachment.has("payload") ){ JSONObject attachment_payload = attachment.getJSONObject("payload"); String url = (attachment_payload.has("url")) ? attachment_payload.getString("url") : null; this.message_received_webhook.get("message." + z).setAttachment("file", url); } }else if( type.equals("image") ){ if( attachment.has("payload") ){ JSONObject attachment_payload = attachment.getJSONObject("payload"); String url = (attachment_payload.has("url")) ? attachment_payload.getString("url") : null; this.message_received_webhook.get("message." + z).setAttachment("image", url); } }else if( type.equals("video") ){ if( attachment.has("payload") ){ JSONObject attachment_payload = attachment.getJSONObject("payload"); String url = (attachment_payload.has("url")) ? attachment_payload.getString("url") : null; this.message_received_webhook.get("message." + z).setAttachment("video", url); } }else if( type.equals("location") ){ if( attachment.has("payload") ){ JSONObject attachment_payload = attachment.getJSONObject("payload"); Long coordinates_lat = (attachment_payload.has("coordinates.lat")) ? attachment_payload.getLong("coordinates.lat") : null; Long coordinates_long = (attachment_payload.has("coordinates.long")) ? attachment_payload.getLong("coordinates.long") : null; this.message_received_webhook.get("message." + z).setAttachment("location", coordinates_lat, coordinates_long); } } } } } } // Message Delivery if( messaging_item.has("delivery") ){ JSONObject delivery = messaging_item.getJSONObject("delivery"); z += 1; this.message_delivered_webhook.put("message." + z, new MessageDeliveredWebhook()); this.message_delivered_webhook.get("message." + z).setUserId(sender_id); this.message_delivered_webhook.get("message." + z).setPageId(recipient_id); if( delivery.has("watermark") ){ this.message_delivered_webhook.get("message." + z).setWatermark(delivery.getLong("watermark")); } if( delivery.has("seq") ){ this.message_delivered_webhook.get("message." + z).setSeq(delivery.getInt("seq")); } //this.message_delivered_webhook.get("message." + z).setMid(); } // Message Read if( messaging_item.has("read") ){ JSONObject read = messaging_item.getJSONObject("read"); z += 1; this.message_read_webhook.put("message." + z, new MessageReadWebhook()); this.message_read_webhook.get("message." + z).setUserId(sender_id); this.message_read_webhook.get("message." + z).setPageId(recipient_id); this.message_read_webhook.get("message." + z).setTimestamp(timestamp); if( read.has("watermark") ){ this.message_read_webhook.get("message." + z).setWatermark(read.getLong("watermark")); } if( read.has("seq") ){ this.message_read_webhook.get("message." + z).setSeq(read.getInt("seq")); } } // Post Back if( messaging_item.has("postback") ){ JSONObject postback = messaging_item.getJSONObject("postback"); z += 1; this.postback_webhook.put("message." + z, new PostbackWebhook()); this.postback_webhook.get("message." + z).setUserId(sender_id); this.postback_webhook.get("message." + z).setPageId(recipient_id); this.postback_webhook.get("message." + z).setTimestamp(timestamp); //this.postback_webhook.get("message." + z).setPostback(); } } } } return this; } /** * Get parsed message * * @return Map<String, MessageReceivedWebhook> */ public Map<String, MessageReceivedWebhook> getMessages() { return this.message_received_webhook; } /** * Get delivered data * * @return Map<String, MessageDeliveredWebhook> */ public Map<String, MessageDeliveredWebhook> getDelivered() { return this.message_delivered_webhook; } /** * Get echo data * * @return Map<String, MessageEchoWebhook> */ public Map<String, MessageEchoWebhook> getEcho() { return this.message_echo_webhook; } /** * Get read data * * @return Map<String, MessageReadWebhook> */ public Map<String, MessageReadWebhook> getRead() { return this.message_read_webhook; } /** * Get postback data * * @return Map<String, PostbackWebhook> */ public Map<String, PostbackWebhook> getPostback() { return this.postback_webhook; } /** * Get message as a string * * @return String */ public String getMessageString() { return this.message_string; } /** * Get message as an object * * @return JSONObject */ public JSONObject getMessageObject() { return this.message_object; } }
package org.apache.poi.benchmark.suite; import com.google.common.base.Preconditions; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.ExecuteException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.poi.benchmark.util.TailLogOutputStream; import org.dstadler.commons.arrays.ArrayUtils; import org.dstadler.commons.exec.ExecutionHelper; import org.dstadler.commons.logging.jdk.DefaultFormatter; import org.dstadler.commons.logging.jdk.LoggerFactory; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; @SuppressWarnings("JmhInspections") @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Thread) @Fork(value = 0, warmups = 0) public abstract class BaseBenchmark { private static final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1); private static final long TEN_MINUTES = TimeUnit.MINUTES.toMillis(10); private static final long ONE_HOUR = TimeUnit.HOURS.toMillis(1); private static final long TWO_HOURS = TimeUnit.HOURS.toMillis(2); private static final Map<String, String> ENVIRONMENT = new HashMap<>(); private static final int TAIL_LINES = 100; static { // set up logging configuration configureLoggingFramework(); } private static final Logger log = LoggerFactory.make(); protected final File srcDir = new File("sources"); private static void configureLoggingFramework() { try { LoggerFactory.sendCommonsLogToJDKLog(); try (InputStream resource = new FileInputStream("src/jmh/resources/logging.properties")) { // apply configuration try { LogManager.getLogManager().readConfiguration(resource); } finally { resource.close(); } // apply a default format to the log handlers here before throwing an exception further down Logger log = Logger.getLogger(""); // NOSONAR - local logger used on purpose here for (Handler handler : log.getHandlers()) { handler.setFormatter(new DefaultFormatter()); } } } catch (IOException e) { throw new IllegalStateException("Current directory: " + new File(".").getAbsolutePath(), e); } } @SuppressWarnings("unused") @Setup public final void baseSetUp() throws IOException { // ensure directories exist if(!srcDir.exists()) { Preconditions.checkState(srcDir.mkdir(), "Could not create directory " + srcDir.getAbsolutePath()); } // clean up checkout if(new File(srcDir, ".svn").exists()) { svnCleanup(); } svnCheckout(); patchTestExecution(); svnStatus(); printEnvironment(); } private void svnCleanup() throws IOException { runSVN("cleanup"); } private void svnCheckout() throws IOException { // svn checkout/update try (TailLogOutputStream out = new TailLogOutputStream(TAIL_LINES)) { try { CommandLine cmd = new CommandLine("svn"); if (new File(srcDir, ".svn").exists()) { cmd.addArgument("up"); ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, ONE_MINUTE, out, ENVIRONMENT); } else { cmd.addArgument("co"); cmd.addArgument("https://svn.apache.org/repos/asf/poi/trunk"); cmd.addArgument(srcDir.getName()); ExecutionHelper.getCommandResultIntoStream(cmd, srcDir.getParentFile(), 0, ONE_MINUTE, out, ENVIRONMENT); } } catch (IOException e) { throw new IOException("Log-Tail: " + out.getLines(), e); } } } private void patchTestExecution() throws IOException { String content = FileUtils.readFileToString(new File(srcDir, "build.gradle"), "UTF-8"); // use the "Marlin" rendering engine as the default "pisces" causes endless loops for some integration-test-files if (!content.contains("Xbootclasspath")) { content = content.replace("strategy=dynamic',", "strategy=dynamic'," + "'-Xbootclasspath/p:" + srcDir.getAbsoluteFile().getParentFile().getAbsolutePath() + "/marlin-0.9.4.5-Unsafe.jar'," + "'-Dsun.java2d.renderer=sun.java2d.marlin.DMarlinRenderingEngine',"); FileUtils.writeStringToFile(new File(srcDir, "build.gradle"), content, "UTF-8"); } } private void svnStatus() throws IOException { runSVN("status"); } protected void clean() throws IOException { // these files are modified locally, we want to avoid conflicts runSVN("revert", "poi-examples/src/main/java9/module-info.class", "poi-excelant/src/main/java9/module-info.class", "poi-excelant/src/test/java9/module-info.class", "poi-integration/src/test/java9/module-info.class", "poi-ooxml-full/src/main/java9/module-info.class", "poi-ooxml-lite-agent/src/main/java9/module-info.class", "poi-ooxml-lite/src/main/java9/module-info.class", "poi-ooxml/src/main/java9/module-info.class", "poi-ooxml/src/test/java9/module-info.class", "poi-scratchpad/src/main/java9/module-info.class", "poi-scratchpad/src/test/java9/module-info.class", "poi/src/main/java9/module-info.class", "poi/src/test/java9/module-info.class"); runGradleTarget("clean", TEN_MINUTES); } private void printEnvironment() throws IOException { try (TailLogOutputStream out = new TailLogOutputStream(TAIL_LINES)) { CommandLine cmd = new CommandLine("bash"); cmd.addArgument("-c"); cmd.addArguments("set"); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, ONE_MINUTE, out, ENVIRONMENT); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to print the environment variables", e); throw new IOException("Log-Tail: " + out.getLines(), e); } } } protected void compileAll() throws IOException { runGradleTarget("compileJava", ONE_HOUR, // let's run more than one target in one go "compileTestJava", "getDeps"); } protected void testMain() throws IOException { runGradleTarget(":poi:check", ONE_HOUR); } protected void testScratchpad() throws IOException { runGradleTarget(":poi-scratchpad:check", ONE_HOUR); } protected void testOOXML() throws IOException { runGradleTarget(":poi-ooxml:check", ONE_HOUR); } protected void testOOXMLLite() throws IOException { // need to clean one file here to avoid not doing anything if the code // was already compiled before final File testfile = new File(srcDir, "build/ooxml-lite-testokfile.txt"); if(testfile.exists()) { if(!testfile.delete()) { throw new IOException("Could not delete file " + testfile); } } runGradleTarget(":poi-ooxml-lite:check", ONE_HOUR); } protected void testExcelant() throws IOException { runGradleTarget(":poi-excelant:check", ONE_HOUR); } protected void testIntegration() throws IOException { runGradleTarget(":poi-integration:check", TWO_HOURS); } private void runGradleTarget(String target, long timeout, String... args) throws IOException { try (TailLogOutputStream out = new TailLogOutputStream(TAIL_LINES)) { CommandLine cmd = new CommandLine("bash"); cmd.addArgument("./gradlew"); cmd.addArgument(target); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, timeout, out, ENVIRONMENT); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run Gradle with target: '" + target + "' and args: " + ArrayUtils.toString(args, " ", "", ""), e); throw new IOException("Log-Tail: " + out.getLines(), e); } } } private void runSVN(String command, String... args) throws IOException { try (TailLogOutputStream out = new TailLogOutputStream(TAIL_LINES)) { CommandLine cmd = new CommandLine("svn"); cmd.addArgument(command); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, ONE_MINUTE, out, ENVIRONMENT); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run SVN with command " + command + " and args: " + Arrays.toString(args), e); throw new IOException("Log-Tail: " + out.getLines(), e); } } } protected void runPOIApplication(@SuppressWarnings("SameParameterValue") String clazz, long timeout, String... args) throws IOException { List<String> jars = new ArrayList<>(); addJarsFromDir(jars, "poi/build/runtime"); addJarsFromDir(jars, "poi-examples/build/runtime"); //addJarsFromDir(jars, "poi-excelant/build/runtime"); addJarsFromDir(jars, "poi-ooxml/build/runtime"); //addJarsFromDir(jars, "poi-ooxml-full/build/runtime"); //addJarsFromDir(jars, "poi-ooxml-lite-agent/build/runtime"); //addJarsFromDir(jars, "poi-ooxml-lite/build/runtime"); addJarsFromDir(jars, "poi-scratchpad/build/runtime"); // Collect third-party jar-files (only available after running Ant, replaced by "build/runtime" above) /*addJarsFromDir(jars, "lib/excelant"); addJarsFromDir(jars, "lib/main"); addJarsFromDir(jars, "lib/main-tests"); addJarsFromDir(jars, "lib/ooxml"); addJarsFromDir(jars, "lib/ooxml-provided"); addJarsFromDir(jars, "lib/ooxml-tests"); addJarsFromDir(jars, "lib/util");*/ // Collect complied classes for Apache POI itself addClassesDir(jars, "build"); // new directories after starting move to Gradle addClassesDir(jars, "poi/build"); addClassesDir(jars, "poi-examples/build"); addClassesDir(jars, "poi-excelant/build"); addClassesDir(jars, "poi-integration/build"); addClassesDir(jars, "poi-ooxml/build"); addClassesDir(jars, "poi-ooxml-full/build"); addClassesDir(jars, "poi-scratchpad/build"); try (TailLogOutputStream out = new TailLogOutputStream(TAIL_LINES)) { CommandLine cmd = new CommandLine("java"); cmd.addArgument("-cp"); cmd.addArgument(ArrayUtils.toString(jars.toArray(), ":", "", "")); cmd.addArgument(clazz); cmd.addArguments(args); try { ExecutionHelper.getCommandResultIntoStream(cmd, srcDir, 0, timeout, out, ENVIRONMENT); } catch (ExecuteException e) { log.log(Level.WARNING, "Failed to run POI application " + clazz + "" + " and args: " + Arrays.toString(args), e); throw new IOException("Log-Tail: " + out.getLines(), e); } } } @SuppressWarnings("SameParameterValue") private void addClassesDir(List<String> jars, String dir) { File[] files = new File(srcDir, dir).listFiles((FileFilter) new SuffixFileFilter("classes")); Preconditions.checkNotNull(files, "Sub-Directory %s in %s does not exist", dir, srcDir.getAbsolutePath()); for(File file : files) { jars.add(file.getAbsolutePath()); if (new File(file.getAbsolutePath(), "java/main").exists()) { jars.add(file.getAbsolutePath() + "/java/main"); } if (new File(file.getAbsolutePath(), "ant/java").exists()) { jars.add(file.getAbsolutePath() + "/ant/java"); } } } private void addJarsFromDir(List<String> jars, String dir) { File[] files = new File(srcDir, dir).listFiles((FileFilter) new AndFileFilter( new SuffixFileFilter(".jar"), new NotFileFilter(new AndFileFilter( new SuffixFileFilter("-sources.jar"), new SuffixFileFilter("xmlbeans-2.3.0.jar"))))); Preconditions.checkNotNull(files, "Sub-Directory %s in %s does not exist", dir, srcDir.getAbsolutePath()); for(File file : files) { jars.add(file.getAbsolutePath()); } } }
package uk.co.uwcs.choob.plugins; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; public final class HaxSunPluginClassLoader extends ClassLoader { private final String path; private final ProtectionDomain domain; public HaxSunPluginClassLoader( final String pluginName, final String path, final ProtectionDomain domain ) { super(); this.path = path; this.domain = domain; // super.definePackage("plugins", "", "", "", "", "", "", null); try { definePackage("plugins." + pluginName, "", "", "", "", "", "", null); } catch (IllegalArgumentException e) { e.printStackTrace(); System.err.println(); System.err.println("Couldn't create plugins package. " + "This is probably because your debugger is interfering. Your plugin probably hasn't been reloaded."); System.err.println(); } } @Override public Class<?> findClass(final String name) throws ClassNotFoundException { try { return AccessController .doPrivileged(new PrivilegedExceptionAction<Class<?>>() { public Class<?> run() throws ClassNotFoundException { try { final String fileName = path + name.replace('.', File.separatorChar) + ".class"; final File classFile = new File(fileName); if (!classFile.isFile()) { throw new ClassNotFoundException("Class file " + fileName + " is not a file."); } final URL classURL = classFile.toURI().toURL(); final URLConnection classConn = classURL.openConnection(); final int size = classConn.getContentLength(); if (size == -1) { // XXX throw new ClassNotFoundException("Class " + name + " has unknown content length; not loaded."); } final InputStream classStream = new FileInputStream(classFile); final byte[] classData = new byte[size]; int read = 0; int avail; while((avail = classStream.available()) > 0) { avail = classStream.read(classData, read, avail); read += avail; } if (read != size) throw new ClassNotFoundException("Class " + name + " has was not fully read; not loaded."); final Class<?> theClass = defineClass(name, classData, 0, classData.length, domain); return theClass; } catch (final IOException e) { System.err.println("Could not open class URL: " + e); throw new ClassNotFoundException("Class " + name + " not found!", e); } catch (final ClassFormatError e) { System.err.println("Could not open class URL: " + e); throw new ClassNotFoundException("Class " + name + " not valid.", e); } catch (final NoClassDefFoundError e) { System.err.println("n class URL: " + e); throw new ClassNotFoundException("Class " + name + " contained no class.", e); } } } ); } catch (final PrivilegedActionException e) { throw (ClassNotFoundException)e.getException(); } } }
package com.zenplanner.sql; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.util.*; import java.util.List; public class FormMain extends JFrame { private JPanel panel1; private JTextField tbSrcServer; private JTextField tbSrcDb; private JTextField tbSrcUsername; private JPasswordField tbSrcPassword; private JTextField tbDstServer; private JTextField tbDstDb; private JTextField tbDstUsername; private JProgressBar pbMain; private JButton btnGo; private JPasswordField tbDstPassword; private JTextField tbFilterColumn; private JTextField tbFilterValue; private JTextArea tbIgnore; private JLabel lblCurrentTable; private JLabel lblCurrentRow; private static final String conTemplate = "jdbc:jtds:sqlserver://%s:1433/%s;user=%s;password=%s"; private final DbComparator comp = new DbComparator(); public FormMain() { setDefaultCloseOperation(EXIT_ON_CLOSE); add(panel1); setSize(800, 600); setVisible(true); pack(); loadProps(); // Restore constraints if the app crashed Map<String, List<String>> constraints = comp.loadConstraints(); if(constraints != null) { int res = JOptionPane.showConfirmDialog(this, "Abnormal termination detected, would you like to restore constraints from backup file?", "Warning", JOptionPane.YES_NO_OPTION); if(res == JOptionPane.YES_OPTION){ String dstCon = getDstCon(); try (Connection dcon = DriverManager.getConnection(dstCon)) { comp.setConstraints(dcon, constraints, true); } catch (Exception ex) { throw new RuntimeException("Error restoring constraints!", ex); } comp.unloadConstraints(); } } Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pbMain.setMaximum(comp.getRowCount()); pbMain.setValue(comp.getCurrentRow()); lblCurrentTable.setText(comp.getCurrentTableName()); lblCurrentRow.setText("" + comp.getCurrentRow() + " / " + comp.getRowCount()); } }); comp.addListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if(comp.getCurrentTable() > comp.getTableCount()) { timer.stop(); lblCurrentTable.setText(""); lblCurrentRow.setText(""); btnGo.setEnabled(true); pbMain.setValue(0); JOptionPane.showMessageDialog(FormMain.this, "Synchronization complete!"); } } }); } }); btnGo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnGo.setEnabled(false); new Thread(new Runnable() { @Override public void run() { try { timer.start(); saveProps(); sync(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("Error syncing DBs!", ex); // TODO: Pop-up } } }).start(); } }); } private String getDstCon() { String dstCon = String.format(conTemplate, tbDstServer.getText(), tbDstDb.getText(), tbDstUsername.getText(), tbDstPassword.getText()); return dstCon; } private void sync() throws Exception { Map<String,List<Object>> filters = new HashMap<String,List<Object>>(); List<Object> vals = Arrays.asList(tbFilterValue.getText().split(",")); filters.put(tbFilterColumn.getText().toLowerCase(), vals); java.util.List<String> ignoreTables = Arrays.asList(tbIgnore.getText().split(",")); String srcCon = String.format(conTemplate, tbSrcServer.getText(), tbSrcDb.getText(), tbSrcUsername.getText(), tbSrcPassword.getText()); String dstCon = getDstCon(); try (Connection scon = DriverManager.getConnection(srcCon)) { scon.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); try (Connection dcon = DriverManager.getConnection(dstCon)) { comp.synchronize(scon, dcon, filters, ignoreTables); } } } private void loadProps() { Properties props = comp.loadProps(); tbSrcServer.setText(props.getProperty("SourceServer")); tbSrcDb.setText(props.getProperty("SourceDb")); tbSrcUsername.setText(props.getProperty("SourceUsername")); tbSrcPassword.setText(props.getProperty("SourcePassword")); tbDstServer.setText(props.getProperty("DestServer")); tbDstDb.setText(props.getProperty("DestDb")); tbDstUsername.setText(props.getProperty("DestUsername")); tbDstPassword.setText(props.getProperty("DestPassword")); tbFilterColumn.setText(props.getProperty("FilterColumn")); tbFilterValue.setText(props.getProperty("FilterValue")); tbIgnore.setText(props.getProperty("IgnoreTables")); } private void saveProps() throws Exception { Properties props = comp.loadProps(); props.setProperty("SourceServer", tbSrcServer.getText()); props.setProperty("SourceDb", tbSrcDb.getText()); props.setProperty("SourceUsername", tbSrcUsername.getText()); props.setProperty("SourcePassword", tbSrcPassword.getText()); props.setProperty("DestServer", tbDstServer.getText()); props.setProperty("DestDb", tbDstDb.getText()); props.setProperty("DestUsername", tbDstUsername.getText()); props.setProperty("DestPassword", tbDstPassword.getText()); props.setProperty("FilterColumn", tbFilterColumn.getText()); props.setProperty("FilterValue", tbFilterValue.getText()); props.setProperty("IgnoreTables", tbIgnore.getText()); comp.saveProps(props); } }
package org.zendesk.client.v2; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.UUID; import org.junit.After; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.zendesk.client.v2.model.AgentRole; import org.zendesk.client.v2.model.Audit; import org.zendesk.client.v2.model.Brand; import org.zendesk.client.v2.model.Collaborator; import org.zendesk.client.v2.model.Comment; import org.zendesk.client.v2.model.Field; import org.zendesk.client.v2.model.Group; import org.zendesk.client.v2.model.Identity; import org.zendesk.client.v2.model.JobStatus; import org.zendesk.client.v2.model.Organization; import org.zendesk.client.v2.model.Request; import org.zendesk.client.v2.model.Status; import org.zendesk.client.v2.model.SuspendedTicket; import org.zendesk.client.v2.model.Ticket; import org.zendesk.client.v2.model.TicketForm; import org.zendesk.client.v2.model.User; import org.zendesk.client.v2.model.events.Event; import org.zendesk.client.v2.model.hc.Article; import org.zendesk.client.v2.model.hc.Category; import org.zendesk.client.v2.model.hc.Section; import org.zendesk.client.v2.model.hc.Subscription; import org.zendesk.client.v2.model.hc.Translation; import org.zendesk.client.v2.model.schedules.Holiday; import org.zendesk.client.v2.model.schedules.Interval; import org.zendesk.client.v2.model.schedules.Schedule; import org.zendesk.client.v2.model.targets.Target; /** * @author stephenc * @since 04/04/2013 13:57 */ public class RealSmokeTest { private static Properties config; private Zendesk instance; @BeforeClass public static void loadConfig() { config = ZendeskConfig.load(); assumeThat("We have a configuration", config, notNullValue()); assertThat("Configuration has an url", config.getProperty("url"), notNullValue()); } public void assumeHaveToken() { assumeThat("We have a username", config.getProperty("username"), notNullValue()); assumeThat("We have a token", config.getProperty("token"), notNullValue()); } public void assumeHavePassword() { assumeThat("We have a username", config.getProperty("username"), notNullValue()); assumeThat("We have a password", config.getProperty("password"), notNullValue()); } public void assumeHaveTokenOrPassword() { assumeThat("We have a username", config.getProperty("username"), notNullValue()); assumeThat("We have a token or password", config.getProperty("token") != null || config.getProperty("password") != null, is( true)); } @After public void closeClient() { if (instance != null) { instance.close(); } instance = null; } @Test public void createClientWithToken() throws Exception { assumeHaveToken(); instance = new Zendesk.Builder(config.getProperty("url")) .setUsername(config.getProperty("username")) .setToken(config.getProperty("token")) .build(); } @Test public void createClientWithTokenOrPassword() throws Exception { assumeHaveTokenOrPassword(); final Zendesk.Builder builder = new Zendesk.Builder(config.getProperty("url")) .setUsername(config.getProperty("username")); if (config.getProperty("token") != null) { builder.setToken(config.getProperty("token")); } else if (config.getProperty("password") != null) { builder.setPassword(config.getProperty("password")); } instance = builder.build(); } @Test public void getBrands() throws Exception { createClientWithTokenOrPassword(); List<Brand> brands = instance.getBrands(); assertTrue(brands.iterator().hasNext()); for(Brand brand : brands){ assertThat(brand, notNullValue()); } } @Test public void getTicket() throws Exception { createClientWithTokenOrPassword(); Ticket ticket = instance.getTicket(1); assertThat(ticket, notNullValue()); } @Test @Ignore("Needs instance with ticket form") public void getTicketForm() throws Exception { createClientWithTokenOrPassword(); TicketForm ticketForm = instance.getTicketForm(27562); assertThat(ticketForm, notNullValue()); assertTrue(ticketForm.isEndUserVisible()); } @Test @Ignore("Needs instance with ticket form") public void getTicketForms() throws Exception { createClientWithTokenOrPassword(); Iterable<TicketForm> ticketForms = instance.getTicketForms(); assertTrue(ticketForms.iterator().hasNext()); for(TicketForm ticketForm : ticketForms){ assertThat(ticketForm, notNullValue()); } } @Test @Ignore("Needs instance with ticket form") public void getTicketFieldsOnForm() throws Exception { createClientWithTokenOrPassword(); TicketForm ticketForm = instance.getTicketForm(27562); for(Long id :ticketForm.getTicketFieldIds()){ Field f = instance.getTicketField(id); assertNotNull(f); } assertThat(ticketForm, notNullValue()); assertTrue(ticketForm.isEndUserVisible()); } @Test public void getTargets() throws Exception { createClientWithTokenOrPassword(); Long firstTargetId = null; for (Target target : instance.getTargets()) { assertNotNull(target); if (firstTargetId != null) { assertNotEquals(firstTargetId, target.getId()); // check for infinite loop } else { firstTargetId = target.getId(); } } } @Test @Ignore("Needs test data setup correctly") public void getTicketsPagesRequests() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Ticket t : instance.getTickets()) { assertThat(t.getSubject(), notNullValue()); if (++count > 150) { break; } } assertThat(count, is(151)); } @Test @Ignore("Needs test data setup correctly") public void getRecentTickets() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Ticket t : instance.getRecentTickets()) { assertThat(t.getSubject(), notNullValue()); if (++count > 150) { break; } } assertThat(count, is(151)); } @Test public void getTicketsById() throws Exception { createClientWithTokenOrPassword(); long count = 22; for (Ticket t : instance.getTickets(22, 24, 26)) { assertThat(t.getSubject(), notNullValue()); assertThat(t.getId(), is(count)); count += 2; } assertThat(count, is(28L)); } @Test public void getTicketsIncrementally() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Ticket t : instance.getTicketsIncrementally(new Date(0L))) { assertThat(t.getId(), notNullValue()); if (++count > 10) { break; } } } @Test public void getTicketAudits() throws Exception { createClientWithTokenOrPassword(); for (Audit a : instance.getTicketAudits(1L)) { assertThat(a, notNullValue()); assertThat(a.getEvents(), not(Collections.<Event>emptyList())); } } @Test public void getTicketFields() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Field f : instance.getTicketFields()) { assertThat(f, notNullValue()); assertThat(f.getId(), notNullValue()); assertThat(f.getType(), notNullValue()); if (++count > 10) { break; } } } @Test public void createClientWithPassword() throws Exception { assumeHavePassword(); instance = new Zendesk.Builder(config.getProperty("url")) .setUsername(config.getProperty("username")) .setPassword(config.getProperty("password")) .build(); Ticket t = instance.getTicket(1); assertThat(t, notNullValue()); System.out.println(t); } @Test public void createAnonymousClient() { instance = new Zendesk.Builder(config.getProperty("url")) .build(); } @Test @Ignore("Don't spam zendesk") public void createDeleteTicket() throws Exception { createClientWithTokenOrPassword(); assumeThat("Must have a requester email", config.getProperty("requester.email"), notNullValue()); Ticket t = new Ticket( new Ticket.Requester(config.getProperty("requester.name"), config.getProperty("requester.email")), "This is a test", new Comment("Please ignore this ticket")); t.setCollaborators(Arrays.asList(new Collaborator("Bob Example", "bob@example.org"), new Collaborator("Alice Example", "alice@example.org"))); Ticket ticket = instance.createTicket(t); System.out.println(ticket.getId() + " -> " + ticket.getUrl()); assertThat(ticket.getId(), notNullValue()); try { Ticket t2 = instance.getTicket(ticket.getId()); assertThat(t2, notNullValue()); assertThat(t2.getId(), is(ticket.getId())); List<User> ticketCollaborators = instance.getTicketCollaborators(ticket.getId()); assertThat("Collaborators", ticketCollaborators.size(), is(2)); assertThat("First Collaborator", ticketCollaborators.get(0).getEmail(), anyOf(is("alice@example.org"), is("bob@example.org"))); } finally { instance.deleteTicket(ticket.getId()); } assertThat(ticket.getSubject(), is(t.getSubject())); assertThat(ticket.getRequester(), nullValue()); assertThat(ticket.getRequesterId(), notNullValue()); assertThat(ticket.getDescription(), is(t.getComment().getBody())); assertThat("Collaborators", ticket.getCollaboratorIds().size(), is(2)); assertThat(instance.getTicket(ticket.getId()), nullValue()); } @Test @Ignore("Don't spam zendesk") public void createSolveTickets() throws Exception { createClientWithTokenOrPassword(); assumeThat("Must have a requester email", config.getProperty("requester.email"), notNullValue()); Ticket ticket; long firstId = Long.MAX_VALUE; do { Ticket t = new Ticket( new Ticket.Requester(config.getProperty("requester.name"), config.getProperty("requester.email")), "This is a test " + UUID.randomUUID().toString(), new Comment("Please ignore this ticket")); ticket = instance.createTicket(t); System.out.println(ticket.getId() + " -> " + ticket.getUrl()); assertThat(ticket.getId(), notNullValue()); Ticket t2 = instance.getTicket(ticket.getId()); assertThat(t2, notNullValue()); assertThat(t2.getId(), is(ticket.getId())); t2.setAssigneeId(instance.getCurrentUser().getId()); t2.setStatus(Status.CLOSED); instance.updateTicket(t2); assertThat(ticket.getSubject(), is(t.getSubject())); assertThat(ticket.getRequester(), nullValue()); assertThat(ticket.getRequesterId(), notNullValue()); assertThat(ticket.getDescription(), is(t.getComment().getBody())); assertThat(instance.getTicket(ticket.getId()), notNullValue()); firstId = Math.min(ticket.getId(), firstId); } while (ticket.getId() < firstId + 200L); // seed enough data for the paging tests } @Test public void lookupUserByEmail() throws Exception { createClientWithTokenOrPassword(); String requesterEmail = config.getProperty("requester.email"); assumeThat("Must have a requester email", requesterEmail, notNullValue()); for (User user : instance.lookupUserByEmail(requesterEmail)) { assertThat(user.getEmail(), is(requesterEmail)); } } @Test public void searchUserByEmail() throws Exception { createClientWithTokenOrPassword(); String requesterEmail = config.getProperty("requester.email"); assumeThat("Must have a requester email", requesterEmail, notNullValue()); for (User user : instance.getSearchResults(User.class, "requester:"+requesterEmail)) { assertThat(user.getEmail(), is(requesterEmail)); } } @Test public void lookupUserIdentities() throws Exception { createClientWithTokenOrPassword(); User user = instance.getCurrentUser(); for (Identity i : instance.getUserIdentities(user)) { assertThat(i.getId(), notNullValue()); Identity j = instance.getUserIdentity(user, i); assertThat(j.getId(), is(i.getId())); assertThat(j.getType(), is(i.getType())); assertThat(j.getValue(), is(i.getValue())); } } @Test @Ignore("Failing and I don't know why") // TODO: Fix this test public void updateUserIdentity() throws Exception { createClientWithTokenOrPassword(); User user = instance.getCurrentUser(); Identity identity = new Identity(); identity.setUserId(user.getId()); identity.setType("email"); identity.setValue("first@test.com"); Identity createdIdentity = instance.createUserIdentity(user, identity); try { assertThat(createdIdentity.getValue(), is("first@test.com")); createdIdentity.setValue("second@test.com"); Identity updatedIdentity = instance.updateUserIdentity(user, createdIdentity); assertThat(updatedIdentity.getValue(), is("second@test.com")); } finally { if (createdIdentity != null) { instance.deleteUserIdentity(user, createdIdentity.getId()); } } } @Test public void getUserRequests() throws Exception { createClientWithTokenOrPassword(); User user = instance.getCurrentUser(); int count = 5; for (Request r : instance.getUserRequests(user)) { assertThat(r.getId(), notNullValue()); for (Comment c : instance.getRequestComments(r)) { assertThat(c.getId(), notNullValue()); } if (--count < 0) { break; } } } @Test public void getUsers() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (User u : instance.getUsers()) { assertThat(u.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void getUsersIncrementally() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (User u : instance.getUsersIncrementally(new Date(0L))) { assertThat(u.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void getSuspendedTickets() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (SuspendedTicket ticket : instance.getSuspendedTickets()) { assertThat(ticket.getId(), notNullValue()); if (++count > 10) { break; } } } @Test public void getOrganizations() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Organization t : instance.getOrganizations()) { assertThat(t.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void getOrganizationsIncrementally() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Organization t : instance.getOrganizationsIncrementally(new Date(0L))) { assertThat(t.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void createOrganization() throws Exception { createClientWithTokenOrPassword(); // Clean up to avoid conflicts for (Organization t : instance.getOrganizations()) { if ("testorg".equals(t.getExternalId())) { instance.deleteOrganization(t); } } Organization org = new Organization(); org.setExternalId("testorg"); org.setName("Test Organization"); Organization result = instance.createOrganization(org); assertNotNull(result); assertNotNull(result.getId()); assertEquals("Test Organization", result.getName()); assertEquals("testorg", result.getExternalId()); instance.deleteOrganization(result); } @Test(timeout = 10000) public void createOrganizations() throws Exception { createClientWithTokenOrPassword(); // Clean up to avoid conflicts for (Organization t : instance.getOrganizations()) { if ("testorg1".equals(t.getExternalId()) || "testorg2".equals(t.getExternalId())) { instance.deleteOrganization(t); } } Organization org1 = new Organization(); org1.setExternalId("testorg1"); org1.setName("Test Organization 1"); Organization org2 = new Organization(); org2.setExternalId("testorg2"); org2.setName("Test Organization 2"); JobStatus<Organization> result = instance.createOrganizations(org1, org2); assertNotNull(result); assertNotNull(result.getId()); assertNotNull(result.getStatus()); while (result.getStatus() != JobStatus.JobStatusEnum.completed) { result = instance.getJobStatus(result); assertNotNull(result); assertNotNull(result.getId()); assertNotNull(result.getStatus()); } List<Organization> resultOrgs = result.getResults(); assertEquals(2, resultOrgs.size()); for (Organization org : resultOrgs) { assertNotNull(org.getId()); instance.deleteOrganization(org); } } @Test(timeout = 10000) public void bulkCreateMultipleJobs() throws Exception { createClientWithTokenOrPassword(); List<Organization> orgs = new ArrayList<Organization>(4); for (int i = 1; i <= 5; i++) { Organization org = new Organization(); org.setExternalId("testorg" + i); org.setName("Test Organization " + i); orgs.add(org); } // Clean up to avoid conflicts for (Organization t : instance.getOrganizations()) { for (Organization org : orgs) { if (org.getExternalId().equals(t.getExternalId())) { instance.deleteOrganization(t); } } } JobStatus result1 = instance.createOrganizations(orgs.subList(0, 2)); JobStatus result2 = instance.createOrganizations(orgs.subList(2, 5)); while (result1.getStatus() != JobStatus.JobStatusEnum.completed || result2.getStatus() != JobStatus.JobStatusEnum.completed) { List<JobStatus<HashMap<String, Object>>> results = instance.getJobStatuses(Arrays.asList(result1, result2)); result1 = results.get(0); result2 = results.get(1); assertNotNull(result1); assertNotNull(result1.getId()); assertNotNull(result2); assertNotNull(result2.getId()); } List<HashMap> resultOrgs1 = result1.getResults(); assertEquals(2, resultOrgs1.size()); List<HashMap> resultOrgs2 = result2.getResults(); assertEquals(3, resultOrgs2.size()); for (HashMap org : resultOrgs1) { assertNotNull(org.get("id")); instance.deleteOrganization(((Number) org.get("id")).longValue()); } for (HashMap org : resultOrgs2) { assertNotNull(org.get("id")); instance.deleteOrganization(((Number) org.get("id")).longValue()); } } @Test public void getGroups() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Group t : instance.getGroups()) { assertThat(t.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void getArticles() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Article t : instance.getArticles()) { assertThat(t.getTitle(), notNullValue()); if (++count > 40) { // Check enough to pull 2 result pages break; } } } @Test public void getArticleSubscriptions() throws Exception { createClientWithTokenOrPassword(); int articleCount = 0; int subCount = 0; for (Article t : instance.getArticles()) { if (++articleCount > 50) { break; // Stop if we're not finding articles with subscriptions } for (Subscription sub : instance.getArticleSubscriptions(t.getId())) { assertThat(sub.getId(), notNullValue()); assertThat(sub.getUserId(), notNullValue()); assertThat(sub.getContentId(), notNullValue()); assertThat(sub.getCreatedAt(), notNullValue()); assertThat(sub.getUpdatedAt(), notNullValue()); if (++subCount > 10) { break; } } } } @Test public void getArticleTranslations() throws Exception { createClientWithTokenOrPassword(); int articleCount = 0; int translationCount = 0; // Count total translations checked, not per-article for (Article art : instance.getArticles()) { assertNotNull(art.getId()); if (++articleCount > 10) { break; // Do not overwhelm the getArticles API } for (Translation t : instance.getArticleTranslations(art.getId())) { assertNotNull(t.getId()); assertNotNull(t.getTitle()); assertNotNull(t.getBody()); if (++translationCount > 3) { return; } } } } @Test public void getSectionTranslations() throws Exception { createClientWithTokenOrPassword(); int sectionCount = 0; int translationCount = 0; for (Section sect : instance.getSections()) { assertNotNull(sect.getId()); if (++sectionCount > 10) { break; } for (Translation t : instance.getSectionTranslations(sect.getId())) { assertNotNull(t.getId()); assertNotNull(t.getTitle()); assertNotNull(t.getBody()); if (++translationCount > 3) { return; } } } } @Test public void getCategoryTranslations() throws Exception { createClientWithTokenOrPassword(); int categoryCount = 0; int translationCount = 0; for (Category cat : instance.getCategories()) { assertNotNull(cat.getId()); if (++categoryCount > 10) { break; } for (Translation t: instance.getCategoryTranslations(cat.getId())) { assertNotNull(t.getId()); assertNotNull(t.getTitle()); assertNotNull(t.getBody()); if (++translationCount > 3) { return; } } } } @Test public void getArticlesIncrementally() throws Exception { createClientWithTokenOrPassword(); final long ONE_WEEK = 7*24*60*60*1000; int count = 0; try { for (Article t : instance.getArticlesIncrementally(new Date(new Date().getTime() - ONE_WEEK))) { assertThat(t.getTitle(), notNullValue()); if (++count > 10) { break; } } } catch (ZendeskResponseException zre) { if (zre.getStatusCode() == 502) { // Ignore, this is an API limitation // A "Bad Gateway" response is returned if HelpCenter was not active at the given time } else { throw zre; } } } @Test public void getCategories() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Category cat : instance.getCategories()) { assertThat(cat.getName(), notNullValue()); if (++count > 10) { break; } } } @Test public void getSections() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Section s : instance.getSections()) { assertThat(s.getName(), notNullValue()); assertThat(s.getCategoryId(), notNullValue()); if (++count > 10) { break; } } } @Test public void getSectionSubscriptions() throws Exception { createClientWithTokenOrPassword(); int sectionCount = 0; int count = 0; for (Section s : instance.getSections()) { if (++sectionCount > 50) { break; // Stop if we're not finding sections with subscriptions } for (Subscription sub : instance.getSectionSubscriptions(s.getId())) { assertThat(sub.getId(), notNullValue()); assertThat(sub.getUserId(), notNullValue()); assertThat(sub.getContentId(), notNullValue()); assertThat(sub.getCreatedAt(), notNullValue()); assertThat(sub.getUpdatedAt(), notNullValue()); if (++count > 10) { break; } } } } @Test public void getSchedules() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (Schedule t : instance.getSchedules()) { assertThat(t.getId(), notNullValue()); assertThat(t.getName(), notNullValue()); assertThat(t.getCreatedAt(), notNullValue()); assertThat(t.getUpdatedAt(), notNullValue()); assertThat(t.getTimeZone(), notNullValue()); for (Interval i : t.getIntervals()) { assertThat(i.getStartTime(), notNullValue()); assertThat(i.getEndTime(), notNullValue()); } for (Holiday h : instance.getHolidaysForSchedule(t)) { assertThat(h.getId(), notNullValue()); assertThat(h.getName(), notNullValue()); assertThat(h.getStartDate(), notNullValue()); assertThat(h.getEndDate(), notNullValue()); } if (++count > 10) { break; } } } @Test @Ignore("Needs instance with custom agent roles") public void getCustomAgentRoles() throws Exception { createClientWithTokenOrPassword(); int count = 0; for (AgentRole role : instance.getCustomAgentRoles()) { assertThat(role.getId(), notNullValue()); assertThat(role.getName(), notNullValue()); assertThat(role.getCreatedAt(), notNullValue()); assertThat(role.getUpdatedAt(), notNullValue()); assertThat(role.getConfiguration(), notNullValue()); assertTrue(role.getConfiguration().containsKey("ticket_access")); if (++count > 10) { break; } } } @Test @Ignore("Failing and I don't know why - caching issue ?") // TODO: Fix this test public void createOrUpdateUser() throws Exception { createClientWithTokenOrPassword(); String name = "testCreateOrUpdateUser"; String externalId = "testCreateOrUpdateUser"; // Clean up to avoid conflicts for (User u: instance.lookupUserByExternalId(externalId)){ instance.deleteUser(u.getId()); } String phoneAtCreation = "5555551234"; User user = new User(true, name); user.setExternalId(externalId); user.setPhone(phoneAtCreation); User createResult = instance.createOrUpdateUser(user); assertNotNull(createResult); assertNotNull(createResult.getId()); assertEquals(name, createResult.getName()); assertEquals(externalId, createResult.getExternalId()); assertEquals(phoneAtCreation, createResult.getPhone()); String phoneAtUpdate = "5555551235"; User updateUser = new User(true, name); updateUser.setId(createResult.getId()); updateUser.setExternalId(externalId); updateUser.setPhone(phoneAtUpdate); User updateResult = instance.createOrUpdateUser(updateUser); assertNotNull(updateResult); assertEquals(createResult.getId(), updateResult.getId()); assertEquals(name, updateResult.getName()); assertEquals(externalId, updateResult.getExternalId()); assertEquals(phoneAtUpdate, updateResult.getPhone()); instance.deleteUser(updateResult); } }
package org.biojava.bio.seq; import java.util.*; import java.lang.reflect.*; import org.biojava.utils.*; import org.biojava.utils.bytecode.*; import org.biojava.bio.*; import org.biojava.bio.seq.impl.*; import org.biojava.bio.seq.projection.*; import org.biojava.bio.symbol.*; import org.biojava.bio.program.das.*; /** * Helper class for projecting Feature objects into an alternative * coordinate system. This class offers a view onto a set of features, * projecting them into a different coordinate system, and also changing * their <code>parent</code> property. The destination coordinate system * can run in the opposite direction from the source, in which case the * <code>strand</code> property of StrandedFeatures is flipped. * * <p> * The projected features returned by this class are small proxy objects. * Proxy classes are autogenerated on demand for any sub-interface of * <code>Feature</code>. These <code>getLocation</code>, <code>getParent</code>, * <code>getSequence</code> and (where applicable) <code>getStrand</code> methods * of projected features may return different values from the underlying * feature. All other methods are proxied directly. * </p> * * <p> * Originally, <code>ProjectedFeatureHolder</code> was a self-contained * class containing the full projection infrastructure. Since BioJava * 1.2, most of the projection infrastructure has been moved to separate * classes in the package <code>org.biojava.bio.seq.projection</code>. * Custom applications may wish to use that code directly. * </p> * * @author Thomas Down * @author Matthew Pocock * @since 1.1 */ public class ProjectedFeatureHolder extends AbstractFeatureHolder { private final FeatureHolder wrapped; private final FeatureHolder parent; private final int translate; private FeatureHolder projectedFeatures; private boolean oppositeStrand; private boolean cachingProjections = true; private FeatureFilter filter; private ChangeListener underlyingFeaturesChange; private PFHContext projectionContext; private static Location extractInterestingLocation(FeatureFilter ff) { if (ff instanceof FeatureFilter.OverlapsLocation) { return ((FeatureFilter.OverlapsLocation) ff).getLocation(); } else if (ff instanceof FeatureFilter.ContainedByLocation) { return ((FeatureFilter.ContainedByLocation) ff).getLocation(); } else if (ff instanceof FeatureFilter.And) { FeatureFilter.And ffa = (FeatureFilter.And) ff; Location l1 = extractInterestingLocation(ffa.getChild1()); Location l2 = extractInterestingLocation(ffa.getChild2()); if (l1 != null) { if (l2 != null) { return LocationTools.intersection(l1,l2); } else { return l1; } } else { if (l2 != null) { return l2; } else { return null; } } } // Don't know how this filter relates to location. return null; } public static FeatureHolder projectFeatureHolder(FeatureHolder fh, FeatureHolder parent, int translation, boolean flip) { if (fh instanceof DASOptimizableFeatureHolder) { return new ProjectedOptimizedFeatureHolder((DASOptimizableFeatureHolder) fh, parent, translation, flip); } else { return new ProjectedFeatureHolder(fh, parent, translation, flip); } } /** * Construct a new FeatureHolder which projects a set of features * into a new coordinate system. If <code>translation</code> is 0 * and <code>oppositeStrand</code> is <code>false</code>, the features * are simply reparented without any transformation. * * @param fh The set of features to project. * @param filter A FeatureFilter to apply to the set of features before projection. * @param parent The FeatureHolder which is to act as parent * for the projected features. * @param translation The translation to apply to map locations into * the projected coordinate system. This is the point * in the destination coordinate system which is equivalent * to 0 in the source coordinate system. * @param oppositeStrand <code>true</code> if translating into the opposite coordinate system. * This alters the transformation applied to locations, and also flips * the <code>strand</code> property of StrandedFeatures. */ public ProjectedFeatureHolder(FeatureHolder fh, FeatureFilter filter, FeatureHolder parent, int translation, boolean oppositeStrand) { this.wrapped = fh; this.parent = parent; this.translate = translation; this.oppositeStrand = oppositeStrand; this.filter = filter; this.projectionContext = new PFHContext(); underlyingFeaturesChange = new ChangeListener() { public void preChange(ChangeEvent e) throws ChangeVetoException { if (changeSupport != null) { changeSupport.firePreChangeEvent(new ChangeEvent(this, FeatureHolder.FEATURES, e.getChange(), e.getPrevious(), e)); } } public void postChange(ChangeEvent e) { projectedFeatures = null; // Flush all the cached projections -- // who knows what might have changed. if (changeSupport != null) { changeSupport.firePostChangeEvent(new ChangeEvent(this, FeatureHolder.FEATURES, e.getChange(), e.getPrevious(), e)); } } } ; wrapped.addChangeListener(underlyingFeaturesChange); } public boolean isCachingProjections() { return cachingProjections; } /** * Determine whether or not the projected features should be cached. * This is a temporary optimization, and might go away once feature * filtering is more intelligent. * * @since 1.2 */ public void setIsCachingProjections(boolean b) { cachingProjections = b; projectedFeatures = null; } /** * Construct a new FeatureHolder which projects a set of features * into a new coordinate system. If <code>translation</code> is 0 * and <code>oppositeStrand</code> is <code>false</code>, the features * are simply reparented without any transformation. * * @param fh The set of features to project. * @param parent The FeatureHolder which is to act as parent * for the projected features. * @param translation The translation to apply to map locations into * the projected coordinate system. This is the point * in the destination coordinate system which is equivalent * to 0 in the source coordinate system. * @param oppositeStrand <code>true</code> if translating into the opposite coordinate system. * This alters the transformation applied to locations, and also flips * the <code>strand</code> property of StrandedFeatures. */ public ProjectedFeatureHolder(FeatureHolder fh, FeatureHolder parent, int translation, boolean oppositeStrand) { this(fh, null, parent, translation, oppositeStrand); } protected FeatureHolder getProjectedFeatures() { if (projectedFeatures != null) { return projectedFeatures; } FeatureHolder toProject = wrapped; if (filter != null) { toProject = toProject.filter(filter, false); } SimpleFeatureHolder sfh = new SimpleFeatureHolder(); for (Iterator i = toProject.features(); i.hasNext(); ) { Feature f = (Feature) i.next(); Feature wf = ProjectionEngine.DEFAULT.projectFeature(f, projectionContext); try { sfh.addFeature(wf); } catch (ChangeVetoException cve) { throw new BioError( cve, "Assertion failure: Should be able to manipulate this FeatureHolder" ); } } if (cachingProjections) { projectedFeatures = sfh; } return sfh; } public int countFeatures() { if (filter != null) { return getProjectedFeatures().countFeatures(); } else { return wrapped.countFeatures(); } } public Iterator features() { return getProjectedFeatures().features(); } public boolean containsFeature(Feature f) { return getProjectedFeatures().containsFeature(f); } public FeatureHolder filter(FeatureFilter ff, boolean recurse) { return getProjectedFeatures().filter(ff, recurse); } public Feature projectFeature(Feature f){ return ProjectionEngine.DEFAULT.projectFeature(f, projectionContext); } public Location getProjectedLocation(Location oldLoc) { if (oppositeStrand) { if (oldLoc.isContiguous()) { if (oldLoc instanceof PointLocation){ return new PointLocation(translate - oldLoc.getMin()); } else { return new RangeLocation(translate - oldLoc.getMax(), translate - oldLoc.getMin()); } } else { Location compound = Location.empty; Vector locList = new Vector(); for (Iterator i = oldLoc.blockIterator(); i.hasNext(); ) { Location oldBlock = (Location) i.next(); locList.addElement(new RangeLocation(translate - oldBlock.getMax(), translate - oldBlock.getMin())); } compound = LocationTools.union(locList); return compound; } } else { return oldLoc.translate(translate); } } public int getTranslation() { return translate; } public boolean isOppositeStrand() { return oppositeStrand; } public FeatureHolder getParent() { return parent; } public StrandedFeature.Strand getProjectedStrand(StrandedFeature.Strand s) { if (isOppositeStrand()) { if (s == StrandedFeature.POSITIVE) { return StrandedFeature.NEGATIVE; } else if (s == StrandedFeature.NEGATIVE) { return StrandedFeature.POSITIVE; } else { return StrandedFeature.UNKNOWN; } } else { return s; } } /** * ProjectionContext implementation tied to a given ProjectedFeatureHolder */ private class PFHContext implements ProjectionContext { public FeatureHolder getParent(Feature f) { return parent; } public Sequence getSequence(Feature f) { FeatureHolder fh = parent; while (fh instanceof Feature) { fh = ((Feature) fh).getParent(); } return (Sequence) fh; } public Location getLocation(Feature f) { Location oldLoc = f.getLocation(); if (oppositeStrand) { if (oldLoc.isContiguous()) { if (oldLoc instanceof PointLocation){ return new PointLocation(translate - oldLoc.getMin()); } else { return new RangeLocation(translate - oldLoc.getMax(), translate - oldLoc.getMin()); } } else { Location compound = Location.empty; Vector locList = new Vector(); for (Iterator i = oldLoc.blockIterator(); i.hasNext(); ) { Location oldBlock = (Location) i.next(); locList.addElement(new RangeLocation(translate - oldBlock.getMax(), translate - oldBlock.getMin())); } compound = LocationTools.union(locList); return compound; } } else { return oldLoc.translate(translate); } } public StrandedFeature.Strand getStrand(StrandedFeature sf) { if (isOppositeStrand()) { StrandedFeature.Strand s = sf.getStrand(); if (s == StrandedFeature.POSITIVE) { return StrandedFeature.NEGATIVE; } else if (s == StrandedFeature.NEGATIVE) { return StrandedFeature.POSITIVE; } else { return StrandedFeature.UNKNOWN; } } else { return sf.getStrand(); } } public Annotation getAnnotation(Feature f) { return f.getAnnotation(); } public FeatureHolder projectChildFeatures(Feature f, FeatureHolder parent) { return projectFeatureHolder(f, parent, getTranslation(), isOppositeStrand()); } public Feature createFeature(Feature f, Feature.Template templ) throws ChangeVetoException { throw new ChangeVetoException("Can't create features in this projection"); } public void removeFeature(Feature f, Feature f2) throws ChangeVetoException { throw new ChangeVetoException("Can't create features in this projection"); } } private static class ProjectedOptimizedFeatureHolder extends AbstractFeatureHolder implements DASOptimizableFeatureHolder { private final DASOptimizableFeatureHolder wrapped; private final FeatureHolder parent; private final int translate; private boolean oppositeStrand; private MergeFeatureHolder mfh = null; private ChangeListener underlyingFeaturesChange; public ProjectedOptimizedFeatureHolder(DASOptimizableFeatureHolder fh, FeatureHolder parent, int translation, boolean oppositeStrand) { this.wrapped = fh; this.parent = parent; this.translate = translation; this.oppositeStrand = oppositeStrand; underlyingFeaturesChange = new ChangeListener() { public void preChange(ChangeEvent e) throws ChangeVetoException { if (changeSupport != null) { changeSupport.firePreChangeEvent(new ChangeEvent(this, FeatureHolder.FEATURES, e.getChange(), e.getPrevious(), e)); } } public void postChange(ChangeEvent e) { mfh = null; // Flush all the cached projections -- // who knows what might have changed. if (changeSupport != null) { changeSupport.firePostChangeEvent(new ChangeEvent(this, FeatureHolder.FEATURES, e.getChange(), e.getPrevious(), e)); } } } ; wrapped.addChangeListener(underlyingFeaturesChange, ChangeType.UNKNOWN); } protected MergeFeatureHolder getProjectedFeatures() { if (mfh == null) { try { Set optimizableFilters = wrapped.getOptimizableFilters(); mfh = new MergeFeatureHolder(); for (Iterator i = optimizableFilters.iterator(); i.hasNext(); ) { FeatureFilter potFilter = (FeatureFilter) i.next(); FeatureHolder potHolder = wrapped.getOptimizedSubset(potFilter); FeatureFilter projectedPotFilter = potFilter; // System.err.println("projecting for: " + potFilter); if (extractInterestingLocation(projectedPotFilter) != null) { if (projectedPotFilter instanceof FeatureFilter.ContainedByLocation) { if (oppositeStrand) { System.err.println("*** Warning: flipped projection, can't fixup!"); projectedPotFilter = FeatureFilter.all; } else { Location loc = ((FeatureFilter.ContainedByLocation) projectedPotFilter).getLocation(); projectedPotFilter = new FeatureFilter.ContainedByLocation(loc.translate(translate)); } } else { System.err.println("*** Warning: complex location-filter, can't fixup!"); projectedPotFilter = FeatureFilter.all; } } FeatureHolder projectedPotHolder = projectFeatureHolder(potHolder, parent, translate, oppositeStrand); mfh.addFeatureHolder(projectedPotHolder, projectedPotFilter); } } catch (BioException bex) { throw new BioRuntimeException(bex); } catch (ChangeVetoException cve) { throw new BioError(cve, "Change to internal featureset vetoed!"); } } return mfh; } public int countFeatures() { return wrapped.countFeatures(); } public Iterator features() { return getProjectedFeatures().features(); } public boolean containsFeature(Feature f) { return getProjectedFeatures().containsFeature(f); } public FeatureHolder filter(FeatureFilter ff, boolean recurse) { return getProjectedFeatures().filter(ff, recurse); } public Set getOptimizableFilters() { Map mm = getProjectedFeatures().getMergeMap(); Set osf = new HashSet(); for (Iterator i = mm.values().iterator(); i.hasNext(); ) { osf.add(i.next()); } return osf; } public FeatureHolder getOptimizedSubset(FeatureFilter ff) throws BioException { List ss = new ArrayList(); Map mm = getProjectedFeatures().getMergeMap(); for (Iterator i = mm.entrySet().iterator(); i.hasNext(); ) { Map.Entry me = (Map.Entry) i.next(); FeatureHolder fh = (FeatureHolder) me.getKey(); FeatureFilter tff = (FeatureFilter) me.getValue(); if (tff.equals(ff)) { ss.add(fh); } } if (ss.size() == 0) { throw new BioException("No optimized subset matching: " + ff); } else if (ss.size() == 1) { return (FeatureHolder) ss.get(0); } else { MergeFeatureHolder mfh = new MergeFeatureHolder(); for (Iterator i = ss.iterator(); i.hasNext(); ) { try { mfh.addFeatureHolder((FeatureHolder) i.next()); } catch (ChangeVetoException cve) { throw new BioError(cve, "Change to internal featureset vetoed!"); } } return mfh; } } } }
package com.twilio.twiliochat; public class ApplicationTest { }
package coolsquid.react.base; import static coolsquid.react.api.event.EventManager.registerEvent; import static coolsquid.react.api.event.EventManager.registerVariable; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.stats.StatList; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderLivingEvent; import net.minecraftforge.client.event.RenderPlayerEvent; import net.minecraftforge.client.event.RenderSpecificHandEvent; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.EntityMountEvent; import net.minecraftforge.event.entity.EntityTravelToDimensionEvent; import net.minecraftforge.event.entity.living.AnimalTameEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.living.LivingHealEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.LivingSpawnEvent; import net.minecraftforge.event.entity.player.FillBucketEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent; import net.minecraftforge.event.terraingen.SaplingGrowTreeEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.CropGrowEvent; import net.minecraftforge.event.world.ExplosionEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import coolsquid.react.util.BlockWrapper; import com.google.common.collect.Lists; public class Events { public static void register() { registerEvent("server_chat", ServerChatEvent.class); registerVariable(ServerChatEvent.class, "mob", (event) -> event.getPlayer()); registerVariable(ServerChatEvent.class, "world", (event) -> event.getPlayer().world); registerVariable(ServerChatEvent.class, "message", (event) -> event.getMessage()); registerVariable(ServerChatEvent.class, "sender", (event) -> event.getPlayer()); registerEvent("client_chat", ClientChatReceivedEvent.class); registerVariable(ClientChatReceivedEvent.class, "message", (event) -> event.getMessage().getUnformattedText()); registerVariable(EntityEvent.class, "mob", (event) -> event.getEntity() instanceof EntityLivingBase ? event.getEntity() : null); registerVariable(EntityEvent.class, "world", (event) -> event.getEntity().world); registerEvent("mob_hurt", LivingHurtEvent.class); registerEvent("mob_attacked", LivingAttackEvent.class); registerEvent("mob_death", LivingDeathEvent.class); registerVariable(LivingHurtEvent.class, "attacker", (event) -> event.getSource().getTrueSource()); registerVariable(LivingAttackEvent.class, "attacker", (event) -> event.getSource().getTrueSource()); registerVariable(LivingDeathEvent.class, "attacker", (event) -> event.getSource().getTrueSource()); registerEvent("animal_tame", AnimalTameEvent.class); registerVariable(AnimalTameEvent.class, "tamer", (event) -> event.getTamer()); registerEvent("mob_fall", LivingFallEvent.class); registerEvent("mob_heal", LivingHealEvent.class); registerEvent("mob_jump", LivingJumpEvent.class); registerEvent("mob_mount", EntityMountEvent.class, (event) -> event.isMounting()); registerEvent("mob_dismount", EntityMountEvent.class, (event) -> event.isDismounting()); registerVariable(EntityMountEvent.class, "mounted_mob", (event) -> event.getEntityBeingMounted()); registerEvent("mob_spawn", LivingSpawnEvent.SpecialSpawn.class); registerEvent("mob_update", LivingUpdateEvent.class); registerVariable(net.minecraftforge.fml.common.gameevent.PlayerEvent.class, "mob", (event) -> event.player); registerVariable(net.minecraftforge.fml.common.gameevent.PlayerEvent.class, "player", (event) -> event.player); registerVariable(net.minecraftforge.fml.common.gameevent.PlayerEvent.class, "world", (event) -> event.player.world); registerEvent("player_log_in", PlayerLoggedInEvent.class); registerEvent("player_log_out", PlayerLoggedOutEvent.class); registerEvent("player_respawn", PlayerRespawnEvent.class, (event) -> !event.isEndConquered()); registerEvent("interact_with_entity", PlayerInteractEvent.EntityInteractSpecific.class); registerVariable(PlayerInteractEvent.EntityInteractSpecific.class, "interaction_target", (event) -> event.getTarget()); registerEvent("left_click_block", PlayerInteractEvent.LeftClickBlock.class); registerEvent("right_click_block", PlayerInteractEvent.RightClickBlock.class); registerEvent("right_click_item", PlayerInteractEvent.RightClickItem.class); registerVariable(EntityJoinWorldEvent.class, "mob", (event) -> { if (event.getEntity() instanceof EntityLivingBase) { return event.getEntity(); } return null; }); registerVariable(EntityJoinWorldEvent.class, "player", (event) -> { if (event.getEntity() instanceof EntityPlayer) { return event.getEntity(); } return null; }); registerVariable(EntityJoinWorldEvent.class, "world", (event) -> event.getEntity().world); registerEvent("player_spawn", PlayerLoggedInEvent.class, (event) -> FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList() .getPlayerStatsFile(event.player).readStat(StatList.LEAVE_GAME) == 0); registerEvent("player_wake_up", PlayerWakeUpEvent.class); registerEvent("player_sleep", PlayerSleepInBedEvent.class); registerVariable(PlayerSleepInBedEvent.class, "block", (event) -> new BlockWrapper(event.getEntityPlayer().world.getBlockState(event.getPos()), event.getPos())); registerEvent("fill_bucket", FillBucketEvent.class); registerEvent("render_player", RenderPlayerEvent.Pre.class, Side.CLIENT); registerEvent("render_hand", RenderSpecificHandEvent.class, Side.CLIENT); registerVariable(RenderSpecificHandEvent.class, "hand", (event) -> event.getHand()); registerEvent("render_mob", RenderLivingEvent.Pre.class, (event) -> !(event.getEntity() instanceof EntityPlayer), Side.CLIENT); registerVariable(RenderLivingEvent.class, "mob", (event) -> event.getEntity()); registerVariable(RenderLivingEvent.class, "world", (event) -> event.getEntity().world); registerVariable(LivingHurtEvent.class, "damage_amount", (event) -> event.getAmount()); registerVariable(LivingAttackEvent.class, "damage_amount", (event) -> event.getAmount()); registerVariable(LivingHurtEvent.class, "damage_source", (event) -> event.getSource()); registerVariable(LivingAttackEvent.class, "damage_source", (event) -> event.getSource()); registerVariable(LivingDeathEvent.class, "damage_source", (event) -> event.getSource()); registerEvent("command", CommandEvent.class); registerVariable(CommandEvent.class, "command", (event) -> event.getCommand()); registerVariable(CommandEvent.class, "command_arguments", (event) -> event.getParameters()); registerVariable(CommandEvent.class, "sender", (event) -> event.getSender()); registerVariable(CommandEvent.class, "world", (event) -> event.getSender().getEntityWorld()); registerEvent("dimension_travel", EntityTravelToDimensionEvent.class); registerVariable(EntityTravelToDimensionEvent.class, "target_dimension", (event) -> DimensionManager.getWorld(event.getDimension())); registerVariable(WorldEvent.class, "world", (event) -> event.getWorld()); registerEvent("sapling_grow", SaplingGrowTreeEvent.class); //registerVariable(SaplingGrowTreeEvent.class, "block", // (event) -> event.getWorld().getBlockState(event.getPos())); registerVariable(SaplingGrowTreeEvent.class, "block", (event) -> new BlockWrapper(event.getWorld().getBlockState(event.getPos()), event.getPos())); registerVariable(BlockEvent.class, "world", (event) -> event.getWorld()); //registerVariable(BlockEvent.class, "block", (event) -> event.getState()); registerVariable(BlockEvent.class, "block", (event) -> new BlockWrapper(event.getState(), event.getPos())); registerVariable(BlockEvent.BreakEvent.class, "mob", (event) -> event.getPlayer()); registerVariable(BlockEvent.PlaceEvent.class, "mob", (event) -> event.getPlayer()); registerEvent("block_break", BlockEvent.BreakEvent.class); registerEvent("block_place", BlockEvent.PlaceEvent.class); registerEvent("crop_grow", CropGrowEvent.Pre.class); registerVariable(TickEvent.WorldTickEvent.class, "world", (event) -> event.world); registerEvent("world_tick", TickEvent.WorldTickEvent.class); registerEvent("pre_explosion", ExplosionEvent.Start.class); registerVariable(ExplosionEvent.class, "world", (event) -> event.getWorld()); registerVariable(ExplosionEvent.class, "explosion", (event) -> event.getExplosion()); registerVariable(ExplosionEvent.class, "exploder", (event) -> event.getExplosion().getExplosivePlacedBy()); registerEvent("explosion", ExplosionEvent.Detonate.class); registerVariable(ExplosionEvent.Detonate.class, "exploding_blocks", (event) -> { List<String> list = Lists.transform(event.getAffectedBlocks(), (e) -> { Block block = event.getWorld().getBlockState(e).getBlock(); if (block == Blocks.AIR) { return null; } return "[" + block.getRegistryName().toString() + " at " + String.valueOf(e.getX()) + "," + String.valueOf(e.getY()) + "," + String.valueOf(e.getZ()) + "]"; }); list.removeIf((e) -> e == null); return list; }); registerVariable(ExplosionEvent.Detonate.class, "exploding_mobs", (event) -> { List<String> list = Lists.transform(event.getAffectedEntities(), (e) -> { if (e instanceof EntityLivingBase) { return "[" + e.getName() + " at " + String.valueOf(e.posX) + "," + String.valueOf(e.posY) + "," + String.valueOf(e.posZ) + "]"; } return null; }); list.removeIf((e) -> e == null); return list; }); } }
package com.deftech.viewtils.helpers; import android.app.Dialog; import android.view.ViewGroup; /*** * Helps interact with an {@link android.app.Dialog}. When * searching for a view, it starts at the view returned * by {@code dialog.findViewById(android.R.id.content)} * @see com.deftech.viewtils.helpers.ViewGroupHelper */ public class DialogHelper extends ViewGroupHelper { private final Dialog dialog; /*** * Create a new instance to help interact with the * provided {@link android.app.Activity} * @param instance Activity to be used for carrying out operations */ DialogHelper(Dialog instance) { super((ViewGroup)instance.findViewById(android.R.id.content)); this.dialog = instance; } }
package store.common; import static com.google.common.base.Objects.toStringHelper; import java.util.Map; import static java.util.Objects.hash; import store.common.value.Value; /** * Aggregates various info about a replication. If replication is not started, only its source and destination * definitions will be available. */ public final class ReplicationInfo implements Mappable { private static final String SOURCE_DEF = "sourceDef"; private static final String DESTINATION_DEF = "destinationdef"; private static final String AGENT_INFO = "agentInfo"; private static final String SOURCE = "source"; private static final String DESTINATION = "destination"; private static final String STARTED = "started"; private static final String AGENT = "agent"; private final RepositoryDef sourceDef; private final RepositoryDef destinationdef; private final AgentInfo agentInfo; /** * Constructor for an started replication. * * @param sourceDef Source repository definition. * @param destinationdef Destination repository definition. * @param agentInfo Replication agent info. */ public ReplicationInfo(RepositoryDef sourceDef, RepositoryDef destinationdef, AgentInfo agentInfo) { this.sourceDef = sourceDef; this.destinationdef = destinationdef; this.agentInfo = agentInfo; } /** * Constructor for a stopped replication. * * @param sourceDef Source repository definition. * @param destinationdef Destination repository definition. */ public ReplicationInfo(RepositoryDef sourceDef, RepositoryDef destinationdef) { this(sourceDef, destinationdef, null); } /** * @return If this replication is started. */ public boolean isStarted() { return agentInfo != null; } /** * @return The source repository definition. */ public RepositoryDef getSourceDef() { return sourceDef; } /** * @return The destination repository definition. */ public RepositoryDef getDestinationdef() { return destinationdef; } /** * @return The replication agent info. Fails if replication is not started. */ public AgentInfo getAgentInfo() { if (!isStarted()) { throw new IllegalStateException(); } return agentInfo; } @Override public Map<String, Value> toMap() { MapBuilder builder = new MapBuilder() .put(SOURCE, sourceDef.toMap()) .put(DESTINATION, destinationdef.toMap()) .put(STARTED, isStarted()); if (isStarted()) { builder.put(AGENT, agentInfo.toMap()); } return builder.build(); } /** * Read a new instance from supplied map of values. * * @param map A map of values. * @return A new instance. */ public static ReplicationInfo fromMap(Map<String, Value> map) { if (!map.get(STARTED).asBoolean()) { return new ReplicationInfo(RepositoryDef.fromMap(map.get(SOURCE).asMap()), RepositoryDef.fromMap(map.get(DESTINATION).asMap())); } return new ReplicationInfo(RepositoryDef.fromMap(map.get(SOURCE).asMap()), RepositoryDef.fromMap(map.get(DESTINATION).asMap()), AgentInfo.fromMap(map.get(AGENT).asMap())); } @Override public String toString() { return toStringHelper(this) .add(SOURCE_DEF, sourceDef) .add(DESTINATION_DEF, destinationdef) .add(AGENT_INFO, agentInfo) .toString(); } @Override public int hashCode() { return hash(sourceDef, destinationdef, agentInfo); } @Override public boolean equals(Object obj) { if (!(obj instanceof ReplicationInfo)) { return false; } ReplicationInfo other = (ReplicationInfo) obj; return new EqualsBuilder() .append(sourceDef, other.sourceDef) .append(destinationdef, other.destinationdef) .append(agentInfo, other.agentInfo) .build(); } }
package seedu.task.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import org.junit.Test; import seedu.task.logic.commandlibrary.CommandLibrary; import seedu.task.logic.commandlibrary.CommandLibrary.CommandInstance; import seedu.task.logic.commands.AddCommand; import seedu.task.logic.parser.AddCommandParser; public class CommandLibraryTest { private static HashMap<String, CommandInstance> hm = CommandLibrary.getInstance().getCommandTable(); @Test public void getHashTable() { assertNotNull(hm); } @Test public void getCommandFromTable() { assertEquals(CommandLibrary.getCommandTable().get("Add".toLowerCase()).getCommandParser().getClass(), AddCommandParser.class); assertEquals(CommandLibrary.getCommandTable().get("add").getCommandKey(), AddCommand.COMMAND_WORD_1); } }
package cat.xojan.random1.service; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; import android.util.Log; import com.crashlytics.android.Crashlytics; import java.io.IOException; import cat.xojan.random1.R; import cat.xojan.random1.commons.PlayerUtil; import cat.xojan.random1.domain.entity.Podcast; import cat.xojan.random1.ui.activity.RadioPlayerActivity; public class RadioPlayerService extends Service { public static final String TAG = RadioPlayerService.class.getSimpleName(); public static final String EXTRA_PODCAST = "extra_podcast"; private static final int NOTIFICATION_ID = 1; private MediaPlayer mMediaPlayer; private Handler mHandler; private IBinder mBinder; private Listener mListener; public void registerClient(Listener listener) { mListener = listener; } public boolean isPlaying() { return mMediaPlayer.isPlaying(); } public void pause() { mMediaPlayer.pause(); } public void start() { mMediaPlayer.start(); } public void removeCallbacks() { mHandler.removeCallbacks(mUpdateTimeTask); } public int getDuration() { return mMediaPlayer.getDuration(); } public void seekTo(int currentPosition) { mMediaPlayer.seekTo(currentPosition); } public class RadioPlayerServiceBinder extends Binder { public RadioPlayerService getServiceInstance(){ return RadioPlayerService.this; } } @Override public void onCreate() { // The service is being created mHandler = new Handler(); mBinder = new RadioPlayerServiceBinder(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (mListener == null || intent == null || !intent.hasExtra(EXTRA_PODCAST)) { stopSelf(); } Podcast podcast = intent.getParcelableExtra(EXTRA_PODCAST); Notification notification = getNotification(RadioPlayerActivity.class, podcast); startForeground(NOTIFICATION_ID, notification); startMediaPlayer(podcast.link()); return START_REDELIVER_INTENT; } protected Notification getNotification(Class clazz, Podcast podcast) { final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); builder.setSmallIcon(R.drawable.ic_podcast_notification) .setContentTitle(getApplicationContext().getString(R.string.app_name)) .setContentText(podcast.category() + " " + podcast.description()); Intent foregroundIntent = new Intent(getApplicationContext(), clazz); foregroundIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, foregroundIntent, 0); builder.setContentIntent(contentIntent); return builder.build(); } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder ; } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); stopMediaPlayer(); stopForeground(true); mListener = null; } @Override public void onTaskRemoved(Intent rootIntent) { if (mListener != null) { onUnbind(rootIntent); onDestroy(); } } /** * Update timer on seek bar. */ public void updateSeekBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } private void startMediaPlayer(String url) { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { Log.d(TAG, "setDataSource: " + url); mMediaPlayer.setDataSource(url); } catch (IOException e) { Crashlytics.logException(e); return; } mMediaPlayer.prepareAsync(); Log.d(TAG, "prepareAsync"); mMediaPlayer.setOnPreparedListener(new MediaPlayerPreparedListener()); mMediaPlayer.setOnBufferingUpdateListener(new BufferingUpdateListener()); mMediaPlayer.setOnCompletionListener(new MediaPlayerCompletionListener()); mMediaPlayer.setOnErrorListener(new MediaPlayerErrorListener()); } private void stopMediaPlayer() { Log.d(TAG, "stopMediaPlayer"); mMediaPlayer.stop(); mMediaPlayer.release(); mHandler.removeCallbacks(mUpdateTimeTask); } /** * Background Runnable thread. */ private Runnable mUpdateTimeTask = new Runnable() { public void run() { long totalDuration = mMediaPlayer.getDuration(); int currentDuration = mMediaPlayer.getCurrentPosition(); int progress = PlayerUtil.getProgressPercentage(currentDuration, totalDuration); mListener.progressUpdate(progress, currentDuration); // Running this thread after 100 milliseconds mHandler.postDelayed(this, 100); } }; private class MediaPlayerPreparedListener implements MediaPlayer.OnPreparedListener { @Override public void onPrepared(MediaPlayer mp) { Log.d(TAG, "onPrepared"); if (mListener == null) { stopSelf(); } else { mListener.onPrepared(mMediaPlayer.getDuration()); mMediaPlayer.start(); updateSeekBar(); } } } private class BufferingUpdateListener implements MediaPlayer.OnBufferingUpdateListener { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mListener.updateBufferProgress(percent); } } } private class MediaPlayerCompletionListener implements MediaPlayer.OnCompletionListener { @Override public void onCompletion(MediaPlayer mp) { mListener.updateButton(R.drawable.ic_play_arrow); mMediaPlayer.seekTo(0); } } public interface Listener { void onPrepared(int duration); void progressUpdate(int progress, int currentDuration); void updateBufferProgress(int percent); void updateButton(int ic_play_arrow); } private class MediaPlayerErrorListener implements MediaPlayer.OnErrorListener { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Crashlytics.log("Media player error listener: " + what + ", " + extra); Log.e(TAG, "Media player error listener: " + what + ", " + extra); return false; } } }
package de.berlin.hu.util; public class Constants { public static enum ChemicalID {CHID, CHEB, CAS, PUBC, PUBS, INCH, DRUG, HMBD, KEGG, KEGD, MESH, FDA, FDA_DATE}; public static enum ChemicalType {SYSTEMATIC, IDENTIFIER, FORMULA, TRIVIAL, ABBREVIATION, FAMILY, MULTIPLE, UNKNOWN; public static ChemicalType fromString(String s) { if (s == null) { return UNKNOWN; } else { s = s.trim(); } if (ABBREV.equals(s)) { return ABBREVIATION; } else if (CRF.equals(s) || s.toLowerCase().contains("iupac")) { return SYSTEMATIC; } else if (DICTIONARY.equals(s)) { return SYSTEMATIC; } else if (SUM_TAGGER.equals(s) || "sum".equalsIgnoreCase(s)) { return FORMULA; } try { return ChemicalType.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { return UNKNOWN; } } }; public static final String ABBREV = "ABBREV"; public static final String CRF = "crf"; public static final String DICTIONARY = "dictionary"; public static final String SUM_TAGGER = "sum_tagger"; public static final String DRUG = "drug tagger"; public static final String GOLDSTANDARD = "goldstandard"; public static final String UNKNOWN = "unknown"; }
package cn.ian2018.whattoeat.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import cn.ian2018.whattoeat.MyApplication; import cn.ian2018.whattoeat.R; import cn.ian2018.whattoeat.bean.Shop; public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { private List<Shop> mShopList; private OnRecyclerViewOnClickListener mListener; static class ViewHolder extends RecyclerView.ViewHolder { View shopView; ImageView shopImage; TextView shopNameText; TextView shopPhoneText; TextView shopLocText; public ViewHolder(View itemView) { super(itemView); shopView = itemView; shopImage = (ImageView) itemView.findViewById(R.id.shop_image); shopNameText = (TextView) itemView.findViewById(R.id.shop_name); shopPhoneText = (TextView) itemView.findViewById(R.id.shop_phone); shopLocText = (TextView) itemView.findViewById(R.id.shop_loction); } } /** * item */ public interface OnRecyclerViewOnClickListener { void onItemClick(View view, int position); } public void setItemClickListener(OnRecyclerViewOnClickListener listener){ this.mListener = listener; } public RecyclerAdapter(List<Shop> fruitList) { mShopList = fruitList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false); final ViewHolder holder = new ViewHolder(view); holder.shopView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = holder.getAdapterPosition(); mListener.onItemClick(view, position); } }); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Shop shop = mShopList.get(position); Glide.with(MyApplication.getContext()).load(shop.getImageUrl()).placeholder(R.drawable.ic_placeholder).into(holder.shopImage); holder.shopNameText.setText(shop.getName()); holder.shopPhoneText.setText(shop.getPhone()); holder.shopLocText.setText(shop.getLocation()); } @Override public int getItemCount() { return mShopList.size(); } }
package uk.ac.ebi.subs.api; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.rest.webmvc.RestMediaTypes; import org.springframework.http.MediaType; import org.springframework.restdocs.JUnitRestDocumentation; import org.springframework.restdocs.hypermedia.LinkDescriptor; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer; import org.springframework.restdocs.operation.preprocess.ContentModifier; import org.springframework.restdocs.operation.preprocess.ContentModifyingOperationPreprocessor; import org.springframework.restdocs.payload.FieldDescriptor; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; import uk.ac.ebi.subs.ApiApplication; import uk.ac.ebi.subs.DocumentationProducer; import uk.ac.ebi.subs.api.handlers.SubmissionEventHandler; import uk.ac.ebi.subs.api.handlers.SubmissionStatusEventHandler; import uk.ac.ebi.subs.api.services.SubmissionEventService; import uk.ac.ebi.subs.data.component.Team; import uk.ac.ebi.subs.data.component.SampleRelationship; import uk.ac.ebi.subs.data.component.Submitter; import uk.ac.ebi.subs.repository.model.Sample; import uk.ac.ebi.subs.repository.model.Submission; import uk.ac.ebi.subs.repository.model.SubmissionStatus; import uk.ac.ebi.subs.repository.repos.SubmissionRepository; import uk.ac.ebi.subs.repository.repos.status.ProcessingStatusRepository; import uk.ac.ebi.subs.repository.repos.status.SubmissionStatusRepository; import uk.ac.ebi.subs.repository.repos.submittables.SampleRepository; import java.io.IOException; import java.io.UncheckedIOException; import java.text.SimpleDateFormat; import java.util.*; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes = ApiApplication.class) @Category(DocumentationProducer.class) public class ApiDocumentation { private static final String HOST = "submission-dev.ebi.ac.uk"; private static final String SCHEME = "http"; @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("build/generated-snippets"); @Autowired private SubmissionRepository submissionRepository; @Autowired private SubmissionStatusRepository submissionStatusRepository; @Autowired private SampleRepository sampleRepository; @Autowired private ProcessingStatusRepository processingStatusRepository; @Autowired private SubmissionEventHandler submissionEventHandler; @Autowired private SubmissionStatusEventHandler submissionStatusEventHandler; private ObjectMapper objectMapper; @Autowired private WebApplicationContext context; @MockBean private RabbitMessagingTemplate rabbitMessagingTemplate; private MockMvc mockMvc; private SubmissionEventService fakeSubmissionEventService = new SubmissionEventService() { @Override public void submissionCreated(Submission submission) { } @Override public void submissionUpdated(Submission submission) { } @Override public void submissionDeleted(Submission submission) { } @Override public void submissionSubmitted(Submission submission) { } }; @Before public void setUp() { objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); submissionEventHandler.setSubmissionEventService(fakeSubmissionEventService); submissionStatusEventHandler.setSubmissionEventService(fakeSubmissionEventService); clearDatabases(); MockMvcRestDocumentationConfigurer docConfig = documentationConfiguration(this.restDocumentation); docConfig.uris() .withScheme(SCHEME) .withHost(HOST) .withPort(80); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(docConfig) .build(); } private void clearDatabases() { this.submissionRepository.deleteAll(); this.sampleRepository.deleteAll(); this.submissionStatusRepository.deleteAll(); } @After public void tearDown() { clearDatabases(); } @Test public void invalidJson() throws Exception { this.mockMvc.perform( post("/api/submissions").content("Tyger Tyger, burning bright, In the forests of the night") .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isBadRequest()) .andDo( document("invalid-json", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(), responseFields( fieldWithPath("cause").description("Cause of the error"), fieldWithPath("message").description("Error message") ) ) ); } @Test public void jsonArrayInsteadOfObject() throws Exception { uk.ac.ebi.subs.data.Submission submission = goodClientSubmission(); String jsonRepresentation = objectMapper.writeValueAsString(Arrays.asList(submission, submission)); this.mockMvc.perform( post("/api/submissions").content(jsonRepresentation) .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isBadRequest()) .andDo( document("json-array-instead-of-object", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(), responseFields( fieldWithPath("cause").description("Cause of the error"), fieldWithPath("message").description("Error message") ) ) ); } private uk.ac.ebi.subs.data.Submission goodClientSubmission() { uk.ac.ebi.subs.data.Submission submission = new uk.ac.ebi.subs.data.Submission(); submission.setTeam(new Team()); submission.getTeam().setName("my-team"); submission.setSubmitter(new Submitter()); submission.getSubmitter().setEmail("alice@test.org"); return submission; } @Test public void invalidSubmission() throws Exception { uk.ac.ebi.subs.data.Submission submission = badClientSubmission(); String jsonRepresentation = objectMapper.writeValueAsString(submission); this.mockMvc.perform( post("/api/submissions").content(jsonRepresentation) .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isBadRequest()) .andDo( document("invalid-submission", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("errors").description("List of errors"), fieldWithPath("errors[0].entity").description("Type of the entity with the error"), fieldWithPath("errors[0].property").description("Path of the field with the error"), fieldWithPath("errors[0].invalidValue").description("Value of the field that has caused the error"), fieldWithPath("errors[0].message").description("Message describing the error") ) ) ); } @Test public void validSubmission() throws Exception { uk.ac.ebi.subs.data.Submission submission = goodClientSubmission(); String jsonRepresentation = objectMapper.writeValueAsString(submission); this.mockMvc.perform( post("/api/submissions").content(jsonRepresentation) .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isCreated()) .andDo( document("create-submission", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("_links").description("Links"), fieldWithPath("submitter").description("Submitter who is responsible for this submission"), fieldWithPath("team").description("Team this submission belongs to"), fieldWithPath("createdDate").description("Date this resource was created"), fieldWithPath("lastModifiedDate").description("Date this resource was modified"), fieldWithPath("createdBy").description("User who created this resource"), fieldWithPath("lastModifiedBy").description("User who last modified this resource") ), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("submission").description("This submission"), linkWithRel("self:update").description("This submission can be updated"), linkWithRel("self:delete").description("This submission can be deleted"), linkWithRel("team").description("The team this submission belongs to"), linkWithRel("analyses").description("Analyses within this submission"), linkWithRel("assays").description("Assays within this submission"), linkWithRel("assayData").description("Assay data within this submission"), linkWithRel("egaDacs").description("DACs within this submission"), linkWithRel("egaDacPolicies").description("DAC policies within this submission"), linkWithRel("egaDatasets").description("EGA datasets within this submission"), linkWithRel("projects").description("Projects within this submission"), linkWithRel("protocols").description("Protocols within this submission"), linkWithRel("samples").description("Samples within this submission"), linkWithRel("sampleGroups").description("Sample groups within this submission"), linkWithRel("studies").description("Studies within this submission"), linkWithRel("submissionStatus").description("Status of this submission"), linkWithRel("sampleGroups:create").description("This submission can accept new sample groups"), linkWithRel("analyses:create").description("This submission can accept new analyses"), linkWithRel("egaDatasets:create").description("This submission can accept new EGA datasets"), linkWithRel("projects:create").description("This submission can accept new projects"), linkWithRel("assays:create").description("This submission can accept new assays"), linkWithRel("protocols:create").description("This submission can accept new protocols"), linkWithRel("assayData:create").description("This submission can accept new assay data"), linkWithRel("egaDacs:create").description("This submission can accept new DACs"), linkWithRel("samples:create").description("This submission can accept new samples"), linkWithRel("egaDacPolicies:create").description("This submission can accept new DAC policies"), linkWithRel("studies:create").description("This submission can accept new studies"), linkWithRel("processingStatuses").description("All processing statuses for the contents of this submission"), linkWithRel("processingStatusSummary").description("Summary of processing statuses for this submission"), linkWithRel("typeProcessingStatusSummary").description("Summary of processing statuses per type, for this submission") ) ) ); SubmissionStatus status = submissionStatusRepository.findAll().get(0); Assert.notNull(status); this.mockMvc.perform( patch("/api/submissionStatuses/{id}",status.getId()).content("{\"status\": \"Submitted\"}") .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("patch-submission-status", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("_links").description("Links"), fieldWithPath("status").description("Current status value"), fieldWithPath("createdDate").description("Date this resource was created"), fieldWithPath("lastModifiedDate").description("Date this resource was modified"), fieldWithPath("createdBy").description("User who created this resource"), fieldWithPath("lastModifiedBy").description("User who last modified this resource") ), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("submissionStatus").description("This resource"), linkWithRel("statusDescription").description("Description of this status") ) ) ); } @Test public void createSample() throws Exception { Submission sub = storeSubmission(); uk.ac.ebi.subs.data.client.Sample sample = Helpers.generateTestClientSamples(1).get(0); sample.setSubmission(SCHEME+"://"+HOST+"/api/submissions/"+sub.getId()); String jsonRepresentation = objectMapper.writeValueAsString(sample); this.mockMvc.perform( post("/api/samples").content(jsonRepresentation) .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isCreated()) .andDo( document("create-sample", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("_links").description("Links"), fieldWithPath("alias").description("Unique name for the sample within the team"), fieldWithPath("title").description("Title for the sample"), fieldWithPath("description").description("Description for the sample"), fieldWithPath("attributes").description("A list of attributes for the sample"), fieldWithPath("sampleRelationships").description("Relationships to other samples"), fieldWithPath("taxonId").description("NCBI Taxon ID for this sample"), fieldWithPath("taxon").description("Scientific name for this taxon"), fieldWithPath("_embedded.submission").description("Submission that this sample is part of"), fieldWithPath("_embedded.processingStatus").description("Processing status for this sample."), fieldWithPath("team").description("Team this sample belongs to"), fieldWithPath("createdDate").description("Date this resource was created"), fieldWithPath("lastModifiedDate").description("Date this resource was modified"), fieldWithPath("createdBy").description("User who created this resource"), fieldWithPath("lastModifiedBy").description("User who last modified this resource") ), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("sample").description("This resource"), linkWithRel("self:update").description("This resource can be updated"), linkWithRel("self:delete").description("This resource can be deleted"), linkWithRel("submission").description("Submission that this sample is part of"), linkWithRel("processingStatus").description("Processing status for this sample"), linkWithRel("history").description("Collection of resources for samples with the same team and alias as this resource"), linkWithRel("current-version").description("Current version of this sample, as identified by team and alias") ) ) ); String sampleId = sampleRepository.findAll().get(0).getId(); SampleRelationship sampleRelationship = new SampleRelationship(); sampleRelationship.setAlias("D0"); sampleRelationship.setTeam(sub.getTeam().getName()); sampleRelationship.setRelationshipNature("Child of"); sample.getSampleRelationships().add(sampleRelationship); jsonRepresentation = objectMapper.writeValueAsString(sample); this.mockMvc.perform( put("/api/samples/{id}",sampleId).content(jsonRepresentation) .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("update-sample", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("_links").description("Links"), fieldWithPath("alias").description("Unique name for the sample within the team"), fieldWithPath("title").description("Title for the sample"), fieldWithPath("description").description("Description for the sample"), fieldWithPath("attributes").description("A list of attributes for the sample"), fieldWithPath("sampleRelationships").description("Relationships to other samples"), fieldWithPath("taxonId").description("NCBI Taxon ID for this sample"), fieldWithPath("taxon").description("Scientific name for this taxon"), fieldWithPath("_embedded.submission").description("Submission that this sample is part of"), fieldWithPath("_embedded.processingStatus").description("Processing status for this sample."), fieldWithPath("team").description("Team this sample belongs to"), fieldWithPath("createdDate").description("Date this resource was created"), fieldWithPath("lastModifiedDate").description("Date this resource was modified"), fieldWithPath("createdBy").description("User who created this resource"), fieldWithPath("lastModifiedBy").description("User who last modified this resource") ), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("sample").description("This resource"), linkWithRel("self:update").description("This resource can be updated"), linkWithRel("self:delete").description("This resource can be deleted"), linkWithRel("submission").description("Submission that this sample is part of"), linkWithRel("processingStatus").description("Processing status for this sample"), linkWithRel("history").description("Collection of resources for samples with the same team and alias as this resource"), linkWithRel("current-version").description("Current version of this sample, as identified by team and alias") ) ) ); this.mockMvc.perform( patch("/api/samples/{id}",sampleId).content("{\"archive\":\"BioSamples\"}") .contentType(RestMediaTypes.HAL_JSON) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("patch-sample", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("_links").description("Links"), fieldWithPath("alias").description("Unique name for the sample within the team"), fieldWithPath("title").description("Title for the sample"), fieldWithPath("description").description("Description for the sample"), fieldWithPath("attributes").description("A list of attributes for the sample"), fieldWithPath("sampleRelationships").description("Relationships to other samples"), fieldWithPath("taxonId").description("NCBI Taxon ID for this sample"), fieldWithPath("taxon").description("Scientific name for this taxon"), fieldWithPath("_embedded.submission").description("Submission that this sample is part of"), fieldWithPath("_embedded.processingStatus").description("Processing status for this sample."), fieldWithPath("team").description("Team this sample belongs to"), fieldWithPath("archive").description("Team this sample belongs to"), fieldWithPath("createdDate").description("Date this resource was created"), fieldWithPath("lastModifiedDate").description("Date this resource was modified"), fieldWithPath("createdBy").description("User who created this resource"), fieldWithPath("lastModifiedBy").description("User who last modified this resource") ), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("sample").description("This resource"), linkWithRel("self:update").description("This resource can be updated"), linkWithRel("self:delete").description("This resource can be deleted"), linkWithRel("submission").description("Submission that this sample is part of"), linkWithRel("processingStatus").description("Processing status for this sample"), linkWithRel("history").description("Collection of resources for samples with the same team and alias as this resource"), linkWithRel("current-version").description("Current version of this sample, as identified by team and alias") ) ) ); } private uk.ac.ebi.subs.data.Submission badClientSubmission() { return new uk.ac.ebi.subs.data.Submission(); } private ContentModifyingOperationPreprocessor maskEmbedded() { return new ContentModifyingOperationPreprocessor(new MaskElement("_embedded")); } private ContentModifyingOperationPreprocessor maskLinks() { return new ContentModifyingOperationPreprocessor(new MaskElement("_links")); } @Test public void pageExample() throws Exception { String teamName = null; for (int i = 0; i < 50; i++) { Submission s = Helpers.generateTestSubmission(); submissionStatusRepository.insert(s.getSubmissionStatus()); submissionRepository.insert(s); teamName = s.getTeam().getName(); } this.mockMvc.perform(get("/api/submissions/search/by-team?teamName={teamName}&page=1&size=10", teamName)) .andExpect(status().isOk()) .andDo(document( "page-example", preprocessRequest(prettyPrint()), preprocessResponse(maskEmbedded(), prettyPrint()), links(halLinks(), linkWithRel("self").description("This resource list"), linkWithRel("first").description("The first page in the resource list"), linkWithRel("next").description("The next page in the resource list"), linkWithRel("prev").description("The previous page in the resource list"), linkWithRel("last").description("The last page in the resource list") ), responseFields( fieldWithPath("_links").description("<<resources-page-links,Links>> to other resources"), fieldWithPath("_embedded").description("The list of resources"), fieldWithPath("page.size").description("The number of resources in this page"), fieldWithPath("page.totalElements").description("The total number of resources"), fieldWithPath("page.totalPages").description("The total number of pages"), fieldWithPath("page.number").description("The page number") ) )); } @Test public void conditionalRequests() throws Exception { Submission sub = storeSubmission(); List<Sample> samples = storeSamples(sub, 1); Sample s = samples.get(0); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM YYYY H:m:s zzz"); String etagValueString = String.format("ETag: \"%d\"", s.getVersion()); String lastModifiedString = dateFormat.format(s.getLastModifiedDate()); this.mockMvc.perform( get("/api/samples/{sampleId}", s.getId()) .accept(MediaType.APPLICATION_JSON) .header("If-None-Match", etagValueString) ).andExpect(status().isNotModified()) .andDo( document("conditional-fetch-etag-get-if-none-match", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint() ) ) ); this.mockMvc.perform( delete("/api/samples/{sampleId}", s.getId()) .accept(MediaType.APPLICATION_JSON) .header("If-Match", "ETag: \"10\"") ).andExpect(status().isPreconditionFailed()) .andDo( document("conditional-delete-if-etag-match", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint() ) ) ); this.mockMvc.perform( get("/api/samples/{sampleId}", s.getId()) .accept(MediaType.APPLICATION_JSON) .header("If-Modified-Since", lastModifiedString) ).andExpect(status().isNotModified()) .andDo( document("conditional-fetch-if-modified-since", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint() ) ) ); } @Test public void sampleList() throws Exception { Submission sub = storeSubmission(); List<Sample> samples = storeSamples(sub, 30); this.mockMvc.perform( get("/api/samples/search/by-submission?submissionId={submissionId}&size=2", sub.getId()) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("samples/by-submission", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), selfRelLink(), nextRelLink(), firstRelLink(), lastRelLink() ), responseFields( linksResponseField(), fieldWithPath("_embedded.samples").description("Samples within the submission"), paginationPageSizeDescriptor(), paginationTotalElementsDescriptor(), paginationTotalPagesDescriptor(), paginationPageNumberDescriptor() ) ) ); this.mockMvc.perform( get("/api/samples/{sample}", samples.get(0).getId()) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("samples/fetch-one", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), selfRelLink(), processingStatusLink(), submissionLink(), linkWithRel("sample").description("Link to this sample"), linkWithRel("self:update").description("This sample can be updated"), linkWithRel("self:delete").description("This sample can be deleted") ), responseFields( //TODO fill out the descriptions linksResponseField(), fieldWithPath("alias").description(""), fieldWithPath("title").description(""), fieldWithPath("description").description(""), fieldWithPath("sampleRelationships").description(""), fieldWithPath("taxonId").description(""), fieldWithPath("taxon").description(""), fieldWithPath("attributes").description(""), fieldWithPath("createdDate").description(""), fieldWithPath("lastModifiedDate").description(""), fieldWithPath("createdBy").description(""), fieldWithPath("lastModifiedBy").description(""), fieldWithPath("_embedded.submission").description(""), fieldWithPath("_embedded.processingStatus").description("") ) )); } private List<Sample> storeSamples(Submission sub, int numberRequired) { List<Sample> samples = Helpers.generateTestSamples(numberRequired); for (Sample s : samples) { s.setCreatedDate(new Date()); s.setSubmission(sub); processingStatusRepository.insert(s.getProcessingStatus()); sampleRepository.insert(s); } return samples; } @Test public void samplesSearchResource() throws Exception { this.mockMvc.perform( get("/api/samples/search") .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("samples-search-resource", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("by-submission").description("Search for all samples within a submission"), linkWithRel("by-team").description("Search for samples within a team"), linkWithRel("by-accession").description("Find the current version of a sample by archive accession"), linkWithRel("current-version").description("Find the current version of a sample by team and alias"), linkWithRel("history").description("Search for all versions of a sample by team and alias ") ), responseFields( linksResponseField() ) ) ); } @Test public void team() throws Exception { Submission submission = storeSubmission(); Team team = submission.getTeam(); this.mockMvc.perform( get("/api/teams/{teamName}", team.getName()) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("get-team", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), linkWithRel("self").description("This resource"), linkWithRel("submissions").description("Collection of submissions within this team"), linkWithRel("analyses").description("Collection of analyses within this team"), linkWithRel("assays").description("Collection of assays within this team"), linkWithRel("assayData").description("Collection of assay data within this team"), linkWithRel("egaDacs").description("Collection of DACs within this team"), linkWithRel("egaDacPolicies").description("Collection of DAC policies within this team"), linkWithRel("egaDatasets").description("Collection of EGA Datasets within this team"), linkWithRel("projects").description("Collection of projects within this team"), linkWithRel("protocols").description("Collection of protocols within this team"), linkWithRel("samples").description("Collection of samples within this team"), linkWithRel("sampleGroups").description("Collection of sample groups within this team"), linkWithRel("studies").description("Collection of studies within this team") ), responseFields( linksResponseField(), fieldWithPath("name").description("Name of this team") ) ) ); } @Test public void rootEndpoint() throws Exception { this.mockMvc.perform( get("/api") .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("root-endpoint", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), //team linkWithRel("teams").description("Teams"), //submissions linkWithRel("submissions:search").description("Search resource for submissions"), linkWithRel("submissions:create").description("Create a new submission resource"), //submittables linkWithRel("analyses:create").description("Create a new analysis resource"), linkWithRel("analyses:search").description("Search resource for analyses"), linkWithRel("assayData:create").description("Create a new assay data resource"), linkWithRel("assayData:search").description("Search resource for assay data"), linkWithRel("assays:create").description("Create a new assay resource"), linkWithRel("assays:search").description("Search resource for assays"), linkWithRel("egaDacPolicies:create").description("Create a new DAC policy resource"), linkWithRel("egaDacPolicies:search").description("Search resource for policies"), linkWithRel("egaDacs:create").description("Create a new DAC resource"), linkWithRel("egaDacs:search").description("Search resource for DACs"), linkWithRel("egaDatasets:create").description("Create a new EGA dataset resource"), linkWithRel("egaDatasets:search").description("Search resource for EGA datasets"), linkWithRel("projects:create").description("Create a new project resource"), linkWithRel("projects:search").description("Search resource for projects"), linkWithRel("protocols:create").description("Create a new protocol resource"), linkWithRel("protocols:search").description("Search resource for protocols"), linkWithRel("sampleGroups:create").description("Create a new sample group resource"), linkWithRel("sampleGroups:search").description("Search resource for sample groups"), linkWithRel("samples:create").description("Create a new sample resource"), linkWithRel("samples:search").description("Search resource for samples"), linkWithRel("studies:create").description("Create a new study resource"), linkWithRel("studies:search").description("Search resource for studies"), //status descriptions linkWithRel("submissionStatusDescriptions").description("Collection resource for submission status descriptions"), linkWithRel("processingStatusDescriptions").description("Collection resource for processing status descriptions "), linkWithRel("releaseStatusDescriptions").description("Collection resource for release status descriptions"), //statuses linkWithRel("processingStatuses:search").description("Search resource for processing statuses"), //profile linkWithRel("profile").description("Application level details") ), responseFields( linksResponseField() ) ) ); } @Test public void submissionsByTeam() throws Exception { Submission sub = storeSubmission(); this.mockMvc.perform( get("/api/submissions/search/by-team?teamName={teamName}", sub.getTeam().getName()) .accept(RestMediaTypes.HAL_JSON) ).andExpect(status().isOk()) .andDo( document("submissions/by-team", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links( halLinks(), selfRelLink() ), responseFields( linksResponseField(), fieldWithPath("_embedded.submissions").description("Submissions matching the team name"), paginationPageSizeDescriptor(), paginationTotalElementsDescriptor(), paginationTotalPagesDescriptor(), paginationPageNumberDescriptor() ) ) ); } private FieldDescriptor linksResponseField() { return fieldWithPath("_links").description("Links to other resources"); } private LinkDescriptor selfRelLink() { return linkWithRel("self").description("Canonical link for this resource"); } private Submission storeSubmission() { Submission sub = Helpers.generateTestSubmission(); this.submissionStatusRepository.save(sub.getSubmissionStatus()); this.submissionRepository.save(sub); return sub; } private FieldDescriptor paginationPageNumberDescriptor() { return fieldWithPath("page.number").description("The page number"); } private FieldDescriptor paginationTotalPagesDescriptor() { return fieldWithPath("page.totalPages").description("The total number of pages"); } private FieldDescriptor paginationTotalElementsDescriptor() { return fieldWithPath("page.totalElements").description("The total number of resources"); } private FieldDescriptor paginationPageSizeDescriptor() { return fieldWithPath("page.size").description("The number of resources in this page"); } private LinkDescriptor nextRelLink() { return linkWithRel("next").description("Next page of this resource"); } private LinkDescriptor lastRelLink() { return linkWithRel("last").description("Last page for this resource"); } private LinkDescriptor firstRelLink() { return linkWithRel("first").description("First page for this resource"); } private LinkDescriptor prevRelLink() { return linkWithRel("prev").description("Previous page for this resource"); } private LinkDescriptor submissionLink() { return linkWithRel("submission").description("Submission in which this record was created"); } private LinkDescriptor processingStatusLink() { return linkWithRel("processingStatus").description("Current status of this record"); } private class MaskElement implements ContentModifier { private String keyToRemove; public MaskElement(String keyToRemove) { this.keyToRemove = keyToRemove; } @Override public byte[] modifyContent(byte[] originalContent, MediaType contentType) { TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; Map<String, Object> o = null; try { o = objectMapper.readValue(originalContent, typeRef); } catch (IOException e) { throw new UncheckedIOException(e); } o.put("_embedded", "..."); try { return objectMapper.writeValueAsBytes(o); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } }
package com.axelor.auth; import com.axelor.event.Event; import com.axelor.event.NamedLiteral; import com.axelor.events.LoginRedirectException; import com.axelor.events.PostLogin; import com.axelor.events.PreLogin; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Map; import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.util.WebUtils; public class AuthFilter extends FormAuthenticationFilter { @Inject private Event<PreLogin> preLogin; @Inject private Event<PostLogin> postLogin; @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { AuthenticationToken token = createToken(request, response); if (token == null) { String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " + "must be created in order to execute a login attempt."; throw new IllegalStateException(msg); } try { try { preLogin.fire(new PreLogin(token)); Subject subject = getSubject(request, response); subject.login(token); postLogin .select(NamedLiteral.of(PostLogin.SUCCESS)) .fire(new PostLogin(token, AuthUtils.getUser(), null)); return onLoginSuccess(token, subject, request, response); } catch (AuthenticationException e) { postLogin.select(NamedLiteral.of(PostLogin.FAILURE)).fire(new PostLogin(token, null, e)); return onLoginFailure(token, e, request, response); } } catch (LoginRedirectException e) { WebUtils.issueRedirect(request, response, e.getLocation()); return false; } } private boolean isRootWithoutSlash(ServletRequest request) { final HttpServletRequest req = (HttpServletRequest) request; final String ctx = WebUtils.getContextPath(req); final String uri = WebUtils.getRequestUri(req); return ctx != null && uri != null && !uri.endsWith("/") && ctx.length() == uri.length(); } @Override public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { // tomcat 7.0.67 doesn't redirect with / if root request is sent without slash // see RM-4500 for more details if (!SecurityUtils.getSubject().isAuthenticated() && isRootWithoutSlash(request)) { WebUtils.issueRedirect(request, response, "/"); return; } if (isLoginRequest(request, response) && SecurityUtils.getSubject().isAuthenticated()) { // in case of login submission with ajax if (isXHR(request) && isLoginSubmission(request, response)) { WebUtils.toHttp(response).setStatus(200); return; } WebUtils.issueRedirect(request, response, "/"); } super.doFilterInternal(request, response, chain); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { // set encoding to UTF-8 (see RM-4304) request.setCharacterEncoding("UTF-8"); if (isXHR(request)) { int status = 401; if (isLoginRequest(request, response) && isLoginSubmission(request, response)) { if (doLogin(request, response)) { status = 200; } } // set HTTP status for ajax requests ((HttpServletResponse) response).setStatus(status); // don't process further, otherwise login.jsp will be rendered as response data return false; } return super.onAccessDenied(request, response); } @Override protected boolean onLoginSuccess( AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { // change session id to prevent session fixation ((HttpServletRequest) request).changeSessionId(); return super.onLoginSuccess(token, subject, request, response); } @SuppressWarnings("unchecked") private boolean doLogin(ServletRequest request, ServletResponse response) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final Map<String, String> data = mapper.readValue(request.getInputStream(), Map.class); final String username = data.get("username"); final String password = data.get("password"); final AuthenticationToken token = createToken(username, password, request, response); final Subject subject = getSubject(request, response); try { preLogin.fire(new PreLogin(token)); subject.login(token); postLogin .select(NamedLiteral.of(PostLogin.SUCCESS)) .fire(new PostLogin(token, AuthUtils.getUser(), null)); } catch (AuthenticationException e) { postLogin.select(NamedLiteral.of(PostLogin.FAILURE)).fire(new PostLogin(token, null, e)); return false; } return true; } private boolean isXHR(ServletRequest request) { final HttpServletRequest req = (HttpServletRequest) request; return "XMLHttpRequest".equals(req.getHeader("X-Requested-With")) || "application/json".equals(req.getHeader("Accept")) || "application/json".equals(req.getHeader("Content-Type")); } }
package bisq.cli; import bisq.proto.grpc.CancelOfferRequest; import bisq.proto.grpc.ConfirmPaymentReceivedRequest; import bisq.proto.grpc.ConfirmPaymentStartedRequest; import bisq.proto.grpc.CreateOfferRequest; import bisq.proto.grpc.CreatePaymentAccountRequest; import bisq.proto.grpc.GetAddressBalanceRequest; import bisq.proto.grpc.GetBalanceRequest; import bisq.proto.grpc.GetFundingAddressesRequest; import bisq.proto.grpc.GetOfferRequest; import bisq.proto.grpc.GetOffersRequest; import bisq.proto.grpc.GetPaymentAccountsRequest; import bisq.proto.grpc.GetTradeRequest; import bisq.proto.grpc.GetVersionRequest; import bisq.proto.grpc.KeepFundsRequest; import bisq.proto.grpc.LockWalletRequest; import bisq.proto.grpc.RegisterDisputeAgentRequest; import bisq.proto.grpc.RemoveWalletPasswordRequest; import bisq.proto.grpc.SetWalletPasswordRequest; import bisq.proto.grpc.TakeOfferRequest; import bisq.proto.grpc.UnlockWalletRequest; import bisq.proto.grpc.WithdrawFundsRequest; import io.grpc.StatusRuntimeException; import joptsimple.OptionParser; import joptsimple.OptionSet; import java.io.IOException; import java.io.PrintStream; import java.math.BigDecimal; import java.util.List; import lombok.extern.slf4j.Slf4j; import static bisq.cli.CurrencyFormat.formatSatoshis; import static bisq.cli.CurrencyFormat.toSatoshis; import static bisq.cli.NegativeNumberOptions.hasNegativeNumberOptions; import static bisq.cli.TableFormat.formatAddressBalanceTbl; import static bisq.cli.TableFormat.formatOfferTable; import static bisq.cli.TableFormat.formatPaymentAcctTbl; import static java.lang.String.format; import static java.lang.System.err; import static java.lang.System.exit; import static java.lang.System.out; import static java.math.BigDecimal.ZERO; import static java.util.Collections.singletonList; /** * A command-line client for the Bisq gRPC API. */ @SuppressWarnings("ResultOfMethodCallIgnored") @Slf4j public class CliMain { private enum Method { createoffer, canceloffer, getoffer, getoffers, takeoffer, gettrade, confirmpaymentstarted, confirmpaymentreceived, keepfunds, withdrawfunds, createpaymentacct, getpaymentaccts, getversion, getbalance, getaddressbalance, getfundingaddresses, lockwallet, unlockwallet, removewalletpassword, setwalletpassword, registerdisputeagent } public static void main(String[] args) { try { run(args); } catch (Throwable t) { err.println("Error: " + t.getMessage()); exit(1); } } public static void run(String[] args) { var parser = new OptionParser(); var helpOpt = parser.accepts("help", "Print this help text") .forHelp(); var hostOpt = parser.accepts("host", "rpc server hostname or IP") .withRequiredArg() .defaultsTo("localhost"); var portOpt = parser.accepts("port", "rpc server port") .withRequiredArg() .ofType(Integer.class) .defaultsTo(9998); var passwordOpt = parser.accepts("password", "rpc server password") .withRequiredArg(); var negativeNumberOpts = hasNegativeNumberOptions(args) ? new NegativeNumberOptions() : null; // Cache any negative number params that will not be accepted by the parser. if (negativeNumberOpts != null) args = negativeNumberOpts.removeNegativeNumberOptions(args); // Parse the options after temporarily removing any negative number params we // do not want the parser recognizing as invalid option arguments, e.g., -0.05. OptionSet options = parser.parse(args); if (options.has(helpOpt)) { printHelp(parser, out); return; } @SuppressWarnings("unchecked") var nonOptionArgs = (List<String>) options.nonOptionArguments(); if (nonOptionArgs.isEmpty()) { printHelp(parser, err); throw new IllegalArgumentException("no method specified"); } // Restore any cached negative number params to the nonOptionArgs list. if (negativeNumberOpts != null) nonOptionArgs = negativeNumberOpts.restoreNegativeNumberOptions(nonOptionArgs); var methodName = nonOptionArgs.get(0); Method method; try { method = getMethodFromCmd(methodName); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException(format("'%s' is not a supported method", methodName)); } var host = options.valueOf(hostOpt); var port = options.valueOf(portOpt); var password = options.valueOf(passwordOpt); if (password == null) throw new IllegalArgumentException("missing required 'password' option"); GrpcStubs grpcStubs = new GrpcStubs(host, port, password); var disputeAgentsService = grpcStubs.disputeAgentsService; var offersService = grpcStubs.offersService; var paymentAccountsService = grpcStubs.paymentAccountsService; var tradesService = grpcStubs.tradesService; var versionService = grpcStubs.versionService; var walletsService = grpcStubs.walletsService; try { switch (method) { case getversion: { var request = GetVersionRequest.newBuilder().build(); var version = versionService.getVersion(request).getVersion(); out.println(version); return; } case getbalance: { var request = GetBalanceRequest.newBuilder().build(); var reply = walletsService.getBalance(request); var btcBalance = formatSatoshis(reply.getBalance()); out.println(btcBalance); return; } case getaddressbalance: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("no address specified"); var request = GetAddressBalanceRequest.newBuilder() .setAddress(nonOptionArgs.get(1)).build(); var reply = walletsService.getAddressBalance(request); out.println(formatAddressBalanceTbl(singletonList(reply.getAddressBalanceInfo()))); return; } case getfundingaddresses: { var request = GetFundingAddressesRequest.newBuilder().build(); var reply = walletsService.getFundingAddresses(request); out.println(formatAddressBalanceTbl(reply.getAddressBalanceInfoList())); return; } case createoffer: { if (nonOptionArgs.size() < 9) throw new IllegalArgumentException("incorrect parameter count," + " expecting payment acct id, buy | sell, currency code, amount, min amount," + " use-market-based-price, fixed-price | mkt-price-margin, security-deposit"); var paymentAcctId = nonOptionArgs.get(1); var direction = nonOptionArgs.get(2); var currencyCode = nonOptionArgs.get(3); var amount = toSatoshis(nonOptionArgs.get(4)); var minAmount = toSatoshis(nonOptionArgs.get(5)); var useMarketBasedPrice = Boolean.parseBoolean(nonOptionArgs.get(6)); var fixedPrice = ZERO.toString(); var marketPriceMargin = ZERO; if (useMarketBasedPrice) marketPriceMargin = new BigDecimal(nonOptionArgs.get(7)); else fixedPrice = nonOptionArgs.get(7); var securityDeposit = new BigDecimal(nonOptionArgs.get(8)); var request = CreateOfferRequest.newBuilder() .setDirection(direction) .setCurrencyCode(currencyCode) .setAmount(amount) .setMinAmount(minAmount) .setUseMarketBasedPrice(useMarketBasedPrice) .setPrice(fixedPrice) .setMarketPriceMargin(marketPriceMargin.doubleValue()) .setBuyerSecurityDeposit(securityDeposit.doubleValue()) .setPaymentAccountId(paymentAcctId) .build(); var reply = offersService.createOffer(request); out.println(formatOfferTable(singletonList(reply.getOffer()), currencyCode)); return; } case canceloffer: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting offer id"); var offerId = nonOptionArgs.get(1); var request = CancelOfferRequest.newBuilder() .setId(offerId) .build(); offersService.cancelOffer(request); out.println("offer canceled and removed from offer book"); return; } case getoffer: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting offer id"); var offerId = nonOptionArgs.get(1); var request = GetOfferRequest.newBuilder() .setId(offerId) .build(); var reply = offersService.getOffer(request); out.println(formatOfferTable(singletonList(reply.getOffer()), reply.getOffer().getCounterCurrencyCode())); return; } case getoffers: { if (nonOptionArgs.size() < 3) throw new IllegalArgumentException("incorrect parameter count," + " expecting direction (buy|sell), currency code"); var direction = nonOptionArgs.get(1); var currencyCode = nonOptionArgs.get(2); var request = GetOffersRequest.newBuilder() .setDirection(direction) .setCurrencyCode(currencyCode) .build(); var reply = offersService.getOffers(request); out.println(formatOfferTable(reply.getOffersList(), currencyCode)); return; } case takeoffer: { if (nonOptionArgs.size() < 3) throw new IllegalArgumentException("incorrect parameter count, expecting offer id, payment acct id"); var offerId = nonOptionArgs.get(1); var paymentAccountId = nonOptionArgs.get(2); var request = TakeOfferRequest.newBuilder() .setOfferId(offerId) .setPaymentAccountId(paymentAccountId) .build(); var reply = tradesService.takeOffer(request); out.printf("trade '%s' successfully taken", reply.getTrade().getShortId()); return; } case gettrade: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting trade id, [,showcontract = true|false]"); var tradeId = nonOptionArgs.get(1); var showContract = false; if (nonOptionArgs.size() == 3) showContract = Boolean.getBoolean(nonOptionArgs.get(2)); var request = GetTradeRequest.newBuilder() .setTradeId(tradeId) .build(); var reply = tradesService.getTrade(request); if (showContract) out.println(reply.getTrade().getContractAsJson()); else out.println(TradeFormat.format(reply.getTrade())); return; } case confirmpaymentstarted: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting trade id"); var tradeId = nonOptionArgs.get(1); var request = ConfirmPaymentStartedRequest.newBuilder() .setTradeId(tradeId) .build(); tradesService.confirmPaymentStarted(request); out.printf("trade '%s' payment started message sent", tradeId); return; } case confirmpaymentreceived: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting trade id"); var tradeId = nonOptionArgs.get(1); var request = ConfirmPaymentReceivedRequest.newBuilder() .setTradeId(tradeId) .build(); tradesService.confirmPaymentReceived(request); out.printf("trade '%s' payment received message sent", tradeId); return; } case keepfunds: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("incorrect parameter count, expecting trade id"); var tradeId = nonOptionArgs.get(1); var request = KeepFundsRequest.newBuilder() .setTradeId(tradeId) .build(); tradesService.keepFunds(request); out.printf("funds from trade '%s' saved in bisq wallet", tradeId); return; } case withdrawfunds: { if (nonOptionArgs.size() < 3) throw new IllegalArgumentException("incorrect parameter count, expecting trade id, bitcoin wallet address"); var tradeId = nonOptionArgs.get(1); var address = nonOptionArgs.get(2); var request = WithdrawFundsRequest.newBuilder() .setTradeId(tradeId) .setAddress(address) .build(); tradesService.withdrawFunds(request); out.printf("funds from trade '%s' sent to btc address '%s'", tradeId, address); return; } case createpaymentacct: { if (nonOptionArgs.size() < 5) throw new IllegalArgumentException( "incorrect parameter count, expecting payment method id," + " account name, account number, currency code"); var paymentMethodId = nonOptionArgs.get(1); var accountName = nonOptionArgs.get(2); var accountNumber = nonOptionArgs.get(3); var currencyCode = nonOptionArgs.get(4); var request = CreatePaymentAccountRequest.newBuilder() .setPaymentMethodId(paymentMethodId) .setAccountName(accountName) .setAccountNumber(accountNumber) .setCurrencyCode(currencyCode).build(); paymentAccountsService.createPaymentAccount(request); out.printf("payment account %s saved", accountName); return; } case getpaymentaccts: { var request = GetPaymentAccountsRequest.newBuilder().build(); var reply = paymentAccountsService.getPaymentAccounts(request); out.println(formatPaymentAcctTbl(reply.getPaymentAccountsList())); return; } case lockwallet: { var request = LockWalletRequest.newBuilder().build(); walletsService.lockWallet(request); out.println("wallet locked"); return; } case unlockwallet: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("no password specified"); if (nonOptionArgs.size() < 3) throw new IllegalArgumentException("no unlock timeout specified"); long timeout; try { timeout = Long.parseLong(nonOptionArgs.get(2)); } catch (NumberFormatException e) { throw new IllegalArgumentException(format("'%s' is not a number", nonOptionArgs.get(2))); } var request = UnlockWalletRequest.newBuilder() .setPassword(nonOptionArgs.get(1)) .setTimeout(timeout).build(); walletsService.unlockWallet(request); out.println("wallet unlocked"); return; } case removewalletpassword: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("no password specified"); var request = RemoveWalletPasswordRequest.newBuilder() .setPassword(nonOptionArgs.get(1)).build(); walletsService.removeWalletPassword(request); out.println("wallet decrypted"); return; } case setwalletpassword: { if (nonOptionArgs.size() < 2) throw new IllegalArgumentException("no password specified"); var requestBuilder = SetWalletPasswordRequest.newBuilder() .setPassword(nonOptionArgs.get(1)); var hasNewPassword = nonOptionArgs.size() == 3; if (hasNewPassword) requestBuilder.setNewPassword(nonOptionArgs.get(2)); walletsService.setWalletPassword(requestBuilder.build()); out.println("wallet encrypted" + (hasNewPassword ? " with new password" : "")); return; } case registerdisputeagent: { if (nonOptionArgs.size() < 3) throw new IllegalArgumentException( "incorrect parameter count, expecting dispute agent type, registration key"); var disputeAgentType = nonOptionArgs.get(1); var registrationKey = nonOptionArgs.get(2); var requestBuilder = RegisterDisputeAgentRequest.newBuilder() .setDisputeAgentType(disputeAgentType).setRegistrationKey(registrationKey); disputeAgentsService.registerDisputeAgent(requestBuilder.build()); out.println(disputeAgentType + " registered"); return; } default: { throw new RuntimeException(format("unhandled method '%s'", method)); } } } catch (StatusRuntimeException ex) { // Remove the leading gRPC status code (e.g. "UNKNOWN: ") from the message String message = ex.getMessage().replaceFirst("^[A-Z_]+: ", ""); throw new RuntimeException(message, ex); } } private static Method getMethodFromCmd(String methodName) { // TODO if we use const type for enum we need add some mapping. Even if we don't // change now it is handy to have flexibility in case we change internal code // and don't want to break user commands. return Method.valueOf(methodName.toLowerCase()); } private static void printHelp(OptionParser parser, PrintStream stream) { try { stream.println("Bisq RPC Client"); stream.println(); stream.println("Usage: bisq-cli [options] <method> [params]"); stream.println(); parser.printHelpOn(stream); stream.println(); String rowFormat = "%-22s%-50s%s%n"; stream.format(rowFormat, "Method", "Params", "Description"); stream.format(rowFormat, " stream.format(rowFormat, "getversion", "", "Get server version"); stream.format(rowFormat, "getbalance", "", "Get server wallet balance"); stream.format(rowFormat, "getaddressbalance", "address", "Get server wallet address balance"); stream.format(rowFormat, "getfundingaddresses", "", "Get BTC funding addresses"); stream.format(rowFormat, "createoffer", "payment acct id, buy | sell, currency code, \\", "Create and place an offer"); stream.format(rowFormat, "", "amount (btc), min amount, use mkt based price, \\", ""); stream.format(rowFormat, "", "fixed price (btc) | mkt price margin (%), \\", ""); stream.format(rowFormat, "", "security deposit (%)", ""); stream.format(rowFormat, "canceloffer", "offer id", "Cancel offer with id"); stream.format(rowFormat, "getoffer", "offer id", "Get current offer with id"); stream.format(rowFormat, "getoffers", "buy | sell, currency code", "Get current offers"); stream.format(rowFormat, "takeoffer", "offer id", "Take offer with id"); stream.format(rowFormat, "gettrade", "trade id [,showcontract]", "Get trade summary or full contract"); stream.format(rowFormat, "confirmpaymentstarted", "trade id", "Confirm payment started"); stream.format(rowFormat, "confirmpaymentreceived", "trade id", "Confirm payment received"); stream.format(rowFormat, "keepfunds", "trade id", "Keep received funds in Bisq wallet"); stream.format(rowFormat, "withdrawfunds", "trade id, bitcoin wallet address", "Withdraw received funds to external wallet address"); stream.format(rowFormat, "createpaymentacct", "account name, account number, currency code", "Create PerfectMoney dummy account"); stream.format(rowFormat, "getpaymentaccts", "", "Get user payment accounts"); stream.format(rowFormat, "lockwallet", "", "Remove wallet password from memory, locking the wallet"); stream.format(rowFormat, "unlockwallet", "password timeout", "Store wallet password in memory for timeout seconds"); stream.format(rowFormat, "setwalletpassword", "password [newpassword]", "Encrypt wallet with password, or set new password on encrypted wallet"); stream.println(); } catch (IOException ex) { ex.printStackTrace(stream); } } }
package uk.co.johnjtaylor; import java.util.TimerTask; import java.util.Timer; public class Time { private Long elapsed; private Timer scheduler = new Timer(); private TimerTask increment; public Time() { elapsed = 0L; } public synchronized void start() { increment = new TimerTask() { @Override public void run() { elapsed++; } }; scheduler.scheduleAtFixedRate(increment, 0L, 1L); } public synchronized void pause() { stop(); } public synchronized void unpause() { start(); } public synchronized void stop() { increment.cancel(); } public synchronized Long getTime() { return elapsed; } }
package com.intellij.diagnostic.logging; import com.intellij.diagnostic.DiagnosticBundle; import com.intellij.execution.filters.TextConsoleBuidlerFactory; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.io.FileUtil; import com.intellij.ui.FilterComponent; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.*; public abstract class LogConsole extends JPanel implements Disposable{ private final ConsoleView myConsole; private final LightProcessHandler myProcessHandler = new LightProcessHandler(); private ReaderThread myReaderThread; private final boolean mySkipContents; @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private Document myOriginalDocument = null; @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private String myPrevType = null; private FilterComponent myFilter = new FilterComponent("LOG_FILTER_HISTORY", 5) { protected void filter() { LogConsolePreferences.getInstance().updateCustomFilter(getFilter()); filterConsoleOutput(); } }; private static final long PROCESS_IDLE_TIMEOUT = 200; public LogConsole(Project project, File file, boolean skipContents) { super(new BorderLayout()); mySkipContents = skipContents; myReaderThread = new ReaderThread(file); TextConsoleBuilder builder = TextConsoleBuidlerFactory.getInstance().createBuilder(project); myConsole = builder.getConsole(); myConsole.attachToProcess(myProcessHandler); add(myConsole.getComponent(), BorderLayout.CENTER); add(createToolbar(), BorderLayout.NORTH); myReaderThread.start(); } private JComponent createToolbar(){ DefaultActionGroup group = new DefaultActionGroup(); group.add(new FilterAction(LogConsolePreferences.INFO, IconLoader.getIcon("/ant/filterInfo.png"))); group.add(new FilterAction(LogConsolePreferences.WARNING, IconLoader.getIcon("/ant/filterWarning.png"))); group.add(new FilterAction(LogConsolePreferences.ERROR, IconLoader.getIcon("/ant/filterError.png"))); final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true); JPanel panel = new JPanel(new BorderLayout()); panel.add(actionToolbar.getComponent(), BorderLayout.WEST); myFilter.reset(); panel.add(myFilter, BorderLayout.EAST); return panel; } public abstract boolean isActive(); public void dispose() { myConsole.dispose(); myReaderThread.stopRunning(false); } public void stopRunning(){ myReaderThread.stopRunning(true); } public JComponent getComponent() { return this; } private void addMessage(final String text){ final String key = LogConsolePreferences.getType(text); if (LogConsolePreferences.getInstance().isApplicable(text, myPrevType)){ myProcessHandler.notifyTextAvailable(text + "\n", key != null ? LogConsolePreferences.getProcessOutputTypes(key) : (myPrevType == LogConsolePreferences.ERROR ? ProcessOutputTypes.STDERR : ProcessOutputTypes.STDOUT)); } if (key != null) { myPrevType = key; } myOriginalDocument = getOriginalDocument(); if (myOriginalDocument != null){ ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myOriginalDocument.insertString(myOriginalDocument.getTextLength(), text + "\n"); } }); } }, ModalityState.NON_MMODAL); } } public void attachStopLogConsoleTrackingListener(final ProcessHandler process) { if (process != null) { final ProcessAdapter stopListener = new ProcessAdapter() { public void processTerminated(final ProcessEvent event) { process.removeProcessListener(this); stopRunning(); } }; process.addProcessListener(stopListener); } } private Document getOriginalDocument(){ if (myOriginalDocument == null) { final Editor editor = (Editor)((ConsoleViewImpl)myConsole).getData(DataConstants.EDITOR); if (editor != null){ myOriginalDocument = new DocumentImpl(editor.getDocument().getText()); } } return myOriginalDocument; } private void filterConsoleOutput() { myOriginalDocument = getOriginalDocument(); if (myOriginalDocument != null){ myConsole.clear(); LogConsolePreferences preferences = LogConsolePreferences.getInstance(); final int lineCount = myOriginalDocument.getLineCount(); for (int line = 0; line < lineCount; line++) { final String text = myOriginalDocument.getCharsSequence().subSequence(myOriginalDocument.getLineStartOffset(line), myOriginalDocument.getLineEndOffset(line)).toString(); final String contentType = LogConsolePreferences.getType(text); if (preferences.isApplicable(text, myPrevType)){ myConsole.print(text + "\n", contentType != null ? LogConsolePreferences.getContentType(contentType) : (myPrevType == LogConsolePreferences.ERROR ? ConsoleViewContentType.ERROR_OUTPUT : ConsoleViewContentType.NORMAL_OUTPUT)); } if (contentType != null) { myPrevType = contentType; } } } } private static class LightProcessHandler extends ProcessHandler { protected void destroyProcessImpl() { throw new UnsupportedOperationException(); } protected void detachProcessImpl() { throw new UnsupportedOperationException(); } public boolean detachIsDefault() { return false; } @Nullable public OutputStream getProcessInput() { return null; } } private static final Logger LOG = Logger.getInstance("com.intellij.diagnostic.logging.LogConsole"); private class ReaderThread extends Thread{ private BufferedReader myFileStream; private boolean myRunning = true; @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"}) public ReaderThread(File file){ //noinspection HardCodedStringLiteral super("Reader Thread"); try { try { myFileStream = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { FileUtil.createParentDirs(file); if (!file.createNewFile()) return; myFileStream = new BufferedReader(new FileReader(file)); } if (mySkipContents) myFileStream.skip(file.length()); } catch (Throwable e) { myFileStream = null; } } public synchronized void run() { if (myFileStream == null) return; while (myRunning){ try { long endTime = System.currentTimeMillis() + PROCESS_IDLE_TIMEOUT; while (System.currentTimeMillis() < endTime){ if (myRunning && myFileStream != null && myFileStream.ready()){ addMessage(myFileStream.readLine()); } } synchronized (this) { wait(PROCESS_IDLE_TIMEOUT); while (myRunning && !isActive()){ wait(PROCESS_IDLE_TIMEOUT/4); } } } catch (IOException e) { LOG.error(e); } catch (InterruptedException e) { LOG.error(e); } } } public synchronized void stopRunning(boolean flush){ myRunning = false; try { if (myFileStream != null){ if (flush) {//flush everything to log on stop String line = myFileStream.readLine(); while (line != null){ addMessage(line); line = myFileStream.readLine(); } } myFileStream.close(); myFileStream = null; } } catch (IOException e) { LOG.error(e); } } } private class FilterAction extends ToggleAction { private String myFilter; protected FilterAction(final String filter, Icon icon) { super(DiagnosticBundle.message("log.console.filter.by.type", filter), DiagnosticBundle.message("log.console.filter.by.type", filter), icon); myFilter = filter; } public boolean isSelected(AnActionEvent e) { return LogConsolePreferences.getInstance().isFilter(myFilter); } public void setSelected(AnActionEvent e, boolean state) { LogConsolePreferences.getInstance().setFilter(myFilter, state); filterConsoleOutput(); } } }
package com.apps.adrcotfas.goodtime; import android.annotation.SuppressLint; import android.os.Handler; import android.support.v7.app.ActionBar; import android.view.MotionEvent; import android.view.View; class FullscreenHelper { private boolean mVisible; private static final boolean AUTO_HIDE = true; private static final int AUTO_HIDE_DELAY_MILLIS = 3000; private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); private View mContentView; private ActionBar mActionBar; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements mActionBar.show(); } }; private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(); } }; FullscreenHelper(View contentView, ActionBar actionBar) { mVisible = true; mContentView = contentView; mActionBar = actionBar; mContentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggle(); } }); mContentView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }); hide(); } private void toggle() { if (mVisible) { hide(); } else { show(); } } public void hide() { // Hide UI first if (mActionBar != null) { mActionBar.hide(); } mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } void disable() { mContentView.setOnClickListener(null); mContentView.setOnTouchListener(null); mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.removeCallbacks(mHidePart2Runnable); show(); } }
package com.edicatad.emvi.handlers; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import com.edicatad.emvi.world.storage.VillagerData; import net.minecraft.world.World; public class NBTDataHandler { private static VillagerData villagerData; private static final String tagName = "EmVi"; public static void init(World world){ if(villagerData == null){ villagerData = (VillagerData) world.getPerWorldStorage().getOrLoadData(VillagerData.class, tagName); if(villagerData == null){ villagerData = new VillagerData(tagName); world.getPerWorldStorage().setData(tagName, villagerData); } } } public static int getVillagersSpawnedForChunk(int chunkX, int chunkZ){ // this returns 0 if no villagers have spawned or if there is no data stored - functionally the same return villagerData.getData().getInteger(String.format("x%iz%i", chunkX, chunkZ)); } public static void incrementVillagersSpawnedForChunk(int chunkX, int chunkZ){ villagerData.getData().setInteger(String.format("x%iz%i", chunkX, chunkZ), getVillagersSpawnedForChunk(chunkX, chunkZ) + 1); } public static void decrementVillagersSpawnedForChunk(int chunkX, int chunkZ){ if(getVillagersSpawnedForChunk(chunkX, chunkZ) > 0){ villagerData.getData().setInteger(String.format("x%iz%i", chunkX, chunkZ), getVillagersSpawnedForChunk(chunkX, chunkZ) - 1); } else { LogManager.getLogger().log(Level.WARN, String.format("Tried to decrement villager spawn count for chunk at x%iz%i below 0", chunkX, chunkZ)); } } }
package htmlcheck; import java.io.StringReader; import org.jdom.Element; import org.jdom.input.SAXBuilder; public class Page { private String page; public Page(String page) { this.page = page; } public String getSource() { return page; } public Element getRoot() throws Exception { return new SAXBuilder().build(new StringReader(page)).getRootElement(); } }
package org.flymine.web.widget; import java.util.Collections; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.Constraint; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathNode; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.widget.WidgetURLQuery; /** * Builds a query to get all the genes (in bag) associated with specified go term. * @author Julie Sullivan */ public class TiffinURLQuery implements WidgetURLQuery { private InterMineBag bag; private String key; private ObjectStore os; private static final String DATASET = "Tiffin"; /** * @param key which bar the user clicked on * @param bag bag * @param os object store */ public TiffinURLQuery(ObjectStore os, InterMineBag bag, String key) { this.bag = bag; this.key = key; this.os = os; } /** * {@inheritDoc} */ public PathQuery generatePathQuery() { PathQuery q = new PathQuery(os.getModel()); PathNode node = q.addNode("Gene.upstreamIntergenicRegion.overlappingFeatures"); node.setType("TFBindingSite"); String path = "Gene.upstreamIntergenicRegion.overlappingFeatures.motif.primaryIdentifier"; q.setView("Gene.secondaryIdentifier," + path); q.addConstraint(path, Constraints.eq (key)); q.addConstraint("TFBindingSite.dataSets.title", Constraints.eq(DATASET)); q.addConstraint(bag.getType(), Constraints.in(bag.getName())); q.setConstraintLogic("A and B and C"); q.syncLogicExpression("and"); return q; } }
package VASSAL.tools; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import VASSAL.build.BadDataReport; import VASSAL.build.GameModule; import VASSAL.i18n.Resources; public class Mp3AudioClip implements AudioClip { private static final Logger log = LoggerFactory.getLogger(Mp3AudioClip.class); protected URL url = null; protected String name = null; public Mp3AudioClip(String name) { this.name = name; } public Mp3AudioClip(URL url) { this.url = url; } protected InputStream getStream() { try { return name != null ? GameModule.getGameModule().getDataArchive().getInputStream(name) : url.openStream(); } catch (FileNotFoundException e) { ErrorDialog.dataWarning(new BadDataReport( Resources.getString( "Error.not_found", name != null ? name : url.toString() ), "", e )); } catch (IOException e) { ReadErrorDialog.error(e, name != null ? name : url.toString()); } return null; } protected Player getPlayer(InputStream stream) { Player player = null; try { player = new Player(stream); } catch (JavaLayerException e) { ErrorDialog.bug(e); } finally { if (player == null) { // close the stream if player ctor fails // otherwise, keep it open for the thread to close if (stream != null) { try { stream.close(); } catch (IOException e) { log.error("Error while closing stream", e); } } } } return player; } @Override public void play() { // load the stream final InputStream stream = getStream(); if (stream == null) { return; } // create the player final Player player = getPlayer(stream); if (player == null) { return; } // run in new thread to play in background new Thread() { @Override public void run() { try (stream) { player.play(); } catch (JavaLayerException | IOException e) { ErrorDialog.dataWarning(new BadDataReport( "Error reading sound file", name, e )); } } }.start(); } }
package io.hawt.web; import io.hawt.system.ConfigManager; import org.jolokia.converter.Converters; import org.jolokia.converter.json.JsonConvertOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.AttributeNotFoundException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class BrandingServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final transient Logger LOG = LoggerFactory.getLogger(BrandingServlet.class); List<String> propertiesToCheck = new ArrayList<String>(); List<String> wantedStrings = new ArrayList<String>(); boolean forceBranding = false; boolean useBranding = true; String profile; Converters converters = new Converters(); JsonConvertOptions options = JsonConvertOptions.DEFAULT; @Override public void init(ServletConfig servletConfig) throws ServletException { ConfigManager config = (ConfigManager) servletConfig.getServletContext().getAttribute("ConfigManager"); if (config != null) { String propertiesToCheckString = config.get("propertiesToCheck", "karaf.version"); String wantedStringsString = config.get("wantedStrings", "redhat,fuse"); forceBranding = Boolean.parseBoolean(config.get("forceBranding", "false")); useBranding = Boolean.parseBoolean(config.get("useBranding", "true")); if (propertiesToCheckString != null) { for (String str : propertiesToCheckString.split(",")) { propertiesToCheck.add(str.trim()); } } if (wantedStringsString != null) { for (String str : wantedStringsString.split(",")) { wantedStrings.add(str.trim()); } } } // we'll look for this as a system property for now... profile = System.getProperty("profile"); if (forceBranding) { LOG.debug("Branding enabled via forceBranding"); } else { if (useBranding) { LOG.debug("Will check if branding should be enabled or not"); LOG.debug("Checking properties: {}", propertiesToCheck); LOG.debug("Strings that will enable branding: {}", wantedStrings); } else { LOG.debug("Will use the default hawtio branding"); } } super.init(servletConfig); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> answer = new HashMap<String, String>(); answer.put("profile", profile); answer.put("enable", enableBranding().toString()); response.setContentType("application/json"); final PrintWriter out = response.getWriter(); Object result = null; try { result = converters.getToJsonConverter().convertToJson(answer, null, options); } catch (AttributeNotFoundException e) { LOG.warn("Failed to convert plugin list to json", e); } if (result != null) { out.write(result.toString()); out.flush(); out.close(); } else { out.write("{ \"enable\":\"false\"}"); } } private Boolean enableBranding() { if (forceBranding) { return true; } if (!useBranding) { return false; } Properties systemProperties = System.getProperties(); List<String> hits = new ArrayList<String>(); for (String property : propertiesToCheck) { if (systemProperties.containsKey(property)) { hits.add(property); } } for (String property : hits) { String value = systemProperties.getProperty(property); if (value != null) { for (String wanted : wantedStrings) { if (value.contains(wanted)) { return true; } } } } return false; } private void writeTrue(PrintWriter out) { writeValue(out, true); } private void writeFalse(PrintWriter out) { writeValue(out, false); } private void writeValue(PrintWriter out, boolean value) { out.write(Boolean.valueOf(value).toString()); out.flush(); out.close(); } }
package org.opennms.web.graph; import org.apache.log4j.Category; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.utils.IfLabel; import org.opennms.netmgt.utils.RrdFileConstants; import org.opennms.web.Util; public abstract class GraphModelAbstract implements GraphModel { private PrefabGraph[] m_queries; private Map m_reportMap; private File m_rrdDirectory; private String m_defaultReport; protected void loadProperties(String homeDir, String fileName) throws IOException { if (homeDir == null) { throw new IllegalArgumentException("Cannot take null " + "parameters."); } loadProperties(homeDir + fileName); } protected void loadProperties(String file) throws IOException { Properties m_properties; m_properties = new java.util.Properties(); FileInputStream propertiesStream = new FileInputStream(file); m_properties.load(propertiesStream); m_rrdDirectory = new File(m_properties.getProperty("command.input.dir")); if(m_properties.getProperty("default.report") != null) { m_defaultReport = new String(m_properties.getProperty("default.report")); } else { m_defaultReport = new String("none"); } m_reportMap = PrefabGraph.getPrefabGraphDefinitions(m_properties); } public File getRrdDirectory() { return m_rrdDirectory; } public String getDefaultReport() { return m_defaultReport; } public PrefabGraph getQuery(String queryName) { return (PrefabGraph) m_reportMap.get(queryName); } /** * Return a list of all known prefabricated graph definitions. */ public PrefabGraph[] getQueries() { if (m_queries == null) { initQueries(); } return m_queries; } private void initQueries() { Collection values = m_reportMap.values(); Iterator iter = values.iterator(); PrefabGraph[] graphs = new PrefabGraph[values.size()]; for (int i = 0; i < graphs.length; i++) { graphs[i] = (PrefabGraph) iter.next(); } m_queries = graphs; } public PrefabGraph[] getQueries(int nodeId) { return getQueries(String.valueOf(nodeId)); } public PrefabGraph[] getQueries(String nodeId) { if (nodeId == null) { throw new IllegalArgumentException("Cannot take null parameters."); } // create a temporary list of queries to return List returnList = new LinkedList(); // get the full list of all possible queries PrefabGraph[] queries = getQueries(); // get all the data sources supported by node List availDataSourceList = getDataSourceList(nodeId); // for each query, see if all the required data sources are available // in the available data source list, if so, add that query to the // returnList for (int i = 0; i < queries.length; i++) { List requiredList = Arrays.asList(queries[i].getColumns()); if (availDataSourceList.containsAll(requiredList)) { returnList.add(queries[i]); } } // put the queries in returnList into an array PrefabGraph[] availQueries = (PrefabGraph[]) returnList.toArray(new PrefabGraph[returnList.size()]); return availQueries; } public PrefabGraph[] getQueries(int nodeId, String intf, boolean includeNodeQueries) { boolean isNode = true; return getQueries(String.valueOf(nodeId), intf, includeNodeQueries, isNode); } public PrefabGraph[] getQueries(String nodeId, String intf, boolean includeNodeQueries) { boolean isNode = true; return getQueries(nodeId, intf, includeNodeQueries, isNode); } public PrefabGraph[] getQueries(String nodeOrDomain, String intf, boolean includeNodeQueries, boolean isNode) { if (nodeOrDomain == null || intf == null) { throw new IllegalArgumentException("Cannot take null parameters."); } // create a temporary list of queries to return List returnList = new LinkedList(); // get the full list of all possible queries PrefabGraph[] queries = getQueries(); // get all the data sources supported by this interface (and possibly // node) List availDataSourceList = getDataSourceList(nodeOrDomain, intf, includeNodeQueries, isNode); // for each query, see if all the required data sources are available // in the available data source list, if so, add that query to the // returnList for (int i = 0; i < queries.length; i++) { List requiredList = Arrays.asList(queries[i].getColumns()); if (availDataSourceList.containsAll(requiredList)) { if(isNode || queries[i].getExternalValues().length == 0) { returnList.add(queries[i]); } } } // put the queries in returnList into an array PrefabGraph[] availQueries = (PrefabGraph[]) returnList.toArray(new PrefabGraph[returnList.size()]); return availQueries; } public PrefabGraph[] getQueriesForDomain(String domain, String intf) { boolean includeNodeQueries = false; boolean isNode = false; return getQueries(domain, intf, includeNodeQueries, isNode); } public PrefabGraph[] getAllQueries(String nodeOrDomain, boolean isNode) { if (nodeOrDomain == null) { throw new IllegalArgumentException("Cannot take null parameters."); } Category log = ThreadCategory.getInstance(this.getClass()); boolean includeNodeQueries = false; HashMap queryCount = new HashMap(); String mostFreqQuery = "none"; int mostFreqCount = 0; // get the full list of all possible queries PrefabGraph[] queries = getQueries(); File nodeOrDomainDir = new File(getRrdDirectory(), nodeOrDomain); // get each interface directory File[] intfDir = nodeOrDomainDir.listFiles(RrdFileConstants.INTERFACE_DIRECTORY_FILTER); // for each interface directory, get all available data sources for (int j = 0; j < intfDir.length; j++) { String dirName = intfDir[j].getName(); List availDataSourceList = getDataSourceList(nodeOrDomain, dirName, includeNodeQueries, isNode); // for each query, see if all the required data sources are available // in the available data source list, if so, add that query to the // queryCount HashMap for (int i = 0; i < queries.length; i++) { String qname = queries[i].getName(); List requiredList = Arrays.asList(queries[i].getColumns()); if (availDataSourceList.containsAll(requiredList)) { if(isNode || queries[i].getExternalValues().length == 0) { if(queryCount.containsKey(queries[i])) { int x = ( (Integer) queryCount.get(queries[i])).intValue(); queryCount.put(queries[i], new Integer(x++)); } else { queryCount.put(queries[i], new Integer(1)); } if(( (Integer) queryCount.get(queries[i])).intValue() > mostFreqCount) { mostFreqCount = ( (Integer) queryCount.get(queries[i])).intValue(); mostFreqQuery = qname; } } } } } // put the queries in queryCount keySet into an array PrefabGraph[] availQueries = (PrefabGraph[]) queryCount.keySet().toArray(new PrefabGraph[queryCount.size() + 1]); // determine working default graph and copy to end of array. It will be pulled // off again by the calling method. for(int i = 0; i < queryCount.size(); i++ ) { if(availQueries[i].getName().equals(getDefaultReport())) { availQueries[queryCount.size()] = availQueries[i]; break; } if(availQueries[i].getName().equals(mostFreqQuery)) { availQueries[queryCount.size()] = availQueries[i]; } } if (log.isDebugEnabled() && queryCount.size() > 0) { if(availQueries[queryCount.size()].getName().equals(getDefaultReport())) { log.debug("Found default report " + getDefaultReport() + " in list of available queries"); } else { log.debug("Default report " + getDefaultReport() + " not found in list of available queries. Using most frequent query " + mostFreqQuery + " as the default."); } } return availQueries; } // Check to see whether any of the public String[] getDataSources listed below are used // Remove them if not. public String[] getDataSources(int nodeId) { return getDataSources(String.valueOf(nodeId)); } public String[] getDataSources(String nodeId) { List dataSourceList = getDataSourceList(String.valueOf(nodeId)); String[] dataSources = (String[]) dataSourceList.toArray(new String[dataSourceList.size()]); return dataSources; } public String[] getDataSources(int nodeId, String intf, boolean includeNodeQueries) { return getDataSources(String.valueOf(nodeId), intf, includeNodeQueries); } public String[] getDataSources(String nodeId, String intf, boolean includeNodeQueries) { List dataSourceList = getDataSourceList(String.valueOf(nodeId), intf, includeNodeQueries); String[] dataSources = (String[]) dataSourceList.toArray(new String[dataSourceList.size()]); return dataSources; } public List getDataSourceList(int nodeId) { return getDataSourceList(String.valueOf(nodeId)); } public List getDataSourceList(String nodeId) { if (nodeId == null) { throw new IllegalArgumentException("Cannot take null parameters."); } List dataSources = new LinkedList(); File nodeDir = new File(getRrdDirectory(), nodeId); int suffixLength = RrdFileConstants.RRD_SUFFIX.length(); // get the node data sources File[] nodeFiles = nodeDir.listFiles(RrdFileConstants.RRD_FILENAME_FILTER); if (nodeFiles != null) { for (int i = 0; i < nodeFiles.length; i++) { String fileName = nodeFiles[i].getName(); String dsName = fileName.substring(0, fileName.length() - suffixLength); dataSources.add(dsName); } } return dataSources; } public List getDataSourceList(int nodeId, String intf, boolean includeNodeQueries) { boolean isNode = true; return getDataSourceList(String.valueOf(nodeId), intf, includeNodeQueries, isNode); } public List getDataSourceList(String nodeIdOrDomain, String intf, boolean includeNodeQueries, boolean isNode) { Category log = ThreadCategory.getInstance(this.getClass()); if (nodeIdOrDomain == null || intf == null) { throw new IllegalArgumentException("Cannot take null parameters."); } List dataSources = new ArrayList(); File nodeOrDomainDir = new File(getRrdDirectory(), nodeIdOrDomain); File intfDir = new File(nodeOrDomainDir, intf); int suffixLength = RrdFileConstants.RRD_SUFFIX.length(); // get the node data sources if (includeNodeQueries && isNode) { dataSources.addAll(this.getDataSourceList(nodeIdOrDomain)); } // get the interface data sources File[] intfFiles = intfDir.listFiles(RrdFileConstants.RRD_FILENAME_FILTER); if (intfFiles == null) { // See if perhaps this is a response graph rather than a performance graph // TODO - Do this a better way. Should distinguish response from performance // coming in. log.debug("getDataSourceList: No interface files. Looking for performance data"); intfDir = new File(getRrdDirectory(), intf); intfFiles = intfDir.listFiles(RrdFileConstants.RRD_FILENAME_FILTER); } if (intfFiles != null) { for (int i = 0; i < intfFiles.length; i++) { String fileName = intfFiles[i].getName(); String dsName = fileName.substring(0, fileName.length() - suffixLength); dataSources.add(dsName); log.debug("getDataSourceList: adding " + dsName); } } return dataSources; } /** * Return a human-readable description (usually an IP address or hostname) * for the interface given. */ protected String getHumanReadableNameForIfLabel(int nodeId, String ifLabel, boolean isPerformanceModel) throws SQLException { if (nodeId < 1) { throw new IllegalArgumentException("Illegal nodeid encountered " + "when looking for performance " + "information: \"" + String.valueOf(nodeId) + "\""); } if (ifLabel == null) { throw new IllegalArgumentException("Cannot take null parameters."); } // Retrieve the extended information for this nodeid/ifLabel pair Map intfMap = IfLabel.getInterfaceInfoFromIfLabel(nodeId, ifLabel); StringBuffer descr = new StringBuffer(); /* * If there is no extended information, the ifLabel is not associated * with a current SNMP interface. */ if (intfMap.size() < 1) { descr.append(ifLabel); if (isPerformanceModel) { descr.append(" (Not Currently Updated)"); } } else { // Otherwise, add the extended information to the description StringBuffer parenString = new StringBuffer(); if (isPerformanceModel && intfMap.get("snmpifalias") != null) { parenString.append((String) intfMap.get("snmpifalias")); } if ((intfMap.get("ipaddr") != null) && !((String) intfMap.get("ipaddr")).equals("0.0.0.0")) { String ipaddr = (String) intfMap.get("ipaddr"); if (parenString.length() > 0) { parenString.append(", "); } parenString.append(ipaddr); } if ((intfMap.get("snmpifspeed") != null) && (Integer.parseInt((String) intfMap.get("snmpifspeed")) != 0)) { int intSpeed = Integer.parseInt((String) intfMap.get("snmpifspeed")); String speed = Util.getHumanReadableIfSpeed(intSpeed); if (parenString.length() > 0) { parenString.append(", "); } parenString.append(speed); } if (intfMap.get("snmpifname") != null) { descr.append((String) intfMap.get("snmpifname")); } else if (intfMap.get("snmpifdescr") != null) { descr.append((String) intfMap.get("snmpifdescr")); } else { /* * Should never reach this point, since ifLabel is based on * the values of ifName and ifDescr but better safe than sorry. */ descr.append(ifLabel); } /* Add the extended information in parenthesis after the ifLabel, * if such information was found. */ if (parenString.length() > 0) { descr.append(" ("); descr.append(parenString); descr.append(")"); } } return Util.htmlify(descr.toString()); } public abstract List getDataSourceList(String nodeId, String intf, boolean includeNodeQueries); public List getDataSourcesInDirectory(File directory) { int suffixLength = RrdFileConstants.RRD_SUFFIX.length(); // get the interface data sources File[] files = directory.listFiles(RrdFileConstants.RRD_FILENAME_FILTER); ArrayList dataSources = new ArrayList(files.length); for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); String dsName = fileName.substring(0, fileName.length() - suffixLength); dataSources.add(dsName); } return dataSources; } /** Convenient data structure for storing nodes with RRDs available. */ public static class QueryableNode { private int m_nodeId; private String m_nodeLabel; public QueryableNode(int nodeId, String nodeLabel) { m_nodeId = nodeId; m_nodeLabel = nodeLabel; } public int getNodeId() { return m_nodeId; } public String getNodeLabel() { return m_nodeLabel; } } }
package jade.core; import jade.util.leap.Properties; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Iterator; import jade.util.BasicProperties; import java.io.IOException; import java.net.*; import java.util.Hashtable; /** * This class allows the JADE core to retrieve configuration-dependent classes * and boot parameters. * <p> * Take care of using different instances of this class when launching * different containers/main-containers on the same JVM otherwise * they would conflict! * * @author Federico Bergenti * @author Giovanni Caire - TILAB * @author Giovanni Rimassa - Universita' di Parma * @version 1.0, 22/11/00 * */ public class ProfileImpl extends Profile { private BasicProperties props = null; // private Properties props = null; /** * Default communication port number. */ public static final int DEFAULT_PORT = 1099; /** This constant is the key of the property whose value is the class name of the mobility manager. **/ public static final String MOBILITYMGRCLASSNAME = "mobility"; private ServiceManager myServiceManager = null; private ServiceFinder myServiceFinder = null; private CommandProcessor myCommandProcessor = null; private MainContainerImpl myMain = null; private IMTPManager myIMTPManager = null; private ResourceManager myResourceManager = null; public ProfileImpl(BasicProperties aProp) { props = aProp; try { // Set default values String host = InetAddress.getLocalHost().getHostName(); props.setProperty(MAIN, "true"); props.setProperty(MAIN_PROTO, "rmi"); props.setProperty(MAIN_HOST, host); props.setProperty(MAIN_PORT, Integer.toString(DEFAULT_PORT)); updatePlatformID(); Specifier s = new Specifier(); s.setClassName("jade.mtp.iiop.MessageTransportProtocol"); List l = new ArrayList(1); l.add(s); props.put(MTPS, l); } catch (UnknownHostException uhe) { uhe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Creates a Profile implementation with the default configuration * for launching a main-container on the localhost, * RMI internal Message Transport Protocol, port number 1099, * iiop MTP. */ public ProfileImpl() { this(new BasicProperties()); } /** * This constructor creates a default Profile for launching a platform. * @param host is the name of the host where the main-container should * be listen to. A null value means use the default (i.e. localhost) * @param port is the port number where the main-container should be * listen * for other containers. A negative value should be used for using * the default port number. * @param platformID is the synbolic name of the platform, if * different from default. A null value means use the default * (i.e. localhost) **/ public ProfileImpl(String host, int port, String platformID) { this(); // Call default constructor if(host != null) props.setProperty(MAIN_HOST, host); if(port > 0) props.setIntProperty(MAIN_PORT, port); if(platformID != null) props.setProperty(PLATFORM_ID, platformID); else updatePlatformID(); } public void updatePlatformID() { String h = props.getProperty(MAIN_HOST); String p = props.getProperty(MAIN_PORT); props.setProperty(PLATFORM_ID, h + ":" + p + "/JADE"); } /** * Copy a collection of properties into this profile. * @param source The collection to be copied. */ void copyProperties(BasicProperties source) { props.copyProperties(source); } /** * Return the underlying properties collection. * @return BasicProperties The properties collection. */ public BasicProperties getProperties() { return props; } /** HP. private MainContainerImpl theMainContainer = null; public void addPlatformListener(AgentManager.Listener aListener) throws NotFoundException { if (theMainContainer == null) { throw new NotFoundException("Unable to add listener, main container not set"); } theMainContainer.addListener(aListener); } public void removePlatformListener(AgentManager.Listener aListener) throws NotFoundException { if (theMainContainer == null) { throw new NotFoundException("Unable to remove listener, main container not set"); } theMainContainer.removeListener(aListener); } **/ /** * Assign the given value to the given property name. * * @param key is the property name * @param value is the property value */ public void setParameter(String key, String value) { props.put(key, value); } /** * Assign the given property value to the given property name * * @param key is the property name * @param value is the property value */ public void setSpecifiers(String key, List value) { props.put(key, value); } /** Access the platform service manager. @return The platform service manager, either the real implementation or a remote proxy object. @throws ProfileException If some needed information is wrong or missing from the profile. */ protected ServiceManager getServiceManager() throws ProfileException { if(myServiceManager == null) { createServiceManager(); } return myServiceManager; } /** Access the platform service finder. @return The platform service finder, either the real implementation or a remote proxy object. @throws ProfileException If some needed information is wrong or missing from the profile. */ protected ServiceFinder getServiceFinder() throws ProfileException { if(myServiceFinder == null) { createServiceFinder(); } return myServiceFinder; } protected CommandProcessor getCommandProcessor() throws ProfileException { if(myCommandProcessor == null) { createCommandProcessor(); } return myCommandProcessor; } protected MainContainerImpl getMain() throws ProfileException { return myMain; } protected IMTPManager getIMTPManager() throws ProfileException { if (myIMTPManager == null) { createIMTPManager(); } return myIMTPManager; } public ResourceManager getResourceManager() throws ProfileException { if (myResourceManager == null) { createResourceManager(); } return myResourceManager; } public jade.security.PwdDialog getPwdDialog() throws ProfileException { //default is GUI swing password dialog String className = getParameter(PWD_DIALOG_CLASS, "jade.security.impl.PwdDialogSwingImpl"); jade.security.PwdDialog dialog=null; try { dialog = (jade.security.PwdDialog) Class.forName(className).newInstance(); } catch (Exception e) { //throw new ProfileException("Error loading jade.security password dialog:"+className); //e.printStackTrace(); System.out.println("\nError: Could not load jade.security password dialog class: '"+PWD_DIALOG_CLASS+"' "); System.out.println("\n Check parameter: '"+Profile.PWD_DIALOG_CLASS+"' in your JADE config file." ); System.out.println("\n Its default value is: jade.security.impl.PwdDialogSwingImpl" ); System.exit(-1); } return dialog; } private void createServiceManager() throws ProfileException { try { // Make sure the IMTP manager is initialized myIMTPManager = getIMTPManager(); // Make sure the Command Processor is initialized myCommandProcessor = getCommandProcessor(); String isMain = props.getProperty(MAIN); if(isMain == null || CaseInsensitiveString.equalsIgnoreCase(isMain, "true")) { // This is a main container: create a real Service Manager and export it myMain = new MainContainerImpl(this); myServiceManager = new ServiceManagerImpl(this, myMain); myIMTPManager.exportServiceManager((ServiceManagerImpl)myServiceManager); } else { // This is a peripheral container: create a Service Manager Proxy myServiceManager = myIMTPManager.createServiceManagerProxy(myCommandProcessor); } } catch(IMTPException imtpe) { ProfileException pe = new ProfileException("Can't get a proxy for the platform Service Manager"); pe.initCause(imtpe); throw pe; } } private void createServiceFinder() throws ProfileException { try { // Make sure the IMTP manager is initialized myIMTPManager = getIMTPManager(); String isMain = props.getProperty(MAIN); if(isMain == null || CaseInsensitiveString.equalsIgnoreCase(isMain, "true")) { // This is a main container: use the real // implementation of the Service Manager as the // service finder. myServiceFinder = (ServiceFinder)myServiceManager; } else { // This is a peripheral container: create a Service Finder Proxy myServiceFinder = myIMTPManager.createServiceFinderProxy(); } } catch(IMTPException imtpe) { ProfileException pe = new ProfileException("Can't get a proxy for the platform Service Manager"); pe.initCause(imtpe); throw pe; } } private void createCommandProcessor() throws ProfileException { try { myCommandProcessor = new CommandProcessor(); } catch(Exception e) { ProfileException pe = new ProfileException("Exception creating the Command Processor"); pe.initCause(e); throw pe; } } /** * Method declaration * * @throws ProfileException * * @see */ private void createIMTPManager() throws ProfileException { // Get the parameter from the profile, use the RMI IMTP by default String className = getParameter(IMTP, "jade.imtp.rmi.RMIIMTPManager"); try { myIMTPManager = (IMTPManager) Class.forName(className).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new ProfileException("Error loading IMTPManager class "+className); } } private void createResourceManager() throws ProfileException { myResourceManager = new FullResourceManager(); } /** * Retrieve a String value from the configuration properties. * If no parameter corresponding to the specified key is found, * return the provided default. * @param key The key identifying the parameter to be retrieved * among the configuration properties. */ public String getParameter(String key, String aDefault) { return props.getProperty(key, aDefault); } /** * Retrieve a list of Specifiers from the configuration properties. * Agents, MTPs and other items are specified among the configuration * properties in this way. * If no list of Specifiers corresponding to the specified key is found, * an empty list is returned. * @param key The key identifying the list of Specifiers to be retrieved * among the configuration properties. */ public List getSpecifiers(String key) throws ProfileException { // Check if the list of specs is already in the properties as a list List l = null; try { l = (List) props.get(key); if (l == null) { l = new ArrayList(0); } return l; } catch (ClassCastException cce) { } // Otherwise the list should be present as a string --> parse it String specsLine = getParameter(key, null); try { return Specifier.parseSpecifierList(specsLine); } catch (Exception e) { throw new ProfileException("Error parsing specifier list "+specsLine+". "+e.getMessage()); } } public String toString() { StringBuffer str = new StringBuffer("(Profile"); String[] properties = props.toStringArray(); if (properties != null) for (int i=0; i<properties.length; i++) str.append(" "+properties[i]); str.append(")"); return str.toString(); } }
package de.mxro.metrics; import de.mxro.async.callbacks.ValueCallback; import de.mxro.async.promise.Promise; import de.mxro.fn.Success; import de.mxro.metrics.helpers.RecordOperation; public interface MetricsNode { public void record(RecordOperation op); public <T> Promise<T> retrieve(String id, Class<T> type); public <T> void retrieve(String id, Class<T> type, ValueCallback<T> cb); /** * <p> * Retrieves a metric with the specified id. * * @param id * @return */ public Promise<Object> retrieve(String id); public void retrieve(String id, ValueCallback<Object> cb); public Promise<Success> stop(); public void stop(ValueCallback<Success> cb); /** * Prints all metrics to standard out. */ public void print(); }
package com.example.iuris.ustglobalproject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LoginJSON { @SerializedName("login") @Expose private String login; @SerializedName("password") @Expose private String password; /** * @return The login */ public String getLogin() { return login; } /** * @param login The login */ public void setLogin(String login) { this.login = login; } /** * @return The password */ public String getPassword() { return password; } /** * @param password The password */ public void setPassword(String password) { this.password = password; } }
package com.epam.ta.reportportal.ws.model; import com.epam.ta.reportportal.ws.annotations.ElementLength; import com.epam.ta.reportportal.ws.annotations.NotEmpty; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; import java.util.Set; import static com.epam.ta.reportportal.ws.model.ValidationConstraints.MAX_NAME_LENGTH; /** * Base entity for start requests * * @author Andrei Varabyeu */ @JsonInclude(Include.NON_NULL) public class StartRQ { @NotNull @NotEmpty @Size(min = ValidationConstraints.MIN_LAUNCH_NAME_LENGTH, max = ValidationConstraints.MAX_NAME_LENGTH) @JsonProperty(value = "name", required = true) @ApiModelProperty(required = true) private String name; @JsonProperty(value = "description") private String description; @ElementLength(max = MAX_NAME_LENGTH) @JsonProperty("attributes") private Set<ItemAttributeResource> attributes; @NotNull @JsonProperty(value = "startTime", required = true) @ApiModelProperty(required = true) private Date startTime; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Set<ItemAttributeResource> getAttributes() { return attributes; } public void setAttributes(Set<ItemAttributeResource> attributes) { this.attributes = attributes; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public String toString() { final StringBuilder sb = new StringBuilder("StartRQ{"); sb.append("name='").append(name).append('\''); sb.append(", description='").append(description).append('\''); sb.append(", attributes=").append(attributes); sb.append(", startTime=").append(startTime); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StartRQ startRQ = (StartRQ) o; if (name != null ? !name.equals(startRQ.name) : startRQ.name != null) { return false; } if (description != null ? !description.equals(startRQ.description) : startRQ.description != null) { return false; } if (attributes != null ? !attributes.equals(startRQ.attributes) : startRQ.attributes != null) { return false; } return startTime != null ? startTime.equals(startRQ.startTime) : startRQ.startTime == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (attributes != null ? attributes.hashCode() : 0); result = 31 * result + (startTime != null ? startTime.hashCode() : 0); return result; } }
package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.Range; import org.jfree.data.xy.VectorXYDataset; import org.jfree.data.xy.XYDataset; /** * A renderer that represents data from an {@link VectorXYDataset} by drawing a * line with an arrow at each (x, y) point. * * @since 1.0.6 */ public class VectorRenderer extends AbstractXYItemRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** The length of the base. */ private double baseLength = 0.10; /** The length of the head. */ private double headLength = 0.14; /** * Creates a new <code>XYBlockRenderer</code> instance with default * attributes. */ public VectorRenderer() { } /** * Returns the lower and upper bounds (range) of the x-values in the * specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ public Range findDomainBounds(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; if (dataset instanceof VectorXYDataset) { VectorXYDataset vdataset = (VectorXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double delta = vdataset.getVectorXValue(series, item); if (delta < 0.0) { uvalue = vdataset.getXValue(series, item); lvalue = uvalue + delta; } else { lvalue = vdataset.getXValue(series, item); uvalue = lvalue + delta; } minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getXValue(series, item); uvalue = lvalue; minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Returns the range of values the renderer requires to display all the * items from the specified dataset. * * @param dataset the dataset (<code>null</code> permitted). * * @return The range (<code>null</code> if the dataset is <code>null</code> * or empty). */ public Range findRangeBounds(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; if (dataset instanceof VectorXYDataset) { VectorXYDataset vdataset = (VectorXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double delta = vdataset.getVectorYValue(series, item); if (delta < 0.0) { uvalue = vdataset.getYValue(series, item); lvalue = uvalue + delta; } else { lvalue = vdataset.getYValue(series, item); uvalue = lvalue + delta; } minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getYValue(series, item); uvalue = lvalue; minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Draws the block representing the specified item. * * @param g2 the graphics device. * @param state the state. * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the x-axis. * @param rangeAxis the y-axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double dx = 0.0; double dy = 0.0; if (dataset instanceof VectorXYDataset) { dx = ((VectorXYDataset) dataset).getVectorXValue(series, item); dy = ((VectorXYDataset) dataset).getVectorYValue(series, item); } double xx0 = domainAxis.valueToJava2D(x, dataArea, plot.getDomainAxisEdge()); double yy0 = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()); double xx1 = domainAxis.valueToJava2D(x + dx, dataArea, plot.getDomainAxisEdge()); double yy1 = rangeAxis.valueToJava2D(y + dy, dataArea, plot.getRangeAxisEdge()); Line2D line; PlotOrientation orientation = plot.getOrientation(); if (orientation.equals(PlotOrientation.HORIZONTAL)) { line = new Line2D.Double(yy0, xx0, yy1, xx1); } else { line = new Line2D.Double(xx0, yy0, xx1, yy1); } g2.setPaint(getItemPaint(series, item)); g2.setStroke(getItemStroke(series, item)); g2.draw(line); // calculate the arrow head and draw it... double dxx = (xx1 - xx0); double dyy = (yy1 - yy0); double bx = xx0 + (1.0 - this.baseLength) * dxx; double by = yy0 + (1.0 - this.baseLength) * dyy; double cx = xx0 + (1.0 - this.headLength) * dxx; double cy = yy0 + (1.0 - this.headLength) * dyy; double angle = 0.0; if (dxx != 0.0) { angle = Math.PI / 2.0 - Math.atan(dyy / dxx); } double deltaX = 2.0 * Math.cos(angle); double deltaY = 2.0 * Math.sin(angle); double leftx = cx + deltaX; double lefty = cy - deltaY; double rightx = cx - deltaX; double righty = cy + deltaY; GeneralPath p = new GeneralPath(); if (orientation == PlotOrientation.VERTICAL) { p.moveTo((float) xx1, (float) yy1); p.lineTo((float) rightx, (float) righty); p.lineTo((float) bx, (float) by); p.lineTo((float) leftx, (float) lefty); } else { // orientation is HORIZONTAL p.moveTo((float) yy1, (float) xx1); p.lineTo((float) righty, (float) rightx); p.lineTo((float) by, (float) bx); p.lineTo((float) lefty, (float) leftx); } p.closePath(); g2.draw(p); // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); if (entities != null) { addEntity(entities, line.getBounds(), dataset, series, item, 0.0, 0.0); } } } /** * Tests this <code>VectorRenderer</code> for equality with an arbitrary * object. This method returns <code>true</code> if and only if: * <ul> * <li><code>obj</code> is an instance of <code>VectorRenderer</code> (not * <code>null</code>);</li> * <li><code>obj</code> has the same field values as this * <code>VectorRenderer</code>;</li> * </ul> * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof VectorRenderer)) { return false; } VectorRenderer that = (VectorRenderer) obj; if (this.baseLength != that.baseLength) { return false; } if (this.headLength != that.headLength) { return false; } return super.equals(obj); } /** * Returns a clone of this renderer. * * @return A clone of this renderer. * * @throws CloneNotSupportedException if there is a problem creating the * clone. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package amu.zhcet.firebase; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.annotation.Cacheable; import org.springframework.http.CacheControl; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; @Slf4j @RestController public class FirebaseConfigController { private final FirebaseProperties firebaseProperties; private final TemplateEngine templateEngine; private Context firebaseContext; @Autowired public FirebaseConfigController(FirebaseProperties firebaseProperties, @Qualifier("extraTemplateEngine") TemplateEngine templateEngine) { this.firebaseProperties = firebaseProperties; this.templateEngine = templateEngine; } private Context getFirebaseContext() { if (firebaseContext == null) { Map<String, Object> payload = new HashMap<>(); payload.put("config", firebaseProperties.getConfig()); firebaseContext = new Context(Locale.getDefault(), payload); } return firebaseContext; } @Cacheable("firebase-config") @GetMapping("/js/firebase-config.js") public ResponseEntity<String> firebaseConfig() { String rendered = templateEngine.process("js/firebase-config", getFirebaseContext()); return ResponseEntity.accepted() .contentType(MediaType.parseMediaType("text/javascript")) .cacheControl(CacheControl .maxAge(365, TimeUnit.DAYS) .sMaxAge(365, TimeUnit.DAYS) .cachePublic()) .body(rendered); } @Cacheable("firebase-messaging-sw") @GetMapping("/firebase-messaging-sw.js") public ResponseEntity<String> firebaseMessagingSw() { String rendered = templateEngine.process("js/firebase-messaging-sw", getFirebaseContext()); return ResponseEntity.accepted() .contentType(MediaType.parseMediaType("text/javascript")) .cacheControl(CacheControl .maxAge(1, TimeUnit.DAYS) .sMaxAge(1, TimeUnit.DAYS)) .body(rendered); } }
package org.concord.sensor.impl; import org.concord.framework.data.stream.DataChannelDescription; import org.concord.framework.data.stream.DataStreamDescription; import org.concord.sensor.ExperimentConfig; import org.concord.sensor.ExperimentRequest; import org.concord.sensor.SensorConfig; import org.concord.sensor.SensorRequest; /** * @author scott * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class DataStreamDescUtil { /** * The result can be null. * * @param dDesc * @param request * @param result */ public static void setupDescription(DataStreamDescription dDesc, ExperimentRequest request, ExperimentConfig result) { SensorConfig [] sensConfigs = null; SensorRequest [] sensRequests = request.getSensorRequests(); int firstValueChannelIndex = 0; if(result != null) { sensConfigs = result.getSensorConfigs(); } dDesc.setChannelsPerSample(sensRequests.length); if(result != null) { dDesc.setDt(result.getPeriod()); DataChannelDescription chDescrip = new DataChannelDescription(); chDescrip.setName("time"); chDescrip.setUnit(new SensorUnit("s")); chDescrip.setPrecision(-2); chDescrip.setNumericData(true); if(result.getExactPeriod()) { dDesc.setDataType(DataStreamDescription.DATA_SEQUENCE); dDesc.setDtChannelDescription(chDescrip); } else { dDesc.setDataType(DataStreamDescription.DATA_SERIES); dDesc.setChannelDescription(chDescrip, 0); firstValueChannelIndex = 1; dDesc.setChannelsPerSample(sensRequests.length+1); } } else { dDesc.setDt(request.getPeriod()); } for(int i=0; i<sensRequests.length; i++) { DataChannelDescription chDescrip = new DataChannelDescription(); if(result != null) { chDescrip.setName(sensConfigs[i].getName()); } chDescrip.setUnit(sensRequests[i].getUnit()); chDescrip.setPrecision(sensRequests[i].getDisplayPrecision()); chDescrip.setNumericData(true); dDesc.setChannelDescription(chDescrip, i+firstValueChannelIndex); } } }
package dk.itu.kelvin.parser; // I/O utilities import java.io.File; // File type utilities import javax.activation.FileTypeMap; import javax.activation.MimetypesFileTypeMap; // Utilities import dk.itu.kelvin.util.Collection; // Functional utilities import dk.itu.kelvin.util.function.Callback; // Threading import dk.itu.kelvin.thread.TaskQueue; // Models import dk.itu.kelvin.model.Address; import dk.itu.kelvin.model.BoundingBox; import dk.itu.kelvin.model.Land; import dk.itu.kelvin.model.Node; import dk.itu.kelvin.model.Relation; import dk.itu.kelvin.model.Way; /** * Parser class. */ public abstract class Parser { private static final FileTypeMap TYPES = new MimetypesFileTypeMap(); /** * Read and parse an input file. * * <p> * All I/O and parsing takes place on a separate thread and the specified * callback is invoked once the parsing has finished. * * @param file The file to read. * @param callback The callback to invoke once the parsing has finished. */ public void read(final File file, final Callback callback) { TaskQueue.run(() -> { try { this.parse(file); } catch (Exception ex) { ex.printStackTrace(); } finally { callback.done(); } }); } /** * Parse the contents of the specified file. * * <p> * This method must be implemented by superclasses and is where the actual * file parsing happens. * * @param file The file whose contents to parse. * * @throws Exception In case of an error during parsing. */ protected abstract void parse(final File file) throws Exception; /** * Get the parsed bounds. * * @return The parsed bounds. */ public abstract BoundingBox bounds(); /** * Get the parsed node elements. * * @return The parsed node elements. */ public abstract Collection<Node> nodes(); /** * Get the parsed way elements. * * @return The parsed way elements. */ public abstract Collection<Way> ways(); /** * Get the parsed relation elements. * * @return The parsed relation elements. */ public abstract Collection<Relation> relations(); /** * Get the parsed land polygons. * * @return The parsed land polygons. */ public abstract Collection<Way> land(); /** * Get the parsed addresses. * * @return The parsed addresses. */ public abstract Collection<Address> addresses(); /** * Return a parser instance that can parse the specified file. * * @param file The file to find a matching parser for. * @return A parser instance that can parse the specified file or * {@code null} if no matching parser was found. */ public static final Parser probe(final File file) { if (file == null || !file.isFile()) { return null; } // Get the MIME type of the file. String type = TYPES.getContentType(file); switch (type.toLowerCase()) { case "application/xml": case "application/x-bzip2": return null; case "application/octet-stream": return null; default: return null; } } }
package com.futurice.freesound.utils; import android.support.annotation.Nullable; import java.util.Collection; import java.util.Iterator; public final class CollectionUtils { /** * Verifies if the content of the collections is the same. * * @param first Collection * @param second Collection * @return True if the content and the order of the collection are equal, otherwise false */ public static <T> boolean areEqual(@Nullable final Collection<T> first, @Nullable final Collection<T> second) { if (first == null || second == null || first.size() != second.size()) { return false; } Iterator<T> firstIterator = first.iterator(); Iterator<T> secondIterator = second.iterator(); while (firstIterator.hasNext()) { if (!firstIterator.next().equals(secondIterator.next())) { return false; } } return true; } }
package com.primix.tapestry.form; import com.primix.tapestry.*; // Appease Javadoc import com.primix.tapestry.util.*; /** * A component which uses either * &lt;select&gt; and &lt;option&gt; elements * or &lt;input type=radio&gt; to * set a property of some object. Typically, the values for the object * are defined using an {@link Enum}. A PropertySelection is dependent on * an {@link IPropertySelectionModel} to provide the list of possible values. * * <p>Often, this is used to select a particular {@link Enum} to assign to a property; the * {@link EnumPropertySelectionModel} class simplifies this. * * <p> * * <table border=1> * <tr> * <td>Parameter</td> * <td>Type</td> * <td>Read / Write </td> * <td>Required</td> * <td>Default</td> * <td>Description</td> * </tr> * * <tr> * <td>value</td> * <td>java.lang.Object</td> * <td>R / W</td> * <td>yes</td> * <td>&nbsp;</td> * <td>The property to set. During rendering, this property is read, and sets * the default value of the selection (if it is null, no element is selected). * When the form is submitted, this property is updated based on the new * selection. </td> </tr> * * <tr> * <td>renderer</td> * <td>{@link IPropertySelectionRenderer}</td> * <td>R</td> * <td>no</td> * <td>shared instance of {@link SelectPropertySelectionRenderer}</td> * <td>Defines the object used to render the PropertySelection. * <p>{@link SelectPropertySelectionRenderer} renders the component as a &lt;select&gt;. * <p>{@link RadioPropertySelectionRenderer} renders the component as a table of * radio buttons.</td></tr> * * <tr> * <td>model</td> * <td>{@link IPropertySelectionModel}</td> * <td>R</td> * <td>yes</td> * <td>&nbsp;</td> * <td>The model provides a list of possible labels, and matches those labels * against possible values that can be assigned back to the property.</td> </tr> * * <tr> * <td>disabled</td> * <td>boolean</td> * <td>R</td> * <td>no</td> * <td>false</td> * <td>Controls whether the &lt;select&gt; is active or not. A disabled PropertySelection * does not update its value parameter. * * <p>Corresponds to the <code>disabled</code> HTML attribute.</td> * </tr> * * </table> * * <p>Informal parameters are allowed, and are applied to the &lt;select&gt; element. * A body is not allowed. * * * @version $Id$ * @author Howard Ship * */ public class PropertySelection extends AbstractFormComponent { private IBinding valueBinding; private IBinding modelBinding; private IBinding disabledBinding; private IBinding rendererBinding; private String name; private boolean disabled; /** * A shared instance of {@link SelectPropertySelectionRenderer}. * */ public static final IPropertySelectionRenderer DEFAULT_SELECT_RENDERER = new SelectPropertySelectionRenderer(); /** * A shared instance of {@link RadioPropertySelectionRenderer}. * */ public static final IPropertySelectionRenderer DEFAULT_RADIO_RENDERER = new RadioPropertySelectionRenderer(); public IBinding getValueBinding() { return valueBinding; } public void setValueBinding(IBinding value) { valueBinding = value; } public IBinding getModelBinding() { return modelBinding; } public void setModelBinding(IBinding value) { modelBinding = value; } public IBinding getDisabledBinding() { return disabledBinding; } public void setDisabledBinding(IBinding value) { disabledBinding = value; } public void setRendererBinding(IBinding value) { rendererBinding = value; } public IBinding getRendererBinding() { return rendererBinding; } /** * Returns the name assigned to this PropertySelection by the {@link Form} * that wraps it. * */ public String getName() { return name; } /** * Returns true if this PropertySelection's disabled parameter yields true. * The corresponding HTML control(s) should be disabled. */ public boolean isDisabled() { return disabled; } /** * Returns the default {@link SelectPropertySelectionRenderer} instance. * This is a shared instance. * * @deprecated Use {@link #DEFAULT_SELECT_RENDERER} instead. */ public IPropertySelectionRenderer getDefaultSelectRenderer() { return DEFAULT_SELECT_RENDERER; } /** * Returns a shared instance of {@link RadioPropertySelectionRenderer}. * * @deprecated Use {@link #DEFAULT_RADIO_RENDERER instead}. */ public IPropertySelectionRenderer getDefaultRadioRenderer() { return DEFAULT_RADIO_RENDERER; } /** * Renders the component, much of which is the responsiblity * of the {@link IPropertySelectionRenderer renderer}. The possible options, * thier labels, and the values to be encoded in the form are provided * by the {@link IPropertySelectionModel model}. * */ public void render(IResponseWriter writer, IRequestCycle cycle) throws RequestCycleException { IPropertySelectionRenderer renderer = null; Object newValue; Object currentValue; Object option; String optionValue; int i; boolean selected = false; boolean foundSelected = false; int count; boolean radio = false; IForm form = getForm(cycle); boolean rewinding = form.isRewinding(); if (disabledBinding == null) disabled = false; else disabled = disabledBinding.getBoolean(); IPropertySelectionModel model = (IPropertySelectionModel) modelBinding.getObject( "model", IPropertySelectionModel.class); if (model == null) throw new RequiredParameterException(this, "model", modelBinding); name = form.getElementId(this); if (rewinding) { // If disabled, ignore anything that comes up from the client. if (disabled) return; optionValue = cycle.getRequestContext().getParameter(name); if (optionValue == null) newValue = null; else newValue = model.translateValue(optionValue); valueBinding.setObject(newValue); return; } if (rendererBinding != null) renderer = (IPropertySelectionRenderer) rendererBinding.getObject( "renderer", IPropertySelectionRenderer.class); if (renderer == null) renderer = getDefaultSelectRenderer(); renderer.beginRender(this, writer, cycle); count = model.getOptionCount(); currentValue = valueBinding.getObject(); for (i = 0; i < count; i++) { option = model.getOption(i); if (!foundSelected) { selected = isEqual(option, currentValue); if (selected) foundSelected = true; } renderer.renderOption(this, writer, cycle, model, option, i, selected); selected = false; } // A PropertySelection doesn't allow a body, so no need to worry about // wrapped components. renderer.endRender(this, writer, cycle); } private boolean isEqual(Object left, Object right) { // Both null, or same object, then are equal if (left == right) return true; // If one is null, the other isn't, then not equal. if (left == null || right == null) return false; // Both non-null; use standard comparison. return left.equals(right); } }
package org.jfree.data.statistics; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; /** * A dataset that can be used for creating histograms. * * @see SimpleHistogramDataset */ public class HistogramDataset extends AbstractIntervalXYDataset implements IntervalXYDataset, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6341668077370231153L; /** A list of maps. */ private List list; /** The histogram type. */ private HistogramType type; /** * Creates a new (empty) dataset with a default type of * {@link HistogramType}.FREQUENCY. */ public HistogramDataset() { this.list = new ArrayList(); this.type = HistogramType.FREQUENCY; } /** * Returns the histogram type. * * @return The type (never <code>null</code>). */ public HistogramType getType() { return this.type; } /** * Sets the histogram type and sends a {@link DatasetChangeEvent} to all * registered listeners. * * @param type the type (<code>null</code> not permitted). */ public void setType(HistogramType type) { if (type == null) { throw new IllegalArgumentException("Null 'type' argument"); } this.type = type; notifyListeners(new DatasetChangeEvent(this, this)); } /** * Adds a series to the dataset, using the specified number of bins. * * @param key the series key (<code>null</code> not permitted). * @param values the values (<code>null</code> not permitted). * @param bins the number of bins (must be at least 1). */ public void addSeries(Comparable key, double[] values, int bins) { // defer argument checking... double minimum = getMinimum(values); double maximum = getMaximum(values); addSeries(key, values, bins, minimum, maximum); } /** * Adds a series to the dataset. Any data value less than minimum will be * assigned to the first bin, and any data value greater than maximum will * be assigned to the last bin. Values falling on the boundary of * adjacent bins will be assigned to the higher indexed bin. * * @param key the series key (<code>null</code> not permitted). * @param values the raw observations. * @param bins the number of bins (must be at least 1). * @param minimum the lower bound of the bin range. * @param maximum the upper bound of the bin range. */ public void addSeries(Comparable key, double[] values, int bins, double minimum, double maximum) { if (key == null) { throw new IllegalArgumentException("Null 'key' argument."); } if (values == null) { throw new IllegalArgumentException("Null 'values' argument."); } else if (bins < 1) { throw new IllegalArgumentException( "The 'bins' value must be at least 1."); } double binWidth = (maximum - minimum) / bins; double lower = minimum; double upper; List binList = new ArrayList(bins); for (int i = 0; i < bins; i++) { HistogramBin bin; // make sure bins[bins.length]'s upper boundary ends at maximum // to avoid the rounding issue. the bins[0] lower boundary is // guaranteed start from min if (i == bins - 1) { bin = new HistogramBin(lower, maximum); } else { upper = minimum + (i + 1) * binWidth; bin = new HistogramBin(lower, upper); lower = upper; } binList.add(bin); } // fill the bins for (int i = 0; i < values.length; i++) { int binIndex = bins - 1; if (values[i] < maximum) { double fraction = (values[i] - minimum) / (maximum - minimum); if (fraction < 0.0) { fraction = 0.0; } binIndex = (int) (fraction * bins); // rounding could result in binIndex being equal to bins // which will cause an IndexOutOfBoundsException - see bug // report 1553088 if (binIndex >= bins) { binIndex = bins - 1; } } HistogramBin bin = (HistogramBin) binList.get(binIndex); bin.incrementCount(); } // generic map for each series Map map = new HashMap(); map.put("key", key); map.put("bins", binList); map.put("values.length", new Integer(values.length)); map.put("bin width", new Double(binWidth)); this.list.add(map); } /** * Returns the minimum value in an array of values. * * @param values the values (<code>null</code> not permitted and * zero-length array not permitted). * * @return The minimum value. */ private double getMinimum(double[] values) { if (values == null || values.length < 1) { throw new IllegalArgumentException( "Null or zero length 'values' argument."); } double min = Double.MAX_VALUE; for (int i = 0; i < values.length; i++) { if (values[i] < min) { min = values[i]; } } return min; } /** * Returns the maximum value in an array of values. * * @param values the values (<code>null</code> not permitted and * zero-length array not permitted). * * @return The maximum value. */ private double getMaximum(double[] values) { if (values == null || values.length < 1) { throw new IllegalArgumentException( "Null or zero length 'values' argument."); } double max = -Double.MAX_VALUE; for (int i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } return max; } /** * Returns the bins for a series. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * * @return A list of bins. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ List getBins(int series) { Map map = (Map) this.list.get(series); return (List) map.get("bins"); } /** * Returns the total number of observations for a series. * * @param series the series index. * * @return The total. */ private int getTotal(int series) { Map map = (Map) this.list.get(series); return ((Integer) map.get("values.length")).intValue(); } /** * Returns the bin width for a series. * * @param series the series index (zero based). * * @return The bin width. */ private double getBinWidth(int series) { Map map = (Map) this.list.get(series); return ((Double) map.get("bin width")).doubleValue(); } /** * Returns the number of series in the dataset. * * @return The series count. */ public int getSeriesCount() { return this.list.size(); } /** * Returns the key for a series. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * * @return The series key. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Comparable getSeriesKey(int series) { Map map = (Map) this.list.get(series); return (Comparable) map.get("key"); } /** * Returns the number of data items for a series. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * * @return The item count. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public int getItemCount(int series) { return getBins(series).size(); } /** * Returns the X value for a bin. This value won't be used for plotting * histograms, since the renderer will ignore it. But other renderers can * use it (for example, you could use the dataset to create a line * chart). * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The start value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getX(int series, int item) { List bins = getBins(series); HistogramBin bin = (HistogramBin) bins.get(item); double x = (bin.getStartBoundary() + bin.getEndBoundary()) / 2.; return new Double(x); } /** * Returns the y-value for a bin (calculated to take into account the * histogram type). * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The y-value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getY(int series, int item) { List bins = getBins(series); HistogramBin bin = (HistogramBin) bins.get(item); double total = getTotal(series); double binWidth = getBinWidth(series); if (this.type == HistogramType.FREQUENCY) { return new Double(bin.getCount()); } else if (this.type == HistogramType.RELATIVE_FREQUENCY) { return new Double(bin.getCount() / total); } else if (this.type == HistogramType.SCALE_AREA_TO_1) { return new Double(bin.getCount() / (binWidth * total)); } else { // pretty sure this shouldn't ever happen throw new IllegalStateException(); } } /** * Returns the start value for a bin. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The start value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getStartX(int series, int item) { List bins = getBins(series); HistogramBin bin = (HistogramBin) bins.get(item); return new Double(bin.getStartBoundary()); } /** * Returns the end value for a bin. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The end value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getEndX(int series, int item) { List bins = getBins(series); HistogramBin bin = (HistogramBin) bins.get(item); return new Double(bin.getEndBoundary()); } /** * Returns the start y-value for a bin (which is the same as the y-value, * this method exists only to support the general form of the * {@link IntervalXYDataset} interface). * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The y-value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getStartY(int series, int item) { return getY(series, item); } /** * Returns the end y-value for a bin (which is the same as the y-value, * this method exists only to support the general form of the * {@link IntervalXYDataset} interface). * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * @param item the item index (zero based). * * @return The Y value. * * @throws IndexOutOfBoundsException if <code>series</code> is outside the * specified range. */ public Number getEndY(int series, int item) { return getY(series, item); } /** * Tests this dataset for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof HistogramDataset)) { return false; } HistogramDataset that = (HistogramDataset) obj; if (!ObjectUtilities.equal(this.type, that.type)) { return false; } if (!ObjectUtilities.equal(this.list, that.list)) { return false; } return true; } /** * Returns a clone of the dataset. * * @return A clone of the dataset. * * @throws CloneNotSupportedException if the object cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package ar.com.fernandospr.wns.model; import java.util.ArrayList; import ar.com.fernandospr.wns.model.types.WnsTileTemplate; public class WnsTileBuilder { private WnsTile tile; public WnsTileBuilder() { this.tile = new WnsTile(); } protected WnsVisual getVisual() { if (this.tile.visual == null) { this.tile.visual = new WnsVisual(); } return this.tile.visual; } protected WnsBinding getBinding() { if (getVisual().binding == null) { getVisual().binding = new WnsBinding(); } return this.tile.visual.binding; } public WnsTileBuilder visualVersion(Integer version) { getVisual().version = version; return this; } public WnsTileBuilder visualLang(String lang) { getVisual().lang = lang; return this; } public WnsTileBuilder visualBaseUri(String baseUri) { getVisual().baseUri = baseUri; return this; } public WnsTileBuilder visualBranding(String branding) { getVisual().branding = branding; return this; } public WnsTileBuilder visualAddImageQuery(Boolean addImageQuery) { getVisual().addImageQuery = addImageQuery; return this; } public WnsTileBuilder bindingFallback(String fallback) { getBinding().fallback = fallback; return this; } public WnsTileBuilder bindingLang(String lang) { getBinding().lang = lang; return this; } public WnsTileBuilder bindingBaseUri(String baseUri) { getBinding().baseUri = baseUri; return this; } public WnsTileBuilder bindingBranding(String branding) { getBinding().branding = branding; return this; } public WnsTileBuilder bindingAddImageQuery(Boolean addImageQuery) { getBinding().addImageQuery = addImageQuery; return this; } /** * @param template should be any of {@link ar.com.fernandospr.wns.model.types.WnsTileTemplate} */ protected WnsTileBuilder bindingTemplate(String template) { getBinding().template = template; getBinding().texts = null; getBinding().images = null; return this; } public WnsTileBuilder bindingTemplateTileSquareBlock(String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREBLOCK) .setBindingTextFields(textField1, textField2); } public WnsTileBuilder bindingTemplateTileSquareText01(String textField1, String textField2, String textField3, String textField4) { return this.bindingTemplate(WnsTileTemplate.TILESQUARETEXT01) .setBindingTextFields(textField1, textField2, textField3, textField4); } public WnsTileBuilder bindingTemplateTileSquareText02(String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILESQUARETEXT02) .setBindingTextFields(textField1, textField2); } public WnsTileBuilder bindingTemplateTileSquareText03(String textField1, String textField2, String textField3, String textField4) { return this.bindingTemplate(WnsTileTemplate.TILESQUARETEXT03) .setBindingTextFields(textField1, textField2, textField3, textField4); } public WnsTileBuilder bindingTemplateTileSquareText04(String textField1) { return this.bindingTemplate(WnsTileTemplate.TILESQUARETEXT04) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileSquareImage(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREIMAGE) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileSquarePeekImageAndText01(String imgSrc1, String textField1, String textField2, String textField3, String textField4) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREPEEKIMAGEANDTEXT01) .setBindingTextFields(textField1, textField2, textField3, textField4) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileSquarePeekImageAndText02(String imgSrc1, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREPEEKIMAGEANDTEXT02) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileSquarePeekImageAndText03(String imgSrc1, String textField1, String textField2, String textField3, String textField4) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREPEEKIMAGEANDTEXT03) .setBindingTextFields(textField1, textField2, textField3, textField4) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileSquarePeekImageAndText04(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILESQUAREPEEKIMAGEANDTEXT04) .setBindingImages(imgSrc1) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWideText01(String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT01) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5); } public WnsTileBuilder bindingTemplateTileWideText02(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT02) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9); } public WnsTileBuilder bindingTemplateTileWideText03(String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT03) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWideText04(String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT04) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWideText05(String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT05) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5); } public WnsTileBuilder bindingTemplateTileWideText06(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9, String textField10) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT06) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9, textField10); } public WnsTileBuilder bindingTemplateTileWideText07(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT07) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9); } public WnsTileBuilder bindingTemplateTileWideText08(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9, String textField10) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT08) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9, textField10); } public WnsTileBuilder bindingTemplateTileWideText09(String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT09) .setBindingTextFields(textField1, textField2); } public WnsTileBuilder bindingTemplateTileWideText10(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT10) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9); } public WnsTileBuilder bindingTemplateTileWideText11(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6, String textField7, String textField8, String textField9, String textField10) { return this.bindingTemplate(WnsTileTemplate.TILEWIDETEXT11) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6, textField7, textField8, textField9, textField10); } public WnsTileBuilder bindingTemplateTileWideImage(String imgSrc1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEIMAGE) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideImageCollection(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEIMAGECOLLECTION) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5); } public WnsTileBuilder bindingTemplateTileWideImageAndText01(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEIMAGEANDTEXT01) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideImageAndText02(String imgSrc1, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEIMAGEANDTEXT02) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideBlockAndText01(String textField1, String textField2, String textField3, String textField4, String textField5, String textField6) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEBLOCKANDTEXT01) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5, textField6); } public WnsTileBuilder bindingTemplateTileWideBlockAndText02(String textField1, String textField2, String textField3) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEBLOCKANDTEXT02) .setBindingTextFields(textField1, textField2, textField3); } public WnsTileBuilder bindingTemplateTileWideSmallImageAndText01(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDESMALLIMAGEANDTEXT01) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideSmallImageAndText02(String imgSrc1, String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDESMALLIMAGEANDTEXT02) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideSmallImageAndText03(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDESMALLIMAGEANDTEXT03) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideSmallImageAndText04(String imgSrc1, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDESMALLIMAGEANDTEXT04) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWideSmallImageAndText05(String imgSrc1, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDESMALLIMAGEANDTEXT05) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection01(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION01) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5) .setBindingTextFields(textField1, textField2); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection02(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION02) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection03(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION03) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection04(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION04) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection05(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String imgSrc6, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION05) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5, imgSrc6) .setBindingTextFields(textField1, textField2); } public WnsTileBuilder bindingTemplateTileWidePeekImageCollection06(String imgSrc1, String imgSrc2, String imgSrc3, String imgSrc4, String imgSrc5, String imgSrc6, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGECOLLECTION06) .setBindingImages(imgSrc1, imgSrc2, imgSrc3, imgSrc4, imgSrc5, imgSrc6) .setBindingTextFields(textField1); } public WnsTileBuilder bindingTemplateTileWidePeekImageAndText01(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGEANDTEXT01) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImageAndText02(String imgSrc1, String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGEANDTEXT02) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImage01(String imgSrc1, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE01) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImage02(String imgSrc1, String textField1, String textField2, String textField3, String textField4, String textField5) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE02) .setBindingTextFields(textField1, textField2, textField3, textField4, textField5) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImage03(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE03) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImage04(String imgSrc1, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE04) .setBindingTextFields(textField1) .setBindingImages(imgSrc1); } public WnsTileBuilder bindingTemplateTileWidePeekImage05(String imgSrc1, String imgSrc2, String textField1, String textField2) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE05) .setBindingTextFields(textField1, textField2) .setBindingImages(imgSrc1, imgSrc2); } public WnsTileBuilder bindingTemplateTileWidePeekImage06(String imgSrc1, String imgSrc2, String textField1) { return this.bindingTemplate(WnsTileTemplate.TILEWIDEPEEKIMAGE06) .setBindingTextFields(textField1) .setBindingImages(imgSrc1, imgSrc2); } protected WnsTileBuilder setBindingTextFields(String ... textFields) { getBinding().texts = new ArrayList<WnsText>(); for (int i = 0; i < textFields.length; i++) { WnsText txt = new WnsText(); txt.id = i+1; txt.value = textFields[i] != null ? textFields[i] : ""; getBinding().texts.add(txt); } return this; } protected WnsTileBuilder setBindingImages(String ... imgSrcs) { getBinding().images = new ArrayList<WnsImage>(); for (int i = 0; i < imgSrcs.length; i++) { WnsImage img = new WnsImage(); img.id = i+1; img.src = imgSrcs[i] != null ? imgSrcs[i] : ""; getBinding().images.add(img); } return this; } public WnsTile build() { return this.tile; } }
package cn.cerc.mis.ado; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.cerc.db.core.CacheLevelEnum; import cn.cerc.db.core.DataRow; import cn.cerc.db.core.DataSet; import cn.cerc.db.core.EntityKey; import cn.cerc.db.core.FieldDefs; import cn.cerc.db.core.IHandle; import cn.cerc.db.core.ISession; import cn.cerc.db.core.SqlQuery; import cn.cerc.db.core.SqlText; import cn.cerc.db.core.SqlWhere; import cn.cerc.db.redis.JedisFactory; import cn.cerc.mis.core.SystemBuffer; import redis.clients.jedis.Jedis; public class EntityCache<T> implements IHandle { private static final Logger log = LoggerFactory.getLogger(EntityCache.class); private static Predicate<Object> IsEmptyArrayString = text -> (text instanceof String) && ((String) text).length() == 0; public static final int MaxRecord = 2000; private ISession session; private Class<T> clazz; private EntityKey entityKey; public static <U> EntityCache<U> Create(IHandle handle, Class<U> clazz) { return new EntityCache<U>(handle, clazz); } public EntityCache(IHandle handle, Class<T> clazz) { super(); if (handle != null) this.session = handle.getSession(); this.entityKey = clazz.getDeclaredAnnotation(EntityKey.class); if (this.entityKey == null) throw new RuntimeException("entityKey not define: " + clazz.getSimpleName()); this.clazz = clazz; } public Optional<T> locate(Map<String, Optional<T>> buffer, Object... values) { StringBuffer sb = new StringBuffer(); for (Object value : values) sb.append(value); String key = sb.toString(); Optional<T> result = buffer.get(key); if (result == null) { result = get(values); buffer.put(key, result); } return result; } /** * @param values EntityCache.values * @return SessionRedis */ public Optional<T> get(Object... values) { if (List.of(values).stream().allMatch(IsEmptyArrayString)) return Optional.empty(); log.debug("getSession: {}.{}", clazz.getSimpleName(), joinToKey(values)); if (entityKey.cache() == CacheLevelEnum.Disabled) return getStorage(values); if (entityKey.cache() == CacheLevelEnum.RedisAndSession) { Object[] keys = this.buildKeys(values); DataRow row = SessionCache.get(keys); if (row != null && row.size() > 0) { try { return Optional.of(row.asEntity(clazz)); } catch (Exception e) { log.error("asEntity {} error: {}", clazz.getSimpleName(), row.json()); e.printStackTrace(); SessionCache.del(keys); } } } return getRedis(values); } /** * @param values EntityCache.values * @return Redis */ public Optional<T> getRedis(Object... values) { if (entityKey.cache() != CacheLevelEnum.Disabled) { log.debug("getRedis: {}.{}", clazz.getSimpleName(), joinToKey(values)); Object[] keys = this.buildKeys(values); try (Jedis jedis = JedisFactory.getJedis()) { String json = jedis.get(EntityCache.buildKey(keys)); if ("".equals(json) || "{}".equals(json)) return Optional.empty(); else if (json != null) { try { DataRow row = new DataRow().setJson(json); if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.set(keys, row); return Optional.of(row.asEntity(clazz)); } catch (Exception e) { log.error("asEntity {} error: {}", clazz.getSimpleName(), json); e.printStackTrace(); jedis.del(EntityCache.buildKey(keys)); if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.del(keys); } } } } return getStorage(values); } /** * @param values EntityCache.values * @return databasesessionredis */ public Optional<T> getStorage(Object... values) { log.debug("getStorage: {}.{}", clazz.getSimpleName(), joinToKey(values)); T entity = null; if (entityKey.virtual()) { entity = getVirtualEntity(values); } else { entity = getTableEntity(values); } if (entity == null && entityKey.cache() != CacheLevelEnum.Disabled) { Object[] keys = this.buildKeys(values); try (Jedis jedis = JedisFactory.getJedis()) { if (this.clazz.getSimpleName().equals("PartinfoEntity")) throw new RuntimeException(": " + values[0]); jedis.setex(buildKey(keys), entityKey.expire(), ""); } if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.set(keys, new DataRow()); } return Optional.ofNullable(entity); } protected T getVirtualEntity(Object... values) { int diff = entityKey.version() == 0 ? 1 : 2; Object[] keys = this.buildKeys(values); // entity DataRow headIn = new DataRow(new FieldDefs(clazz)); for (int i = 0; i < keys.length - diff; i++) headIn.setValue(entityKey.fields()[i], keys[i + diff]); T obj = headIn.asEntity(clazz); VirtualEntityImpl impl = (VirtualEntityImpl) obj; if (impl.fillItem(this, obj, headIn)) { DataRow row = new DataRow(); row.loadFromEntity(obj); try (Jedis jedis = JedisFactory.getJedis()) { jedis.setex(buildKey(keys), entityKey.expire(), row.json()); } if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.set(keys, row); return obj; } // Entity DataSet query = impl.loadItems(this, headIn); if (query == null || query.size() == 0) return null; if (entityKey.cache() != CacheLevelEnum.Disabled) { try (Jedis jedis = JedisFactory.getJedis()) { for (DataRow row : query) { Object[] rowKeys = buildKeys(row); jedis.setex(buildKey(rowKeys), entityKey.expire(), row.json()); if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.set(rowKeys, row); } } } // entity for (DataRow row : query) { boolean exists = true; for (int i = 0; i < keys.length - diff; i++) { Object value = keys[i + diff]; if (!row.getValue(entityKey.fields()[i]).equals(value)) exists = false; } if (exists) return row.asEntity(clazz); } return null; } private T getTableEntity(Object... values) { T entity = null; int diff = entityKey.version() == 0 ? 1 : 2; // key Object[] keys = this.buildKeys(values); if (listKeys() == null && entityKey.corpNo()) { SqlText sql = SqlWhere.create(this, clazz).build(); SqlQuery query = EntityFactory.buildQuery(this, clazz); query.setSql(sql); query.open(); for (DataRow row : query) { boolean exists = true; for (int i = 0; i < keys.length - diff; i++) { Object value = keys[i + diff]; if (!value.equals(row.getValue(entityKey.fields()[i]))) exists = false; } if (exists) entity = row.asEntity(clazz); } } else { entity = EntityFactory.loadOne(this, clazz, values).get().orElse(null); } return entity; } public void del(Object... values) { if (entityKey.cache() == CacheLevelEnum.Disabled) return; Object[] keys = this.buildKeys(values); try (Jedis jedis = JedisFactory.getJedis()) { jedis.del(buildKey(keys)); } if (entityKey.cache() == CacheLevelEnum.RedisAndSession) SessionCache.del(keys); } /** * @return key*0null */ public Set<String> listKeys() { if (entityKey.cache() == CacheLevelEnum.Disabled) return null; int offset = 1; if (entityKey.version() > 0) offset++; if (entityKey.corpNo()) offset++; Object[] keys = new Object[offset + 1]; keys[0] = clazz.getSimpleName(); if (entityKey.version() > 0) keys[1] = "" + entityKey.version(); if (entityKey.corpNo()) keys[offset - 1] = this.getCorpNo(); keys[offset] = "*"; try (Jedis jedis = JedisFactory.getJedis()) { Set<String> items = jedis.keys(EntityCache.buildKey(keys)); return items.size() > 0 ? items : null; } } public static String buildKey(Object... keys) { int flag = SystemBuffer.Entity.Cache.getStartingPoint() + SystemBuffer.Entity.Cache.ordinal(); return flag + "." + joinToKey(keys); } public static String joinToKey(Object... keys) { StringBuffer sb = new StringBuffer(); int count = 0; for (Object key : keys) { if (++count > 1) sb.append("."); if (key instanceof Boolean) sb.append((Boolean) key ? 1 : 0); else if (key != null) sb.append(key); } return sb.toString(); } public Object[] buildKeys(Object... values) { if ((values.length + (entityKey.corpNo() ? 1 : 0)) != entityKey.fields().length) throw new RuntimeException("params size is not match"); int offset = 1; if (entityKey.version() > 0) offset++; if (entityKey.corpNo()) offset++; Object[] keys = new Object[offset + values.length]; keys[0] = clazz.getSimpleName(); if (entityKey.version() > 0) keys[1] = "" + entityKey.version(); if (entityKey.corpNo()) keys[offset - 1] = this.getCorpNo(); for (int i = 0; i < values.length; i++) keys[offset + i] = values[i]; return keys; } public Object[] buildKeys(DataRow row) { int offset = 1; if (entityKey.version() > 0) offset++; Object[] keys = new Object[offset + entityKey.fields().length]; keys[0] = clazz.getSimpleName(); if (entityKey.version() > 0) keys[1] = "" + entityKey.version(); for (int i = 0; i < entityKey.fields().length; i++) keys[offset + i] = row.getValue(entityKey.fields()[i]); return keys; } public interface VirtualEntityImpl { /** * @param handle IHandle * @param entity Entity Object * @param headIn * @return entity values */ boolean fillItem(IHandle handle, Object entity, DataRow headIn); /** * fillEntityfalse * * @param handle IHandle * @param headIn headIn * @return null */ DataSet loadItems(IHandle handle, DataRow headIn); } @Override public ISession getSession() { return session; } @Override public void setSession(ISession session) { this.session = session; } public static <T> Optional<T> find(IHandle handle, Class<T> clazz, Object... keys) { EntityCache<T> cache = new EntityCache<T>(handle, clazz); return cache.get(keys); } }
package com.github.gfx.hankei_n.dependency; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Places; import com.github.gfx.hankei_n.BuildConfig; import com.github.gfx.hankei_n.event.LocationChangedEvent; import com.github.gfx.hankei_n.event.LocationMemoAddedEvent; import com.github.gfx.hankei_n.event.LocationMemoChangedEvent; import com.github.gfx.hankei_n.event.LocationMemoFocusedEvent; import com.github.gfx.hankei_n.event.LocationMemoRemovedEvent; import com.github.gfx.hankei_n.model.LocationMemoManager; import android.app.Application; import android.content.Context; import android.content.res.Resources; import android.location.Geocoder; import android.os.Vibrator; import android.util.DisplayMetrics; import java.util.Locale; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subjects.PublishSubject; @Module public class AppModule { static final String DB_NAME = "main.db"; final Context context; public AppModule(Context context) { this.context = context; } @Provides Application provideApplication() { return (Application) context.getApplicationContext(); } @Provides Context provideContext() { return context; } @Singleton @Provides GoogleAnalytics provideGoogleAnalytics(Application application) { GoogleAnalytics ga = GoogleAnalytics.getInstance(application); ga.enableAutoActivityReports(application); return ga; } @Singleton @Provides Tracker provideTracker(GoogleAnalytics ga) { Tracker tracker = ga.newTracker(BuildConfig.GA_TRACKING_ID); tracker.setAnonymizeIp(true); tracker.enableAutoActivityTracking(true); tracker.enableExceptionReporting(true); return tracker; } @Provides Locale providesLocale() { return Locale.getDefault(); } @Provides Geocoder provideGeocoder(Context context, Locale locale) { return new Geocoder(context, locale); } @Provides GoogleApiClient provideGoogleApiClient(Context context) { return new GoogleApiClient.Builder(context) .addApi(Places.GEO_DATA_API) .addApi(LocationServices.API) .build(); } @Provides Vibrator provideVibrator(Context context) { return (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); } @Provides GoogleApiAvailability provideGoogleApiAvailability() { return GoogleApiAvailability.getInstance(); } @Singleton @Provides LocationMemoManager provideLocationMemoList(Context context) { return new LocationMemoManager(context, DB_NAME); } @Provides DisplayMetrics provideDisplayMetrics() { return Resources.getSystem().getDisplayMetrics(); } @Singleton @Provides PublishSubject<LocationChangedEvent> provideLocationChangedEventSubject() { return PublishSubject.create(); } @Singleton @Provides PublishSubject<LocationMemoAddedEvent> provideLocationMemoAddedEventSubject() { return PublishSubject.create(); } @Singleton @Provides PublishSubject<LocationMemoRemovedEvent> provideLocationMemoRemovedEventSubject() { return PublishSubject.create(); } @Singleton @Provides PublishSubject<LocationMemoChangedEvent> provideLocationMemoChangedEventSubject() { return PublishSubject.create(); } @Singleton @Provides PublishSubject<LocationMemoFocusedEvent> provideLocationMemoFocusedEventSubject() { return PublishSubject.create(); } }
package org.statmt.hg4; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; public class Hypergraph { Set<Vertex> sinkVertices = new HashSet<Vertex>(); Set<Vertex> sourceVertices = new HashSet<Vertex>(); //no children /** * active and passive edges * * passive edge (rule,phrase pair, introduced at start) * active edge (hypothesis) * parse: 2 adgenda/lists * finishing agenda * put all rules in passive, one empty passive edge * @param vertex */ public void addNode(Vertex vertex) { if (!vertex.hasChildren()) sourceVertices.add(vertex); sinkVertices.add(vertex); } /** * Assumes vertex and edge's children are already in graph * @param vertex * @param edge */ public void addLink(Vertex vertex, Hyperarc arc) { vertex.addArc(arc); for(Vertex child : arc.getTail()) { sinkVertices.remove(child); } sourceVertices.remove(vertex); } public String toString() { String x = "HG\n SRC="+sourceVertices + "\n SINK="+sinkVertices +"\n"; for (Vertex v : sinkVertices) { x += "\n V="+v; } return x; } static class Rule extends Phrase { public Rule(Phrase p) { super(p.d); } public String getTarget() { String r = ""; for (int i =0; i<d.length; i++) r+=(i == 0 ? d[i] : " " + d[i]); return r; } } static abstract class ArcVisitor { /** * * @param h - the arc in question * @param children - the results of applying transition to children * @return application of the rule/value/etc associated with h to children */ public abstract Object transition(Hyperarc h, Object[] children); } static class StringifyPB extends ArcVisitor { HashMap<Hyperarc, Rule> map; public StringifyPB(HashMap<Hyperarc, Rule> m) { map = m; } public Object transition(Hyperarc h, Object[] children) { Rule r = map.get(h); if (children.length > 0 && children[0] != null) { return (String)children[0] + " " + r.getTarget(); } else return r.getTarget(); } } static abstract class Traverser { public abstract Object traverse(Vertex sink, ArcVisitor v); } static class ViterbiTraverser extends Traverser { public Object traverse(Vertex vertex, ArcVisitor visitor) { if (vertex.incomingArcs == null) { return null; } // get best (first == best) Hyperarc arc = vertex.incomingArcs.get(0); List<Vertex> vs = arc.getTail(); Object[] children = null; if (vs != null) { children = new Object[vs.size()]; int c = 0; for (Vertex vc : vs) { children[c] = traverse(vc, visitor); c++; } } return visitor.transition(arc, children); } } public static Object viterbi(Hypergraph g, ArcVisitor v) { Traverser t = new ViterbiTraverser(); return t.traverse(g.sinkVertices.iterator().next(), v); } public static void main(String[] args) { PTable pt = new PTable(); pt.add(new Phrase("guten"), new Phrase("well")); pt.add(new Phrase("guten"), new Phrase("good")); pt.add(new Phrase("tag"), new Phrase("day")); pt.add(new Phrase("tag"), new Phrase("hi")); pt.add(new Phrase("guten tag"), new Phrase("hello")); pt.add(new Phrase("guten tag"), new Phrase("good day")); Phrase sent = new Phrase("guten tag"); HashMap<Hyperarc, Rule> rules = new HashMap<Hyperarc, Rule>(); ArrayList<ArrayList<ArrayList<Phrase>>> lattice = pt.buildLattice(sent); Vertex source = new Vertex(null); ArrayList<Vertex>[] stacks = new ArrayList[sent.size() + 1]; for (int i = 0; i < stacks.length; i++) stacks[i] = new ArrayList<Vertex>(); stacks[0].add(source); Hypergraph hg = new Hypergraph(); hg.addNode(source); for (int i = 0; i < sent.size(); i++) { ArrayList<Vertex> shs = stacks[i]; for (Vertex prevHyp : shs) { ArrayList<Vertex> tail = new ArrayList<Vertex>(1); tail.add(prevHyp); int c = i; for (int e = c; e < sent.size(); e++) { lattice.get(c); ArrayList<Phrase> opts = lattice.get(c).get(e-c); for (Phrase opt : opts) { Rule r = new Rule(opt); Hyperarc ext = new Hyperarc(tail); int targetStack = e + 1; ArrayList<Vertex> targetS = stacks[targetStack]; if (targetS.size() == 0) { targetS.add(new Vertex(new ArrayList<Hyperarc>())); hg.addNode(targetS.get(0)); } hg.addLink(targetS.get(0), ext); rules.put(ext, r); System.out.println(ext + " r="+r + " dest=" + targetStack); } } } } Object r = viterbi(hg, new StringifyPB(rules)); System.out.println(r); } }
package com.eyeq.pivot4j.ui.html; import com.eyeq.pivot4j.ui.AbstractTableBuilder; import com.eyeq.pivot4j.ui.BuildContext; import com.eyeq.pivot4j.ui.CellType; public class HtmlTableBuilder extends AbstractTableBuilder<HtmlTableModel, HtmlTableRow, HtmlTableCell> { private String tableId; private String tableStyle; private String tableStyleClass = "pv-table"; private String rowStyleClass = "pv-row"; private String evenRowStyleClass = "pv-row-even"; private String oddRowStyleClass = "pv-row-odd"; private String columnHeaderStyleClass = "pv-col-hdr"; private String rowHeaderStyleClass = "pv-row-hdr"; private String columnTitleStyleClass = columnHeaderStyleClass; private String rowTitleStyleClass = rowHeaderStyleClass; private String cellStyleClass = "pv-cell"; private String cornerStyleClass = "pv-corner"; private int rowHeaderLevelPadding = 10; /** * @return the tableId */ public String getTableId() { return tableId; } /** * @param tableId * the tableId to set */ public void setTableId(String tableId) { this.tableId = tableId; } /** * @return the tableStyle */ public String getTableStyle() { return tableStyle; } /** * @param tableStyle * the tableStyle to set */ public void setTableStyle(String tableStyle) { this.tableStyle = tableStyle; } /** * @return the tableStyleClass */ public String getTableStyleClass() { return tableStyleClass; } /** * @param tableStyleClass * the tableStyleClass to set */ public void setTableStyleClass(String tableStyleClass) { this.tableStyleClass = tableStyleClass; } /** * @return the rowStyleClass */ public String getRowStyleClass() { return rowStyleClass; } /** * @param rowStyleClass * the rowStyleClass to set */ public void setRowStyleClass(String rowStyleClass) { this.rowStyleClass = rowStyleClass; } /** * @return the evenRowStyleClass */ public String getEvenRowStyleClass() { return evenRowStyleClass; } /** * @param evenRowStyleClass * the evenRowStyleClass to set */ public void setEvenRowStyleClass(String evenRowStyleClass) { this.evenRowStyleClass = evenRowStyleClass; } /** * @return the oddRowStyleClass */ public String getOddRowStyleClass() { return oddRowStyleClass; } /** * @param oddRowStyleClass * the oddRowStyleClass to set */ public void setOddRowStyleClass(String oddRowStyleClass) { this.oddRowStyleClass = oddRowStyleClass; } /** * @return the columnHeaderStyleClass */ public String getColumnHeaderStyleClass() { return columnHeaderStyleClass; } /** * @param columnHeaderStyleClass * the columnHeaderStyleClass to set */ public void setColumnHeaderStyleClass(String columnHeaderStyleClass) { this.columnHeaderStyleClass = columnHeaderStyleClass; } /** * @return the rowHeaderStyleClass */ public String getRowHeaderStyleClass() { return rowHeaderStyleClass; } /** * @param rowHeaderStyleClass * the rowHeaderStyleClass to set */ public void setRowHeaderStyleClass(String rowHeaderStyleClass) { this.rowHeaderStyleClass = rowHeaderStyleClass; } /** * @return the columnTitleStyleClass */ public String getColumnTitleStyleClass() { return columnTitleStyleClass; } /** * @param columnTitleStyleClass * the columnTitleStyleClass to set */ public void setColumnTitleStyleClass(String columnTitleStyleClass) { this.columnTitleStyleClass = columnTitleStyleClass; } /** * @return the rowTitleStyleClass */ public String getRowTitleStyleClass() { return rowTitleStyleClass; } /** * @param rowTitleStyleClass * the rowTitleStyleClass to set */ public void setRowTitleStyleClass(String rowTitleStyleClass) { this.rowTitleStyleClass = rowTitleStyleClass; } /** * @return the cellStyleClass */ public String getCellStyleClass() { return cellStyleClass; } /** * @param cellStyleClass * the cellStyleClass to set */ public void setCellStyleClass(String cellStyleClass) { this.cellStyleClass = cellStyleClass; } /** * @return the cornerStyleClass */ public String getCornerStyleClass() { return cornerStyleClass; } /** * @param cornerStyleClass * the cornerStyleClass to set */ public void setCornerStyleClass(String cornerStyleClass) { this.cornerStyleClass = cornerStyleClass; } /** * @return the rowHeaderLevelPadding */ public int getRowHeaderLevelPadding() { return rowHeaderLevelPadding; } /** * @param rowHeaderLevelPadding * the rowHeaderLevelPadding to set */ public void setRowHeaderLevelPadding(int rowHeaderLevelPadding) { this.rowHeaderLevelPadding = rowHeaderLevelPadding; } /** * @see com.eyeq.pivot4j.ui.AbstractTableBuilder#createTable(com.eyeq.pivot4j * .ui.BuildContext) */ @Override protected HtmlTableModel createTable(BuildContext context) { HtmlTableModel table = new HtmlTableModel(); table.setId(tableId); table.setStyle(tableStyle); table.setStyleClass(tableStyleClass); return table; } /** * @see com.eyeq.pivot4j.ui.AbstractTableBuilder#createRow(com.eyeq.pivot4j.ui * .BuildContext, com.eyeq.pivot4j.ui.TableModel, int) */ @Override protected HtmlTableRow createRow(BuildContext context, HtmlTableModel table, int rowIndex) { HtmlTableRow row = new HtmlTableRow(); StringBuilder builder = new StringBuilder(); if (rowStyleClass != null) { builder.append(rowStyleClass); } int mod = rowIndex % 2; if (evenRowStyleClass != null && mod == 0) { if (rowStyleClass != null) { builder.append(' '); } builder.append(evenRowStyleClass); } else if (oddRowStyleClass != null && mod == 1) { if (rowStyleClass != null) { builder.append(' '); } builder.append(oddRowStyleClass); } row.setStyleClass(builder.toString()); return row; } /** * @see com.eyeq.pivot4j.ui.AbstractTableBuilder#createCell(com.eyeq.pivot4j.ui.BuildContext, * com.eyeq.pivot4j.ui.TableModel, com.eyeq.pivot4j.ui.TableRow, * com.eyeq.pivot4j.ui.CellType, int, int, int, int) */ @Override protected HtmlTableCell createCell(BuildContext context, HtmlTableModel table, HtmlTableRow row, CellType type, int colIndex, int rowIndex, int colSpan, int rowSpan) { HtmlTableCell cell = new HtmlTableCell(type); cell.setColSpan(colSpan); cell.setRowSpan(rowSpan); return cell; } /** * @see com.eyeq.pivot4j.ui.AbstractTableBuilder#configureCell(com.eyeq.pivot4j.ui.BuildContext, * com.eyeq.pivot4j.ui.TableModel, com.eyeq.pivot4j.ui.TableRow, int, * int, com.eyeq.pivot4j.ui.TableCell) */ @Override protected void configureCell(BuildContext context, HtmlTableModel table, HtmlTableRow row, int colIndex, int rowIndex, HtmlTableCell cell) { super.configureCell(context, table, row, colIndex, rowIndex, cell); CellType type = cell.getType(); cell.setHeader(type != CellType.Value); switch (type) { case ColumnHeader: cell.setStyleClass(columnHeaderStyleClass); break; case RowHeader: cell.setStyleClass(rowHeaderStyleClass); if (rowHeaderLevelPadding > 0) { int padding = rowHeaderLevelPadding * (1 + context.getMember().getDepth()); cell.setStyle("padding-left: " + padding + "px;"); } break; case ColumnTitle: cell.setStyleClass(columnTitleStyleClass); break; case RowTitle: cell.setStyleClass(rowTitleStyleClass); break; case Value: cell.setStyleClass(cellStyleClass); break; case None: cell.setStyleClass(cornerStyleClass); break; default: assert false; } } }
package au.com.noojee.acceloapi.filter; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import au.com.noojee.acceloapi.AcceloApi; import au.com.noojee.acceloapi.AcceloException; import au.com.noojee.acceloapi.entities.AcceloEntity; import au.com.noojee.acceloapi.entities.meta.fieldTypes.FilterField; import au.com.noojee.acceloapi.entities.meta.fieldTypes.OrderByField.Order; import au.com.noojee.acceloapi.entities.types.AgainstType; public class AcceloFilter<E extends AcceloEntity<E>> { public static Logger logger = LogManager.getLogger(); public static final String ALL = "_ALL"; // Used by limit(int) to remove any limit on the // no. of rows returned. public static final int UNLIMITED = -1; private Optional<Expression> expression = Optional.empty(); private Optional<Search> search = Optional.empty(); private boolean refreshCache = false; public AcceloFilter<E> copy() { AcceloFilter<E> filter = new AcceloFilter<>(); this.expression.ifPresent(e -> filter.expression = Optional.of(e.copy())); this.expression = this.expression.map(Expression::copy); // this.search = this.search.map(Search::copy);/ this.search.ifPresent(s -> filter.search = Optional.of(s.copy())); filter.refreshCache = this.refreshCache; filter.limit = this.limit; filter.offset = this.offset; filter.orderBy = this.orderBy.map(OrderBy::copy); return filter; } /** * Limits the no. of pages returned during a query. A page can contain up to 50 rows. We default to 1 page (50 rows) * unless the caller explicitly over-rides the default. */ private int limit = 1; /** * Used with limit to iterate through a large list of entities. Defaults to 0 so we get the first page. The offset * is the page to start from (0 based). Increment the offset each time you call getByFilter to move forward a page * at a time. */ private int offset = 0; /** * List of order by clauses. */ // private List<OrderBy<E>> orderByList = new ArrayList<>(); @SuppressWarnings("rawtypes") private Optional<OrderBy> orderBy = Optional.empty(); public void where(Search search) throws AcceloException { if (expression.isPresent()) throw new AcceloException("You may not combine filters and searches"); this.search = Optional.of(search); } public AcceloFilter<E> where(Expression expression) throws AcceloException { if (search.isPresent()) throw new AcceloException("You may not combine filters and searches"); this.expression = Optional.of(expression); return this; } public void orderBy(FilterField<E, Integer> field, Order order) { // this.orderByList.add(new OrderBy<E>(field, order)); this.orderBy = Optional.of(new OrderBy<>(field, order)); } public Search search(String searchValue) { if (expression.isPresent()) throw new AcceloException("You may not combine filters and searches"); this.search = Optional.of(new Search(searchValue)); return this.search.orElseThrow(() -> new IllegalStateException()); } public AcceloFilter<E> and(Expression child) throws IllegalStateException { this.expression = Optional.of(new And(this.expression.orElseThrow(() -> new IllegalStateException()), child)); return this; } public AcceloFilter<E> or(Expression child) { this.expression = Optional.of(new Or(this.expression.orElseThrow(() -> new IllegalStateException()), child)); return this; } public Expression eq(FilterField<E, Integer> field, int operand) { return new Eq<>(field, operand); } public Expression eq(FilterField<E, String> field, String operand) { return new Eq<>(field, operand); } public Expression eq(FilterField<E, String> field, AgainstType operand) { return new Eq<>(field, operand.getName()); } public <T extends Enum<T>> Expression eq(FilterField<E, T> field, T operand) { return new Eq<>(field, operand); } public Expression eq(FilterField<E, String[]> field, String[] operand) { return new Eq<>(field, operand); } public Expression eq(FilterField<E, LocalDate> field, LocalDate operand) { return new Eq<>(field, operand); } public Expression before(FilterField<E, LocalDateTime> field, LocalDateTime operand) { return new Before<>(field, operand); } public Expression before(FilterField<E, LocalDate> field, LocalDate operand) { return new Before<>(field, operand); } public Expression after(FilterField<E, LocalDate> field, LocalDate operand) { return new After<>(field, operand); } public Expression afterOrEq(FilterField<E, LocalDate> field, LocalDate operand) { return new AfterOrEq<>(field, operand); } public Expression eq(FilterField<E, LocalDateTime> field, LocalDateTime operand) { return new Eq<>(field, operand); } public Expression after(FilterField<E, LocalDateTime> field, LocalDateTime operand) { return new After<>(field, operand); } public Expression afterOrEq(FilterField<E, LocalDateTime> field, LocalDateTime operand) { return new AfterOrEq<>(field, operand); } public Expression against(AgainstType type, Integer operand) { return new Against(type, operand); } public Expression against(AgainstType type, Integer... operand) { return new Against(type, operand); } public Expression empty(FilterField<E, LocalDate> dateField) { return new Empty<>(dateField); } public Expression greaterThan(FilterField<E, Integer> field, Integer operand) { return new GreaterThan<>(field, operand); } public Expression greaterThan(FilterField<E, String> field, String operand) { return new GreaterThan<>(field, operand); } public Expression lessThan(FilterField<E, Integer> field, Integer operand) { return new LessThan<>(field, operand); } public Expression lessThan(FilterField<E, String> field, String operand) { return new LessThan<>(field, operand); } public Expression greaterThanOrEq(FilterField<E, Integer> field, Integer operand) { return new GreaterThanOrEq<>(field, operand); } public Expression greaterThanOrEq(FilterField<E, String> field, String operand) { return new GreaterThanOrEq<>(field, operand); } public Expression lessThanOrEq(FilterField<E, Integer> field, Integer operand) { return new LessThanOrEq<>(field, operand); } public Expression lessThanOrEq(FilterField<E, String> field, String operand) { return new LessThanOrEq<>(field, operand); } /** * Use this method to invalid any cache data associated with this filter. This will force the system to re-fetch the * data from the accelo servers. */ public void refreshCache() { this.refreshCache = true; } public boolean isRefreshCache() { return refreshCache; } /** * Returns the accelo json expression for this filter. "_filters": { "_OR" : { "email": "pepper@test.com", "email" : * "salt@test.com" } } * * @param filterMap * @return * @return */ public String toJson() { Optional<String> result = Optional.empty(); // this.expression.ifPresent(e -> filter.expression = Optional.of(e.copy())); result = expression.map(exp -> { String json = "\"_filters\": {\n"; json += exp.toJson(); json += this.orderBy.map(ob -> "," + ob.toJson()).orElse(""); json += "}"; return json; }); if (!result.isPresent()) { result = search.map(s -> { String json = "\"_search\": "; json += "\"" + s.getOperand() + "\""; return json; }); } return result.orElse(""); } @Override public String toString() { return toJson().replaceAll("\n", " ") + " limit: " + this.limit + " offset: " + this.offset; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expression == null) ? 0 : expression.hashCode()); result = prime * result + limit; result = prime * result + offset; result = prime * result + ((orderBy == null) ? 0 : orderBy.hashCode()); result = prime * result + ((search == null) ? 0 : search.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("rawtypes") AcceloFilter other = (AcceloFilter) obj; if (expression == null) { if (other.expression != null) return false; } else if (!expression.equals(other.expression)) return false; if (limit != other.limit) return false; if (offset != other.offset) return false; if (orderBy == null) { if (other.orderBy != null) return false; } else if (!orderBy.equals(other.orderBy)) return false; if (search == null) { if (other.search != null) return false; } else if (!search.equals(other.search)) return false; return true; } /** * Returns true if the filter is for a simple id match. * * @return */ public boolean isIDFilter() { return expression.filter(Eq.class::isInstance).map(Eq.class::cast).filter(ex -> ex.isFieldName("id")) .isPresent(); } /** * Sets the maximum no. of pages (default is 50 entities per page) the filter will return. * @param limit */ public void limit(int limit) { this.limit = limit; } // removes the limit on the no. of entities returned. // becareful because you can crash accelo. public void noLimit() { limit(AcceloFilter.UNLIMITED); } /** * @return the maximum no. of pages (default is 50 entities per page) the filter will return. */ private int getLimit() { return this.limit; } public void offset(int offset) { this.offset = offset; } public int getOffset() { return this.offset; } public void showHashCode() { logger.error("Filter hashcode=" + this.hashCode()); logger.error("Expression: " + expression.hashCode()); logger.error("OrderBy: " + orderBy.hashCode()); } // returns true of no. of entities retrieved is less than the // limit imposed by this filter. public boolean belowLimit(int entitiesRetrieved) { return limit == UNLIMITED || (entitiesRetrieved < (getLimit() * AcceloApi.PAGE_SIZE)); } }
// FileStitcher.java package loci.formats; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Vector; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.in.MetadataLevel; import loci.formats.in.MetadataOptions; import loci.formats.meta.MetadataStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileStitcher implements IFormatReader { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(FileStitcher.class); // -- Fields -- /** * FormatReader to use as a template for constituent readers. * * The constituent readers must be dimension swappers so that the * file stitcher can reorganize the dimension order as needed based on * the result of the axis guessing algorithm. * * @see AxisGuesser#getAdjustedOrder() */ private DimensionSwapper reader; /** * Whether string ids given should be treated * as file patterns rather than single file paths. */ private boolean patternIds = false; /** Current file pattern string. */ private String currentId; /** File pattern object used to build the list of files. */ private FilePattern fp; /** Axis guesser object used to guess which dimensional axes are which. */ private AxisGuesser[] ag; /** The matching files. */ private String[][] files; /** Used files list. Only initialized in certain cases, upon request. */ private String[] usedFiles; /** Reader used for each file. */ private DimensionSwapper[][] readers; /** Blank image bytes, for use when image counts vary between files. */ private byte[][] blankBytes; /** Blank thumbnail bytes, for use when image counts vary between files. */ private byte[][] blankThumbBytes; /** Number of images per file. */ private int[] imagesPerFile; /** Dimensional axis lengths per file. */ private int[] sizeZ, sizeC, sizeT; /** Component lengths for each axis type. */ private int[][] lenZ, lenC, lenT; /** Core metadata. */ private CoreMetadata[] core; /** Current series number. */ private int series; private String[] originalOrder; private String[] seriesBlocks; private Vector<String[]> fileVector; private Vector<String> seriesNames; private boolean seriesInFile; private boolean noStitch; private MetadataStore store; // -- Constructors -- /** Constructs a FileStitcher around a new image reader. */ public FileStitcher() { this(new ImageReader()); } /** * Constructs a FileStitcher around a new image reader. * @param patternIds Whether string ids given should be treated as file * patterns rather than single file paths. */ public FileStitcher(boolean patternIds) { this(new ImageReader(), patternIds); } /** * Constructs a FileStitcher with the given reader. * @param r The reader to use for reading stitched files. */ public FileStitcher(IFormatReader r) { this(r, false); } /** * Constructs a FileStitcher with the given reader. * @param r The reader to use for reading stitched files. * @param patternIds Whether string ids given should be treated as file * patterns rather than single file paths. */ public FileStitcher(IFormatReader r, boolean patternIds) { reader = DimensionSwapper.makeDimensionSwapper(r); setUsingPatternIds(patternIds); } // -- FileStitcher API methods -- /** Gets the wrapped reader prototype. */ public IFormatReader getReader() { return reader; } /** Sets whether the reader is using file patterns for IDs. */ public void setUsingPatternIds(boolean patternIds) { this.patternIds = patternIds; } /** Gets whether the reader is using file patterns for IDs. */ public boolean isUsingPatternIds() { return patternIds; } /** Gets the reader appropriate for use with the given image plane. */ public IFormatReader getReader(int no) throws FormatException, IOException { if (noStitch) return reader; int[] q = computeIndices(no); int sno = seriesInFile ? 0 : getSeries(); int fno = q[0]; IFormatReader r = readers[sno][fno]; if (seriesInFile) r.setSeries(getSeries()); return r; } /** Gets the local reader index for use with the given image plane. */ public int getAdjustedIndex(int no) throws FormatException, IOException { if (noStitch) return no; int[] q = computeIndices(no); int ino = q[1]; return ino; } /** * Gets the axis type for each dimensional block. * @return An array containing values from the enumeration: * <ul> * <li>AxisGuesser.Z_AXIS: focal planes</li> * <li>AxisGuesser.T_AXIS: time points</li> * <li>AxisGuesser.C_AXIS: channels</li> * <li>AxisGuesser.S_AXIS: series</li> * </ul> */ public int[] getAxisTypes() { FormatTools.assertId(currentId, true, 2); return ag[getSeries()].getAxisTypes(); } /** * Sets the axis type for each dimensional block. * @param axes An array containing values from the enumeration: * <ul> * <li>AxisGuesser.Z_AXIS: focal planes</li> * <li>AxisGuesser.T_AXIS: time points</li> * <li>AxisGuesser.C_AXIS: channels</li> * <li>AxisGuesser.S_AXIS: series</li> * </ul> */ public void setAxisTypes(int[] axes) throws FormatException { FormatTools.assertId(currentId, true, 2); ag[getSeries()].setAxisTypes(axes); computeAxisLengths(); } /** Gets the file pattern object used to build the list of files. */ public FilePattern getFilePattern() { FormatTools.assertId(currentId, true, 2); return fp; } /** * Gets the axis guesser object used to guess * which dimensional axes are which. */ public AxisGuesser getAxisGuesser() { FormatTools.assertId(currentId, true, 2); return ag[getSeries()]; } /** * Finds the file pattern for the given ID, based on the state of the file * stitcher. Takes both ID map entries and the patternIds flag into account. */ public FilePattern findPattern(String id) { if (!patternIds) { // find the containing pattern HashMap<String, Object> map = Location.getIdMap(); String pattern = null; if (map.containsKey(id)) { // search ID map for pattern, rather than files on disk String[] idList = new String[map.size()]; map.keySet().toArray(idList); pattern = FilePattern.findPattern(id, null, idList); } else { // id is an unmapped file path; look to similar files on disk pattern = FilePattern.findPattern(new Location(id)); } if (pattern != null) id = pattern; } return new FilePattern(id); } // -- IMetadataConfigurable API methods -- /* (non-Javadoc) * @see loci.formats.IMetadataConfigurable#getSupportedMetadataLevels() */ public Set<MetadataLevel> getSupportedMetadataLevels() { return reader.getSupportedMetadataLevels(); } /* (non-Javadoc) * @see loci.formats.IMetadataConfigurable#getMetadataOptions() */ public MetadataOptions getMetadataOptions() { return reader.getMetadataOptions(); } /* (non-Javadoc) * @see loci.formats.IMetadataConfigurable#setMetadataOptions(loci.formats.in.MetadataOptions) */ public void setMetadataOptions(MetadataOptions options) { reader.setMetadataOptions(options); } // -- IFormatReader API methods -- /* @see IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { return reader.isThisType(name, open); } /* @see IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return reader.isThisType(block); } /* @see IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { return reader.isThisType(stream); } /* @see IFormatReader#getImageCount() */ public int getImageCount() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getImageCount() : core[getSeries()].imageCount; } /* @see IFormatReader#isRGB() */ public boolean isRGB() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isRGB() : core[getSeries()].rgb; } /* @see IFormatReader#getSizeX() */ public int getSizeX() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSizeX() : core[getSeries()].sizeX; } /* @see IFormatReader#getSizeY() */ public int getSizeY() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSizeY() : core[getSeries()].sizeY; } /* @see IFormatReader#getSizeZ() */ public int getSizeZ() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSizeZ() : core[getSeries()].sizeZ; } /* @see IFormatReader#getSizeC() */ public int getSizeC() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSizeC() : core[getSeries()].sizeC; } /* @see IFormatReader#getSizeT() */ public int getSizeT() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSizeT() : core[getSeries()].sizeT; } /* @see IFormatReader#getPixelType() */ public int getPixelType() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getPixelType() : core[getSeries()].pixelType; } /* @see IFormatReader#getBitsPerPixel() */ public int getBitsPerPixel() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getBitsPerPixel() : core[getSeries()].bitsPerPixel; } /* @see IFormatReader#getEffectiveSizeC() */ public int getEffectiveSizeC() { FormatTools.assertId(currentId, true, 2); return getImageCount() / (getSizeZ() * getSizeT()); } /* @see IFormatReader#getRGBChannelCount() */ public int getRGBChannelCount() { FormatTools.assertId(currentId, true, 2); return getSizeC() / getEffectiveSizeC(); } /* @see IFormatReader#isIndexed() */ public boolean isIndexed() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isIndexed() : core[getSeries()].indexed; } /* @see IFormatReader#isFalseColor() */ public boolean isFalseColor() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isFalseColor() : core[getSeries()].falseColor; } /* @see IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.get8BitLookupTable() : readers[seriesInFile ? 0 : getSeries()][0].get8BitLookupTable(); } /* @see IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.get16BitLookupTable() : readers[seriesInFile ? 0 : getSeries()][0].get16BitLookupTable(); } /* @see IFormatReader#getChannelDimLengths() */ public int[] getChannelDimLengths() { FormatTools.assertId(currentId, true, 2); if (noStitch) return reader.getChannelDimLengths(); if (core[getSeries()].cLengths == null) { return new int[] {core[getSeries()].sizeC}; } return core[getSeries()].cLengths; } /* @see IFormatReader#getChannelDimTypes() */ public String[] getChannelDimTypes() { FormatTools.assertId(currentId, true, 2); if (noStitch) return reader.getChannelDimTypes(); if (core[getSeries()].cTypes == null) { return new String[] {FormatTools.CHANNEL}; } return core[getSeries()].cTypes; } /* @see IFormatReader#getThumbSizeX() */ public int getThumbSizeX() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getThumbSizeX() : readers[seriesInFile ? 0 : getSeries()][0].getThumbSizeX(); } /* @see IFormatReader#getThumbSizeY() */ public int getThumbSizeY() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getThumbSizeY() : readers[seriesInFile ? 0 : getSeries()][0].getThumbSizeY(); } /* @see IFormatReader#isLittleEndian() */ public boolean isLittleEndian() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isLittleEndian() : readers[seriesInFile ? 0 : getSeries()][0].isLittleEndian(); } /* @see IFormatReader#getDimensionOrder() */ public String getDimensionOrder() { FormatTools.assertId(currentId, true, 2); if (noStitch) return reader.getDimensionOrder(); return originalOrder[getSeries()]; } /* @see IFormatReader#isOrderCertain() */ public boolean isOrderCertain() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isOrderCertain() : core[getSeries()].orderCertain; } /* @see IFormatReader#isThumbnailSeries() */ public boolean isThumbnailSeries() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isThumbnailSeries() : core[getSeries()].thumbnail; } /* @see IFormatReader#isInterleaved() */ public boolean isInterleaved() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isInterleaved() : readers[seriesInFile ? 0 : getSeries()][0].isInterleaved(); } /* @see IFormatReader#isInterleaved(int) */ public boolean isInterleaved(int subC) { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.isInterleaved(subC) : readers[seriesInFile ? 0 : getSeries()][0].isInterleaved(subC); } /* @see IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { return openBytes(no, 0, 0, getSizeX(), getSizeY()); } /* @see IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { return openBytes(no, buf, 0, 0, getSizeX(), getSizeY()); } /* @see IFormatReader#openBytes(int, int, int, int, int) */ public byte[] openBytes(int no, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); IFormatReader r = getReader(no); int ino = getAdjustedIndex(no); if (ino < r.getImageCount()) return r.openBytes(ino, x, y, w, h); // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankBytes[sno] == null) { int bytes = FormatTools.getBytesPerPixel(getPixelType()); blankBytes[sno] = new byte[w * h * bytes * getRGBChannelCount()]; } return blankBytes[sno]; } /* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); IFormatReader r = getReader(no); int ino = getAdjustedIndex(no); if (ino < r.getImageCount()) return r.openBytes(ino, buf, x, y, w, h); // return a blank image to cover for the fact that // this file does not contain enough image planes Arrays.fill(buf, (byte) 0); return buf; } /* @see IFormatReader#openPlane(int, int, int, int, int) */ public Object openPlane(int no, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); IFormatReader r = getReader(no); int ino = getAdjustedIndex(no); if (ino < r.getImageCount()) return r.openPlane(ino, x, y, w, h); return null; } /* @see IFormatReader#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); IFormatReader r = getReader(no); int ino = getAdjustedIndex(no); if (ino < r.getImageCount()) return r.openThumbBytes(ino); // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankThumbBytes[sno] == null) { int bytes = FormatTools.getBytesPerPixel(getPixelType()); blankThumbBytes[sno] = new byte[getThumbSizeX() * getThumbSizeY() * bytes * getRGBChannelCount()]; } return blankThumbBytes[sno]; } /* @see IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { if (readers == null) reader.close(fileOnly); else { for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { if (readers[i][j] != null) readers[i][j].close(fileOnly); } } } if (!fileOnly) { noStitch = false; readers = null; blankBytes = null; currentId = null; fp = null; ag = null; files = null; usedFiles = null; blankThumbBytes = null; imagesPerFile = null; sizeZ = sizeC = sizeT = null; lenZ = lenC = lenT = null; core = null; series = 0; seriesBlocks = null; fileVector = null; seriesNames = null; seriesInFile = false; store = null; originalOrder = null; } } /* @see IFormatReader#getSeriesCount() */ public int getSeriesCount() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getSeriesCount() : core.length; } /* @see IFormatReader#setSeries(int) */ public void setSeries(int no) { FormatTools.assertId(currentId, true, 2); int n = reader.getSeriesCount(); if (n > 1) reader.setSeries(no); else series = no; } /* @see IFormatReader#getSeries() */ public int getSeries() { FormatTools.assertId(currentId, true, 2); return seriesInFile || noStitch ? reader.getSeries() : series; } /* @see IFormatReader#setGroupFiles(boolean) */ public void setGroupFiles(boolean group) { reader.setGroupFiles(group); for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { readers[i][j].setGroupFiles(group); } } } /* @see IFormatReader#isGroupFiles() */ public boolean isGroupFiles() { return reader.isGroupFiles(); } /* @see IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return reader.fileGroupOption(id); } /* @see IFormatReader#isMetadataComplete() */ public boolean isMetadataComplete() { return reader.isMetadataComplete(); } /* @see IFormatReader#setNormalized(boolean) */ public void setNormalized(boolean normalize) { FormatTools.assertId(currentId, false, 2); if (readers == null) reader.setNormalized(normalize); else { for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { readers[i][j].setNormalized(normalize); } } } } /* @see IFormatReader#isNormalized() */ public boolean isNormalized() { return reader.isNormalized(); } /** * @deprecated * @see IFormatReader#setMetadataCollected(boolean) */ public void setMetadataCollected(boolean collect) { FormatTools.assertId(currentId, false, 2); if (readers == null) reader.setMetadataCollected(collect); else { for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { readers[i][j].setMetadataCollected(collect); } } } } /** * @deprecated * @see IFormatReader#isMetadataCollected() */ public boolean isMetadataCollected() { return reader.isMetadataCollected(); } /* @see IFormatReader#setOriginalMetadataPopulated(boolean) */ public void setOriginalMetadataPopulated(boolean populate) { FormatTools.assertId(currentId, false, 1); if (readers == null) reader.setOriginalMetadataPopulated(populate); else { for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { readers[i][j].setOriginalMetadataPopulated(populate); } } } } /* @see IFormatReader#isOriginalMetadataPopulated() */ public boolean isOriginalMetadataPopulated() { return reader.isOriginalMetadataPopulated(); } /* @see IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 2); if (noStitch) return reader.getUsedFiles(); // returning the files list directly here is fast, since we do not // have to call initFile on each constituent file; but we can only do so // when each constituent file does not itself have multiple used files if (reader.getUsedFiles().length > 1) { // each constituent file has multiple used files; we must build the list // this could happen with, e.g., a stitched collection of ICS/IDS pairs // we have no datasets structured this way, so this logic is untested if (usedFiles == null) { String[][][] used = new String[files.length][][]; int total = 0; for (int i=0; i<files.length; i++) { used[i] = new String[files[i].length][]; for (int j=0; j<files[i].length; j++) { try { initReader(i, j); } catch (FormatException exc) { LOGGER.info("", exc); return null; } catch (IOException exc) { LOGGER.info("", exc); return null; } used[i][j] = readers[i][j].getUsedFiles(); total += used[i][j].length; } } usedFiles = new String[total]; for (int i=0, off=0; i<used.length; i++) { for (int j=0; j<used[i].length; j++) { System.arraycopy(used[i][j], 0, usedFiles, off, used[i][j].length); off += used[i][j].length; } } } return usedFiles; } // assume every constituent file has no other used files // this logic could fail if the first constituent has no extra used files, // but later constituents do; in practice, this scenario seems unlikely Vector<String> v = new Vector<String>(); for (int i=0; i<files.length; i++) { for (int j=0; j<files[i].length; j++) { v.add(files[i][j]); } } return v.toArray(new String[0]); } /* @see IFormatReader#getUsedFiles() */ public String[] getUsedFiles(boolean noPixels) { return noPixels && noStitch ? reader.getUsedFiles(noPixels) : getUsedFiles(); } /* @see IFormatReader#getSeriesUsedFiles() */ public String[] getSeriesUsedFiles() { return getUsedFiles(); } /* @see IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { return getUsedFiles(noPixels); } /* @see IFormatReader#getAdvancedUsedFiles(boolean) */ public FileInfo[] getAdvancedUsedFiles(boolean noPixels) { String[] files = getUsedFiles(noPixels); if (files == null) return null; FileInfo[] infos = new FileInfo[files.length]; for (int i=0; i<infos.length; i++) { infos[i] = new FileInfo(); infos[i].filename = files[i]; try { infos[i].reader = reader.unwrap().getClass(); } catch (FormatException e) { LOGGER.debug("", e); } catch (IOException e) { LOGGER.debug("", e); } infos[i].usedToInitialize = files[i].endsWith(getCurrentFile()); } return infos; } /* @see IFormatReader#getAdvancedSeriesUsedFiles(boolean) */ public FileInfo[] getAdvancedSeriesUsedFiles(boolean noPixels) { String[] files = getSeriesUsedFiles(noPixels); if (files == null) return null; FileInfo[] infos = new FileInfo[files.length]; for (int i=0; i<infos.length; i++) { infos[i] = new FileInfo(); infos[i].filename = files[i]; try { infos[i].reader = reader.unwrap().getClass(); } catch (FormatException e) { LOGGER.debug("", e); } catch (IOException e) { LOGGER.debug("", e); } infos[i].usedToInitialize = files[i].endsWith(getCurrentFile()); } return infos; } /* @see IFormatReader#getCurrentFile() */ public String getCurrentFile() { return currentId; } /* @see IFormatReader#getIndex(int, int, int) */ public int getIndex(int z, int c, int t) { FormatTools.assertId(currentId, true, 2); return FormatTools.getIndex(this, z, c, t); } /* @see IFormatReader#getZCTCoords(int) */ public int[] getZCTCoords(int index) { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getZCTCoords(index) : FormatTools.getZCTCoords(core[getSeries()].dimensionOrder, getSizeZ(), getEffectiveSizeC(), getSizeT(), getImageCount(), index); } /* @see IFormatReader#getMetadataValue(String) */ public Object getMetadataValue(String field) { FormatTools.assertId(currentId, true, 2); return reader.getMetadataValue(field); } /* @see IFormatReader#getGlobalMetadata() */ public Hashtable<String, Object> getGlobalMetadata() { FormatTools.assertId(currentId, true, 2); return reader.getGlobalMetadata(); } /* @see IFormatReader#getSeriesMetadata() */ public Hashtable<String, Object> getSeriesMetadata() { FormatTools.assertId(currentId, true, 2); return reader.getSeriesMetadata(); } /** @deprecated */ public Hashtable<String, Object> getMetadata() { FormatTools.assertId(currentId, true ,2); return reader.getMetadata(); } /* @see IFormatReader#getCoreMetadata() */ public CoreMetadata[] getCoreMetadata() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getCoreMetadata() : core; } /* @see IFormatReader#setMetadataFiltered(boolean) */ public void setMetadataFiltered(boolean filter) { FormatTools.assertId(currentId, false, 2); reader.setMetadataFiltered(filter); } /* @see IFormatReader#isMetadataFiltered() */ public boolean isMetadataFiltered() { return reader.isMetadataFiltered(); } /* @see IFormatReader#setMetadataStore(MetadataStore) */ public void setMetadataStore(MetadataStore store) { FormatTools.assertId(currentId, false, 2); reader.setMetadataStore(store); } /* @see IFormatReader#getMetadataStore() */ public MetadataStore getMetadataStore() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getMetadataStore() : store; } /* @see IFormatReader#getMetadataStoreRoot() */ public Object getMetadataStoreRoot() { FormatTools.assertId(currentId, true, 2); return noStitch ? reader.getMetadataStoreRoot() : store.getRoot(); } /* @see IFormatReader#getUnderlyingReaders() */ public IFormatReader[] getUnderlyingReaders() { List<IFormatReader> list = new ArrayList<IFormatReader>(); for (int i=0; i<readers.length; i++) { for (int j=0; j<readers[i].length; j++) { list.add(readers[i][j]); } } return list.toArray(new IFormatReader[0]); } /* @see IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return reader.isSingleFile(id); } /* @see IFormatReader#getPossibleDomains(String) */ public String[] getPossibleDomains(String id) throws FormatException, IOException { return reader.getPossibleDomains(id); } /* @see IFormatReader#getDomains(String) */ public String[] getDomains() { return reader.getDomains(); } // -- IFormatHandler API methods -- /* @see IFormatHandler#isThisType(String) */ public boolean isThisType(String name) { return reader.isThisType(name); } /* @see IFormatHandler#getFormat() */ public String getFormat() { FormatTools.assertId(currentId, true, 2); return reader.getFormat(); } /* @see IFormatHandler#getSuffixes() */ public String[] getSuffixes() { return reader.getSuffixes(); } /* @see IFormatHandler#getNativeDataType() */ public Class<?> getNativeDataType() { FormatTools.assertId(currentId, true, 2); return reader.getNativeDataType(); } /* @see IFormatHandler#setId(String) */ public void setId(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); } /* @see IFormatHandler#close() */ public void close() throws IOException { close(false); } // -- Internal FormatReader API methods -- /** Initializes the given file or file pattern. */ protected void initFile(String id) throws FormatException, IOException { LOGGER.debug("initFile: {}", id); close(); currentId = id; fp = findPattern(currentId); boolean mustGroup = false; if (patternIds) { mustGroup = fp.isValid() && reader.fileGroupOption(fp.getFiles()[0]) == FormatTools.MUST_GROUP; } else { mustGroup = reader.fileGroupOption(id) == FormatTools.MUST_GROUP; } if (mustGroup) { // reader subclass is handling file grouping noStitch = true; if (patternIds && fp.isValid()) { reader.setId(fp.getFiles()[0]); } else reader.setId(currentId); return; } if (!fp.isValid()) { throw new FormatException("Invalid file pattern: " + fp.getPattern()); } reader.setId(fp.getFiles()[0]); if (reader.getUsedFiles().length > 1) { noStitch = true; return; } AxisGuesser guesser = new AxisGuesser(fp, reader.getDimensionOrder(), reader.getSizeZ(), reader.getSizeT(), reader.getEffectiveSizeC(), reader.isOrderCertain()); // use the dimension order recommended by the axis guesser reader.swapDimensions(guesser.getAdjustedOrder()); // if this is a multi-series dataset, we need some special logic int seriesCount = reader.getSeriesCount(); seriesInFile = true; if (guesser.getAxisCountS() > 0) { int[] axes = guesser.getAxisTypes(); seriesInFile = false; String[] blockPrefixes = fp.getPrefixes(); Vector<String> sBlock = new Vector<String>(); for (int i=0; i<axes.length; i++) { if (axes[i] == AxisGuesser.S_AXIS) sBlock.add(blockPrefixes[i]); } seriesBlocks = sBlock.toArray(new String[0]); fileVector = new Vector<String[]>(); seriesNames = new Vector<String>(); String file = fp.getFiles()[0]; Location dir = new Location(file).getAbsoluteFile().getParentFile(); String dpath = dir.getAbsolutePath(); String[] fs = dir.list(); String ext = ""; if (file.indexOf(".") != -1) { ext = file.substring(file.lastIndexOf(".") + 1); } Vector<String> tmpFiles = new Vector<String>(); for (int i=0; i<fs.length; i++) { if (fs[i].endsWith(ext)) tmpFiles.add(fs[i]); } setFiles(tmpFiles.toArray(new String[0]), seriesBlocks[0], fp.getFirst()[0], fp.getLast()[0], fp.getStep()[0], dpath, 0); seriesCount = fileVector.size(); files = new String[seriesCount][]; for (int i=0; i<seriesCount; i++) { files[i] = fileVector.get(i); } } // verify that file pattern is valid and matches existing files String msg = " Please rename your files or disable file stitching."; if (!fp.isValid()) { throw new FormatException("Invalid " + (patternIds ? "file pattern" : "filename") + " (" + currentId + "): " + fp.getErrorMessage() + msg); } if (files == null) { files = new String[1][]; files[0] = fp.getFiles(); } if (files == null) { throw new FormatException("No files matching pattern (" + fp.getPattern() + "). " + msg); } for (int i=0; i<files.length; i++) { for (int j=0; j<files[i].length; j++) { String file = files[i][j]; // HACK: skip file existence check for fake files if (file.toLowerCase().endsWith(".fake")) continue; if (!new Location(file).exists()) { throw new FormatException("File " (" + file + ") does not exist."); } } } // determine reader type for these files; assume all are the same type Class<? extends IFormatReader> readerClass = reader.unwrap(files[0][0]).getClass(); // construct list of readers for all files readers = new DimensionSwapper[files.length][]; for (int i=0; i<readers.length; i++) { readers[i] = new DimensionSwapper[files[i].length]; for (int j=0; j<readers[i].length; j++) { readers[i][j] = i == 0 && j == 0 ? reader : (DimensionSwapper) reader.duplicate(readerClass); } } ag = new AxisGuesser[seriesCount]; blankBytes = new byte[seriesCount][]; blankThumbBytes = new byte[seriesCount][]; imagesPerFile = new int[seriesCount]; sizeZ = new int[seriesCount]; sizeC = new int[seriesCount]; sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; lenZ = new int[seriesCount][]; lenC = new int[seriesCount][]; lenT = new int[seriesCount][]; originalOrder = new String[seriesCount]; // analyze first file; assume each file has the same parameters core = new CoreMetadata[seriesCount]; int oldSeries = reader.getSeries(); IFormatReader rr = reader; for (int i=0; i<seriesCount; i++) { if (seriesInFile) rr.setSeries(i); else { initReader(i, 0); rr = readers[i][0]; } core[i] = new CoreMetadata(); core[i].sizeX = rr.getSizeX(); core[i].sizeY = rr.getSizeY(); // NB: core.sizeZ populated in computeAxisLengths below // NB: core.sizeC populated in computeAxisLengths below // NB: core.sizeT populated in computeAxisLengths below core[i].pixelType = rr.getPixelType(); imagesPerFile[i] = rr.getImageCount(); core[i].imageCount = imagesPerFile[i] * files[seriesInFile ? 0 : i].length; core[i].thumbSizeX = rr.getThumbSizeX(); core[i].thumbSizeY = rr.getThumbSizeY(); // NB: core.cLengths[i] populated in computeAxisLengths below // NB: core.cTypes[i] populated in computeAxisLengths below core[i].dimensionOrder = rr.getDimensionOrder(); originalOrder[i] = rr.getDimensionOrder(); // NB: core.orderCertain[i] populated below core[i].rgb = rr.isRGB(); core[i].littleEndian = rr.isLittleEndian(); core[i].interleaved = rr.isInterleaved(); core[i].seriesMetadata = rr.getSeriesMetadata(); core[i].indexed = rr.isIndexed(); core[i].falseColor = rr.isFalseColor(); sizeZ[i] = rr.getSizeZ(); sizeC[i] = rr.getSizeC(); sizeT[i] = rr.getSizeT(); certain[i] = rr.isOrderCertain(); } reader.setSeries(oldSeries); // guess at dimensions corresponding to file numbering for (int i=0; i<seriesCount; i++) { ag[i] = new AxisGuesser(fp, core[i].dimensionOrder, sizeZ[i], sizeT[i], sizeC[i], certain[i]); } // order may need to be adjusted for (int i=0; i<seriesCount; i++) { setSeries(i); core[i].dimensionOrder = ag[i].getAdjustedOrder(); core[i].orderCertain = ag[i].isCertain(); computeAxisLengths(); } setSeries(oldSeries); // populate metadata store store = reader.getMetadataStore(); // don't overwrite pixel info if files aren't actually grouped if (!seriesInFile || files.length > 1 || files[0].length > 1) { MetadataTools.populatePixels(store, this); } for (int i=0; i<core.length; i++) { if (seriesNames != null && !seriesInFile) { store.setImageName(seriesNames.get(i), i); } } } // -- Helper methods -- /** Computes axis length arrays, and total axis lengths. */ protected void computeAxisLengths() throws FormatException { int sno = seriesInFile ? 0 : getSeries(); FilePattern p = new FilePattern(FilePattern.findPattern(files[sno][0], new Location(files[sno][0]).getAbsoluteFile().getParentFile().getPath(), files[sno])); int[] count = p.getCount(); try { initReader(sno, 0); } catch (IOException e) { throw new FormatException(e); } ag[getSeries()] = new AxisGuesser(p, readers[sno][0].getDimensionOrder(), readers[sno][0].getSizeZ(), readers[sno][0].getSizeT(), readers[sno][0].getSizeC(), readers[sno][0].isOrderCertain()); sno = getSeries(); int[] axes = ag[sno].getAxisTypes(); int numZ = ag[sno].getAxisCountZ(); int numC = ag[sno].getAxisCountC(); int numT = ag[sno].getAxisCountT(); core[sno].sizeZ = sizeZ[sno]; core[sno].sizeC = sizeC[sno]; core[sno].sizeT = sizeT[sno]; lenZ[sno] = new int[numZ + 1]; lenC[sno] = new int[numC + 1]; lenT[sno] = new int[numT + 1]; lenZ[sno][0] = sizeZ[sno]; lenC[sno][0] = sizeC[sno]; lenT[sno][0] = sizeT[sno]; for (int i=0, z=1, c=1, t=1; i<count.length; i++) { switch (axes[i]) { case AxisGuesser.Z_AXIS: core[sno].sizeZ *= count[i]; lenZ[sno][z++] = count[i]; break; case AxisGuesser.C_AXIS: core[sno].sizeC *= count[i]; lenC[sno][c++] = count[i]; break; case AxisGuesser.T_AXIS: core[sno].sizeT *= count[i]; lenT[sno][t++] = count[i]; break; case AxisGuesser.S_AXIS: break; default: throw new FormatException("Unknown axis type for axis i + ": " + axes[i]); } } int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int cCount = 0; for (int i=0; i<cLengths.length; i++) { if (cLengths[i] > 1) cCount++; } for (int i=1; i<lenC[sno].length; i++) { if (lenC[sno][i] > 1) cCount++; } if (cCount == 0) { core[sno].cLengths = new int[] {1}; core[sno].cTypes = new String[] {FormatTools.CHANNEL}; } else { core[sno].cLengths = new int[cCount]; core[sno].cTypes = new String[cCount]; } int c = 0; for (int i=0; i<cLengths.length; i++) { if (cLengths[i] == 1) continue; core[sno].cLengths[c] = cLengths[i]; core[sno].cTypes[c] = cTypes[i]; c++; } for (int i=1; i<lenC[sno].length; i++) { if (lenC[sno][i] == 1) continue; core[sno].cLengths[c] = lenC[sno][i]; core[sno].cTypes[c] = FormatTools.CHANNEL; } } /** * Gets the file index, and image index into that file, * corresponding to the given global image index. * * @return An array of size 2, dimensioned {file index, image index}. */ protected int[] computeIndices(int no) throws FormatException, IOException { int sno = getSeries(); int[] axes = ag[sno].getAxisTypes(); int[] count = fp.getCount(); // get Z, C and T positions int[] zct = getZCTCoords(no); int[] posZ = FormatTools.rasterToPosition(lenZ[sno], zct[0]); int[] posC = FormatTools.rasterToPosition(lenC[sno], zct[1]); int[] posT = FormatTools.rasterToPosition(lenT[sno], zct[2]); int[] tmpZ = new int[posZ.length]; System.arraycopy(posZ, 0, tmpZ, 0, tmpZ.length); int[] tmpC = new int[posC.length]; System.arraycopy(posC, 0, tmpC, 0, tmpC.length); int[] tmpT = new int[posT.length]; System.arraycopy(posT, 0, tmpT, 0, tmpT.length); for (int i=0; i<3; i++) { char originalAxis = core[sno].dimensionOrder.charAt(i + 2); char newAxis = originalOrder[sno].charAt(i + 2); if (newAxis != originalAxis) { int src = -1; if (originalAxis == 'Z') src = tmpZ[tmpZ.length - 1]; else if (originalAxis == 'C') src = tmpC[tmpC.length - 1]; else if (originalAxis == 'T') src = tmpT[tmpT.length - 1]; if (newAxis == 'Z') posZ[posZ.length - 1] = src; else if (newAxis == 'C') posC[posC.length - 1] = src; else if (newAxis == 'T') posT[posT.length - 1] = src; } } // convert Z, C and T position lists into file index and image index int[] pos = new int[axes.length]; int z = 1, c = 1, t = 1; for (int i=0; i<axes.length; i++) { if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++]; else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++]; else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++]; else { throw new FormatException("Unknown axis type for axis i + ": " + axes[i]); } } int fno = FormatTools.positionToRaster(count, pos); if (seriesInFile) sno = 0; // configure the reader, in case we haven't done this one yet initReader(sno, fno); int ino; if (posZ[0] < readers[sno][fno].getSizeZ() && posC[0] < readers[sno][fno].getSizeC() && posT[0] < readers[sno][fno].getSizeT()) { if (readers[sno][fno].isRGB() && (posC[0] * readers[sno][fno].getRGBChannelCount() >= lenC[sno][0])) { posC[0] /= lenC[sno][0]; } ino = FormatTools.getIndex(readers[sno][fno], posZ[0], posC[0], posT[0]); } else ino = Integer.MAX_VALUE; // coordinates out of range return new int[] {fno, ino}; } /** * Gets a list of readers to include in relation to the given C position. * @return Array with indices corresponding to the list of readers, and * values indicating the internal channel index to use for that reader. */ protected int[] getIncludeList(int theC) throws FormatException, IOException { int[] include = new int[readers.length]; Arrays.fill(include, -1); for (int t=0; t<sizeT[getSeries()]; t++) { for (int z=0; z<sizeZ[getSeries()]; z++) { int no = getIndex(z, theC, t); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; include[fno] = ino; } } return include; } protected void initReader(int sno, int fno) throws FormatException, IOException { if (files[sno][fno].equals(readers[sno][fno].getCurrentFile())) { return; } readers[sno][fno].setId(files[sno][fno]); readers[sno][fno].setSeries(seriesInFile ? getSeries() : 0); readers[sno][fno].swapDimensions(reader.getInputOrder()); } private FilePattern getPattern(String[] f, String dir, String block) { Vector<String> v = new Vector<String>(); for (int i=0; i<f.length; i++) { if (f[i].indexOf(File.separator) != -1) { f[i] = f[i].substring(f[i].lastIndexOf(File.separator) + 1); } if (dir.endsWith(File.separator)) f[i] = dir + f[i]; else f[i] = dir + File.separator + f[i]; if (f[i].indexOf(block) != -1 && new Location(f[i]).exists()) { v.add(f[i].substring(f[i].lastIndexOf(File.separator) + 1)); } } f = v.toArray(new String[0]); return new FilePattern(FilePattern.findPattern(f[0], dir, f)); } private void setFiles(String[] list, String prefix, BigInteger first, BigInteger last, BigInteger step, String dir, int blockNum) { long f = first.longValue(); long l = last.longValue(); long s = step.longValue(); for (long i=f; i<=l; i+=s) { FilePattern newPattern = getPattern(list, dir, prefix + i); if (blockNum == seriesBlocks.length - 1) { fileVector.add(newPattern.getFiles()); String name = newPattern.getPattern(); if (name.indexOf(File.separator) != -1) { name = name.substring(name.lastIndexOf(File.separator) + 1); } seriesNames.add(name); } else { String next = seriesBlocks[blockNum + 1]; String[] blocks = newPattern.getPrefixes(); BigInteger fi = null; BigInteger la = null; BigInteger st = null; for (int q=0; q<blocks.length; q++) { if (blocks[q].indexOf(next) != -1) { fi = newPattern.getFirst()[q]; la = newPattern.getLast()[q]; st = newPattern.getStep()[q]; break; } } setFiles(newPattern.getFiles(), next, fi, la, st, dir, blockNum + 1); } } } }
package com.fasterxml.jackson.core.io; import java.math.BigDecimal; public final class NumberInput { public final static String NASTY_SMALL_DOUBLE = "2.2250738585072012e-308"; /** * Constants needed for parsing longs from basic int parsing methods */ final static long L_BILLION = 1000000000; final static String MIN_LONG_STR_NO_SIGN = String.valueOf(Long.MIN_VALUE).substring(1); final static String MAX_LONG_STR = String.valueOf(Long.MAX_VALUE); /** * Fast method for parsing integers that are known to fit into * regular 32-bit signed int type. This means that length is * between 1 and 9 digits (inclusive) *<p> * Note: public to let unit tests call it */ public static int parseInt(char[] ch, int off, int len) { int num = ch[off + len - 1] - '0'; switch(len) { case 9: num += (ch[off++] - '0') * 100000000; case 8: num += (ch[off++] - '0') * 10000000; case 7: num += (ch[off++] - '0') * 1000000; case 6: num += (ch[off++] - '0') * 100000; case 5: num += (ch[off++] - '0') * 10000; case 4: num += (ch[off++] - '0') * 1000; case 3: num += (ch[off++] - '0') * 100; case 2: num += (ch[off] - '0') * 10; } return num; } /** * Helper method to (more) efficiently parse integer numbers from * String values. */ public static int parseInt(String s) { /* Ok: let's keep strategy simple: ignoring optional minus sign, * we'll accept 1 - 9 digits and parse things efficiently; * otherwise just defer to JDK parse functionality. */ char c = s.charAt(0); int len = s.length(); boolean neg = (c == '-'); int offset = 1; // must have 1 - 9 digits after optional sign: // negative? if (neg) { if (len == 1 || len > 10) { return Integer.parseInt(s); } c = s.charAt(offset++); } else { if (len > 9) { return Integer.parseInt(s); } } if (c > '9' || c < '0') { return Integer.parseInt(s); } int num = c - '0'; if (offset < len) { c = s.charAt(offset++); if (c > '9' || c < '0') { return Integer.parseInt(s); } num = (num * 10) + (c - '0'); if (offset < len) { c = s.charAt(offset++); if (c > '9' || c < '0') { return Integer.parseInt(s); } num = (num * 10) + (c - '0'); // Let's just loop if we have more than 3 digits: if (offset < len) { do { c = s.charAt(offset++); if (c > '9' || c < '0') { return Integer.parseInt(s); } num = (num * 10) + (c - '0'); } while (offset < len); } } } return neg ? -num : num; } public static long parseLong(char[] ch, int off, int len) { // Note: caller must ensure length is [10, 18] int len1 = len-9; long val = parseInt(ch, off, len1) * L_BILLION; return val + (long) parseInt(ch, off+len1, 9); } public static long parseLong(String s) { /* Ok, now; as the very first thing, let's just optimize case of "fake longs"; * that is, if we know they must be ints, call int parsing */ int length = s.length(); if (length <= 9) { return (long) parseInt(s); } // !!! TODO: implement efficient 2-int parsing... return Long.parseLong(s); } /** * Helper method for determining if given String representation of * an integral number would fit in 64-bit Java long or not. * Note that input String must NOT contain leading minus sign (even * if 'negative' is set to true). * * @param negative Whether original number had a minus sign (which is * NOT passed to this method) or not */ public static boolean inLongRange(char[] ch, int off, int len, boolean negative) { String cmpStr = negative ? MIN_LONG_STR_NO_SIGN : MAX_LONG_STR; int cmpLen = cmpStr.length(); if (len < cmpLen) return true; if (len > cmpLen) return false; for (int i = 0; i < cmpLen; ++i) { int diff = ch[off+i] - cmpStr.charAt(i); if (diff != 0) { return (diff < 0); } } return true; } /** * Similar to {@link #inLongRange(char[],int,int,boolean)}, but * with String argument * * @param negative Whether original number had a minus sign (which is * NOT passed to this method) or not */ public static boolean inLongRange(String s, boolean negative) { String cmp = negative ? MIN_LONG_STR_NO_SIGN : MAX_LONG_STR; int cmpLen = cmp.length(); int alen = s.length(); if (alen < cmpLen) return true; if (alen > cmpLen) return false; // could perhaps just use String.compareTo()? for (int i = 0; i < cmpLen; ++i) { int diff = s.charAt(i) - cmp.charAt(i); if (diff != 0) { return (diff < 0); } } return true; } public static int parseAsInt(String s, int def) { if (s == null) { return def; } s = s.trim(); int len = s.length(); if (len == 0) { return def; } // One more thing: use integer parsing for 'simple' int i = 0; if (i < len) { // skip leading sign: char c = s.charAt(0); if (c == '+') { // for plus, actually physically remove s = s.substring(1); len = s.length(); } else if (c == '-') { // minus, just skip for checks, must retain ++i; } } for (; i < len; ++i) { char c = s.charAt(i); // if other symbols, parse as Double, coerce if (c > '9' || c < '0') { try { return (int) parseDouble(s); } catch (NumberFormatException e) { return def; } } } try { return Integer.parseInt(s); } catch (NumberFormatException e) { } return def; } public static long parseAsLong(String s, long def) { if (s == null) { return def; } s = s.trim(); int len = s.length(); if (len == 0) { return def; } // One more thing: use long parsing for 'simple' int i = 0; if (i < len) { // skip leading sign: char c = s.charAt(0); if (c == '+') { // for plus, actually physically remove s = s.substring(1); len = s.length(); } else if (c == '-') { // minus, just skip for checks, must retain ++i; } } for (; i < len; ++i) { char c = s.charAt(i); // if other symbols, parse as Double, coerce if (c > '9' || c < '0') { try { return (long) parseDouble(s); } catch (NumberFormatException e) { return def; } } } try { return Long.parseLong(s); } catch (NumberFormatException e) { } return def; } public static double parseAsDouble(String s, double def) { if (s == null) { return def; } s = s.trim(); int len = s.length(); if (len == 0) { return def; } try { return parseDouble(s); } catch (NumberFormatException e) { } return def; } public static double parseDouble(String s) throws NumberFormatException { // [JACKSON-486]: avoid some nasty float representations... but should it be MIN_NORMAL or MIN_VALUE? /* as per [JACKSON-827], let's use MIN_VALUE as it is available on all JDKs; normalized * only in JDK 1.6. In practice, should not really matter. */ if (NASTY_SMALL_DOUBLE.equals(s)) { return Double.MIN_VALUE; } return Double.parseDouble(s); } public static BigDecimal parseBigDecimal(String s) throws NumberFormatException { try { return new BigDecimal(s); } catch (NumberFormatException e) { throw _badBD(s); } } public static BigDecimal parseBigDecimal(char[] b) throws NumberFormatException { return parseBigDecimal(b, 0, b.length); } public static BigDecimal parseBigDecimal(char[] b, int off, int len) throws NumberFormatException { try { return new BigDecimal(b, off, len); } catch (NumberFormatException e) { throw _badBD(new String(b, off, len)); } } private static NumberFormatException _badBD(String s) { return new NumberFormatException("Value \""+s+"\" can not be represented as BigDecimal"); } }
package eu.rekawek.coffeegb.gpu; import eu.rekawek.coffeegb.AddressSpace; import eu.rekawek.coffeegb.cpu.InterruptManager; import eu.rekawek.coffeegb.cpu.InterruptManager.InterruptType; import eu.rekawek.coffeegb.cpu.SpeedMode; import eu.rekawek.coffeegb.gpu.phase.GpuPhase; import eu.rekawek.coffeegb.gpu.phase.HBlankPhase; import eu.rekawek.coffeegb.gpu.phase.OamSearch; import eu.rekawek.coffeegb.gpu.phase.PixelTransfer; import eu.rekawek.coffeegb.gpu.phase.VBlankPhase; import eu.rekawek.coffeegb.memory.Dma; import eu.rekawek.coffeegb.memory.MemoryRegisters; import eu.rekawek.coffeegb.memory.Ram; import static eu.rekawek.coffeegb.gpu.GpuRegister.*; public class Gpu implements AddressSpace { public enum Mode { HBlank, VBlank, OamSearch, PixelTransfer } private final AddressSpace videoRam0; private final AddressSpace videoRam1; private final AddressSpace oamRam; private final Display display; private final InterruptManager interruptManager; private final Dma dma; private final Lcdc lcdc; private final boolean gbc; private final ColorPalette bgPalette; private final ColorPalette oamPalette; private final HBlankPhase hBlankPhase; private final OamSearch oamSearchPhase; private final PixelTransfer pixelTransferPhase; private final VBlankPhase vBlankPhase; private boolean lcdEnabled = true; private int lcdEnabledDelay; private MemoryRegisters r; private int ticksInLine; private Mode mode; private GpuPhase phase; public Gpu(Display display, InterruptManager interruptManager, Dma dma, Ram oamRam, boolean gbc) { this.r = new MemoryRegisters(GpuRegister.values()); this.lcdc = new Lcdc(); this.interruptManager = interruptManager; this.gbc = gbc; this.videoRam0 = new Ram(0x8000, 0x2000); if (gbc) { this.videoRam1 = new Ram(0x8000, 0x2000); } else { this.videoRam1 = null; } this.oamRam = oamRam; this.dma = dma; this.bgPalette = new ColorPalette(0xff68); this.oamPalette = new ColorPalette(0xff6a); oamPalette.fillWithFF(); this.oamSearchPhase = new OamSearch(oamRam, lcdc, r); this.pixelTransferPhase = new PixelTransfer(videoRam0, videoRam1, oamRam, display, lcdc, r, gbc, bgPalette, oamPalette); this.hBlankPhase = new HBlankPhase(); this.vBlankPhase = new VBlankPhase(); this.mode = Mode.OamSearch; this.phase = oamSearchPhase.start(); this.display = display; } private AddressSpace getAddressSpace(int address) { if (videoRam0.accepts(address) && mode != Mode.PixelTransfer) { if (gbc && (r.get(VBK) & 1) == 1) { return videoRam1; } else { return videoRam0; } } else if (oamRam.accepts(address) && !dma.isOamBlocked()/* && mode != Mode.OamSearch && mode != Mode.PixelTransfer*/) { return oamRam; } else if (lcdc.accepts(address)) { return lcdc; } else if (r.accepts(address)) { return r; } else if (gbc && bgPalette.accepts(address)) { return bgPalette; } else if (gbc && oamPalette.accepts(address)) { return oamPalette; } else { return null; } } @Override public boolean accepts(int address) { return getAddressSpace(address) != null; } @Override public void setByte(int address, int value) { if (address == STAT.getAddress()) { setStat(value); } else { AddressSpace space = getAddressSpace(address); if (space == lcdc) { setLcdc(value); } else if (space != null) { space.setByte(address, value); } } } @Override public int getByte(int address) { if (address == STAT.getAddress()) { return getStat(); } else { AddressSpace space = getAddressSpace(address); if (space == null) { return 0xff; } else if (address == VBK.getAddress()) { return gbc ? 0xfe : 0xff; } else { return space.getByte(address); } } } public Mode tick() { if (!lcdEnabled) { if (lcdEnabledDelay != -1) { if (--lcdEnabledDelay == 0) { display.enableLcd(); lcdEnabled = true; } } } if (!lcdEnabled) { return null; } Mode oldMode = mode; ticksInLine++; if (phase.tick()) { // switch line 153 to 0 if (ticksInLine == 4 && mode == Mode.VBlank && r.get(LY) == 153) { r.put(LY, 0); requestLycEqualsLyInterrupt(); } } else { switch (oldMode) { case OamSearch: mode = Mode.PixelTransfer; phase = pixelTransferPhase.start(oamSearchPhase.getSprites()); break; case PixelTransfer: mode = Mode.HBlank; phase = hBlankPhase.start(ticksInLine); requestLcdcInterrupt(3); break; case HBlank: ticksInLine = 0; if (r.preIncrement(LY) == 144) { mode = Mode.VBlank; phase = vBlankPhase.start(); interruptManager.requestInterrupt(InterruptType.VBlank); requestLcdcInterrupt(4); } else { mode = Mode.OamSearch; phase = oamSearchPhase.start(); } requestLcdcInterrupt(5); requestLycEqualsLyInterrupt(); break; case VBlank: ticksInLine = 0; if (r.preIncrement(LY) == 1) { mode = Mode.OamSearch; r.put(LY, 0); phase = oamSearchPhase.start(); requestLcdcInterrupt(5); } else { phase = vBlankPhase.start(); } requestLycEqualsLyInterrupt(); break; } } if (oldMode == mode) { return null; } else { return mode; } } public int getTicksInLine() { return ticksInLine; } private void requestLcdcInterrupt(int statBit) { if ((r.get(STAT) & (1 << statBit)) != 0) { interruptManager.requestInterrupt(InterruptType.LCDC); } } private void requestLycEqualsLyInterrupt() { if (r.get(LYC) == r.get(LY)) { requestLcdcInterrupt(6); } } private int getStat() { return r.get(STAT) | mode.ordinal() | (r.get(LYC) == r.get(LY) ? (1 << 2) : 0) | 0x80; } private void setStat(int value) { r.put(STAT, value & 0b11111000); // last three bits are read-only } private void setLcdc(int value) { lcdc.set(value); if ((value & (1 << 7)) == 0) { disableLcd(); } else { enableLcd(); } } private void disableLcd() { r.put(LY, 0); this.ticksInLine = 0; this.phase = hBlankPhase.start(250); this.mode = Mode.HBlank; this.lcdEnabled = false; this.lcdEnabledDelay = -1; display.disableLcd(); } private void enableLcd() { lcdEnabledDelay = 244; } public boolean isLcdEnabled() { return lcdEnabled; } public Lcdc getLcdc() { return lcdc; } }
package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.MDBService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffParser; import ome.xml.model.primitives.PositiveFloat; public class APLReader extends FormatReader { // -- Constants -- private static final String[] METADATA_SUFFIXES = new String[] {"apl", "tnb", "mtb" }; // -- Fields -- private String[] tiffFiles; private String[] xmlFiles; private TiffParser[] parser; private IFDList[] ifds; private Vector<String> used; // -- Constructor -- /** Constructs a new APL reader. */ public APLReader() { super("Olympus APL", new String[] {"apl", "tnb", "mtb", "tif"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; suffixSufficient = false; datasetDescription = "One .apl file, one .mtb file, one .tnb file, and " + "a directory containing one or more .tif files"; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, METADATA_SUFFIXES)) return true; if (checkSuffix(name, "tif") && open) { Location file = new Location(name).getAbsoluteFile(); Location parent = file.getParentFile(); if (parent != null) { try { parent = parent.getParentFile(); parent = parent.getParentFile(); } catch (NullPointerException e) { return false; } Location aplFile = new Location(parent, parent.getName() + ".apl"); return aplFile.exists(); } } return false; } /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return false; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); Vector<String> files = new Vector<String>(); files.addAll(used); if (getSeries() < xmlFiles.length && new Location(xmlFiles[getSeries()]).exists()) { files.add(xmlFiles[getSeries()]); } if (!noPixels && getSeries() < tiffFiles.length && new Location(tiffFiles[getSeries()]).exists()) { files.add(tiffFiles[getSeries()]); } return files.toArray(new String[files.size()]); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { return parser[getSeries()].getSamples(ifds[getSeries()].get(no), buf, x, y, w, h); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { tiffFiles = null; xmlFiles = null; used = null; ifds = null; if (parser != null) { for (TiffParser p : parser) { if (p != null) { p.getStream().close(); } } } } } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#getOptimalTileWidth() */ public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); try { return (int) ifds[getSeries()].get(0).getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); } /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); try { return (int) ifds[getSeries()].get(0).getTileLength(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile height", e); } return super.getOptimalTileHeight(); } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); LOGGER.debug("Initializing {}", id); // find the corresponding .mtb file if (!checkSuffix(id, "mtb")) { if (checkSuffix(id, METADATA_SUFFIXES)) { int separator = id.lastIndexOf(File.separator); if (separator < 0) separator = 0; int underscore = id.lastIndexOf("_"); if (underscore < separator || checkSuffix(id, "apl")) { underscore = id.lastIndexOf("."); } String mtbFile = id.substring(0, underscore) + "_d.mtb"; if (!new Location(mtbFile).exists()) { throw new FormatException(".mtb file not found"); } currentId = new Location(mtbFile).getAbsolutePath(); } else { Location parent = new Location(id).getAbsoluteFile().getParentFile(); parent = parent.getParentFile(); String[] list = parent.list(true); for (String f : list) { if (checkSuffix(f, "mtb")) { currentId = new Location(parent, f).getAbsolutePath(); break; } } if (!checkSuffix(currentId, "mtb")) { throw new FormatException(".mtb file not found"); } } } String mtb = new Location(currentId).getAbsolutePath(); LOGGER.debug("Reading .mtb file '{}'", mtb); MDBService mdb = null; try { ServiceFactory factory = new ServiceFactory(); mdb = factory.getInstance(MDBService.class); } catch (DependencyException de) { throw new FormatException("MDB Tools Java library not found", de); } String[] columnNames = null; Vector<String[]> rows = null; try { mdb.initialize(mtb); rows = mdb.parseDatabase().get(0); columnNames = rows.get(0); String[] tmpNames = columnNames; columnNames = new String[tmpNames.length - 1]; System.arraycopy(tmpNames, 1, columnNames, 0, columnNames.length); } finally { mdb.close(); } // add full table to metadata hashtable if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { for (int i=1; i<rows.size(); i++) { String[] row = rows.get(i); for (int q=0; q<row.length; q++) { addGlobalMeta(columnNames[q] + " " + i, row[q]); } } } used = new Vector<String>(); used.add(mtb); String tnb = mtb.substring(0, mtb.lastIndexOf(".")); if (tnb.lastIndexOf("_") > tnb.lastIndexOf(File.separator)) { tnb = tnb.substring(0, tnb.lastIndexOf("_")); } used.add(tnb + "_1.tnb"); used.add(tnb + ".apl"); String idPath = new Location(id).getAbsolutePath(); if (!used.contains(idPath) && checkSuffix(idPath, METADATA_SUFFIXES)) { used.add(idPath); } // calculate indexes to relevant metadata int calibrationUnit = DataTools.indexOf(columnNames, "Calibration Unit"); int colorChannels = DataTools.indexOf(columnNames, "Color Channels"); int frames = DataTools.indexOf(columnNames, "Frames"); int calibratedHeight = DataTools.indexOf(columnNames, "Height"); int calibratedWidth = DataTools.indexOf(columnNames, "Width"); int path = DataTools.indexOf(columnNames, "Image Path"); int filename = DataTools.indexOf(columnNames, "File Name"); int magnification = DataTools.indexOf(columnNames, "Magnification"); int width = DataTools.indexOf(columnNames, "X-Resolution"); int height = DataTools.indexOf(columnNames, "Y-Resolution"); int imageName = DataTools.indexOf(columnNames, "Image Name"); int zLayers = DataTools.indexOf(columnNames, "Z-Layers"); String parentDirectory = mtb.substring(0, mtb.lastIndexOf(File.separator)); // look for the directory that contains TIFF and XML files LOGGER.debug("Searching {} for a directory with TIFFs", parentDirectory); Location dir = new Location(parentDirectory); String[] list = dir.list(); String topDirectory = null; for (String f : list) { LOGGER.debug(" '{}'", f); Location file = new Location(dir, f); if (file.isDirectory() && f.indexOf("_DocumentFiles") > 0) { topDirectory = file.getAbsolutePath(); LOGGER.debug("Found {}", topDirectory); break; } } if (topDirectory == null) { throw new FormatException("Could not find a directory with TIFF files."); } Vector<Integer> seriesIndexes = new Vector<Integer>(); for (int i=1; i<rows.size(); i++) { String file = rows.get(i)[filename].trim(); if (file.equals("")) continue; file = topDirectory + File.separator + file; if (new Location(file).exists() && checkSuffix(file, "tif")) { seriesIndexes.add(i); } } int seriesCount = seriesIndexes.size(); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } tiffFiles = new String[seriesCount]; xmlFiles = new String[seriesCount]; parser = new TiffParser[seriesCount]; ifds = new IFDList[seriesCount]; for (int i=0; i<seriesCount; i++) { int secondRow = seriesIndexes.get(i); int firstRow = secondRow - 1; String[] row2 = rows.get(firstRow); String[] row3 = rows.get(secondRow); core[i].sizeT = parseDimension(row3[frames]); core[i].sizeZ = parseDimension(row3[zLayers]); core[i].sizeC = parseDimension(row3[colorChannels]); core[i].dimensionOrder = "XYCZT"; if (core[i].sizeZ == 0) core[i].sizeZ = 1; if (core[i].sizeC == 0) core[i].sizeC = 1; if (core[i].sizeT == 0) core[i].sizeT = 1; xmlFiles[i] = topDirectory + File.separator + row2[filename]; tiffFiles[i] = topDirectory + File.separator + row3[filename]; parser[i] = new TiffParser(tiffFiles[i]); parser[i].setDoCaching(false); ifds[i] = parser[i].getIFDs(); for (IFD ifd : ifds[i]) { parser[i].fillInIFD(ifd); } // get core metadata from TIFF file IFD ifd = ifds[i].get(0); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[i].sizeX = (int) ifd.getImageWidth(); core[i].sizeY = (int) ifd.getImageLength(); core[i].rgb = samples > 1 || photo == PhotoInterp.RGB; core[i].pixelType = ifd.getPixelType(); core[i].littleEndian = ifd.isLittleEndian(); core[i].indexed = photo == PhotoInterp.RGB_PALETTE && ifd.containsKey(IFD.COLOR_MAP); core[i].imageCount = ifds[i].size(); if (core[i].sizeZ * core[i].sizeT * (core[i].rgb ? 1 : core[i].sizeC) != core[i].imageCount) { core[i].sizeT = core[i].imageCount / (core[i].rgb ? 1 : core[i].sizeC); core[i].sizeZ = 1; } } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); for (int i=0; i<seriesCount; i++) { String[] row = rows.get(seriesIndexes.get(i)); // populate Image data MetadataTools.setDefaultCreationDate(store, mtb, i); store.setImageName(row[imageName], i); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // populate Dimensions data // calculate physical X and Y sizes double realWidth = Double.parseDouble(row[calibratedWidth]); double realHeight = Double.parseDouble(row[calibratedHeight]); String units = row[calibrationUnit]; double px = realWidth / core[i].sizeX; double py = realHeight / core[i].sizeY; if (units.equals("mm")) { px *= 1000; py *= 1000; } // TODO : add cases for other units if (px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", px); } if (py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", py); } } } } // -- Helper methods -- /** * Parse an integer from the given dimension String. * * @return the parsed integer, or 1 if parsing failed. */ private int parseDimension(String dim) { try { return Integer.parseInt(dim); } catch (NumberFormatException e) { return 1; } } }
package de.fhpotsdam.unfolding.examples.mask; import processing.core.PApplet; import processing.core.PGraphics; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.mapdisplay.OpenGLMapDisplay; import de.fhpotsdam.unfolding.mapdisplay.shaders.MaskedMapDisplayShader; import de.fhpotsdam.unfolding.utils.MapUtils; /** * This example shows the use of an gray-scale mask applied to the map. */ public class SimpleMaskApp extends PApplet { UnfoldingMap map; PGraphics mask; MaskedMapDisplayShader mapDisplayShader; public void setup() { size(830, 420, OPENGL); map = new UnfoldingMap(this, "map1", 10, 10, 400, 400, true, false, null); MapUtils.createDefaultEventDispatcher(this, map); mapDisplayShader = new MaskedMapDisplayShader(this,400,400); ((OpenGLMapDisplay)map.mapDisplay).setMapDisplayShader(mapDisplayShader); mask = mapDisplayShader.getMask(); mask.beginDraw(); mask.background(0); mask.endDraw(); } public void draw() { background(0); updateMask(); map.draw(); // shows the mask next to the map image(mask, 420, 10); } // draw the grayscale mask on an mask object // 255 = invisible // 0 = visible public void updateMask() { mask.beginDraw(); if (mouseX != 0 && mouseY != 0) { mask.noStroke(); mask.fill(255, 255,255); mask.ellipse(mouseX, mouseY, 50, 50); } mask.ellipse(mouseX, mouseY, 100, 100); mask.endDraw(); } public static void main(String[] args) { PApplet.main(new String[] { "de.fhpotsdam.unfolding.examples.ui.SimpleMaskApp" }); } }
package br.com.caelum.tubaina.parser.latex; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import br.com.caelum.tubaina.parser.Tag; public class ImageTag implements Tag { double pageWidth = 175; public String parse(final String path, final String options) { String output = "\\begin{figure}[H]\n\\centering\n"; output = output + "\\includegraphics"; Pattern label = Pattern.compile("(?s)(?i)label=(\\w+)%?"); Matcher labelMatcher = label.matcher(options); Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\""); Matcher descriptionMatcher = description.matcher(options); Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher horizontalMatcher = horizontalScale.matcher(options); Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?)\\]"); Matcher actualWidthMatcher = actualWidth.matcher(options); double width = Double.MAX_VALUE; if (actualWidthMatcher.find()) { width = Double.parseDouble(actualWidthMatcher.group(1)); } if (horizontalMatcher.find()) { output = output + "[width=" + pageWidth * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]"; } else if (width > pageWidth) { output = output + "[width=\\textwidth]"; } else { output = output + "[scale=1]"; } String imgsrc = FilenameUtils.getName(path); output = output + "{" + imgsrc + "}\n"; if (descriptionMatcher.find()) { output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n"; } if (labelMatcher.find()) { output += "\\label{" + labelMatcher.group(1) + "}\n"; } output = output + "\\end{figure}\n\n"; return output; } public Integer getScale(final String string) { if (string == null) { return null; } Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher sMatcher = horizontalScale.matcher(string); if (sMatcher.find()) { return Integer.parseInt(sMatcher.group(1)); } return null; } }
// $Id: ClientGmsImpl.java,v 1.53 2007/09/03 06:39:45 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.protocols.PingRsp; import org.jgroups.util.Promise; import org.jgroups.util.Util; import org.jgroups.util.Digest; import org.jgroups.util.MutableDigest; import java.util.*; /** * Client part of GMS. Whenever a new member wants to join a group, it starts in the CLIENT role. * No multicasts to the group will be received and processed until the member has been joined and * turned into a SERVER (either coordinator or participant, mostly just participant). This class * only implements <code>Join</code> (called by clients who want to join a certain group, and * <code>ViewChange</code> which is called by the coordinator that was contacted by this client, to * tell the client what its initial membership is. * @author Bela Ban * @version $Revision: 1.53 $ */ public class ClientGmsImpl extends GmsImpl { private final Promise<JoinRsp> join_promise=new Promise<JoinRsp>(); public ClientGmsImpl(GMS g) { super(g); } public void init() throws Exception { super.init(); join_promise.reset(); } public void join(Address address){ join(address, false); } public void joinWithStateTransfer(Address address){ join(address, true); } /** * Joins this process to a group. Determines the coordinator and sends a * unicast handleJoin() message to it. The coordinator returns a JoinRsp and * then broadcasts the new view, which contains a message digest and the * current membership (including the joiner). The joiner is then supposed to * install the new view and the digest and starts accepting mcast messages. * Previous mcast messages were discarded (this is done in PBCAST). * <p> * If successful, impl is changed to an instance of ParticipantGmsImpl. * Otherwise, we continue trying to send join() messages to the coordinator, * until we succeed (or there is no member in the group. In this case, we * create our own singleton group). * <p> * When GMS.disable_initial_coord is set to true, then we won't become * coordinator on receiving an initial membership of 0, but instead will * retry (forever) until we get an initial membership of > 0. * * @param mbr Our own address (assigned through SET_LOCAL_ADDRESS) */ private void join(Address mbr, boolean joinWithStateTransfer) { Address coord; JoinRsp rsp; View tmp_view; leaving=false; join_promise.reset(); while(!leaving) { List<PingRsp> responses=findInitialMembers(); if(log.isDebugEnabled()) log.debug("initial_mbrs are " + responses); if(responses.isEmpty()) { if(gms.disable_initial_coord) { if(log.isTraceEnabled()) log.trace("received an initial membership of 0, but cannot become coordinator " + "(disable_initial_coord=true), will retry fetching the initial membership"); continue; } if(log.isDebugEnabled()) log.debug("no initial members discovered: creating group as first member"); becomeSingletonMember(mbr); return; } coord=determineCoord(responses); if(coord == null) { // e.g. because we have all clients only if(gms.handle_concurrent_startup == false) { if(log.isTraceEnabled()) log.trace("handle_concurrent_startup is false; ignoring responses of initial clients"); becomeSingletonMember(mbr); return; } if(log.isTraceEnabled()) log.trace("could not determine coordinator from responses " + responses); // so the member to become singleton member (and thus coord) is // the first of all clients Set<Address> clients=new TreeSet<Address>(); // sorted clients.add(mbr); // add myself again (was removed by // findInitialMembers()) for(PingRsp response: responses) { Address client_addr=response.getAddress(); if(client_addr != null) clients.add(client_addr); } if(log.isTraceEnabled()) log.trace("clients to choose new coord from are: " + clients); Address new_coord=clients.iterator().next(); if(new_coord.equals(mbr)) { if(log.isTraceEnabled()) log.trace("I (" + mbr + ") am the first of the clients, will become coordinator"); becomeSingletonMember(mbr); return; } else { if(log.isTraceEnabled()) log.trace("I (" + mbr + ") am not the first of the clients, " + "waiting for another client to become coordinator"); Util.sleep(500); } continue; } try { if(log.isDebugEnabled()) log.debug("sending handleJoin(" + mbr + ") to " + coord); sendJoinMessage(coord, mbr, joinWithStateTransfer); rsp=join_promise.getResult(gms.join_timeout); if(rsp == null) { if(log.isWarnEnabled()) log.warn("join(" + mbr + ") sent to " + coord + " timed out, retrying"); } else { // 1. check whether JOIN was rejected String failure=rsp.getFailReason(); if(failure != null) throw new SecurityException(failure); // 2. Install digest MutableDigest tmp_digest=new MutableDigest(rsp.getDigest()); tmp_view=rsp.getView(); if(tmp_digest == null || tmp_view == null) { if(log.isErrorEnabled()) log.error("JoinRsp has a null view or digest: view=" + tmp_view + ", digest=" + tmp_digest + ", skipping it"); } else { tmp_digest.incrementHighestDeliveredSeqno(coord); // see DESIGN for details tmp_digest.seal(); gms.setDigest(tmp_digest); if(log.isDebugEnabled()) log.debug("[" + gms.local_addr + "]: JoinRsp=" + tmp_view + " [size=" + tmp_view.size() + "]\n\n"); if(!installView(tmp_view)) { if(log.isErrorEnabled()) log.error("view installation failed, retrying to join group"); Util.sleep(gms.join_retry_timeout); continue; } // send VIEW_ACK to sender of view Message view_ack=new Message(coord, null, null); view_ack.setFlag(Message.OOB); GMS.GmsHeader tmphdr=new GMS.GmsHeader(GMS.GmsHeader.VIEW_ACK); view_ack.putHeader(GMS.name, tmphdr); if(!gms.members.contains(coord)) gms.getDownProtocol().down(new Event(Event.ENABLE_UNICASTS_TO, coord)); gms.getDownProtocol().down(new Event(Event.MSG, view_ack)); return; } } } catch(SecurityException security_ex) { throw security_ex; } catch(IllegalArgumentException illegal_arg) { throw illegal_arg; } catch(Throwable e) { if(log.isDebugEnabled()) log.debug("exception=" + e + ", retrying"); } Util.sleep(gms.join_retry_timeout); } } private List<PingRsp> findInitialMembers() { List<PingRsp> responses=(List<PingRsp>)gms.getDownProtocol().down(new Event(Event.FIND_INITIAL_MBRS)); for(Iterator<PingRsp> iter=responses.iterator(); iter.hasNext();) { PingRsp response=iter.next(); if(response.own_addr != null && response.own_addr.equals(gms.local_addr)) iter.remove(); } return responses; } public void leave(Address mbr) { leaving=true; wrongMethod("leave"); } public void handleJoinResponse(JoinRsp join_rsp) { join_promise.setResult(join_rsp); // will wake up join() method } public void handleLeaveResponse() { } public void suspect(Address mbr) { } public void unsuspect(Address mbr) { } public void handleMembershipChange (Collection<Request> requests) { } /** * Does nothing. Discards all views while still client. */ public synchronized void handleViewChange(View new_view, Digest digest) { if(log.isTraceEnabled()) log.trace("view " + new_view.getVid() + " is discarded as we are not a participant"); } /** * Called by join(). Installs the view returned by calling Coord.handleJoin() and * becomes coordinator. */ private boolean installView(View new_view) { Vector mems=new_view.getMembers(); if(log.isDebugEnabled()) log.debug("new_view=" + new_view); if(gms.local_addr == null || mems == null || !mems.contains(gms.local_addr)) { if(log.isErrorEnabled()) log.error("I (" + gms.local_addr + ") am not member of " + mems + ", will not install view"); return false; } gms.installView(new_view); gms.becomeParticipant(); gms.getUpProtocol().up(new Event(Event.BECOME_SERVER)); gms.getDownProtocol().down(new Event(Event.BECOME_SERVER)); return true; } /** Returns immediately. Clients don't handle suspect() requests */ // public void handleSuspect(Address mbr) { void sendJoinMessage(Address coord, Address mbr,boolean joinWithTransfer) { Message msg; GMS.GmsHeader hdr; msg=new Message(coord, null, null); if(joinWithTransfer) hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER, mbr); else hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ, mbr); msg.putHeader(gms.getName(), hdr); // we have to enable unicasts to coord, as coord is not in our membership (the unicast message would get dropped) gms.getDownProtocol().down(new Event(Event.ENABLE_UNICASTS_TO, coord)); gms.getDownProtocol().down(new Event(Event.MSG, msg)); } /** The coordinator is determined by a majority vote. If there are an equal number of votes for more than 1 candidate, we determine the winner randomly. */ private Address determineCoord(List<PingRsp> mbrs) { int count, most_votes; Address winner=null, tmp; if(mbrs == null || mbrs.size() < 1) return null; Map<Address,Integer> votes=new HashMap<Address,Integer>(5); // count *all* the votes (unlike the 2000 election) for(PingRsp mbr:mbrs) { if(mbr.is_server && mbr.coord_addr != null) { if(!votes.containsKey(mbr.coord_addr)) votes.put(mbr.coord_addr, 1); else { count=votes.get(mbr.coord_addr); votes.put(mbr.coord_addr, count + 1); } } } if(votes.size() > 1) { if(log.isWarnEnabled()) log.warn("there was more than 1 candidate for coordinator: " + votes); } else { if(log.isDebugEnabled()) log.debug("election results: " + votes); } // determine who got the most votes most_votes=0; for(Map.Entry<Address,Integer> entry: votes.entrySet()) { tmp=entry.getKey(); count=entry.getValue(); if(count > most_votes) { winner=tmp; // fixed July 15 2003 (patch submitted by Darren Hobbs, patch-id=771418) most_votes=count; } } votes.clear(); return winner; } void becomeSingletonMember(Address mbr) { Digest initial_digest; ViewId view_id; Vector mbrs=new Vector(1); // set the initial digest (since I'm the first member) initial_digest=new Digest(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1) gms.setDigest(initial_digest); view_id=new ViewId(mbr); // create singleton view with mbr as only member mbrs.addElement(mbr); gms.installView(new View(view_id, mbrs)); gms.becomeCoordinator(); // not really necessary - installView() should do it gms.getUpProtocol().up(new Event(Event.BECOME_SERVER)); gms.getDownProtocol().down(new Event(Event.BECOME_SERVER)); if(log.isDebugEnabled()) log.debug("created group (first member). My view is " + gms.view_id + ", impl is " + gms.getImpl().getClass().getName()); } }
package org.flymine.codegen; import java.io.File; import java.util.Collection; import java.util.Iterator; import java.util.Collections; import java.util.List; import java.util.ArrayList; import org.flymine.util.DatabaseUtil; import org.flymine.metadata.Model; import org.flymine.metadata.ClassDescriptor; import org.flymine.metadata.FieldDescriptor; import org.flymine.metadata.AttributeDescriptor; import org.flymine.metadata.ReferenceDescriptor; import org.flymine.metadata.CollectionDescriptor; /** * Map FlyMine metadata to an OJB repository file * * @author Mark Woodbridge */ public class OJBModelOutput extends ModelOutput { static final String ID = "ID"; static final String CLASS = "CLASS"; protected StringBuffer references, collections; /** * @see ModelOutput#ModelOutput(Model, File) */ public OJBModelOutput(Model model, File file) throws Exception { super(model, file); } /** * @see ModelOutput#process */ public void process() { File path = new File(file, "repository_" + model.getName() + ".xml"); initFile(path); outputToFile(path, generate(model)); } /** * @see ModelOutput#generate(Model) */ protected String generate(Model model) { StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + ENDL) .append("<!DOCTYPE descriptor-repository SYSTEM") .append(" \"http://db.apache.org/ojb/dtds/1.0/repository.dtd\" [" + ENDL) .append("<!ENTITY internal SYSTEM \"repository_internal.xml\">" + ENDL) .append("]>" + ENDL + ENDL) .append("<descriptor-repository version=\"1.0\"") .append(" isolation-level=\"read-uncommitted\">" + ENDL); Iterator iter = model.getClassDescriptors().iterator(); while (iter.hasNext()) { ClassDescriptor cld = (ClassDescriptor) iter.next(); sb.append(generate(cld)); } sb.append("&internal;" + ENDL) .append("</descriptor-repository>" + ENDL); return sb.toString(); } /** * @see ModelOutput#generate(ClassDescriptor) */ protected String generate(ClassDescriptor cld) { references = new StringBuffer(); collections = new StringBuffer(); ClassDescriptor parentCld = cld.getSuperclassDescriptor(); StringBuffer sb = new StringBuffer (); sb.append(INDENT) .append("<class-descriptor class=\"") .append(cld.getName()) .append("\"") .append(parentCld == null ? "" : " extends=\"" + parentCld.getName() + "\"") .append(cld.isInterface() ? "" : " table=\"" + DatabaseUtil.getTableName(cld) + "\"") .append(">" + ENDL); Collection extent = cld.isInterface() ? cld.getImplementorDescriptors() : cld.getSubclassDescriptors(); Iterator iter = extent.iterator(); while (iter.hasNext()) { sb.append(INDENT + INDENT) .append("<extent-class class-ref=\"") .append(((ClassDescriptor) iter.next()).getName()) .append("\"/>" + ENDL); } if (!cld.isInterface()) { sb.append(INDENT + INDENT) .append("<field-descriptor") .append(" name=\"id\"") .append(" column=\"" + ID + "\"") .append(" jdbc-type=\"INTEGER\"") .append(" primarykey=\"true\"") .append(" autoincrement=\"true\"/>" + ENDL); if (parentCld != null || cld.getSubclassDescriptors().size() > 0) { sb.append(INDENT + INDENT) .append("<field-descriptor") .append(" name=\"ojbConcreteClass\"") .append(" column=\"" + CLASS + "\"") .append(" jdbc-type=\"VARCHAR\"/>" + ENDL); } if (parentCld != null) { Iterator superClds = getParents(cld).iterator(); while (superClds.hasNext()) { ClassDescriptor superCld = (ClassDescriptor) superClds.next(); doAttributes(superCld, sb); doAssociations(superCld, sb); } } doAttributes(cld, sb); doAssociations(cld, sb); } sb.append("" + references + collections) .append(INDENT) .append("</class-descriptor>" + ENDL + ENDL); return sb.toString(); } /** * @see ModelOutput#generate(AttributeDescriptor) */ protected String generate(AttributeDescriptor attr) { StringBuffer sb = new StringBuffer(); sb.append(INDENT + INDENT) .append("<field-descriptor name=\"") .append(attr.getName()) .append("\" column=\"") .append(DatabaseUtil.getColumnName(attr)) .append("\" jdbc-type=\"") .append(generateJdbcType(attr.getType())) .append("\"") .append(generateConversion(attr.getType())) .append("/>" + ENDL); return sb.toString(); } /** * @see ModelOutput#generate(ReferenceDescriptor) */ protected String generate(ReferenceDescriptor ref) { StringBuffer sb = new StringBuffer(); sb.append(INDENT + INDENT) .append("<field-descriptor name=\"") .append(ref.getName()) .append("Id\" column=\"") .append(DatabaseUtil.getColumnName(ref)) .append("\" access=\"anonymous\" jdbc-type=\"INTEGER\"/>" + ENDL); references.append(INDENT + INDENT) .append("<reference-descriptor name=\"") .append(ref.getName()) .append("\" class-ref=\"") .append(ref.getReferencedClassDescriptor().getName() + "\"") .append(" proxy=\"true\"") .append(">" + ENDL) .append(INDENT + INDENT + INDENT) .append("<foreignkey field-ref=\"") .append(ref.getName()) .append("Id") .append("\"/>" + ENDL) .append(INDENT + INDENT) .append("</reference-descriptor>" + ENDL); return sb.toString(); } /** * @see ModelOutput#generate(CollectionDescriptor) */ protected String generate(CollectionDescriptor col) { StringBuffer sb = new StringBuffer(); ReferenceDescriptor rd = col.getReverseReferenceDescriptor(); if (FieldDescriptor.M_N_RELATION == col.relationType()) { //many:many collections.append(INDENT + INDENT) .append("<collection-descriptor name=\"") .append(col.getName()) .append("\" element-class-ref=\"") .append(col.getReferencedClassDescriptor().getName()) .append("\" collection-class=\"") .append(col.getCollectionClass().getName()) .append("\" proxy=\"true\"") .append(" indirection-table=\"") .append(DatabaseUtil.getIndirectionTableName(col)) .append("\">" + ENDL) .append(INDENT + INDENT + INDENT) .append("<fk-pointing-to-this-class column=\"") // Name of this class's primary key in linkage table .append(DatabaseUtil.getInwardIndirectionColumnName(col)) .append("\"/>" + ENDL) .append(INDENT + INDENT + INDENT) .append("<fk-pointing-to-element-class column=\"") // Name of related class's primary key in linkage table .append(DatabaseUtil.getOutwardIndirectionColumnName(col)) .append("\"/>" + ENDL) .append(INDENT + INDENT) .append("</collection-descriptor>" + ENDL); } else { //many:one collections.append(INDENT + INDENT) .append("<collection-descriptor name=\"") .append(col.getName()) .append("\" element-class-ref=\"") .append(col.getReferencedClassDescriptor().getName()) .append("\" collection-class=\"") .append(col.getCollectionClass().getName()) .append("\" proxy=\"true\">" + ENDL) .append(INDENT + INDENT + INDENT) .append("<inverse-foreignkey field-ref=\"") .append(rd.getName()) .append("Id\"/>" + ENDL) .append(INDENT + INDENT) .append("</collection-descriptor>" + ENDL); } return sb.toString(); } /** * Get all superclasses of the given class descriptor. * @param cld descriptor for class in question * @return a list of descriptors for superclasses */ protected List getParents(ClassDescriptor cld) { List parentList = new ArrayList(); ClassDescriptor superCld = cld.getSuperclassDescriptor(); while (superCld != null) { parentList.add(superCld); superCld = superCld.getSuperclassDescriptor(); } Collections.reverse(parentList); return parentList; } /** * Iterate over attributes of this class inquestion and generate * ouput text for each. * @param cld descriptor of class in question * @param sb a stringbuffer to write field data to */ protected void doAttributes(ClassDescriptor cld, StringBuffer sb) { Iterator iter = cld.getAttributeDescriptors().iterator(); while (iter.hasNext()) { sb.append(generate((AttributeDescriptor) iter.next())); } } /** * Iterate over associations for given class and create output data * for all references and collections. * @param cld descriptor of class in question * @param sb buffer to write field data to */ protected void doAssociations(ClassDescriptor cld, StringBuffer sb) { Iterator iter; iter = cld.getReferenceDescriptors().iterator(); while (iter.hasNext()) { sb.append(generate((ReferenceDescriptor) iter.next())); } iter = cld.getCollectionDescriptors().iterator(); while (iter.hasNext()) { sb.append(generate((CollectionDescriptor) iter.next())); } } /** * Convert java primitive and object names to those compatible * with ojb repository file. Returns unaltered string if no * conversion is required. * @param type the string to convert * @return ojb mapping file compatible name */ protected static String generateJdbcType(String type) { if (type.equals("int") || type.equals("java.lang.Integer")) { return "INTEGER"; } if (type.equals("java.lang.String")) { return "LONGVARCHAR"; } if (type.equals("boolean") || type.equals("java.lang.Boolean")) { return "INTEGER"; } if (type.equals("float") || type.equals("java.lang.Float")) { return "REAL"; } if (type.equals("double") || type.equals("java.lang.Double")) { return "DOUBLE"; } if (type.equals("java.util.Date")) { return "DATE"; } return type; } /** * Return conversion from Java type to database representation if necessary * @param type the string to convert * @return an XML attribute string for the ojb mapping file */ protected static String generateConversion(String type) { if (type.equals("boolean") || type.equals("java.lang.Boolean")) { return " conversion=\"" + "org.apache.ojb.broker.accesslayer.conversions.Boolean2IntFieldConversion\""; } if (type.equals("java.util.Date")) { return " conversion=\"" + "org.apache.ojb.broker.accesslayer.conversions.JavaDate2SqlDateFieldConversion\""; } return ""; } }
package com.sinyuk.yuk.ui.oauth; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.sinyuk.yuk.App; import com.sinyuk.yuk.R; import com.sinyuk.yuk.api.AccountManager; import com.sinyuk.yuk.api.DribbleApi; import com.sinyuk.yuk.api.oauth.OauthModule; import com.sinyuk.yuk.data.user.User; import com.sinyuk.yuk.ui.BaseActivity; import com.sinyuk.yuk.utils.BetterViewAnimator; import com.sinyuk.yuk.utils.StringUtils; import com.sinyuk.yuk.widgets.NestedWebView; import java.net.URL; import javax.inject.Inject; import butterknife.BindView; import fr.castorflex.android.smoothprogressbar.SmoothProgressBar; import retrofit2.adapter.rxjava.HttpException; import rx.functions.Action1; import timber.log.Timber; public class DribbleOauthActivity extends BaseActivity { @BindView(R.id.view_animator) BetterViewAnimator mViewAnimator; @BindView(R.id.tool_bar) Toolbar mToolbar; @BindView(R.id.web_view) NestedWebView mWebView; @BindView(R.id.menu) ImageView mMenu; @BindView(R.id.failded_layout) RelativeLayout mFailedLayout; @BindView(R.id.favicon) ImageView mFavicon; @BindView(R.id.progress_bar) SmoothProgressBar mProgressBar; @BindView(R.id.root_view) CoordinatorLayout mRootView; @Inject AccountManager accountManager; private URL mIntentUrl; private TextView messageTv; private final Action1<User> handleAuthResult = new Action1<User>() { @Override public void call(User user) { mViewAnimator.setDisplayedChildId(R.id.dribble_oauth_succeed_layout); } }; private final Action1<Throwable> handleAuthError = throwable -> { if (throwable instanceof HttpException) { HttpException error = (HttpException) throwable; handleMillionsOfErrors(error.message(), error.code()); } else { handleMillionsOfErrors(throwable.getLocalizedMessage(), -1); } }; public static Intent getAuthIntent(Context context) { final Intent intent = new Intent(context, DribbleOauthActivity.class); intent.setData(Uri.parse(DribbleApi.LOGIN_URL)); return intent; } @Override protected int getContentViewID() { return R.layout.dribbble_oauth_activity; } @Override protected void beforeInflating() { try { getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); } catch (Exception e) { e.printStackTrace(); } Intent intent = getIntent(); if (intent != null) { try { mIntentUrl = new URL(intent.getData().toString()); } catch (Exception e) { e.printStackTrace(); } } Timber.tag("DribbleOauthActivity"); App.get(this).getAppComponent().plus(new OauthModule()).inject(this); } @Override protected void finishInflating(Bundle savedInstanceState) { mViewAnimator.setDisplayedChildId(R.id.web_view); setupAppBar(); initWebViewSettings(); } /* @Override protected void onNewIntent(Intent intent) { if (intent == null || mWebView == null || intent.getData() == null) { return; } Timber.d("on new -> %s",intent.getData().toString()); mWebView.loadUrl(intent.getData().toString()); } */ private void setupAppBar() { mToolbar.setTitle(R.string.dribbble_oauth_activity_toolbar_title); mToolbar.setNavigationOnClickListener(view -> finish()); } @SuppressLint("SetJavaScriptEnabled") private void initWebViewSettings() { // initProgressBar(); mWebView.setWebViewClient(new MyWebViewClient()); WebSettings webSetting = mWebView.getSettings(); webSetting.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING); } else { webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); } webSetting.setAllowContentAccess(true); webSetting.setUseWideViewPort(true); webSetting.setSupportMultipleWindows(false); webSetting.setLoadWithOverviewMode(true); // Zoom webSetting.setSupportZoom(true); webSetting.setBuiltInZoomControls(true); webSetting.setDisplayZoomControls(false); webSetting.setAppCacheEnabled(false); webSetting.setDatabaseEnabled(false); webSetting.setDomStorageEnabled(true); webSetting.setJavaScriptEnabled(true); webSetting.setGeolocationEnabled(false); //webSetting.setGeolocationDatabasePath(this.getDir("webview_geolocation", 0).getPath()); webSetting.setSaveFormData(false); mWebView.loadUrl(mIntentUrl.toString()); } @Override protected void onResume() { super.onResume(); if (mWebView != null) { mWebView.onResume(); } } @Override protected void onPause() { if (mWebView != null) { mWebView.onPause(); } super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (mWebView != null && mWebView.canGoBack()) { mWebView.goBack(); return true; } else { return super.onKeyDown(keyCode, event); } } return super.onKeyDown(keyCode, event); } @Override public void finish() { clearWebView(); super.finish(); } @Override protected void onDestroy() { clearWebView(); super.onDestroy(); } private void clearWebView() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearCache(true); mWebView.clearHistory(); mWebView.removeAllViews(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } } private void clearCookies() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().removeAllCookies(null); CookieManager.getInstance().flush(); } else { CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(this); cookieSyncMngr.startSync(); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); cookieManager.removeSessionCookie(); cookieSyncMngr.stopSync(); cookieSyncMngr.sync(); } } private boolean isAuthCallback(Uri data) { return data != null && data.getScheme().equals(DribbleApi.REDIRECT_SCHEMA) && data.getAuthority().equals(DribbleApi.REDIRECT_AUTHORITY); } private void handleAuthCallback(Uri data) { // yuk://oauth-callback?code= hideProgress(); mViewAnimator.setDisplayedChildId(R.id.wait_layout); // use the parameter your API exposes for the code (mostly it's "code") String code = data.getQueryParameter("code"); if (!TextUtils.isEmpty(code)) { // get access token we'll do that in a minute addSubscription(accountManager.getAccessToken(code) .doOnNext(accessToken -> accountManager.saveAccessToken(accessToken)) .flatMap(accessToken -> accountManager.refreshUserProfile()) .doOnError(handleAuthError) .doOnTerminate(this::clearCookies) .subscribe(handleAuthResult)); } else if (data.getQueryParameter("error") != null) { // show an error message here handleMillionsOfErrors(data.getQueryParameter("error"), -1); } } public void handleMillionsOfErrors(String msg, int code) { if (messageTv == null) { messageTv = (TextView) mFailedLayout.findViewById(R.id.message_tv); } if (messageTv == null) return; if (code != -1) { messageTv.setText(code + " < } messageTv.append(StringUtils.valueOrDefault(msg, getString(R.string.dribble_oauth_error_message))); hideProgress(); mViewAnimator.setDisplayedChildId(R.id.failded_layout); } private void showProgress() { mProgressBar.setVisibility(View.VISIBLE); mProgressBar.progressiveStart(); } private void hideProgress() { mProgressBar.setVisibility(View.GONE); mProgressBar.progressiveStop(); } /* private boolean isRedirectUri(final String msg, final int code) { Timber.d("Redirect err msg : %s", msg); Timber.d("Redirect err code : %d", code); return (DribbleApi.REDIRECT_AUTHORITY).equals(Uri.parse(msg).getAuthority()) && code == DribbleApi.REDIRECT_URL_ERROR_CODE; } private boolean isRedirectUri(final Uri uri, final int code) { Timber.d("Redirect err msg : %s", uri.toString()); Timber.d("Redirect err code : %d", code); return (DribbleApi.REDIRECT_AUTHORITY).equals(uri.getAuthority()) && code == DribbleApi.REDIRECT_URL_ERROR_CODE; }*/ private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Timber.d("Url -> %s", url); if (isAuthCallback(Uri.parse(url))) { handleAuthCallback(Uri.parse(url)); } else { view.loadUrl(url); } } return false; } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Timber.d("Url -> %s", request.getUrl()); if (isAuthCallback(request.getUrl())) { handleAuthCallback(request.getUrl()); } else { view.loadUrl(request.getUrl().toString()); } } return false; } /* @TargetApi(Build.VERSION_CODES.M) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); if (isRedirectUri(request.getUrl(), error.getErrorCode())) { mViewAnimator.setDisplayedChildId(R.id.wait_layout); } else { handleMillionsOfErrors(error.getDescription().toString(), error.getErrorCode()); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); if (isRedirectUri(failingUrl, errorCode)) { mViewAnimator.setDisplayedChildId(R.id.wait_layout); } else { handleMillionsOfErrors(description, errorCode); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); handleMillionsOfErrors(errorResponse.getReasonPhrase(), errorResponse.getStatusCode()); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); handleMillionsOfErrors(error.getUrl(), error.getPrimaryError()); }*/ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (favicon != null) { mFavicon.setImageBitmap(favicon); } showProgress(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); hideProgress(); } } }
package com.github.tminglei.swagger; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URISyntaxException; import java.util.Optional; import static com.github.tminglei.swagger.SwaggerUtils.*; /** * Filter used to init/scan swagger registering info and serv swagger json */ public class SwaggerFilter implements Filter { private boolean enabled = true; @Override public void init(FilterConfig filterConfig) throws ServletException { enabled = Optional.ofNullable(filterConfig.getInitParameter("enabled")) .map(Boolean::parseBoolean).orElse(true); // set user customized swagger helper String mySwaggerHelper = filterConfig.getInitParameter("my-swagger-helper"); if (!isEmpty(mySwaggerHelper)) { try { Class<MSwaggerHelper> clazz = (Class<MSwaggerHelper>) Class.forName(mySwaggerHelper); SwaggerContext.setMHelper(clazz.newInstance()); } catch (ClassNotFoundException e) { throw new RuntimeException("INVALID swagger helper class: '" + mySwaggerHelper + "'!!!"); } catch (InstantiationException e) { throw new RuntimeException("FAILED to instantiate the swagger helper class: '" + mySwaggerHelper + "'!!!"); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } // scan and register swagger api info String[] scanPackages = Optional.ofNullable(filterConfig.getInitParameter("scan-packages")) .map(s -> s.split(",")).orElse(new String[0]); for(String pkgname : scanPackages) { if (!isEmpty(pkgname)) { try { scan(this.getClass(), pkgname.trim()).forEach(clz -> { try { Class.forName(clz); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }); } catch (URISyntaxException e) { throw new RuntimeException("INVALID package name: '" + pkgname + "'!!!"); } catch (IOException e) { throw new RuntimeException(e); } } } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (enabled) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String swaggerPath = (SwaggerContext.swagger().getBasePath() + "").replaceAll("/$", "") + "/swagger.json"; if (req.getPathInfo().equals(swaggerPath) && "GET".equalsIgnoreCase(req.getMethod())) { // enable cross-origin resource sharing resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, DELETE, HEAD, OPTIONS"); resp.setHeader("Access-Control-Max-Age", "43200"); // half a day String json = new ObjectMapper().writer().writeValueAsString(check(SwaggerContext.swagger())); response.getWriter().write(json); response.flushBuffer(); return; } } filterChain.doFilter(request, response); } @Override public void destroy() { // nothing to do } }
/* * $Id: StatusServiceImpl.java,v 1.25 2004-09-15 22:27:36 tlipkis Exp $ */ package org.lockss.daemon.status; import java.util.*; import org.apache.oro.text.regex.*; import org.lockss.app.*; import org.lockss.daemon.*; import org.lockss.util.*; /** * Main implementation of {@link StatusService} */ public class StatusServiceImpl extends BaseLockssManager implements StatusService { private static Logger logger = Logger.getLogger("StatusServiceImpl"); private Map statusAccessors = new HashMap(); private Map objRefAccessors = new HashMap(); public void startService() { super.startService(); registerStatusAccessor(ALL_TABLES_TABLE, new AllTableStatusAccessor()); } public StatusTable getTable(String tableName, String key) throws StatusService.NoSuchTableException { return getTable(tableName, key, null); } public StatusTable getTable(String tableName, String key, BitSet options) throws StatusService.NoSuchTableException { if (tableName == null) { throw new StatusService.NoSuchTableException("Called with null tableName"); } StatusAccessor statusAccessor; synchronized(statusAccessors) { statusAccessor = (StatusAccessor)statusAccessors.get(tableName); } if (statusAccessor == null) { throw new StatusService.NoSuchTableException("Table not found: " +tableName+" "+key); } StatusTable table = new StatusTable(tableName, key); if (options != null) { BitSet tableOpts = table.getOptions(); tableOpts.xor(tableOpts); tableOpts.or(options); } if (statusAccessor.requiresKey() && table.getKey() == null) { throw new StatusService.NoSuchTableException(tableName + " requires a key value"); } statusAccessor.populateTable(table); if (table.getTitle() == null) { try { table.setTitle(statusAccessor.getDisplayName()); } catch (Exception e) { // ignored } } return table; } static Pattern badTablePat = RegexpUtil.uncheckedCompile("[^a-zA-Z0-9_-]", Perl5Compiler.READ_ONLY_MASK); private boolean isBadTableName(String tableName) { return RegexpUtil.getMatcher().contains(tableName, badTablePat); } public void registerStatusAccessor(String tableName, StatusAccessor statusAccessor) { if (isBadTableName(tableName)) { throw new InvalidTableNameException("Invalid table name: "+tableName); } synchronized(statusAccessors) { Object oldAccessor = statusAccessors.get(tableName); if (oldAccessor != null) { throw new StatusService.MultipleRegistrationException(oldAccessor +" already registered " +"for "+tableName); } statusAccessors.put(tableName, statusAccessor); } logger.debug("Registered statusAccessor for table "+tableName); } public void unregisterStatusAccessor(String tableName){ synchronized(statusAccessors) { statusAccessors.remove(tableName); } logger.debug("Unregistered statusAccessor for table "+tableName); } public StatusTable.Reference getReference(String tableName, Object obj) { ObjRefAccessorSpec spec; synchronized (objRefAccessors) { spec = (ObjRefAccessorSpec)objRefAccessors.get(tableName); } if (spec != null && spec.cls.isInstance(obj)) { return spec.accessor.getReference(obj, tableName); } else { return null; } } // not implemented yet. public List getReferences(Object obj) { return Collections.EMPTY_LIST; } public void registerObjectReferenceAccessor(String tableName, Class cls, ObjectReferenceAccessor objRefAccessor) { synchronized (objRefAccessors) { Object oldEntry = objRefAccessors.get(tableName); if (oldEntry != null) { ObjRefAccessorSpec oldSpec = (ObjRefAccessorSpec)oldEntry; throw new StatusService.MultipleRegistrationException(oldSpec.accessor +" already registered " +"for "+tableName); } ObjRefAccessorSpec spec = new ObjRefAccessorSpec(cls, tableName, objRefAccessor); objRefAccessors.put(tableName, spec); } logger.debug("Registered ObjectReferenceAccessor for table "+tableName + ", class " + cls); } public void unregisterObjectReferenceAccessor(String tableName, Class cls) { synchronized (objRefAccessors) { objRefAccessors.remove(tableName); } logger.debug("Unregistered ObjectReferenceAccessor for table "+tableName); } private class ObjRefAccessorSpec { Class cls; String table; ObjectReferenceAccessor accessor; ObjRefAccessorSpec(Class cls, String table, ObjectReferenceAccessor accessor) { this.cls = cls; this.table = table; this.accessor = accessor; } } private class AllTableStatusAccessor implements StatusAccessor { private List columns; private List sortRules; private static final String COL_NAME = "table_name"; private static final String COL_TITLE = "Available Tables"; private static final String ALL_TABLE_TITLE = "Cache Overview"; public AllTableStatusAccessor() { ColumnDescriptor col = new ColumnDescriptor(COL_NAME, COL_TITLE, ColumnDescriptor.TYPE_STRING); columns = ListUtil.list(col); StatusTable.SortRule sortRule = new StatusTable.SortRule(COL_NAME, true); sortRules = ListUtil.list(sortRule); } public String getDisplayName() { return ALL_TABLE_TITLE; } private List getRows() { synchronized(statusAccessors) { Set tables = statusAccessors.keySet(); Iterator it = tables.iterator(); List rows = new ArrayList(tables.size()); while (it.hasNext()) { String tableName = (String) it.next(); StatusAccessor statusAccessor = (StatusAccessor)statusAccessors.get(tableName); if (!ALL_TABLES_TABLE.equals(tableName) && !statusAccessor.requiresKey()) { Map row = new HashMap(1); //will only have the one key-value pair String title = null; try { title = statusAccessor.getDisplayName(); } catch (Exception e) { // no action, title is null here } // getTitle might return null or throw if (title == null) { title = tableName; } row.put(COL_NAME, new StatusTable.Reference(title, tableName, null)); rows.add(row); } } return rows; } } /** * Returns false * @return false */ public boolean requiresKey() { return false; } /** * Populate the {@link StatusTable} with entries for each table that * doesn't require a key * @param table {@link StatusTable} to populate as the table of all tables * that don't require a key */ public void populateTable(StatusTable table) { table.setColumnDescriptors(columns); table.setDefaultSortRules(sortRules); table.setRows(getRows()); } } }
package org.flymine.task; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.flymine.sql.DatabaseFactory; import org.flymine.dataloader.DataLoaderHelper; import org.flymine.dataloader.PrimaryKey; import org.flymine.metadata.Model; import org.flymine.metadata.ClassDescriptor; import org.flymine.metadata.FieldDescriptor; import org.flymine.metadata.ReferenceDescriptor; import org.flymine.metadata.CollectionDescriptor; import org.flymine.metadata.MetaDataException; import org.flymine.util.DatabaseUtil; import org.flymine.util.StringUtil; /** * Task to create indexes on a database holding objects conforming to a given model by * reading that model's primary key configuration information. * Three types of index are created: for the specified primary key fields, for all N-1 relations, * and for the indirection table columns of M-N relations. * This should speed up primary key queries, and other common queries * Note that all "id" columns are indexed automatically by virtue of FlyMineTorqueModelOuput * specifying them as primary key columns. * @author Mark Woodbridge */ public class CreateIndexesTask extends Task { protected String database, model; protected Connection c; /** * Set the database alias * @param database the database alias */ public void setDatabase(String database) { this.database = database; } /** * Set the model name * @param model the model name */ public void setModel(String model) { this.model = model; } /** * @see Task#execute */ public void execute() throws BuildException { if (database == null) { throw new BuildException("database attribute is not set"); } if (model == null) { throw new BuildException("model attribute is not set"); } try { c = DatabaseFactory.getDatabase(database).getConnection(); c.setAutoCommit(true); Model m = Model.getInstanceByName(model); for (Iterator i = m.getClassDescriptors().iterator(); i.hasNext();) { ClassDescriptor cld = (ClassDescriptor) i.next(); processClassDescriptor(cld); } } catch (Exception e) { e.printStackTrace(System.out); throw new BuildException(e); } finally { if (c != null) { try { c.close(); } catch (Exception e) { } } } } /** * Add indexes to the relevant tables for a given ClassDescriptor * @param cld the ClassDescriptor * @throws SQLException if an error occurs * @throws MetaDataException if a field os not found in model */ protected void processClassDescriptor(ClassDescriptor cld) throws SQLException, MetaDataException { // Set of fieldnames that already are the first element of an index. Set doneFieldNames = new HashSet(); //add an index for each primary key Map primaryKeys = DataLoaderHelper.getPrimaryKeys(cld); for (Iterator j = primaryKeys.entrySet().iterator(); j.hasNext();) { Map.Entry entry = (Map.Entry) j.next(); String keyName = (String) entry.getKey(); PrimaryKey key = (PrimaryKey) entry.getValue(); List fieldNames = new ArrayList(); for (Iterator k = key.getFieldNames().iterator(); k.hasNext();) { String fieldName = (String) k.next(); FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName); if (fd != null) { fieldNames.add(DatabaseUtil.getColumnName(fd)); } else { throw new MetaDataException("field (" + fieldName + ") not found for class: " + cld.getName() + "."); } } String tableName = DatabaseUtil.getTableName(cld); dropIndex(tableName + "__" + keyName); createIndex(tableName + "__" + keyName, tableName, StringUtil.join(fieldNames, ", ")); doneFieldNames.add(fieldNames.get(0)); } //and one for each bidirectional N-to-1 relation to increase speed of //e.g. company.getDepartments //for (Iterator j = cld.getAllReferenceDescriptors().iterator(); j.hasNext();) { for (Iterator j = cld.getReferenceDescriptors().iterator(); j.hasNext();) { ReferenceDescriptor ref = (ReferenceDescriptor) j.next(); if ((FieldDescriptor.N_ONE_RELATION == ref.relationType()) && (ref.getReverseReferenceDescriptor() != null)) { String tableName = DatabaseUtil.getTableName(cld); String fieldName = DatabaseUtil.getColumnName(ref); if (!doneFieldNames.contains(fieldName)) { dropIndex(tableName + "__" + ref.getName()); createIndex(tableName + "__" + ref.getName(), tableName, fieldName); } } } //finally add an index to all M-to-N indirection table columns //for (Iterator j = cld.getAllCollectionDescriptors().iterator(); j.hasNext();) { for (Iterator j = cld.getCollectionDescriptors().iterator(); j.hasNext();) { CollectionDescriptor col = (CollectionDescriptor) j.next(); if (FieldDescriptor.M_N_RELATION == col.relationType()) { String tableName = DatabaseUtil.getIndirectionTableName(col); String columnName = DatabaseUtil.getInwardIndirectionColumnName(col); dropIndex(tableName + "__" + columnName); createIndex(tableName + "__" + columnName, tableName, columnName); } } } /** * Drop an index by name, ignoring errors * @param indexName the index name */ protected void dropIndex(String indexName) { try { execute("drop index " + indexName); } catch (SQLException e) { } } /** * Create an named index on the specified columns of a table * @param indexName the index name * @param tableName the table name * @param columnNames the column names * @throws SQLException if an error occurs */ protected void createIndex(String indexName, String tableName, String columnNames) throws SQLException { execute("create index " + indexName + " on " + tableName + "(" + columnNames + ")"); } /** * Execute an sql statement * @param sql the sql string for the statement to execute * @throws SQLException if an error occurs */ protected void execute(String sql) throws SQLException { System .out.println(sql); c.createStatement().execute(sql); } }
/* $Log$ Revision 1.10 1998/10/18 17:37:34 rimassa Minor changes towards 'search' action implementation. Revision 1.9 1998/10/04 18:01:37 rimassa Added a 'Log:' field to every source file. */ package jade.domain; import java.io.StringReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.util.Enumeration; import java.util.Hashtable; import java.util.NoSuchElementException; import jade.core.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; public class df extends Agent { private abstract class DFBehaviour extends OneShotBehaviour implements BehaviourPrototype { // This String will be set by subclasses private AgentManagementOntology.DFAction myAction; private String myActionName; private ACLMessage myRequest; private ACLMessage myReply; protected DFBehaviour(String name) { super(df.this); myActionName = name; myRequest = null; myReply = null; } protected DFBehaviour(String name, ACLMessage request, ACLMessage reply) { super(df.this); myActionName = name; myRequest = request; myReply = reply; } // This method throws a FIPAException if the attribute is // mandatory for the current DF action but it is a null object // reference private void checkAttribute(String attributeName, String attributeValue) throws FIPAException { if(myOntology.isMandatoryForDF(myAction.getName(), attributeName) && (attributeValue == null)) throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } private void checkAttributeList(String attributeName, Enumeration attributeValue) throws FIPAException { if(myOntology.isMandatoryForDF(myAction.getName(), attributeName) && (!attributeValue.hasMoreElements())) throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } // This method parses the message content and puts // 'FIPA-DF-agent-description' attribute values in instance // variables. If some error is found a FIPA exception is thrown private void crackMessage() throws FIPAException, NoSuchElementException { String content = myRequest.getContent(); // Remove 'action df' from content string content = content.substring(content.indexOf("df") + 2); // FIXME: DF could crash for a bad msg // Obtain a DF action from message content try { myAction = AgentManagementOntology.DFAction.fromText(new StringReader(content)); } catch(ParseException pe) { // pe.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } catch(TokenMgrError tme) { // tme.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } // Finally, assign each attribute value to an instance variable, // making sure mandatory attributes for the current DF action // are non-null AgentManagementOntology.DFAgentDescriptor dfd = myAction.getArg(); checkAttribute(AgentManagementOntology.DFAgentDescriptor.NAME, dfd.getName()); checkAttributeList(AgentManagementOntology.DFAgentDescriptor.SERVICES, dfd.getAgentServices()); checkAttribute(AgentManagementOntology.DFAgentDescriptor.TYPE, dfd.getType()); checkAttributeList(AgentManagementOntology.DFAgentDescriptor.PROTOCOLS, dfd.getInteractionProtocols()); checkAttribute(AgentManagementOntology.DFAgentDescriptor.ONTOLOGY, dfd.getOntology()); checkAttributeList(AgentManagementOntology.DFAgentDescriptor.ADDRESS, dfd.getAddresses()); checkAttribute(AgentManagementOntology.DFAgentDescriptor.OWNERSHIP, dfd.getOwnership()); checkAttribute(AgentManagementOntology.DFAgentDescriptor.DFSTATE, dfd.getDFState()); } // Each concrete subclass will implement this deferred method to // do action-specific work protected abstract void processAction(AgentManagementOntology.DFAction dfa) throws FIPAException; public void action() { try { // Convert message from untyped keyword/value list to ordinary // typed variables, throwing a FIPAException in case of errors crackMessage(); // Do real action, deferred to subclasses processAction(myAction); } catch(FIPAException fe) { sendRefuse(myReply, fe.getMessage()); } catch(NoSuchElementException nsee) { sendRefuse(myReply, AgentManagementOntology.Exception.UNRECOGNIZEDVALUE); } } // The following methods handle the various possibilities arising in // DF <-> Agent interaction. They all receive an ACL message as an // argument, most of whose fields have already been set. Only the // message type and message content have to be filled in. // Send a 'not-understood' message back to the requester protected void sendNotUnderstood(ACLMessage msg) { msg.setType("not-understood"); msg.setContent(""); send(msg); } // Send a 'refuse' message back to the requester protected void sendRefuse(ACLMessage msg, String reason) { msg.setType("refuse"); msg.setContent("( action df " + myActionName + " ) " + reason); send(msg); } // Send a 'failure' message back to the requester protected void sendFailure(ACLMessage msg, String reason) { msg.setType("failure"); msg.setContent("( action df " + myActionName + " ) " + reason); send(msg); } // Send an 'agree' message back to the requester protected void sendAgree(ACLMessage msg) { msg.setType("agree"); msg.setContent("( action df " + myActionName + " )"); send(msg); } // Send an 'inform' message back to the requester protected void sendInform(ACLMessage msg) { msg.setType("inform"); msg.setContent("( done ( " + myActionName + " ) )"); send(msg); } } // End of DFBehaviour class // These four concrete classes serve both as a Prototype and as an // Instance: when seen as BehaviourPrototype they can spawn a new // Behaviour to process a given request, and when seen as // Behaviour they process their request and terminate. private class RegBehaviour extends DFBehaviour { public RegBehaviour() { super(AgentManagementOntology.DFAction.REGISTER); } public RegBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.DFAction.REGISTER, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new RegBehaviour(request, reply); } protected void processAction(AgentManagementOntology.DFAction dfa) throws FIPAException { AgentManagementOntology.DFAgentDescriptor dfd = dfa.getArg(); DFRegister(dfd); sendAgree(myReply); sendInform(myReply); } } // End of RegBehaviour class private class DeregBehaviour extends DFBehaviour { public DeregBehaviour() { super(AgentManagementOntology.DFAction.DEREGISTER); } public DeregBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.DFAction.DEREGISTER, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new DeregBehaviour(request, reply); } protected void processAction(AgentManagementOntology.DFAction dfa) throws FIPAException { AgentManagementOntology.DFAgentDescriptor dfd = dfa.getArg(); DFDeregister(dfd); sendAgree(myReply); sendInform(myReply); } } // End of DeregBehaviour class private class ModBehaviour extends DFBehaviour { public ModBehaviour() { super(AgentManagementOntology.DFAction.MODIFY); } public ModBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.DFAction.MODIFY, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new ModBehaviour(request, reply); } protected void processAction(AgentManagementOntology.DFAction dfa) throws FIPAException { AgentManagementOntology.DFAgentDescriptor dfd = dfa.getArg(); DFModify(dfd); sendAgree(myReply); sendInform(myReply); } } // End of ModBehaviour class private class SrchBehaviour extends DFBehaviour { public SrchBehaviour() { super(AgentManagementOntology.DFAction.SEARCH); } public SrchBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.DFAction.SEARCH, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new SrchBehaviour(request, reply); } protected void processAction(AgentManagementOntology.DFAction dfa) throws FIPAException { AgentManagementOntology.DFAgentDescriptor dfd = dfa.getArg(); AgentManagementOntology.DFSearchAction dfsa = (AgentManagementOntology.DFSearchAction)dfa; Enumeration constraints = dfsa.getConstraints(); DFSearch(dfsa, dfd, constraints); sendAgree(myReply); sendInform(myReply); } } // End of SrchBehaviour class private AgentManagementOntology myOntology; private FipaRequestServerBehaviour dispatcher; private Hashtable descriptors = new Hashtable(); public df() { myOntology = AgentManagementOntology.instance(); MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchLanguage("SL0"), MessageTemplate.MatchOntology("fipa-agent-management")); dispatcher = new FipaRequestServerBehaviour(this, mt); // Associate each DF action name with the behaviour to execute // when the action is requested in a 'request' ACL message dispatcher.registerPrototype(AgentManagementOntology.DFAction.REGISTER, new RegBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.DFAction.DEREGISTER, new DeregBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.DFAction.MODIFY, new ModBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.DFAction.SEARCH, new SrchBehaviour()); } protected void setup() { // add a message dispatcher behaviour addBehaviour(dispatcher); } protected void DFRegister(AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { if(descriptors.containsKey(dfd.getName())) throw myOntology.getException(AgentManagementOntology.Exception.AGENTALREADYREG); descriptors.put(dfd.getName(), dfd); System.out.println(""); } protected void DFDeregister(AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { Object o = descriptors.remove(dfd.getName()); AgentManagementOntology.DFAgentDescriptor toRemove = (AgentManagementOntology.DFAgentDescriptor)o; if(toRemove == null) throw myOntology.getException(AgentManagementOntology.Exception.UNABLETODEREG); } protected void DFModify(AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { Object o = descriptors.get(dfd.getName()); if(o == null) throw myOntology.getException(AgentManagementOntology.Exception.INCONSISTENCY); AgentManagementOntology.DFAgentDescriptor toChange = (AgentManagementOntology.DFAgentDescriptor)o; Enumeration e = dfd.getAddresses(); if(e.hasMoreElements()) toChange.removeAddresses(); while(e.hasMoreElements()) toChange.addAddress((String)e.nextElement()); e = dfd.getAgentServices(); if(e.hasMoreElements()) toChange.removeAgentServices(); while(e.hasMoreElements()) toChange.addService((AgentManagementOntology.ServiceDescriptor)e.nextElement()); String s = dfd.getType(); if(s != null) toChange.setType(s); e = dfd.getInteractionProtocols(); if(e.hasMoreElements()) toChange.removeInteractionProtocols(); while(e.hasMoreElements()) toChange.addInteractionProtocol((String)e.nextElement()); s = dfd.getOntology(); if(s != null) toChange.setOntology(s); s = dfd.getOwnership(); if(s != null) toChange.setOwnership(s); s = dfd.getDFState(); if(s != null) toChange.setDFState(s); } private void DFSearch(AgentManagementOntology.DFSearchAction dfsa, AgentManagementOntology.DFAgentDescriptor dfd, Enumeration constraints) { dfsa.toText(new BufferedWriter(new OutputStreamWriter(System.out))); // FIXME: To be implemented } }
package com.attributestudios.wolfarmor; import com.attributestudios.wolfarmor.api.util.Definitions; import com.attributestudios.wolfarmor.api.util.IProxy; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import javax.annotation.Nonnull; /** * WolfArmorMod main class */ @SuppressWarnings("WeakerAccess") @Mod(modid = Definitions.MOD_ID, name = Definitions.MOD_NAME, version = Definitions.MOD_VERSION, guiFactory = "com.attributestudios.wolfarmor.client.gui.config.WolfArmorGuiFactory", dependencies = "after: sophisticatedwolves") public class WolfArmorMod { //region Fields @SidedProxy(clientSide = "com.attributestudios.wolfarmor.client.ClientProxy", serverSide = "com.attributestudios.wolfarmor.common.CommonProxy") public static IProxy proxy; @Mod.Instance(Definitions.MOD_ID) private static WolfArmorMod instance; private static LogHelper logger; private static WolfArmorConfiguration configuration; //endregion Fields //region Public / Protected Methods public static IProxy getProxy() { return proxy; } public static WolfArmorMod getInstance() { return instance; } /** * Handles pre-initialization tasks * * @param preInitializationEvent The pre-initialization event */ @Mod.EventHandler public void preInit(@Nonnull FMLPreInitializationEvent preInitializationEvent) { logger = new LogHelper(preInitializationEvent.getModLog()); configuration = new WolfArmorConfiguration(preInitializationEvent); proxy.preInit(preInitializationEvent); } /** * Handles initialization tasks * * @param initializationEvent The initialization event */ @Mod.EventHandler public void init(@Nonnull FMLInitializationEvent initializationEvent) { proxy.init(initializationEvent); } /** * Handles post-initialization events * * @param postInitializationEvent The post initialization event */ @Mod.EventHandler public void postInit(@Nonnull FMLPostInitializationEvent postInitializationEvent) { proxy.postInit(postInitializationEvent); } //endregion Public / Protected Methods //region Accessors / Mutators /** * Gets the mod logger * * @return The logger */ @Nonnull public static LogHelper getLogger() { return logger; } /** * Gets the configuration settings * * @return The configuration settings */ @Nonnull public static WolfArmorConfiguration getConfiguration() { return configuration; } //endregion Accessors / Mutators }
package org.objectweb.asm.commons; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * A {@link org.objectweb.asm.MethodAdapter} with convenient methods to * generate code. For example, using this adapter, the class below * *<pre>public class Example { * public static void main (String[] args) { * System.out.println("Hello world!"); * } *}</pre> *can be generated as follows: *<pre>ClassWriter cw = new ClassWriter(true); *cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null); * *Method m = Method.getMethod("void &lt;init&gt; ()"); *GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw); *mg.loadThis(); *mg.invokeConstructor(Type.getType(Object.class), m); *mg.returnValue(); *mg.endMethod(); * *m = Method.getMethod("void main (String[])"); *mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw); *mg.getStatic(Type.getType(System.class), "out", Type.getType(PrintStream.class)); *mg.push("Hello world!"); *mg.invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println (String)")); *mg.returnValue(); *mg.endMethod(); * *cw.visitEnd();</pre> * * @author Juozas Baliuka * @author Chris Nokleberg * @author Eric Bruneton */ public class GeneratorAdapter extends LocalVariablesSorter { private final static Type BYTE_TYPE = Type.getType("Ljava/lang/Byte;"); private final static Type BOOLEAN_TYPE = Type.getType("Ljava/lang/Boolean;"); private final static Type SHORT_TYPE = Type.getType("Ljava/lang/Short;"); private final static Type CHARACTER_TYPE = Type.getType("Ljava/lang/Character;"); private final static Type INTEGER_TYPE = Type.getType("Ljava/lang/Integer;"); private final static Type FLOAT_TYPE = Type.getType("Ljava/lang/Float;"); private final static Type LONG_TYPE = Type.getType("Ljava/lang/Long;"); private final static Type DOUBLE_TYPE = Type.getType("Ljava/lang/Double;"); private final static Type NUMBER_TYPE = Type.getType("Ljava/lang/Number;"); private final static Type OBJECT_TYPE = Type.getType("Ljava/lang/Object;"); private final static Method BOOLEAN_VALUE = Method.getMethod("boolean booleanValue()"); private final static Method CHAR_VALUE = Method.getMethod("char charValue()"); private final static Method INT_VALUE = Method.getMethod("int intValue()"); private final static Method FLOAT_VALUE = Method.getMethod("float floatValue()"); private final static Method LONG_VALUE = Method.getMethod("long longValue()"); private final static Method DOUBLE_VALUE = Method.getMethod("double doubleValue()"); /** * Constant for the {@link #math math} method. */ public final static int ADD = Opcodes.IADD; /** * Constant for the {@link #math math} method. */ public final static int SUB = Opcodes.ISUB; /** * Constant for the {@link #math math} method. */ public final static int MUL = Opcodes.IMUL; /** * Constant for the {@link #math math} method. */ public final static int DIV = Opcodes.IDIV; /** * Constant for the {@link #math math} method. */ public final static int REM = Opcodes.IREM; /** * Constant for the {@link #math math} method. */ public final static int NEG = Opcodes.INEG; /** * Constant for the {@link #math math} method. */ public final static int SHL = Opcodes.ISHL; /** * Constant for the {@link #math math} method. */ public final static int SHR = Opcodes.ISHR; /** * Constant for the {@link #math math} method. */ public final static int USHR = Opcodes.IUSHR; /** * Constant for the {@link #math math} method. */ public final static int AND = Opcodes.IAND; /** * Constant for the {@link #math math} method. */ public final static int OR = Opcodes.IOR; /** * Constant for the {@link #math math} method. */ public final static int XOR = Opcodes.IXOR; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int EQ = Opcodes.IFEQ; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int NE = Opcodes.IFNE; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int LT = Opcodes.IFLT; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int GE = Opcodes.IFGE; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int GT = Opcodes.IFGT; /** * Constant for the {@link #ifCmp ifCmp} method. */ public final static int LE = Opcodes.IFLE; /** * Access flags of the method visited by this adapter. */ private final int access; /** * Return type of the method visited by this adapter. */ private final Type returnType; /** * Argument types of the method visited by this adapter. */ private final Type[] argumentTypes; /** * Types of the local variables of the method visited by this adapter. */ private final List localTypes; /** * Creates a new {@link GeneratorAdapter}. * * @param access access flags of the adapted method. * @param method the adapted method. * @param mv the method visitor to which this adapter delegates calls. */ public GeneratorAdapter ( final int access, final Method method, final MethodVisitor mv) { super(access, method.getDescriptor(), mv); this.access = access; this.returnType = method.getReturnType(); this.argumentTypes = method.getArgumentTypes(); this.localTypes = new ArrayList(); } /** * Creates a new {@link GeneratorAdapter}. * * @param access access flags of the adapted method. * @param method the adapted method. * @param signature the signature of the adapted method * (may be <tt>null</tt>). * @param exceptions the exceptions thrown by the adapted method * (may be <tt>null</tt>). * @param cv the class visitor to which this adapter delegates calls. */ public GeneratorAdapter ( final int access, final Method method, final String signature, final Type[] exceptions, final ClassVisitor cv) { this(access, method, cv.visitMethod( access, method.getName(), method.getDescriptor(), signature, getInternalNames(exceptions))); } /** * Returns the internal names of the given types. * * @param types a set of types. * @return the internal names of the given types. */ private static String[] getInternalNames (final Type[] types) { if (types == null) { return null; } String[] names = new String[types.length]; for (int i = 0; i < names.length; ++i) { names[i] = types[i].getInternalName(); } return names; } // Instructions to push constants on the stack /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final boolean value) { push(value ? 1 : 0); } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final int value) { if (value >= -1 && value <= 5) { mv.visitInsn(Opcodes.ICONST_0 + value); } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { mv.visitIntInsn(Opcodes.BIPUSH, value); } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { mv.visitIntInsn(Opcodes.SIPUSH, value); } else { mv.visitLdcInsn(new Integer(value)); } } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final long value) { if (value == 0L || value == 1L) { mv.visitInsn(Opcodes.LCONST_0 + (int)value); } else { mv.visitLdcInsn(new Long(value)); } } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final float value) { if (value == 0f || value == 1f || value == 2f) { mv.visitInsn(Opcodes.FCONST_0 + (int)value); } else { mv.visitLdcInsn(new Float(value)); } } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final double value) { if (value == 0d || value == 1d) { mv.visitInsn(Opcodes.DCONST_0 + (int)value); } else { mv.visitLdcInsn(new Double(value)); } } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. May be * <tt>null</tt>. */ public void push (final String value) { if (value == null) { mv.visitInsn(Opcodes.ACONST_NULL); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value the value to be pushed on the stack. */ public void push (final Type value) { if (value == null) { mv.visitInsn(Opcodes.ACONST_NULL); } else { mv.visitLdcInsn(value); } } // Instructions to load and store method arguments /** * Returns the index of the given method argument in the frame's local * variables array. * * @param arg the index of a method argument. * @return the index of the given method argument in the frame's local * variables array. */ private int getArgIndex (final int arg) { int index = ((access & Opcodes.ACC_STATIC) == 0 ? 1 : 0); for (int i = 0; i < arg; i++) { index += argumentTypes[i].getSize(); } return index; } /** * Generates the instruction to push a local variable on the stack. * * @param type the type of the local variable to be loaded. * @param index an index in the frame's local variables array. */ private void loadInsn (final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index); } /** * Generates the instruction to store the top stack value in a local * variable. * * @param type the type of the local variable to be stored. * @param index an index in the frame's local variables array. */ private void storeInsn (final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), index); } /** * Generates the instruction to load 'this' on the stack. */ public void loadThis () { if ((access & Opcodes.ACC_STATIC) != 0) { throw new IllegalStateException("no 'this' pointer within static method"); } mv.visitVarInsn(Opcodes.ALOAD, 0); } /** * Generates the instruction to load the given method argument on the stack. * * @param arg the index of a method argument. */ public void loadArg (final int arg) { loadInsn(argumentTypes[arg], getArgIndex(arg)); } /** * Generates the instructions to load the given method arguments on the * stack. * * @param arg the index of the first method argument to be loaded. * @param count the number of method arguments to be loaded. */ public void loadArgs (final int arg, final int count) { int index = getArgIndex(arg); for (int i = 0; i < count; ++i) { Type t = argumentTypes[arg + i]; loadInsn(t, index); index += t.getSize(); } } /** * Generates the instructions to load all the method arguments on the stack. */ public void loadArgs () { loadArgs(0, argumentTypes.length); } /** * Generates the instructions to load all the method arguments on the stack, * as a single object array. */ public void loadArgArray () { push(argumentTypes.length); newArray(OBJECT_TYPE); for (int i = 0; i < argumentTypes.length; i++) { dup(); push(i); loadArg(i); box(argumentTypes[i]); arrayStore(OBJECT_TYPE); } } /** * Generates the instruction to store the top stack value in the given method * argument. * * @param arg the index of a method argument. */ public void storeArg (final int arg) { storeInsn(argumentTypes[arg], getArgIndex(arg)); } // Instructions to load and store local variables /** * Creates a new local variable of the given type. * * @param type the type of the local variable to be created. * @return the identifier of the newly created local variable. */ public int newLocal (final Type type) { localTypes.add(type); return super.newLocal(type.getSize()) - firstLocal; } /** * Returns the type of the given local variable. * * @param local a local variable identifier, as returned by {@link #newLocal * newLocal}. * @return the type of the given local variable. */ public Type getLocalType (final int local) { return (Type)localTypes.get(local); } /** * Returns the index of the given local variable. * * @param local a local variable identifier, as returned by {@link #newLocal * newLocal}. * @return the index of the given local variable in the frame's variables * array. */ public int getLocalIndex (final int local) { int index = firstLocal; for (int i = 0; i < local; ++i) { index += getLocalType(local).getSize(); } return index; } /** * Generates the instruction to load the given local variable on the stack. * * @param local a local variable identifier, as returned by {@link #newLocal * newLocal}. */ public void loadLocal (final int local) { loadInsn(getLocalType(local), getLocalIndex(local)); } /** * Generates the instruction to store the top stack value in the given local * variable. * * @param local a local variable identifier, as returned by {@link #newLocal * newLocal}. */ public void storeLocal (final int local) { storeInsn(getLocalType(local), getLocalIndex(local)); } /** * Generates the instruction to load an element from an array. * * @param type the type of the array element to be loaded. */ public void arrayLoad (final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IALOAD)); } /** * Generates the instruction to store an element in an array. * * @param type the type of the array element to be stored. */ public void arrayStore (final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IASTORE)); } // Instructions to manage the stack /** * Generates a POP instruction. */ public void pop () { mv.visitInsn(Opcodes.POP); } /** * Generates a POP2 instruction. */ public void pop2 () { mv.visitInsn(Opcodes.POP2); } /** * Generates a DUP instruction. */ public void dup () { mv.visitInsn(Opcodes.DUP); } /** * Generates a DUP2 instruction. */ public void dup2 () { mv.visitInsn(Opcodes.DUP2); } /** * Generates a DUP_X1 instruction. */ public void dupX1 () { mv.visitInsn(Opcodes.DUP_X1); } /** * Generates a DUP_X2 instruction. */ public void dupX2 () { mv.visitInsn(Opcodes.DUP_X2); } /** * Generates a DUP2_X1 instruction. */ public void dup2X1 () { mv.visitInsn(Opcodes.DUP2_X1); } /** * Generates a DUP2_X2 instruction. */ public void dup2X2 () { mv.visitInsn(Opcodes.DUP2_X2); } /** * Generates a SWAP instruction. */ public void swap () { mv.visitInsn(Opcodes.SWAP); } /** * Generates the instructions to swap the top two stack values. * * @param prev type of the top - 1 stack value. * @param type type of the top stack value. */ public void swap (final Type prev, final Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dupX1(), pop(); } else { dupX2(); pop(); } } else { if (prev.getSize() == 1) { dup2X1(); pop2(); } else { dup2X2(); pop2(); } } } // Instructions to do mathematical and logical operations /** * Generates the instruction to do the specified mathematical or logical * operation. * * @param op a mathematical or logical operation. Must be one of ADD, SUB, * MUL, DIV, REM, NEG, SHL, SHR, USHR, AND, OR, XOR. * @param type the type of the operand(s) for this operation. */ public void math (final int op, final Type type) { mv.visitInsn(type.getOpcode(op)); } /** * Generates the instructions to compute the bitwise negation of the top * stack value. */ public void not () { mv.visitInsn(Opcodes.ICONST_1); mv.visitInsn(Opcodes.IXOR); } /** * Generates the instruction to increment the given local variable. * * @param local the local variable to be incremented. * @param amount the amount by which the local variable must be incremented. */ public void iinc (final int local, final int amount) { mv.visitIincInsn(getLocalIndex(local), amount); } /** * Generates the instructions to cast a numerical value from one type to * another. * * @param from the type of the top stack value * @param to the type into which this value must be cast. */ public void cast (final Type from, final Type to) { if (from != to) { if (from == Type.DOUBLE_TYPE) { if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.D2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.D2L); } else { mv.visitInsn(Opcodes.D2I); cast(Type.INT_TYPE, to); } } else if (from == Type.FLOAT_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.F2D); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.F2L); } else { mv.visitInsn(Opcodes.F2I); cast(Type.INT_TYPE, to); } } else if (from == Type.LONG_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.L2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.L2F); } else { mv.visitInsn(Opcodes.L2I); cast(Type.INT_TYPE, to); } } else { if (to == Type.BYTE_TYPE) { mv.visitInsn(Opcodes.I2B); } else if (to == Type.CHAR_TYPE) { mv.visitInsn(Opcodes.I2C); } else if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.I2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.I2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.I2L); } else if (to == Type.SHORT_TYPE) { mv.visitInsn(Opcodes.I2S); } } } } // Instructions to do boxing and unboxing operations /** * Generates the instructions to box the top stack value. This value is * replaced by its boxed equivalent on top of the stack. * * @param type the type of the top stack value. */ public void box (final Type type) { if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return; } if (type == Type.VOID_TYPE) { push((String)null); } else { Type boxed = type; switch (type.getSort()) { case Type.BYTE: boxed = BYTE_TYPE; break; case Type.BOOLEAN: boxed = BOOLEAN_TYPE; break; case Type.SHORT: boxed = SHORT_TYPE; break; case Type.CHAR: boxed = CHARACTER_TYPE; break; case Type.INT: boxed = INTEGER_TYPE; break; case Type.FLOAT: boxed = FLOAT_TYPE; break; case Type.LONG: boxed = LONG_TYPE; break; case Type.DOUBLE: boxed = DOUBLE_TYPE; break; } newInstance(boxed); if (type.getSize() == 2) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dupX2(); dupX2(); pop(); } else { // p -> po -> opo -> oop -> o dupX1(); swap(); } invokeConstructor( boxed, new Method("<init>", Type.VOID_TYPE, new Type[] { type })); } } /** * Generates the instructions to unbox the top stack value. This value is * replaced by its unboxed equivalent on top of the stack. * * @param type the type of the top stack value. */ public void unbox (final Type type) { Type t = NUMBER_TYPE; Method sig = null; switch (type.getSort()) { case Type.VOID: return; case Type.CHAR: t = CHARACTER_TYPE; sig = CHAR_VALUE; break; case Type.BOOLEAN: t = BOOLEAN_TYPE; sig = BOOLEAN_VALUE; break; case Type.DOUBLE: sig = DOUBLE_VALUE; break; case Type.FLOAT: sig = FLOAT_VALUE; break; case Type.LONG: sig = LONG_VALUE; break; case Type.INT: case Type.SHORT: case Type.BYTE: sig = INT_VALUE; } if (sig == null) { checkCast(type); } else { checkCast(t); invokeVirtual(t, sig); } } // Instructions to jump to other instructions /** * Creates a new {@link Label}. * * @return a new {@link Label}. */ public Label newLabel () { return new Label(); } /** * Marks the current code position with the given label. * * @param label a label. */ public void mark (final Label label) { mv.visitLabel(label); } /** * Marks the current code position with a new label. * * @return the label that was created to mark the current code position. */ public Label mark () { Label label = new Label(); mv.visitLabel(label); return label; } /** * Generates the instructions to jump to a label based on the comparison of * the top two stack values. * * @param type the type of the top two stack values. * @param mode how these values must be compared. * One of EQ, NE, LT, GE, GT, LE. * @param label where to jump if the comparison result is <tt>true</tt>. */ public void ifCmp (final Type type, final int mode, final Label label) { int intOp = -1; int jumpMode = mode; switch (mode) { case GE: jumpMode = LT; break; case LE: jumpMode = GT; break; } switch (type.getSort()) { case Type.LONG: mv.visitInsn(Opcodes.LCMP); break; case Type.DOUBLE: mv.visitInsn(Opcodes.DCMPG); break; case Type.FLOAT: mv.visitInsn(Opcodes.FCMPG); break; case Type.ARRAY: case Type.OBJECT: switch (mode) { case EQ: mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label); return; case NE: mv.visitJumpInsn(Opcodes.IF_ACMPNE, label); return; } throw new IllegalArgumentException("Bad comparison for type " + type); default: switch (mode) { case EQ: intOp = Opcodes.IF_ICMPEQ; break; case NE: intOp = Opcodes.IF_ICMPNE; break; case GE: swap(); /* fall through */ case LT: intOp = Opcodes.IF_ICMPLT; break; case LE: swap(); /* fall through */ case GT: intOp = Opcodes.IF_ICMPGT; break; } mv.visitJumpInsn(intOp, label); return; } mv.visitJumpInsn(jumpMode, label); } /** * Generates the instructions to jump to a label based on the comparison of * the top two integer stack values. * * @param mode how these values must be compared. * One of EQ, NE, LT, GE, GT, LE. * @param label where to jump if the comparison result is <tt>true</tt>. */ public void ifICmp (final int mode, final Label label) { ifCmp(Type.INT_TYPE, mode, label); } /** * Generates the instruction to jump to the given label if the top stack * value is null. * * @param label where to jump if the condition is <tt>true</tt>. */ public void ifNull (final Label label) { mv.visitJumpInsn(Opcodes.IFNULL, label); } /** * Generates the instruction to jump to the given label if the top stack * value is not null. * * @param label where to jump if the condition is <tt>true</tt>. */ public void ifNonNull (final Label label) { mv.visitJumpInsn(Opcodes.IFNONNULL, label); } /** * Generates the instruction to jump to the given label. * * @param label where to jump if the condition is <tt>true</tt>. */ public void goTo (final Label label) { mv.visitJumpInsn(Opcodes.GOTO, label); } /** * Generates the instructions for a switch statement. * * @param keys the switch case keys. * @param generator a generator to generate the code for the switch cases. */ public void tableSwitch ( final int[] keys, final TableSwitchGenerator generator) { float density; if (keys.length == 0) { density = 0; } else { density = (float)keys.length / (keys[keys.length - 1] - keys[0] + 1); } tableSwitch(keys, generator, density >= 0.5f); } /** * Generates the instructions for a switch statement. * * @param keys the switch case keys. * @param generator a generator to generate the code for the switch cases. * @param useTable <tt>true</tt> to use a TABLESWITCH instruction, or * <tt>false</tt> to use a LOOKUPSWITCH instruction. */ public void tableSwitch ( final int[] keys, final TableSwitchGenerator generator, final boolean useTable) { for (int i = 1; i < keys.length; ++i) { if (keys[i] < keys[i - 1]) { throw new IllegalArgumentException("keys must be sorted ascending"); } } Label def = newLabel(); Label end = newLabel(); if (keys.length > 0) { int len = keys.length; int min = keys[0]; int max = keys[len - 1]; int range = max - min + 1; if (useTable) { Label[] labels = new Label[range]; Arrays.fill(labels, def); for (int i = 0; i < len; ++i) { labels[keys[i] - min] = newLabel(); } mv.visitTableSwitchInsn(min, max, def, labels); for (int i = 0; i < range; ++i) { Label label = labels[i]; if (label != def) { mark(label); generator.generateCase(i + min, end); } } } else { Label[] labels = new Label[len]; for (int i = 0; i < len; ++i) { labels[i] = newLabel(); } mv.visitLookupSwitchInsn(def, keys, labels); for (int i = 0; i < len; ++i) { mark(labels[i]); generator.generateCase(keys[i], end); } } } mark(def); generator.generateDefault(); mark(end); } /** * Generates the instruction to return the top stack value to the caller. */ public void returnValue () { mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); } // Instructions to load and store fields /** * Generates a get field or set field instruction. * * @param opcode the instruction's opcode. * @param ownerType the class in which the field is defined. * @param name the name of the field. * @param fieldType the type of the field. */ private void fieldInsn ( final int opcode, final Type ownerType, final String name, final Type fieldType) { mv.visitFieldInsn( opcode, ownerType.getInternalName(), name, fieldType.getDescriptor()); } /** * Generates the instruction to push the value of a static field on the * stack. * * @param owner the class in which the field is defined. * @param name the name of the field. * @param type the type of the field. */ public void getStatic (final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETSTATIC, owner, name, type); } /** * Generates the instruction to store the top stack value in a static field. * * @param owner the class in which the field is defined. * @param name the name of the field. * @param type the type of the field. */ public void putStatic (final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTSTATIC, owner, name, type); } /** * Generates the instruction to push the value of a non static field on the * stack. * * @param owner the class in which the field is defined. * @param name the name of the field. * @param type the type of the field. */ public void getField (final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETFIELD, owner, name, type); } /** * Generates the instruction to store the top stack value in a non static * field. * * @param owner the class in which the field is defined. * @param name the name of the field. * @param type the type of the field. */ public void putField (final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTFIELD, owner, name, type); } // Instructions to invoke methods /** * Generates an invoke method instruction. * * @param opcode the instruction's opcode. * @param type the class in which the method is defined. * @param method the method to be invoked. */ private void invokeInsn ( final int opcode, final Type type, final Method method) { mv.visitMethodInsn( opcode, type.getInternalName(), method.getName(), method.getDescriptor()); } /** * Generates the instruction to invoke a normal method. * * @param owner the class in which the method is defined. * @param method the method to be invoked. */ public void invokeVirtual (final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEVIRTUAL, owner, method); } /** * Generates the instruction to invoke a constructor. * * @param type the class in which the constructor is defined. * @param method the constructor to be invoked. */ public void invokeConstructor (final Type type, final Method method) { invokeInsn(Opcodes.INVOKESPECIAL, type, method); } /** * Generates the instruction to invoke a static method. * * @param owner the class in which the method is defined. * @param method the method to be invoked. */ public void invokeStatic (final Type owner, final Method method) { invokeInsn(Opcodes.INVOKESTATIC, owner, method); } /** * Generates the instruction to invoke an interface method. * * @param owner the class in which the method is defined. * @param method the method to be invoked. */ public void invokeInterface (final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEINTERFACE, owner, method); } // Instructions to create objects and arrays /** * Generates a type dependent instruction. * * @param opcode the instruction's opcode. * @param type the instruction's operand. */ private void typeInsn (final int opcode, final Type type) { String desc; if (type.getSort() == Type.ARRAY) { desc = type.getDescriptor(); } else { desc = type.getInternalName(); } mv.visitTypeInsn(opcode, desc); } /** * Generates the instruction to create a new object. * * @param type the class of the object to be created. */ public void newInstance (final Type type) { typeInsn(Opcodes.NEW, type); } /** * Generates the instruction to create a new array. * * @param type the type of the array elements. */ public void newArray (final Type type) { int typ; switch (type.getSort()) { case Type.BOOLEAN: typ = Opcodes.T_BOOLEAN; break; case Type.CHAR: typ = Opcodes.T_CHAR; break; case Type.BYTE: typ = Opcodes.T_BYTE; break; case Type.SHORT: typ = Opcodes.T_SHORT; break; case Type.INT: typ = Opcodes.T_INT; break; case Type.FLOAT: typ = Opcodes.T_FLOAT; break; case Type.LONG: typ = Opcodes.T_LONG; break; case Type.DOUBLE: typ = Opcodes.T_DOUBLE; break; default: typeInsn(Opcodes.ANEWARRAY, type); return; } mv.visitIntInsn(Opcodes.NEWARRAY, typ); } // Miscelaneous instructions /** * Generates the instruction to compute the length of an array. */ public void arrayLength () { mv.visitInsn(Opcodes.ARRAYLENGTH); } /** * Generates the instruction to throw an exception. */ public void throwException () { mv.visitInsn(Opcodes.ATHROW); } /** * Generates the instructions to create and throw an exception. The exception * class must have a constructor with a single String argument. * * @param type the class of the exception to be thrown. * @param msg the detailed message of the exception. */ public void throwException (final Type type, final String msg) { newInstance(type); dup(); push(msg); invokeConstructor(type, Method.getMethod("void <init> (String)")); throwException(); } /** * Generates the instruction to check that the top stack value is of the * given type. * * @param type a class or interface type. */ public void checkCast (final Type type) { if (!type.equals(OBJECT_TYPE)) { typeInsn(Opcodes.CHECKCAST, type); } } /** * Generates the instruction to test if the top stack value is of the * given type. * * @param type a class or interface type. */ public void instanceOf (final Type type) { typeInsn(Opcodes.INSTANCEOF, type); } /** * Generates the instruction to get the monitor of the top stack value. */ public void monitorEnter () { mv.visitInsn(Opcodes.MONITORENTER); } /** * Generates the instruction to release the monitor of the top stack value. */ public void monitorExit () { mv.visitInsn(Opcodes.MONITOREXIT); } // Non instructions /** * Marks the end of the visited method. */ public void endMethod () { if ((access & Opcodes.ACC_ABSTRACT) == 0) { mv.visitMaxs(0, 0); } } /** * Marks the start of an exception handler. * * @param start beginning of the exception handler's scope (inclusive). * @param end end of the exception handler's scope (exclusive). * @param exception internal name of the type of exceptions handled by the * handler. */ public void catchException ( final Label start, final Label end, final Type exception) { mv.visitTryCatchBlock(start, end, mark(), exception.getInternalName()); } }
package game.geography.geography; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; public class MapTest { LandName landName = new LandName("Stormland"); @Test public void should_find_land() { Map map = new Map(); Land stormland = map.lookup(landName); assertThat(stormland.named(), is(landName)); } @Test @Ignore("we would like to write test that does not expose inner state like name") public void should_return_land_consistently() { Map map = new Map(); Land stormland1 = map.lookup(landName); Land stormland2 = map.lookup(landName); Land rainland = map.lookup(new LandName("Rainland")); assertThat(stormland1, is(stormland2)); assertThat(stormland1, is(not(rainland))); } @Test public void should_persist_changes_in_land_ownership() { Map map = new Map(); map.landOwnerHasChanged(landName, new OwnerName("Chief Maly")); Land stormland = map.lookup(landName); assertThat(stormland.ownedBy().named(), is(new OwnerName("Chief Maly"))); } }
package gvs.access; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import org.dom4j.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; /** * This class is the endpoint for each incoming connection. * * The class handles protocol commands and stores the incoming data in a xml * file. * * @author mwieland */ public class ClientConnection extends Thread { private final Socket socketClient; private final ConnectionMonitor monitor; private final ModelBuilder modelBuilder; private final XmlReader xmlReader; // protocol messages private static final String OK = "OK"; private static final String FAILED = "FAILED"; private static final String DEFAULT_FILE_NAME = "input.xml"; private static final String THREAD_NAME = "Client Connection Thread"; private static final Logger logger = LoggerFactory .getLogger(ClientConnection.class); /** * Default constructor. * * @param client * incoming client connection. * @param modelBuilder * modelbuilder which processes the parsed xml. * @param monitor * monitor to reserve the GVS service * @param xmlReaderFactory * xml reader used to read the created xml */ @Inject public ClientConnection(ConnectionMonitor monitor, ModelBuilder modelBuilder, XmlReaderFactory xmlReaderFactory, @Assisted Socket client) { super(THREAD_NAME); this.modelBuilder = modelBuilder; this.socketClient = client; this.monitor = monitor; this.xmlReader = xmlReaderFactory.create(DEFAULT_FILE_NAME); } /** * Read the incoming protocol messages and interpret them. Try to get the * monitor lock of {@link ConnectionMonitor} If successful, read the * transfered data and store it locally in a XML file. */ @Override public void run() { clearInputFile(); processInputStream(); if (monitor.isReserved()) { readAndTransformModel(); } releaseService(); } private void clearInputFile() { File file = new File(DEFAULT_FILE_NAME); if (file.exists()) { file.delete(); } } /** * Read the input line by line. * */ private void processInputStream() { try (BufferedReader inputReader = new BufferedReader( new InputStreamReader(socketClient.getInputStream()))) { String line = null; while ((line = inputReader.readLine()) != null) { int endCharIndex = line.indexOf(ProtocolCommand.DATA_END.toString()); if (endCharIndex != -1) { String finalLine = line.substring(0, endCharIndex); processLine(finalLine); break; } else { processLine(line); } } } catch (IOException e) { logger.error("Unable to read incoming message of client {}", socketClient.getInetAddress(), e); } } /** * Case distinctions for the input * * @param line * incoming line * * @throws IOException * I/O error */ private void processLine(String line) throws IOException { if (line.equals(ProtocolCommand.RESERVE_GVS.toString())) { logger.info("Reserve command detected."); reserveService(); } else if (line.equals(ProtocolCommand.RELEASE_GVS.toString())) { logger.info("Release command detected."); releaseService(); } else { logger.info("Data detected"); storeDataOnFilesystem(line); } } /** * Try to get the monitor lock and send status message back to the client. * * @throws IOException * I/O error occurred when creating the output stream */ private void reserveService() throws IOException { String remoteHost = socketClient.getRemoteSocketAddress().toString(); try { monitor.reserveService(remoteHost); logger.info("Service reserved."); sendMessage(OK); } catch (InterruptedException e) { logger.info("Service busy."); sendMessage(FAILED); } } /** * Release monitor lock. */ private void releaseService() { String remoteHost = socketClient.getRemoteSocketAddress().toString(); monitor.releaseService(remoteHost); } /** * Send a message to the connected client * * @param message * hard coded message * * @throws IOException * I/O error occurred when creating the output stream */ private void sendMessage(String message) throws IOException { PrintStream outStream = new PrintStream(socketClient.getOutputStream(), true); outStream.println(message); } /** * Store the incoming data locally. * * @param line * data line * @throws IOException * io exception */ private void storeDataOnFilesystem(String line) throws IOException { Path path = Paths.get(DEFAULT_FILE_NAME); try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { writer.append(line); writer.flush(); } } /** * Read the just written xml file and transform to graph model. */ private void readAndTransformModel() { logger.info("Build model from parsed xml"); Document document = xmlReader.read(); logger.error("BUILD MODEL {}", getId()); modelBuilder.buildModelFromXML(document); } }
package fi.guagua.pixrayandroid; import android.app.Activity; import android.app.DialogFragment; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import java.util.ArrayList; public class ChooseNewScoreDialog extends DialogFragment{ private static final String TAG = "ChooseNewScoreDialog"; private RadioGroup mRadioGroup; private ArrayList<Integer> mIds; private ArrayList<String> mNames; private ArrayList<String> mColors; protected OnScoreSelectedListener mListener; public ChooseNewScoreDialog() { // Empty constructor required for DialogFragment } public static ChooseNewScoreDialog newInstance(ScoreTypes scoreTypes) { ChooseNewScoreDialog frag = new ChooseNewScoreDialog(); Bundle args = new Bundle(); args.putSerializable(Pixray.EXTRA_SCORE_TYPES, scoreTypes); //args.putInt(Pixray.EXTRA_CURRENT_SCORE, scoreId); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_choose_new_score, container); getDialog().setTitle(R.string.choose_score_below); ScoreTypes st = (ScoreTypes) getArguments().getSerializable(Pixray.EXTRA_SCORE_TYPES); mIds = st.getIds(); mNames = st.getNames(); mColors = st.getColors(); // create scoring radio buttons programmatically mRadioGroup = (RadioGroup) view.findViewById(R.id.scoringChoices); for (int i = 0; i < mIds.size(); i++) { RadioButton newRadioButton = new RadioButton(getActivity()); newRadioButton.setText(mNames.get(i)); newRadioButton.setId(mIds.get(i)); newRadioButton.setBackgroundColor(Color.parseColor(mColors.get(i))); newRadioButton.setWidth(350); //newRadioButton.setLayoutParams(); LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); mRadioGroup.addView(newRadioButton, 0, layoutParams); } final Button submitButton = (Button) view.findViewById(R.id.chooseScoreConfirm); submitButton.setEnabled(false); // can't submit before a score is selected mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { submitButton.setEnabled(true); } }); Button cancelButton = (Button) view.findViewById(R.id.chooseScoreCancel); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); // dismiss the dialog } }); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); // dismiss the dialog int scoreId = mRadioGroup.getCheckedRadioButtonId(); // chosen score // transmit data through interface if (mListener != null) { mListener.onNewScoreSelected(scoreId); } } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnScoreSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnScoreSelectedListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnScoreSelectedListener { void onNewScoreSelected(int scoreId); } }
package org.opencms.search.solr; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.types.CmsResourceTypeBinary; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.json.JSONObject; import org.opencms.main.OpenCms; import org.opencms.report.CmsShellReport; import org.opencms.search.CmsSearchException; import org.opencms.search.CmsSearchResource; import org.opencms.search.documents.CmsDocumentDependency; import org.opencms.search.fields.CmsSearchField; import org.opencms.security.CmsRoleViolationException; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import org.opencms.util.CmsRequestUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrInputDocument; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests the Solr field mapping.<p> * * @since 8.5.0 */ public class TestSolrFieldConfiguration extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestSolrFieldConfiguration(String arg0) { super(arg0); } /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestSolrFieldConfiguration.class.getName()); suite.addTest(new TestSolrFieldConfiguration("testAppinfoSolrField")); suite.addTest(new TestSolrFieldConfiguration("testContentLocalesField")); suite.addTest(new TestSolrFieldConfiguration("testDependencies")); suite.addTest(new TestSolrFieldConfiguration("testLanguageDetection")); suite.addTest(new TestSolrFieldConfiguration("testLocaleDependenciesField")); suite.addTest(new TestSolrFieldConfiguration("testLuceneMigration")); suite.addTest(new TestSolrFieldConfiguration("testOfflineIndexAccess")); // this test case must be the last one suite.addTest(new TestSolrFieldConfiguration("testIngnoreMaxRows")); TestSetup wrapper = new TestSetup(suite) { @Override protected void setUp() { setupOpenCms("solrtest", "/", "/../org/opencms/search/solr"); } @Override protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Tests the Solr field configuration that can be done in the XSD of an XML content.<p> * * '@see /sites/default/xmlcontent/article.xsd' * * @throws Throwable if something goes wrong */ public void testAppinfoSolrField() throws Throwable { CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrQuery squery = new CmsSolrQuery( null, CmsRequestUtil.createParameterMap("q=path:\"/sites/default/xmlcontent/article_0001.html\"")); CmsSolrResultList results = index.search(getCmsObject(), squery); // RESULT TEST // // Test the result count AllTests.printResults(getCmsObject(), results, false); assertEquals(1, results.size()); // Test if the result contains the expected resource CmsSearchResource res = results.get(0); assertEquals("/sites/default/xmlcontent/article_0001.html", res.getRootPath()); // FIELD TEST // // Test multiple language field String fieldValue = res.getField("ahtml_en"); assertNotNull(fieldValue); fieldValue = res.getField("ahtml_de"); assertNotNull(fieldValue); // Test the contents of the copy fields fieldValue = res.getField("test_text_de"); assertTrue(fieldValue.contains("Alkacon Software German")); fieldValue = res.getField("test_text_en"); assertTrue(fieldValue.contains("Alkacon Software German")); fieldValue = res.getField("explicit_title"); assertTrue(fieldValue.contains("Sample article 1 (>>SearchEgg1<<)")); // Test locale restricted field fieldValue = res.getField("aauthor_de"); assertTrue(fieldValue.equals("Alkacon Software German")); fieldValue = res.getField("aauthor_en"); assertNull(fieldValue); // Test source field Date dateValue = res.getDateField("arelease_en_dt"); assertTrue("1308210520000".equals(new Long(dateValue.getTime()).toString())); dateValue = res.getDateField("arelease_de_dt"); assertTrue("1308210420000".equals(new Long(dateValue.getTime()).toString())); // test 'default' value for the whole field fieldValue = res.getField("ahomepage_de"); assertTrue(fieldValue.equals("Homepage n.a.")); fieldValue = res.getField("ahomepage_en"); assertTrue(fieldValue.contains("/sites/default/index.html")); // Test the boost to have a complete set of test cases // the boost for a field can only be set for "SolrInputDocument"s // fields of documents that are returned as query result "SolrDocument"s // never have a boost float boost = ((SolrInputDocument)res.getDocument().getDocument()).getField("ahtml_en").getBoost(); assertTrue(1.0F == boost); // MAPPING TEST // fieldValue = res.getField("Description_de"); assertEquals(fieldValue, "My Special OpenCms Solr Description"); // test the 'content' mapping fieldValue = res.getField("ateaser_en"); assertTrue(fieldValue.contains("OpenCms Alkacon This is the article 1 text")); // test the 'item' mapping with default fieldValue = res.getField("ateaser_en"); assertTrue(fieldValue.contains("/sites/default/index.html")); fieldValue = res.getField("ateaser_de"); assertTrue(fieldValue.contains("Homepage n.a.")); // test the property mapping fieldValue = res.getField("atitle_en"); assertTrue(fieldValue.contains("Alkacon Software English")); fieldValue = res.getField("atitle_de"); // properties are not localized assertEquals(false, fieldValue.contains("Alkacon Software German")); assertTrue(fieldValue.contains("Alkacon Software English")); // but the title item value is localized assertTrue(fieldValue.contains(">>GermanSearchEgg1<<")); // test the 'property-search' mapping fieldValue = res.getField("ateaser_en"); assertTrue(fieldValue.contains("Cologne is a nice city")); // test the 'attribute' mapping fieldValue = res.getField("ateaser_en"); // This is NOT the Lucene optimized String representation of the date. // For Solr just the milliseconds are stored to allow mapping to date fields. assertTrue(fieldValue.contains("1308210520000")); // test the 'dynamic' mapping with 'class' attribute fieldValue = res.getField("ateaser_en"); assertTrue(fieldValue.contains("This is an amazing and very 'dynamic' content")); squery = new CmsSolrQuery( null, CmsRequestUtil.createParameterMap("q=path:\"/sites/default/xmlcontent/article_0002.html\"")); results = index.search(getCmsObject(), squery); res = results.get(0); assertEquals("/sites/default/xmlcontent/article_0002.html", res.getRootPath()); assertTrue(res.getMultivaluedField("ateaser2_en_txt").contains("This is teaser 2 in sample article 2.")); // test multi nested elements List<String> teaser = res.getMultivaluedField("mteaser"); assertTrue( teaser.contains("This is the sample article number 2. This is just a demo teaser. (>>SearchEgg2<<)")); assertTrue(teaser.contains("This is teaser 2 in sample article 2.")); squery = new CmsSolrQuery( null, CmsRequestUtil.createParameterMap("q=path:\"/sites/default/flower/flower-0001.html\"")); results = index.search(getCmsObject(), squery); assertEquals(1, results.size()); res = results.get(0); assertEquals("/sites/default/flower/flower-0001.html", res.getRootPath()); List<String> desc = res.getMultivaluedField("desc_en"); assertEquals(3, desc.size()); assertTrue(desc.contains("This is the first paragraph of the test flower.")); assertTrue(desc.contains("This is the second paragraph of the test flower.")); assertTrue(desc.contains("This is the third paragraph of the test flower.")); desc = res.getMultivaluedField("desc_de"); assertEquals(2, desc.size()); assertTrue(desc.contains("Dies ist der erste Absatz der neuen Testblume ...")); assertTrue(desc.contains("Dies ist der sweite Absatz der neuen Testblume ...")); desc = res.getMultivaluedField("mteaser"); assertTrue(desc.contains("First ocurence of a nested content")); assertTrue(desc.contains("Second ocurence of a nested content")); assertTrue(desc.contains("Third ocurence of a nested content")); } /** * Tests the locales stored in the index.<p> * * @throws Throwable if something goes wrong */ public void testContentLocalesField() throws Throwable { Map<String, List<String>> filenames = new HashMap<String, List<String>>(); List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(); List<String> defaultLocalesString = new ArrayList<String>(defaultLocales.size()); for (Locale l : defaultLocales) { defaultLocalesString.add(l.toString()); } filenames.put("rabbit_en_GB.html", Collections.singletonList("en_GB")); filenames.put("rabbit_en_GB", Collections.singletonList("en_GB")); filenames.put("rabbit_en.html", Collections.singletonList("en")); filenames.put("rabbit_en", Collections.singletonList("en")); filenames.put("rabbit_en.", Collections.singletonList("en")); filenames.put("rabbit_enr", defaultLocalesString); filenames.put("rabbit_en.tar.gz", defaultLocalesString); //shouldn't this work differently? filenames.put("rabbit_de_en_GB.html", Collections.singletonList("en_GB")); filenames.put("rabbit_de_DE_EN_DE_en.html", Collections.singletonList("en")); filenames.put("rabbit_de_DE_EN_en_DE.html", Collections.singletonList("en_DE")); // create test folder String folderName = "/filenameTest/"; CmsObject cms = getCmsObject(); CmsResource folder = cms.createResource(folderName, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, null); cms.unlockResource(folderName); for (String filename : filenames.keySet()) { // create master resource importTestResource( cms, "org/opencms/search/pdf-test-112.pdf", folderName + filename, CmsResourceTypeBinary.getStaticTypeId(), Collections.<CmsProperty> emptyList()); } // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrQuery query = new CmsSolrQuery(); query.setSearchRoots(cms.getRequestContext().addSiteRoot(folderName)); CmsSolrResultList results = index.search(cms, query); AllTests.printResults(cms, results, false); assertEquals(10, results.getNumFound()); for (Map.Entry<String, List<String>> filename : filenames.entrySet()) { String absoluteFileName = cms.getRequestContext().addSiteRoot(folderName + filename.getKey()); SolrQuery squery = new CmsSolrQuery(); squery.addFilterQuery("path:\"" + absoluteFileName + "\""); results = index.search(cms, squery); assertEquals(1, results.size()); CmsSearchResource res = results.get(0); List<String> fieldLocales = res.getMultivaluedField(CmsSearchField.FIELD_CONTENT_LOCALES); assertTrue(fieldLocales.size() == filename.getValue().size()); assertTrue(fieldLocales.containsAll(filename.getValue())); assertTrue(filename.getValue().containsAll(fieldLocales)); } CmsProperty localesAvailable = new CmsProperty("locale-available", "en", null); for (String filename : filenames.keySet()) { String resourceName = folderName + filename; cms.lockResource(resourceName); cms.writePropertyObjects(resourceName, Collections.singletonList(localesAvailable)); cms.unlockResource(resourceName); } // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); for (String filename : filenames.keySet()) { String absoluteFileName = cms.getRequestContext().addSiteRoot(folderName + filename); SolrQuery squery = new CmsSolrQuery(); squery.addFilterQuery("path:\"" + absoluteFileName + "\""); results = index.search(cms, squery); assertEquals(1, results.size()); CmsSearchResource res = results.get(0); List<String> fieldLocales = res.getMultivaluedField(CmsSearchField.FIELD_CONTENT_LOCALES); assertTrue(fieldLocales.size() == 1); assertTrue(fieldLocales.contains("en")); } SolrQuery squery = new CmsSolrQuery(); squery.addFilterQuery("path:\"/sites/default/xmlcontent/article_0004.html\""); results = index.search(cms, squery); assertEquals(1, results.size()); CmsSearchResource res = results.get(0); List<String> fieldLocales = res.getMultivaluedField(CmsSearchField.FIELD_CONTENT_LOCALES); assertTrue(fieldLocales.size() == 1); fieldLocales.contains(Collections.singletonList("en")); } /** * * @throws Throwable */ public void testDependencies() throws Throwable { List<String> filenames = new ArrayList<String>(); filenames.add("search_rabbit.pdf"); filenames.add("search_rabbit_vi.pdf"); filenames.add("search_rabbit_pt.pdf"); filenames.add("search_rabbit_fr.pdf"); filenames.add("search_rabbit_fr_001.pdf"); filenames.add("search_rabbit_fr_002.pdf"); // create test folder String folderName = "/testLocaleVariants/"; CmsObject cms = getCmsObject(); cms.createResource(folderName, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, null); cms.unlockResource(folderName); for (String filename : filenames) { importTestResource( cms, "org/opencms/search/pdf-test-112.pdf", folderName + filename, CmsResourceTypeBinary.getStaticTypeId(), Collections.<CmsProperty> emptyList()); } // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrQuery query = new CmsSolrQuery(); query.setSearchRoots(Collections.singletonList(cms.getRequestContext().addSiteRoot(folderName))); CmsSolrResultList results = index.search(cms, query, false); AllTests.printResults(cms, results, false); int count = 0; for (CmsSearchResource res : results) { System.out.println(" System.out.println("DOCUMENT: " + ++count); System.out.println(" System.out.println("TYPE: " + res.getField("dependencyType")); String depField = res.getField("dep_document"); if (depField != null) { System.out.println("DEP_DOC: " + depField); CmsDocumentDependency d = CmsDocumentDependency.fromDependencyString(depField, res.getRootPath()); String depCreated = d.toDependencyString(cms); assertEquals(depField, depCreated); } List<String> variants = res.getMultivaluedField("dep_variant"); if (variants != null) { System.out.println(" System.out.println("VARIANTS"); for (String varField : variants) { System.out.println("DEP_VAR: " + varField); JSONObject varJson = new JSONObject(varField); String path = varJson.getString("path"); CmsDocumentDependency var = CmsDocumentDependency.fromDependencyString(varField, path); String varCreated = var.toDependencyString(cms); assertEquals(varField, varCreated); } } List<String> attachments = res.getMultivaluedField("dep_attachment"); if (attachments != null) { System.out.println(" System.out.println("ATTACHMENTS"); for (String attField : attachments) { System.out.println("DEP_ATT: " + attField); JSONObject attJson = new JSONObject(attField); String path = attJson.getString("path"); CmsDocumentDependency att = CmsDocumentDependency.fromDependencyString(attField, path); String varCreated = att.toDependencyString(cms); assertEquals(attField, varCreated); } } } } /** * @throws Throwable if something goes wrong */ public void testIngnoreMaxRows() throws Throwable { echo("Testing the ignore max rows argument."); String query = "?fq=con_locales:*&fq=parent-folders:*&fl=path&rows=99999"; CmsSolrQuery squery = new CmsSolrQuery(null, CmsRequestUtil.createParameterMap(query)); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrResultList result = index.search(getCmsObject(), squery, true); int found = result.size(); assertTrue( "The number of found documents must be greater than org.opencms.search.solr.CmsSolrIndex.ROWS_MAX", found > CmsSolrIndex.ROWS_MAX); } /** * @throws Throwable */ public void testLanguageDetection() throws Throwable { CmsObject cms = OpenCms.initCmsObject(getCmsObject()); // use a folder that only contains GERMAN content @see manifest.xml -> locale poperty String folderName = "/folder1/subfolder12/subsubfolder121/"; List<CmsProperty> props = new ArrayList<CmsProperty>(); props.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_LOCALE, "de", "de")); CmsResource master = importTestResource( cms, "org/opencms/search/solr/lang-detect-doc.pdf", folderName + "lang-detect-doc.pdf", CmsResourceTypeBinary.getStaticTypeId(), props); // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); // index.setLanguageDetection(true); // is the default configured in opencms-search.xml CmsSolrQuery query = new CmsSolrQuery(cms, null); query.setText("Language Detection Document"); // even if the property is set to German this document should be detected as English // because the language inside the PDF is written in English query.setLocales(Collections.singletonList(Locale.GERMAN)); CmsSolrResultList result = index.search(cms, query); assertTrue(!result.contains(master)); query.setLocales(Collections.singletonList(Locale.ENGLISH)); result = index.search(cms, query); assertTrue(result.contains(master)); // Now test the other way around: German locale-available property with English content // Should be detected as German // This is the OpenCms default behavior: property wins! index.setLanguageDetection(false); props.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_AVAILABLE_LOCALES, "de", "de")); CmsResource master2 = importTestResource( cms, "org/opencms/search/solr/lang-detect-doc.pdf", folderName + "lang-detect-doc2.pdf", CmsResourceTypeBinary.getStaticTypeId(), props); // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); query.setLocales(Collections.singletonList(Locale.GERMAN)); result = index.search(cms, query); assertTrue(result.contains(master2)); query.setLocales(Collections.singletonList(Locale.ENGLISH)); result = index.search(cms, query); assertTrue(!result.contains(master2)); // restore configured value index.setLanguageDetection(true); } /** * * @throws Throwable */ public void testLocaleDependenciesField() throws Throwable { Map<String, List<String>> filenames = new HashMap<String, List<String>>(); filenames.put("search_rabbit.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_de.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_de_001.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_de_002.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_de_003.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_de_004.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_0001.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_0002.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_0003.pdf", Collections.singletonList("de_DE")); filenames.put("search_rabbit_en.pdf", Collections.singletonList("en_EN")); filenames.put("search_rabbit_en_001.pdf", Collections.singletonList("en_EN")); filenames.put("search_rabbit_en_002.pdf", Collections.singletonList("en_EN")); filenames.put("search_rabbit_en_003.pdf", Collections.singletonList("en_EN")); filenames.put("search_rabbit_en_004.pdf", Collections.singletonList("en_EN")); filenames.put("search_rabbit2_0001.pdff", Collections.singletonList("de_DE")); filenames.put("search_rabbit2_0001.pdf", Collections.singletonList("de_DE")); filenames.put("tema_00001.html", Collections.singletonList("de_DE")); filenames.put("ar_00001.xml", Collections.singletonList("de_DE")); // create test folder String folderName = "/filenameTest2/"; CmsObject cms = getCmsObject(); cms.createResource(folderName, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, null); cms.unlockResource(folderName); for (String filename : filenames.keySet()) { // create master resource importTestResource( cms, "org/opencms/search/pdf-test-112.pdf", folderName + filename, CmsResourceTypeBinary.getStaticTypeId(), Collections.<CmsProperty> emptyList()); } // publish the project and update the search index OpenCms.getPublishManager().publishProject(cms, new CmsShellReport(cms.getRequestContext().getLocale())); OpenCms.getPublishManager().waitWhileRunning(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrQuery query = new CmsSolrQuery(); query.setSearchRoots(Collections.singletonList(cms.getRequestContext().addSiteRoot(folderName))); CmsSolrResultList results = index.search(cms, query, false); AllTests.printResults(cms, results, false); // assertEquals(10, results.getNumFound()); for (Map.Entry<String, List<String>> filename : filenames.entrySet()) { String absoluteFileName = cms.getRequestContext().addSiteRoot(folderName + filename.getKey()); SolrQuery squery = new CmsSolrQuery(); squery.addFilterQuery("path:" + absoluteFileName); results = index.search(cms, squery); } } /** * Tests if the field configuration in the 'opencms-search.xml' can also be used for Solr.<p> * * @throws Throwable if something goes wrong */ public void testLuceneMigration() throws Throwable { CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); CmsSolrFieldConfiguration conf = (CmsSolrFieldConfiguration)index.getFieldConfiguration(); assertNotNull(conf.getSolrFields().get("meta")); assertNotNull(conf.getSolrFields().get("description_txt")); assertNotNull(conf.getSolrFields().get("keywords_txt")); assertNotNull(conf.getSolrFields().get("special_txt")); CmsSolrQuery squery = new CmsSolrQuery( null, CmsRequestUtil.createParameterMap("q=path:\"/sites/default/xmlcontent/article_0001.html\"")); CmsSolrResultList results = index.search(getCmsObject(), squery); CmsSearchResource res = results.get(0); String value = "Sample article 1 (>>SearchEgg1<<)"; List<String> metaValue = res.getMultivaluedField("meta"); assertEquals(value, metaValue.get(0)); } /** * Tests the access of Offline indexes.<p> * * @throws Throwable if sth. goes wrong */ public void testOfflineIndexAccess() throws Throwable { echo("Testing offline index access with the guest user."); CmsObject guest = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest()); CmsSolrIndex solrIndex = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_ONLINE); echo("First execute a search on the online index."); solrIndex.search(guest, "q=*:*&rows=0"); echo("OK, search could be executed on the online index."); echo("Now try to execute a search on the Solr Offline index."); solrIndex = OpenCms.getSearchManager().getIndexSolr(AllTests.SOLR_OFFLINE); solrIndex.setEnabled(true); try { solrIndex.search(guest, "q=*:*&rows=0"); } catch (CmsSearchException e) { assertTrue( "The cause must be a CmsRoleViolationException", e.getCause() instanceof CmsRoleViolationException); if (!(e.getCause() instanceof CmsRoleViolationException)) { throw e; } } echo("OK, search could not be executed and the cause was a CmsRoleViolationException."); solrIndex.setEnabled(false); } }
package io.bitsquare.util; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.awt.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URI; import java.util.function.Function; import javafx.animation.AnimationTimer; import javafx.scene.input.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.mightypork.rpack.utils.DesktopApi; /** * General utilities */ public class Utilities { private static final Logger log = LoggerFactory.getLogger(Utilities.class); private static long lastTimeStamp = System.currentTimeMillis(); public static String objectToJson(Object object) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create(); return gson.toJson(object); } public static boolean isWindows() { return getOSName().contains("win"); } public static boolean isOSX() { return getOSName().contains("mac") || getOSName().contains("darwin"); } public static boolean isLinux() { return getOSName().contains("linux"); } private static String getOSName() { return System.getProperty("os.name").toLowerCase(); } public static void copyToClipboard(String content) { if (content != null && content.length() > 0) { Clipboard clipboard = Clipboard.getSystemClipboard(); ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putString(content); clipboard.setContent(clipboardContent); } } public static void openURI(URI uri) throws IOException { if (!isLinux() && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { Desktop.getDesktop().browse(uri); } else { // On Linux Desktop is poorly implemented. if (!DesktopApi.browse(uri)) throw new IOException("Failed to open URI: " + uri.toString()); } } public static void openWebPage(String target) throws Exception { openURI(new URI(target)); } public static <T> T jsonToObject(String jsonString, Class<T> classOfT) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting().create(); return gson.fromJson(jsonString, classOfT); } public static Object deserializeHexStringToObject(String serializedHexString) { Object result = null; try { ByteArrayInputStream byteInputStream = new ByteArrayInputStream(org.bitcoinj.core.Utils.parseAsHexOrBase58(serializedHexString)); try (ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream)) { result = objectInputStream.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { byteInputStream.close(); } } catch (IOException i) { i.printStackTrace(); } return result; } public static String serializeObjectToHexString(Serializable serializable) { String result = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(serializable); result = org.bitcoinj.core.Utils.HEX.encode(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } return result; } private static void printElapsedTime(String msg) { if (!msg.isEmpty()) { msg += " / "; } long timeStamp = System.currentTimeMillis(); log.debug(msg + "Elapsed: " + String.valueOf(timeStamp - lastTimeStamp)); lastTimeStamp = timeStamp; } public static void printElapsedTime() { printElapsedTime(""); } public static Object copy(Serializable orig) { Object obj = null; try { // Write the object out to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); // Make an input stream from the byte array and read // a copy of the object back in. ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return obj; } public static AnimationTimer setTimeout(int delay, Function<AnimationTimer, Void> callback) { AnimationTimer animationTimer = new AnimationTimer() { final long lastTimeStamp = System.currentTimeMillis(); @Override public void handle(long arg0) { if (System.currentTimeMillis() > delay + lastTimeStamp) { callback.apply(this); this.stop(); } } }; animationTimer.start(); return animationTimer; } public static AnimationTimer setInterval(int delay, Function<AnimationTimer, Void> callback) { AnimationTimer animationTimer = new AnimationTimer() { long lastTimeStamp = System.currentTimeMillis(); @Override public void handle(long arg0) { if (System.currentTimeMillis() > delay + lastTimeStamp) { lastTimeStamp = System.currentTimeMillis(); callback.apply(this); } } }; animationTimer.start(); return animationTimer; } }
package io.bxbxbai.zhuanlan.ui.activity; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.Toolbar; import android.view.*; import android.widget.FrameLayout; import android.widget.ListView; import butterknife.ButterKnife; import com.balysv.materialmenu.MaterialMenuDrawable.AnimationState; import com.balysv.materialmenu.MaterialMenuDrawable.IconState; import com.readystatesoftware.systembartint.SystemBarTintManager; import io.bxbxbai.zhuanlan.R; import io.bxbxbai.zhuanlan.ui.DrawerMenuContent; import io.bxbxbai.zhuanlan.ui.OnMenuListClickListener; import io.bxbxbai.zhuanlan.ui.fragment.PeopleListFragment; import io.bxbxbai.zhuanlan.ui.widget.MenuAdapter; import io.bxbxbai.zhuanlan.utils.PrefUtils; import io.bxbxbai.zhuanlan.utils.T; import io.bxbxbai.zhuanlan.utils.ZhuanLanHandler; import java.lang.reflect.Field; import java.lang.reflect.Method; public class MainActivity extends BaseActivity { private DrawerLayout mDrawerLayout; private boolean isDrawerOpened; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDrawerLayout = ButterKnife.findById(this, R.id.drawerLayout); super.initToolBar(); initToolbarAndDrawer(); DrawerMenuContent content = new DrawerMenuContent(this); ListView listView = ButterKnife.findById(this, R.id.drawer_list); listView.setAdapter(new MenuAdapter(this, content.getItems())); listView.setOnItemClickListener(new OnMenuListClickListener(this, mDrawerLayout)); getSupportFragmentManager().beginTransaction().add(R.id.container, PeopleListFragment.instate()).commit(); setOverflowShowAlways(); final ZhuanLanHandler handler = ZhuanLanHandler.get(); handler.postOnWorkThread(new Runnable() { @Override public void run() { if ((boolean) PrefUtils.getValue(MainActivity.this, PrefUtils.KEY_FIRST_ENTER, true)) { handler.postDelay(new Runnable() { @Override public void run() { openDrawer(); } }, 1500); PrefUtils.setValue(MainActivity.this, PrefUtils.KEY_FIRST_ENTER, false); } } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //mDrawerLayoutfitSystemWindowtopMargin SystemBarTintManager.SystemBarConfig config = mTintManager.getConfig(); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mDrawerLayout.getLayoutParams(); params.topMargin = config.getStatusBarHeight(); } } private void initToolbarAndDrawer() { toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: T.showShort("Coming soon..."); return prepareIntent(PrefsActivity.class); // case R.id.action_search: // return PostListActivity.start(MainActivity.this, "limiao"); case R.id.action_about: return WebActivity.start(MainActivity.this, WebActivity.URL_BXBXBAI, "About Me"); } return false; } }); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (materialMenu.getState().equals(IconState.BURGER)) { materialMenu.animatePressedState(IconState.ARROW); openDrawer(); } else { materialMenu.animatePressedState(IconState.BURGER); closeDrawer(); } } }); mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { materialMenu.setTransformationOffset(AnimationState.BURGER_ARROW, isDrawerOpened ? 2 - slideOffset : slideOffset); } @Override public void onDrawerOpened(View drawerView) { isDrawerOpened = true; } @Override public void onDrawerClosed(View drawerView) { isDrawerOpened = false; } @Override public void onDrawerStateChanged(int newState) { } }); materialMenu.setState(IconState.BURGER); } @Override public void onBackPressed() { closeDrawer(); // Otherwise, it may return to the previous fragment stack FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else { // Lastly, it will rely on the system behavior for back super.onBackPressed(); } } public boolean closeDrawer() { // If the drawer is open, back will close it if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.START)) { mDrawerLayout.closeDrawers(); return true; } return false; } private boolean openDrawer() { if (mDrawerLayout != null) { mDrawerLayout.openDrawer(GravityCompat.START); return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_ACTION_BAR && menu != null) { if (menu.getClass().getSimpleName().equals("MenuBuilder")) { try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { } } } return super.onMenuOpened(featureId, menu); } private void setOverflowShowAlways() { ViewConfiguration conf = ViewConfiguration.get(this); try { Field menuKeyField = conf.getClass().getDeclaredField("sHasPermanentMenuKey"); menuKeyField.setAccessible(true); menuKeyField.setBoolean(conf, true); } catch (Exception e) { e.printStackTrace(); } } private boolean prepareIntent(Class clazz) { Intent intent = new Intent(); intent.setClass(MainActivity.this, clazz); startActivity(intent); return true; } public static void start(Activity activity) { activity.startActivity(new Intent(activity, MainActivity.class)); } }
package jadx.core.xmlgen; import jadx.core.codegen.CodeWriter; import jadx.core.xmlgen.entry.EntryConfig; import jadx.core.xmlgen.entry.RawNamedValue; import jadx.core.xmlgen.entry.RawValue; import jadx.core.xmlgen.entry.ResourceEntry; import jadx.core.xmlgen.entry.ValuesParser; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResTableParser extends CommonBinaryParser { private static final Logger LOG = LoggerFactory.getLogger(ResTableParser.class); private static final class PackageChunk { private final int id; private final String name; private final String[] typeStrings; private final String[] keyStrings; private PackageChunk(int id, String name, String[] typeStrings, String[] keyStrings) { this.id = id; this.name = name; this.typeStrings = typeStrings; this.keyStrings = keyStrings; } public int getId() { return id; } public String getName() { return name; } public String[] getTypeStrings() { return typeStrings; } public String[] getKeyStrings() { return keyStrings; } } private String[] strings; private final ResourceStorage resStorage = new ResourceStorage(); public void decode(InputStream inputStream) throws IOException { is = new ParserStream(inputStream); decodeTableChunk(); resStorage.finish(); } public CodeWriter decodeToCodeWriter(InputStream inputStream) throws IOException { decode(inputStream); CodeWriter writer = new CodeWriter(); writer.add("app package: ").add(resStorage.getAppPackage()); writer.startLine(); ValuesParser vp = new ValuesParser(strings, resStorage.getResourcesNames()); for (ResourceEntry ri : resStorage.getResources()) { writer.startLine(ri + ": " + vp.getValueString(ri)); } writer.finish(); return writer; } public ResourceStorage getResStorage() { return resStorage; } void decodeTableChunk() throws IOException { is.checkInt16(RES_TABLE_TYPE, "Not a table chunk"); is.checkInt16(0x000c, "Unexpected table header size"); /*int size = */ is.readInt32(); int pkgCount = is.readInt32(); strings = parseStringPool(); for (int i = 0; i < pkgCount; i++) { parsePackage(); } } private PackageChunk parsePackage() throws IOException { long start = is.getPos(); is.checkInt16(RES_TABLE_PACKAGE_TYPE, "Not a table chunk"); int headerSize = is.readInt16(); if (headerSize != 0x011c && headerSize != 0x0120) { die("Unexpected package header size"); } long size = is.readUInt32(); long endPos = start + size; int id = is.readInt32(); String name = is.readString16Fixed(128); long typeStringsOffset = start + is.readInt32(); /* int lastPublicType = */ is.readInt32(); long keyStringsOffset = start + is.readInt32(); /* int lastPublicKey = */ is.readInt32(); if (headerSize == 0x0120) { /* int typeIdOffset = */ is.readInt32(); } String[] typeStrings = null; if (typeStringsOffset != 0) { is.skipToPos(typeStringsOffset, "Expected typeStrings string pool"); typeStrings = parseStringPool(); } String[] keyStrings = null; if (keyStringsOffset != 0) { is.skipToPos(keyStringsOffset, "Expected keyStrings string pool"); keyStrings = parseStringPool(); } PackageChunk pkg = new PackageChunk(id, name, typeStrings, keyStrings); if (id == 0x7F) { resStorage.setAppPackage(name); } while (is.getPos() < endPos) { long chunkStart = is.getPos(); int type = is.readInt16(); if (type == RES_NULL_TYPE) { continue; } if (type == RES_TABLE_TYPE_SPEC_TYPE) { parseTypeSpecChunk(); } else if (type == RES_TABLE_TYPE_TYPE) { parseTypeChunk(chunkStart, pkg); } } return pkg; } private void parseTypeSpecChunk() throws IOException { is.checkInt16(0x0010, "Unexpected type spec header size"); /*int size = */ is.readInt32(); int id = is.readInt8(); is.skip(3); int entryCount = is.readInt32(); for (int i = 0; i < entryCount; i++) { int entryFlag = is.readInt32(); } } private void parseTypeChunk(long start, PackageChunk pkg) throws IOException { /*int headerSize = */ is.readInt16(); /*int size = */ is.readInt32(); int id = is.readInt8(); is.checkInt8(0, "type chunk, res0"); is.checkInt16(0, "type chunk, res1"); int entryCount = is.readInt32(); long entriesStart = start + is.readInt32(); EntryConfig config = parseConfig(); int[] entryIndexes = new int[entryCount]; for (int i = 0; i < entryCount; i++) { entryIndexes[i] = is.readInt32(); } is.checkPos(entriesStart, "Expected entry start"); for (int i = 0; i < entryCount; i++) { if (entryIndexes[i] != NO_ENTRY) { parseEntry(pkg, id, i, config); } } } private void parseEntry(PackageChunk pkg, int typeId, int entryId, EntryConfig config) throws IOException { /* int size = */ is.readInt16(); int flags = is.readInt16(); int key = is.readInt32(); int resRef = pkg.getId() << 24 | typeId << 16 | entryId; String typeName = pkg.getTypeStrings()[typeId - 1]; String keyName = pkg.getKeyStrings()[key]; ResourceEntry ri = new ResourceEntry(resRef, pkg.getName(), typeName, keyName); ri.setConfig(config); if ((flags & FLAG_COMPLEX) == 0) { ri.setSimpleValue(parseValue()); } else { int parentRef = is.readInt32(); ri.setParentRef(parentRef); int count = is.readInt32(); List<RawNamedValue> values = new ArrayList<RawNamedValue>(count); for (int i = 0; i < count; i++) { values.add(parseValueMap()); } ri.setNamedValues(values); } resStorage.add(ri); } private RawNamedValue parseValueMap() throws IOException { int nameRef = is.readInt32(); return new RawNamedValue(nameRef, parseValue()); } private RawValue parseValue() throws IOException { is.checkInt16(8, "value size"); is.checkInt8(0, "value res0 not 0"); int dataType = is.readInt8(); int data = is.readInt32(); return new RawValue(dataType, data); } private EntryConfig parseConfig() throws IOException { long start = is.getPos(); int size = is.readInt32(); EntryConfig config = new EntryConfig(); is.readInt16(); //mcc is.readInt16(); //mnc config.setLanguage(parseLocale()); config.setCountry(parseLocale()); int orientation = is.readInt8(); int touchscreen = is.readInt8(); int density = is.readInt16(); /* is.readInt8(); // keyboard is.readInt8(); // navigation is.readInt8(); // inputFlags is.readInt8(); // inputPad0 is.readInt16(); // screenWidth is.readInt16(); // screenHeight is.readInt16(); // sdkVersion is.readInt16(); // minorVersion is.readInt8(); // screenLayout is.readInt8(); // uiMode is.readInt16(); // smallestScreenWidthDp is.readInt16(); // screenWidthDp is.readInt16(); // screenHeightDp */ is.skipToPos(start + size, "Skip config parsing"); return config; } private String parseLocale() throws IOException { int b1 = is.readInt8(); int b2 = is.readInt8(); String str = null; if (b1 != 0 && b2 != 0) { if ((b1 & 0x80) == 0) { str = new String(new char[]{(char) b1, (char) b2}); } else { LOG.warn("TODO: parse locale: 0x{}{}", Integer.toHexString(b1), Integer.toHexString(b2)); } } return str; } }
package com.bq.oss.lib.ws.auth.ioc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; import com.bq.oss.lib.token.ioc.TokenIoc; import com.bq.oss.lib.token.parser.TokenParser; import com.bq.oss.lib.ws.auth.*; import com.bq.oss.lib.ws.auth.repository.AuthorizationRulesRepository; import com.bq.oss.lib.ws.auth.repository.RedisAuthorizationRulesRepository; import com.bq.oss.lib.ws.health.AuthorizationRedisHealthCheck; import com.bq.oss.lib.ws.redis.GsonRedisSerializer; import com.google.gson.JsonObject; import com.sun.jersey.spi.container.ContainerRequestFilter; import io.dropwizard.auth.Authenticator; import io.dropwizard.auth.oauth.OAuthProvider; /** * @author Alexander De Leon * */ @Configuration @Import(TokenIoc.class) public class AuthorizationIoc { private static final Logger LOG = LoggerFactory.getLogger(AuthorizationIoc.class); @Bean public AuthorizationRulesRepository getAuthorizationRulesRepository(RedisTemplate<String, JsonObject> redisTemplate) { return new RedisAuthorizationRulesRepository(redisTemplate); } @Bean public RedisTemplate<String, JsonObject> redisTemplate(JedisConnectionFactory jedisConnectionFactory) { final RedisTemplate<String, JsonObject> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GsonRedisSerializer<JsonObject>()); return template; } @Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, @Value("${auth.redis.host:@null}") String host, @Value("${auth.redis.port:@null}") Integer port, @Value("${auth.redis.password:}") String password) { JedisConnectionFactory connFactory = new JedisConnectionFactory(jedisPoolConfig); connFactory.setPassword(password); if (host != null) { connFactory.setHostName(host); } if (port != null) { connFactory.setPort(port); } return connFactory; } @Bean public JedisPoolConfig jedisPoolConfig(@Value("${auth.redis.maxIdle:@null}") Integer maxIdle, @Value("${auth.redis.maxTotal:@null}") Integer maxTotal, @Value("${auth.redis.minIdle:@null}") Integer minIdle, @Value("${auth.redis.testOnBorrow:@null}") Boolean testOnBorrow, @Value("${auth.redis.testOnReturn:@null}") Boolean testOnReturn, @Value("${auth.redis.testWhileIdle:@null}") Boolean testWhileIdle, @Value("${auth.redis.numTestsPerEvictionRun:@null}") Integer numTestsPerEvictionRun, @Value("${auth.redis.maxWaitMillis:@null}") Long maxWaitMillis, @Value("${auth.redis.timeBetweenEvictionRunsMillis:@null}") Long timeBetweenEvictionRunsMillis, @Value("${auth.redis.blockWhenExhausted:@null}") Boolean blockWhenExhausted) { JedisPoolConfig config = new JedisPoolConfig(); if (maxIdle != null) { config.setMaxIdle(maxIdle); } if (maxTotal != null) { config.setMaxTotal(maxTotal); } if (minIdle != null) { config.setMinIdle(minIdle); } if (testOnBorrow != null) { config.setTestOnBorrow(testOnBorrow); } if (testOnReturn != null) { config.setTestOnReturn(testOnReturn); } if (testWhileIdle != null) { config.setTestWhileIdle(testWhileIdle); } if (numTestsPerEvictionRun != null) { config.setNumTestsPerEvictionRun(numTestsPerEvictionRun); } if (timeBetweenEvictionRunsMillis != null) { config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); } if (maxWaitMillis != null) { config.setMaxWaitMillis(maxWaitMillis); } if (blockWhenExhausted != null) { config.setBlockWhenExhausted(blockWhenExhausted); } return config; } @Bean public AuthorizationRulesService authorizationRulesService(AuthorizationRulesRepository authorizationRulesRepository) { return new DefaultAuthorizationRulesService(authorizationRulesRepository); } @Bean public Authenticator<String, AuthorizationInfo> authenticator(@Value("${auth.audience}") String audience, TokenParser tokenParser, AuthorizationRulesService authorizationRulesService) { return new BearerTokenAuthenticator(audience, authorizationRulesService, tokenParser); } @Bean(name = "authProvider") public OAuthProvider<AuthorizationInfo> getOAuthProvider(Authenticator<String, AuthorizationInfo> authenticator, @Value("${auth.realm}") String realm) { return new OAuthProvider<>(authenticator, realm); } @Bean(name = "cookieAuthProvider") public CookieOAuthProvider<AuthorizationInfo> getCookieOAuthProvider( Authenticator<String, AuthorizationInfo> authenticator) { return new CookieOAuthProvider<>(authenticator); } @Bean public ContainerRequestFilter getAuthorizationRequestFilter(OAuthProvider<AuthorizationInfo> oauthProvider, CookieOAuthProvider<AuthorizationInfo> cookieOauthProvider, @Value("${auth.enabled}") boolean authEnabled, @Value("${auth.unAuthenticatedPath}") String unAuthenticatedPath) { if (authEnabled) { return new AuthorizationRequestFilter(oauthProvider, cookieOauthProvider, unAuthenticatedPath); } else { LOG.warn("Authorization validation is disabled. The systen is in a INSECURE mode"); return emptyFilter(); } } @Bean public AuthorizationRedisHealthCheck getAuthorizationRedisHealthCheck( RedisTemplate<String, JsonObject> redisTemplate) { return new AuthorizationRedisHealthCheck(redisTemplate); } private ContainerRequestFilter emptyFilter() { return request -> request; } }
package org.pentaho.di.core.plugins; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSelectInfo; import org.apache.commons.vfs.FileSelector; import org.pentaho.di.core.Const; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.i18n.LanguageChoice; import org.w3c.dom.Node; abstract class BasePluginType { private static Class<?> PKG = BasePluginType.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ protected String id; protected String name; protected List<PluginFolderInterface> pluginFolders; protected PluginRegistry registry; protected LogChannel log; public BasePluginType() { this.pluginFolders = new ArrayList<PluginFolderInterface>(); this.log = new LogChannel("Plugin type"); registry = PluginRegistry.getInstance(); } /** * @param id The plugin type ID * @param name the name of the plugin */ public BasePluginType(String id, String name) { this(); this.id = id; this.name = name; } @Override public String toString() { return name+"("+id+")"; } /** * Let's put in code here to search for the step plugins.. */ public void searchPlugins() throws KettlePluginException { registerNatives(); registerAnnotations(); registerPluginJars(); registerXmlPlugins(); } abstract void registerNatives() throws KettlePluginException; abstract void registerAnnotations() throws KettlePluginException; abstract void registerPluginJars() throws KettlePluginException; abstract void registerXmlPlugins() throws KettlePluginException; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the pluginFolders */ public List<PluginFolderInterface> getPluginFolders() { return pluginFolders; } /** * @param pluginFolders the pluginFolders to set */ public void setPluginFolders(List<PluginFolderInterface> pluginFolders) { this.pluginFolders = pluginFolders; } protected static String getCodedTranslation(String codedString) { if (codedString==null) return null; if (codedString.startsWith("i18n:")) { String[] parts = codedString.split(":"); if (parts.length!=3) return codedString; else { return BaseMessages.getString(parts[1], parts[2]); } } else { return codedString; } } protected static String getTranslation(String string, String packageName, String altPackageName, Class<?> resourceClass) { if (string.startsWith("i18n:")) { String[] parts = string.split(":"); if (parts.length!=3) return string; else { return BaseMessages.getString(parts[1], parts[2]); } } else { int oldLogLevel = LogWriter.getInstance().getLogLevel(); // avoid i18n messages for missing locale LogWriter.getInstance().setLogLevel(LogWriter.LOG_LEVEL_BASIC); // Try the default package name String translation = BaseMessages.getString(packageName, string, resourceClass); if (translation.startsWith("!") && translation.endsWith("!")) translation=BaseMessages.getString(PKG, string, resourceClass); // restore loglevel, when the last alternative fails, log it when loglevel is detailed LogWriter.getInstance().setLogLevel(oldLogLevel); if (translation.startsWith("!") && translation.endsWith("!")) translation=BaseMessages.getString(altPackageName, string, resourceClass); return translation; } } protected List<JarFileAnnotationPlugin> findAnnotatedClassFiles(String annotationClassName) { List<JarFileAnnotationPlugin> classFiles = new ArrayList<JarFileAnnotationPlugin>(); // We want to scan the plugins folder for plugin.xml files... for (PluginFolderInterface pluginFolder : getPluginFolders()) { if (pluginFolder.isPluginAnnotationsFolder()) { try { // Find all the jar files in this folder... FileObject folderObject = KettleVFS.getFileObject( pluginFolder.getFolder() ); FileObject[] fileObjects = folderObject.findFiles(new FileSelector() { public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception { return true; } public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception { return fileSelectInfo.getFile().toString().matches(".*\\.jar$"); } }); for (FileObject fileObject : fileObjects) { // These are the jar files : find annotations in it... JarFile jarFile = new JarFile(KettleVFS.getFilename(fileObject)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); try { ClassFile classFile = new ClassFile( new DataInputStream(new BufferedInputStream(jarFile.getInputStream(entry))) ); AnnotationsAttribute visible = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag); if (visible!=null) { Annotation[] anns = visible.getAnnotations(); for (Annotation ann : anns) { if (ann.getTypeName().equals(annotationClassName)) { classFiles.add(new JarFileAnnotationPlugin(fileObject.getURL(), classFile, ann)); break; } } } } catch(Exception e) { // Not a class, ignore exception } } } } catch(Exception e) { // The plugin folder could not be found or we can't read it // Let's not through an exception here } } } return classFiles; } protected List<FileObject> findPluginXmlFiles(String folder) { List<FileObject> list = new ArrayList<FileObject>(); try { FileObject folderObject = KettleVFS.getFileObject(folder); FileObject[] files = folderObject.findFiles( new FileSelector() { public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception { return true; } public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception { return fileSelectInfo.getFile().toString().matches(".*\\/plugin\\.xml$"); } } ); for (FileObject file : files) { list.add(file); } } catch(Exception e) { } return list; } protected PluginInterface registerPluginFromXmlResource( Node pluginNode, String path, PluginTypeInterface pluginType) throws KettlePluginException { try { String id = XMLHandler.getTagAttribute(pluginNode, "id"); //$NON-NLS-1$ String description = getTagOrAttribute(pluginNode, "description"); //$NON-NLS-1$ String iconfile = getTagOrAttribute(pluginNode, "iconfile"); //$NON-NLS-1$ String tooltip = getTagOrAttribute(pluginNode, "tooltip"); //$NON-NLS-1$ String category = getTagOrAttribute(pluginNode, "category"); //$NON-NLS-1$ String classname = getTagOrAttribute(pluginNode, "classname"); //$NON-NLS-1$ String errorHelpfile = getTagOrAttribute(pluginNode, "errorhelpfile"); //$NON-NLS-1$ String metaclassname = getTagOrAttribute(pluginNode, "metaclassname"); //$NON-NLS-1$ String dialogclassname = getTagOrAttribute(pluginNode, "dialogclassname"); //$NON-NLS-1$ String versionbrowserclassname = getTagOrAttribute(pluginNode, "versionbrowserclassname"); //$NON-NLS-1$ Node libsnode = XMLHandler.getSubNode(pluginNode, "libraries"); //$NON-NLS-1$ int nrlibs = XMLHandler.countNodes(libsnode, "library"); //$NON-NLS-1$ List<String> jarFiles = new ArrayList<String>(); if( path != null ) { for (int j = 0; j < nrlibs; j++) { Node libnode = XMLHandler.getSubNodeByNr(libsnode, "library", j); //$NON-NLS-1$ String jarfile = XMLHandler.getTagAttribute(libnode, "name"); //$NON-NLS-1$ jarFiles.add( new File(path + Const.FILE_SEPARATOR + jarfile).getAbsolutePath() ); } } // Localized categories, descriptions and tool tips Map<String, String> localizedCategories = readPluginLocale(pluginNode, "localized_category", "category"); category = getAlternativeTranslation(category, localizedCategories); Map<String, String> localizedDescriptions = readPluginLocale(pluginNode, "localized_description", "description"); description = getAlternativeTranslation(description, localizedDescriptions); Map<String, String> localizedTooltips = readPluginLocale(pluginNode, "localized_tooltip", "tooltip"); tooltip = getAlternativeTranslation(tooltip, localizedTooltips); String iconFilename = (path == null) ? iconfile : path + Const.FILE_SEPARATOR + iconfile; String errorHelpFileFull = errorHelpfile; if (!Const.isEmpty(errorHelpfile)) errorHelpFileFull = (path == null) ? errorHelpfile : path+Const.FILE_SEPARATOR+errorHelpfile; Map<PluginClassType, String> classMap = new HashMap<PluginClassType, String>(); classMap.put(PluginClassType.MainClassType, classname); classMap.put(PluginClassType.MetaClassType, metaclassname); classMap.put(PluginClassType.DialogClassType, dialogclassname); classMap.put(PluginClassType.RepositoryVersionBrowserClassType, versionbrowserclassname); PluginInterface pluginInterface = new Plugin(id.split(","), pluginType, category, description, tooltip, iconFilename, false, false, classMap, jarFiles, errorHelpFileFull); registry.registerPlugin(pluginType, pluginInterface); return pluginInterface; } catch (Throwable e) { throw new KettlePluginException( BaseMessages.getString(PKG, "BasePluginType.RuntimeError.UnableToReadPluginXML.PLUGIN0001"), e); //$NON-NLS-1$ } } private String getTagOrAttribute(Node pluginNode, String tag) { String string = XMLHandler.getTagValue(pluginNode, tag); if (string==null) { string = XMLHandler.getTagAttribute(pluginNode, tag); //$NON-NLS-1$ } return string; } /** * * @param input * @param localizedMap * @return */ private String getAlternativeTranslation(String input, Map<String, String> localizedMap) { if (Const.isEmpty(input)) { return null; } if (input.startsWith("i18n")) { return getCodedTranslation(input); } else { String defLocale = LanguageChoice.getInstance().getDefaultLocale().toString().toLowerCase(); String alt = localizedMap.get(defLocale); if (!Const.isEmpty(alt)) { return alt; } String failoverLocale = LanguageChoice.getInstance().getFailoverLocale().toString().toLowerCase(); alt = localizedMap.get(failoverLocale); if (!Const.isEmpty(alt)) { return alt; } // Nothing found? // Return the original! return input; } } private Map<String, String> readPluginLocale(Node pluginNode, String localizedTag, String translationTag) { Map<String, String> map = new Hashtable<String, String>(); Node locTipsNode = XMLHandler.getSubNode(pluginNode, localizedTag); int nrLocTips = XMLHandler.countNodes(locTipsNode, translationTag); for (int j=0 ; j < nrLocTips; j++) { Node locTipNode = XMLHandler.getSubNodeByNr(locTipsNode, translationTag, j); if (locTipNode!=null) { String locale = XMLHandler.getTagAttribute(locTipNode, "locale"); String locTip = XMLHandler.getNodeValue(locTipNode); if (!Const.isEmpty(locale) && !Const.isEmpty(locTip)) { map.put(locale.toLowerCase(), locTip); } } } return map; } }
package io.coinswap.client; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.core.*; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.bitcoinj.wallet.KeyChainGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.InetSocketAddress; /** * Contains the settings and state for one currency. Includes an AltcoinJ wallet, * and a JS-side Currency model for interfacing with UI. */ public class Currency { private static final Logger log = LoggerFactory.getLogger(Currency.class); private static final File checkpointDir = new File("./checkpoints"); protected NetworkParameters params; protected WalletAppKit wallet; protected String name, id, symbol; protected String[] pairs; protected int index; protected boolean hashlock; // whether or not this coin can be used on the Alice-side of a swap protected int confirmationDepth; private boolean setup; private SettableFuture<Object> setupFuture; public Currency(NetworkParameters params, File directory, String name, String id, String symbol, String[] pairs, int index, boolean hashlock, int confirmationDepth) { this.params = params; this.name = name; this.id = id; this.symbol = symbol; this.pairs = pairs; this.index = index; this.hashlock = hashlock; this.confirmationDepth = confirmationDepth; setupFuture = SettableFuture.create(); // create the AltcoinJ wallet to interface with the currency wallet = new WalletAppKit(params, directory, name.toLowerCase()) { @Override protected void onSetupCompleted() { peerGroup().setMaxConnections(8); peerGroup().setFastCatchupTimeSecs(wallet.wallet().getEarliestKeyCreationTime()); setup = true; setupFuture.set(null); } }; wallet.setUserAgent(Main.APP_NAME, Main.APP_VERSION); wallet.setBlockingStartup(false); // load a checkpoint file (if it exists) to speed up initial blockchain sync InputStream checkpointStream = Main.class.getResourceAsStream("/checkpoints/"+name.toLowerCase()+".txt"); if(checkpointStream != null) { wallet.setCheckpoints(checkpointStream); } else { log.info("No checkpoints found for " + name); } } public void start() { wallet.startAsync(); wallet.awaitRunning(); } public void stop() { wallet.stopAsync(); wallet.awaitTerminated(); } public String getId() { return id; } public int getIndex() { return index; } public boolean supportsHashlock() { return hashlock; } public int getConfirmationDepth() { return confirmationDepth; } public String[] getPairs() { return pairs; } public boolean isSetup() { return setup; } public WalletAppKit getWallet() { return wallet; } public NetworkParameters getParams() { return params; } public ListenableFuture<Object> getSetupFuture() { return setupFuture; } }
package io.xjhub.samplecontacts; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; class ContactCursorAdapter extends CursorAdapter { private LayoutInflater mInflater; ContactCursorAdapter(Context context, Cursor cursor, int flags) { super(context, cursor, flags); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate the layout for each row return mInflater.inflate(R.layout.fragment_main_row, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tvName = (TextView) view.findViewById(R.id.tvName); TextView tvPhone = (TextView) view.findViewById(R.id.tvPhone); String title = cursor.getString(cursor.getColumnIndex(ContactModel.COLUMN_NAME_TITLE)); String phone = cursor.getString(cursor.getColumnIndex(ContactModel.COLUMN_NAME_PHONE)); tvName.setText(title); tvPhone.setText(phone); } }
package org.pi.litepost.controllers; import java.io.File; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; import org.pi.litepost.App; import org.pi.litepost.Router; import org.pi.litepost.View; import org.pi.litepost.ViewContext; import org.pi.litepost.applicationLogic.Model; import org.pi.litepost.applicationLogic.Post; import org.pi.litepost.html.Validator; import com.google.common.io.Files; import fi.iki.elonen.NanoHTTPD.IHTTPSession; import fi.iki.elonen.NanoHTTPD.Response; import fi.iki.elonen.NanoHTTPD.Response.Status; public class PostController { public static Response getAll(IHTTPSession session, Map<String, String> args, Map<String, String> files, ViewContext context, Model model) { ArrayList<Post> posts = new ArrayList<>(); try { posts = model.getPostManager().getAll(); } catch (SQLException e) { return Router.error(e, context); } context.put("posts", posts); return new Response(View.make("post.all", context)); } public static Response getSingle(IHTTPSession session, Map<String, String> args, Map<String, String> files, ViewContext context, Model model) { int postId = 0; try { postId = Integer.parseInt(args.getOrDefault("post_id", "")); }catch(NumberFormatException e) { return Router.notFound(context); } Post post = null; try { post = model.getPostManager().getById(postId); if(post == null) { return Router.notFound(context); } } catch (SQLException e) { return Router.error(e, context); } context.put("post", post); return new Response(View.make("post.single", context)); } public static Response getNew(IHTTPSession session, Map<String, String> args, Map<String, String> files, ViewContext context, Model model) { return new Response(View.make("post.new", context)); } public static Response postNew(IHTTPSession session, Map<String, String> args, Map<String, String> files, ViewContext context, Model model) { Validator validator = new Validator(model.getSessionManager()) .validateSingle("validCsrfToken", model.getSessionManager()::validateToken, "csrf_token") .validateSingle("hasTitle", View::sanitizeStrict, s -> s.length() > 0, "title") .validateSingle("hasContent", View::sanitizePostContent, s -> s.length() > 0, "content") .validateSingle("hasContact", View::sanitizeStrict, s -> s.length() > 0, "contact") .validateFlag("isEvent", "is-event"); context.setValidator(validator); if(!validator.validate(session.getParms())) { return new Response(View.make("post.new", context)); } String filename = session.getParms().get("image"); if(filename != null) { String filepath = files.get("image"); File input = new File(filepath); String uploadfolder = (String) App.config.get("litepost.public.uploadfolder"); File output = new File(uploadfolder + File.separatorChar + filename); if(input.exists()) { try { Files.copy(input, output); } catch (IOException e) { return Router.error(e, context); } } } try { String title = validator.value("username"); String content = validator.value("content"); String contact = validator.value("contact"); model.getPostManager().insert(title, content, contact); ResultSet rs = model.getQueryManager().executeQuery("getLastId", "Posts"); model.getPostManager().addImage(Router.linkTo("upload", filename), rs.getInt(1)); } catch (SQLException e) { return Router.error(e, context); } return Router.redirectTo("allPosts"); } public static Response commentPost(IHTTPSession session, Map<String, String> args, Map<String, String> files, ViewContext context, Model model) { Validator validator = new Validator(model.getSessionManager()) .validateSingle("validCsrfToken", model.getSessionManager()::validateToken, "csrf_token") .validateSingle("parentIdNumericOrEmpty", s -> s.matches("[0-9]*"), "parent_id") .validateSingle("hasContent", View::sanitizeStrict, s -> s.length() > 0, "content"); context.setValidator(validator); int postId = 0; try { postId = Integer.parseInt(args.getOrDefault("post_id", "")); }catch(NumberFormatException e) { return new Response(Status.NOT_FOUND, "text/html", View.make("404", context)); } if(!validator.validate(session.getParms())) { return getSingle(session, args, files, context, model); } try { int parentId = 0; try { parentId = Integer.parseInt(validator.value("parent_id")); }catch(NumberFormatException e){} String content = validator.value("content"); model.getCommentManager().insert(content, parentId, postId); } catch (SQLException e) { return Router.error(e, context); } return Router.redirectTo("singlePost", postId); } }
package org.stepic.droid.preferences; import android.content.Context; import android.os.Environment; import org.stepic.droid.model.Profile; import java.io.File; import java.io.IOException; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class UserPreferences { Context mContext; SharedPreferenceHelper sharedPreferenceHelper; @Inject public UserPreferences(Context context, SharedPreferenceHelper helper) { mContext = context; sharedPreferenceHelper = helper; } /** * Returns user storage directory under /Android/data/ folder for the currently logged in user. * This is the folder where all video downloads should be kept. * * @return folder for current user, where videos are saved. */ public File getDownloadFolder() { File android = new File(Environment.getExternalStorageDirectory(), "Android"); File downloadsDir = new File(android, "data"); File packDir = new File(downloadsDir, mContext.getPackageName()); File userStepicIdDir = new File(packDir, getUserId() + ""); userStepicIdDir.mkdirs(); try { //hide from gallery our videos. File noMediaFile = new File(userStepicIdDir, ".nomedia"); noMediaFile.createNewFile(); } catch (IOException ioException) { // FIXME: 20.10.15 handle exception } return userStepicIdDir; } private long getUserId() { Profile userProfile = sharedPreferenceHelper.getProfile(); long userId = -1; // default anonymous user id if (userProfile != null) { userId = userProfile.getId(); } return userId; } public boolean isNetworkMobileAllowed() { return sharedPreferenceHelper.isMobileInternetAlsoAllowed(); } }
package com.imcode.imcms.config; import com.imcode.imcms.imagearchive.Config; import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.bidimap.DualHashBidiMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.CustomEditorConfigurer; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.core.env.Environment; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import java.beans.PropertyEditor; import java.io.File; import java.util.Map; @Configuration public class ApplicationConfig { @Autowired private Environment env;// = new StandardServletEnvironment(); @Autowired @Bean public Config imageArchiveConfig(Environment env2) { BidiMap languages = new DualHashBidiMap(); languages.put("eng", "en"); languages.put("swe", "sv"); Config config = new Config(); config.setStoragePath(new File(env2.getProperty("ImageArchiveStoragePath"))); config.setTmpPath(new File(env2.getProperty("ImageArchiveTempPath"))); config.setImageMagickPath(new File(env2.getProperty("ImageMagickPath"))); config.setImagesPath(new File(env2.getProperty("ImageArchiveImagesPath"))); config.setLibrariesPath(new File(env2.getProperty("ImageArchiveLibrariesPath"))); config.setOldLibraryPaths(new File[]{new File(env2.getProperty("ImageArchiveOldLibraryPaths"))}); config.setUsersLibraryFolder(env2.getProperty("ImageArchiveUsersLibraryFolder")); config.setMaxImageUploadSize(Long.parseLong(env2.getProperty("ImageArchiveMaxImageUploadSize"))); config.setMaxZipUploadSize(Long.parseLong(env2.getProperty("ImageArchiveMaxZipUploadSize"))); config.setLanguages(languages); return config; } @Bean public CustomEditorConfigurer customEditorConfigurer() { CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer(); Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new ManagedMap<>(); customEditors.put(java.io.File.class, com.imcode.imcms.imagearchive.util.FileEditor.class); customEditors.put(java.io.File[].class, com.imcode.imcms.imagearchive.util.FileArrayEditor.class); customEditorConfigurer.setCustomEditors(customEditors); return customEditorConfigurer; } @Bean public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() { ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource(); //TODO: Move that values to properties source.setBasenames("/WEB-INF/locale/imcms", "/WEB-INF/locale/image_archive"); source.setFallbackToSystemLocale(false); source.setUseCodeAsDefaultMessage(true); return source; } @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { return new MappingJackson2HttpMessageConverter(); } }
package com.kurento.kmf.content.jsonrpc; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.kurento.kmf.content.jsonrpc.param.JsonRpcRequestParams; import com.kurento.kmf.content.jsonrpc.result.JsonRpcResponseResult; public class GsonUtils { /** * Static instance of Gson object. */ private static Gson gson; /** * Serialize Java object to JSON (as String). * * @param obj * Java Object representing a JSON message to be serialized * @return Serialized JSON message (as String) */ public static String toString(Object obj) { return GsonUtils.getGson().toJson(obj); } /** * Gson object accessor (getter). * * @return son object */ public static Gson getGson() { if (gson != null) { return gson; } GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(JsonRpcRequest.class, new JsonRpcRequestDeserializer()); builder.registerTypeAdapter(JsonRpcResponse.class, new JsonRpcResponseDeserializer()); gson = builder.create(); return gson; } static boolean isIn(JsonObject jObject, String[] clues) { for (String clue : clues) { if (jObject.has(clue)) { return true; } } return false; } } class JsonRpcResponseDeserializer implements JsonDeserializer<JsonRpcResponse> { @Override public JsonRpcResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonObject)) { throw new JsonParseException("JonObject expected, found " + json.getClass().getSimpleName()); } JsonObject jObject = (JsonObject) json; if (!jObject.has("jsonrpc")) { throw new JsonParseException( "Invalid JsonRpc response lacking version 'jsonrpc' field"); } if (!jObject.get("jsonrpc").getAsString() .equals(JsonRpcConstants.JSON_RPC_VERSION)) { throw new JsonParseException("Invalid JsonRpc version"); } if (!jObject.has("id")) { throw new JsonParseException( "Invalid JsonRpc response lacking 'id' field"); } if (jObject.has("result")) { return new JsonRpcResponse( (JsonRpcResponseResult) context.deserialize( jObject.get("result").getAsJsonObject(), JsonRpcResponseResult.class), jObject.get("id") .getAsInt()); } else if (jObject.has("error")) { return new JsonRpcResponse( (JsonRpcResponseError) context.deserialize( jObject.get("error").getAsJsonObject(), JsonRpcResponseError.class), jObject.get("id") .getAsInt()); } else { throw new JsonParseException( "Invalid JsonRpc response lacking 'result' and 'error' fields"); } } } class JsonRpcRequestDeserializer implements JsonDeserializer<JsonRpcRequest> { @Override public JsonRpcRequest deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonObject)) { throw new JsonParseException( "Invalid JsonRpc request showning JsonElement type " + json.getClass().getSimpleName()); } JsonObject jObject = (JsonObject) json; if (!jObject.has("jsonrpc")) { throw new JsonParseException( "Invalid JsonRpc request lacking version 'jsonrpc' field"); } if (!jObject.get("jsonrpc").getAsString() .equals(JsonRpcConstants.JSON_RPC_VERSION)) { throw new JsonParseException("Invalid JsonRpc version"); } if (!jObject.has("method")) { throw new JsonParseException( "Invalid JsonRpc request lacking 'method' field"); } if (!jObject.has("params")) { throw new JsonParseException( "Invalid JsonRpc request lacking 'params' field"); } if (!jObject.has("id")) { throw new JsonParseException( "Invalid JsonRpc request lacking 'id' field"); } return new JsonRpcRequest(jObject.get("method").getAsString(), (JsonRpcRequestParams) context.deserialize(jObject .get("params").getAsJsonObject(), JsonRpcRequestParams.class), jObject.get("id") .getAsInt()); } }
package com.ctrip.zeus.restful.resource; import com.ctrip.zeus.auth.Authorize; import com.ctrip.zeus.exceptions.ValidationException; import com.ctrip.zeus.executor.impl.ResultHandler; import com.ctrip.zeus.lock.DbLockFactory; import com.ctrip.zeus.lock.DistLock; import com.ctrip.zeus.model.entity.*; import com.ctrip.zeus.model.transform.DefaultJsonParser; import com.ctrip.zeus.model.transform.DefaultSaxParser; import com.ctrip.zeus.restful.filter.FilterSet; import com.ctrip.zeus.restful.filter.QueryExecuter; import com.ctrip.zeus.restful.message.ResponseHandler; import com.ctrip.zeus.restful.message.TrimmedQueryParam; import com.ctrip.zeus.service.model.SelectionMode; import com.ctrip.zeus.service.model.SlbRepository; import com.ctrip.zeus.service.model.IdVersion; import com.ctrip.zeus.service.query.SlbCriteriaQuery; import com.ctrip.zeus.tag.PropertyService; import com.ctrip.zeus.tag.TagService; import com.google.common.base.Joiner; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Component @Path("/") public class SlbResource { @Resource private SlbRepository slbRepository; @Resource private SlbCriteriaQuery slbCriteriaQuery; @Resource private ResponseHandler responseHandler; @Resource private DbLockFactory dbLockFactory; @Resource private TagService tagService; @Resource private PropertyService propertyService; private final int TIMEOUT = 1000; @GET @Path("/slbs") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Authorize(name = "getAllSlbs") public Response list(@Context final HttpHeaders hh, @Context HttpServletRequest request, @TrimmedQueryParam("type") final String type, @TrimmedQueryParam("tag") final String tag, @TrimmedQueryParam("pname") final String pname, @TrimmedQueryParam("pvalue") final String pvalue, @TrimmedQueryParam("mode") final String mode) throws Exception { final SelectionMode selectionMode = SelectionMode.getMode(mode); final Long[] slbIds = new QueryExecuter.Builder<Long>() .addFilter(new FilterSet<Long>() { @Override public boolean shouldFilter() throws Exception { return true; } @Override public Set<Long> filter() throws Exception { return slbCriteriaQuery.queryAll(); } }) .addFilter(new FilterSet<Long>() { @Override public boolean shouldFilter() throws Exception { return tag != null; } @Override public Set<Long> filter() throws Exception { return new HashSet<>(tagService.query(tag, "slb")); } }) .addFilter(new FilterSet<Long>() { @Override public boolean shouldFilter() throws Exception { return pname != null; } @Override public Set<Long> filter() throws Exception { if (pvalue != null) return new HashSet<>(propertyService.query(pname, pvalue, "slb")); else return new HashSet<>(propertyService.query(pname, "slb")); } }).build(Long.class).run(); QueryExecuter<IdVersion> executer = new QueryExecuter.Builder<IdVersion>() .addFilter(new FilterSet<IdVersion>() { @Override public boolean shouldFilter() throws Exception { return true; } @Override public Set<IdVersion> filter() throws Exception { return slbIds.length == 0 ? new HashSet<IdVersion>() : slbCriteriaQuery.queryByIdsAndMode(slbIds, selectionMode); } }) .build(IdVersion.class); final SlbList slbList = new SlbList(); for (Slb slb : slbRepository.list(executer.run())) { slbList.addSlb(getSlbByType(slb, type)); } slbList.setTotal(slbList.getSlbs().size()); return responseHandler.handle(slbList, hh.getMediaType()); } @GET @Path("/slb") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Authorize(name = "getSlb") public Response get(@Context HttpHeaders hh, @Context HttpServletRequest request, @QueryParam("slbId") final Long slbId, @TrimmedQueryParam("slbName") final String slbName, @TrimmedQueryParam("ip") final String serverIp, @TrimmedQueryParam("type") String type, @TrimmedQueryParam("mode") final String mode) throws Exception { final SelectionMode selectionMode = SelectionMode.getMode(mode); if (slbId == null && slbName == null && serverIp==null) { throw new Exception("Missing parameter."); } IdVersion[] keys = new QueryExecuter.Builder<IdVersion>() .addFilter(new FilterSet<IdVersion>() { @Override public boolean shouldFilter() throws Exception { return slbId==null && serverIp != null; } @Override public Set<IdVersion> filter() throws Exception { return slbCriteriaQuery.queryBySlbServerIp(serverIp); } }) .addFilter(new FilterSet<IdVersion>() { @Override public boolean shouldFilter() throws Exception { return slbId==null && slbName != null; } @Override public Set<IdVersion> filter() throws Exception { Long _slbId = slbCriteriaQuery.queryByName(slbName); if (_slbId.longValue() == 0L) throw new ValidationException("Slb id cannot be found."); return slbCriteriaQuery.queryByIdsAndMode(new Long[]{_slbId}, selectionMode); } }) .addFilter(new FilterSet<IdVersion>() { @Override public boolean shouldFilter() throws Exception { return slbId!=null; } @Override public Set<IdVersion> filter() throws Exception { return slbCriteriaQuery.queryByIdsAndMode(new Long[]{slbId}, selectionMode); } }) .build(IdVersion.class).run(new ResultHandler<IdVersion, IdVersion>() { @Override public IdVersion[] handle(Set<IdVersion> result) throws Exception { return result.toArray(new IdVersion[result.size()]); } }); SlbList slbList = new SlbList(); for (Slb slb : slbRepository.list(keys)) { slbList.addSlb(getSlbByType(slb, type)); } slbList.setTotal(slbList.getSlbs().size()); return responseHandler.handle(slbList, hh.getMediaType()); } @POST @Path("/slb/new") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "*/*"}) @Authorize(name = "addSlb") public Response add(@Context HttpHeaders hh, @Context HttpServletRequest request, String slb) throws Exception { Slb s = slbRepository.add(parseSlb(hh.getMediaType(), slb)); return responseHandler.handle(s, hh.getMediaType()); } @POST @Path("/slb/update") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "*/*"}) @Authorize(name = "updateSlb") public Response update(@Context HttpHeaders hh, @Context HttpServletRequest request, String slb) throws Exception { Slb s = parseSlb(hh.getMediaType(), slb); DistLock lock = dbLockFactory.newLock(s.getName() + "_updateSlb"); lock.lock(TIMEOUT); try { s = slbRepository.update(s); } finally { lock.unlock(); } return responseHandler.handle(s, hh.getMediaType()); } @GET @Path("/slb/delete") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Authorize(name = "deleteSlb") public Response delete(@Context HttpHeaders hh, @Context HttpServletRequest request, @QueryParam("slbId") Long slbId) throws Exception { if (slbId == null) { throw new Exception("Missing parameter."); } int count = slbRepository.delete(slbId); String message = count == 1 ? "Delete slb successfully." : "No deletion is needed."; return responseHandler.handle(message, hh.getMediaType()); } @GET @Path("/slb/upgradeAll") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response upgradeAll(@Context HttpHeaders hh, @Context HttpServletRequest request) throws Exception { Set<Long> list = slbCriteriaQuery.queryAll(); Set<Long> result = slbRepository.port(list.toArray(new Long[list.size()])); if (result.size() == 0) return responseHandler.handle("Upgrade all successfully.", hh.getMediaType()); else return responseHandler.handle("Upgrade fail on ids: " + Joiner.on(",").join(result), hh.getMediaType()); } private Slb parseSlb(MediaType mediaType, String slb) throws Exception { Slb s; if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) { s = DefaultSaxParser.parseEntity(Slb.class, slb); } else { try { s = DefaultJsonParser.parse(Slb.class, slb); } catch (Exception e) { throw new Exception("Slb cannot be parsed."); } } s.setName(trimIfNotNull(s.getName())); for (VirtualServer virtualServer : s.getVirtualServers()) { virtualServer.setName(trimIfNotNull(virtualServer.getName())); for (Domain domain : virtualServer.getDomains()) { domain.setName(trimIfNotNull(domain.getName())); } } for (SlbServer slbServer : s.getSlbServers()) { slbServer.setIp(trimIfNotNull(slbServer.getIp())); slbServer.setHostName(trimIfNotNull(slbServer.getHostName())); } return s; } private Slb getSlbByType(Slb slb, String type) { if ("INFO".equalsIgnoreCase(type)) { return new Slb().setId(slb.getId()) .setName(slb.getName()); } if ("NORMAL".equalsIgnoreCase(type)) { Slb result = new Slb().setId(slb.getId()) .setName(slb.getName()) .setNginxBin(slb.getNginxBin()) .setNginxConf(slb.getNginxConf()) .setNginxWorkerProcesses(slb.getNginxWorkerProcesses()) .setStatus(slb.getStatus()) .setVersion(slb.getVersion()); for (SlbServer slbServer : slb.getSlbServers()) { result.addSlbServer(slbServer); } return result; } return slb; } private String trimIfNotNull(String value) { return value != null ? value.trim() : value; } }