answer
stringlengths
17
10.2M
package cn.momia.mapi.api.v1.course; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.dto.CourseBookDto; import cn.momia.api.course.dto.CourseDto; import cn.momia.api.course.dto.InstitutionDto; import cn.momia.api.course.dto.TeacherDto; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.UserDto; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.webapp.config.Configuration; import cn.momia.image.api.ImageFile; import cn.momia.mapi.api.v1.AbstractV1Api; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/v1/course") public class CourseV1Api extends AbstractV1Api { @Autowired private CourseServiceApi courseServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam(required = false, defaultValue = "") String utoken, @RequestParam long id, @RequestParam(required = false, defaultValue = "") String pos) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; CourseDto course = processCourse(courseServiceApi.get(id, pos)); JSONObject courseJson = (JSONObject) JSON.toJSON(course); if (!StringUtils.isBlank(utoken)) { UserDto user = userServiceApi.get(utoken); courseJson.put("favored", courseServiceApi.isFavored(user.getId(), id)); } List<TeacherDto> teachers = processTeachers(courseServiceApi.queryTeachers(id, 0, Configuration.getInt("PageSize.CourseTeacher")).getList()); if (!teachers.isEmpty()) courseJson.put("teachers", teachers); return MomiaHttpResponse.SUCCESS(courseJson); } protected CourseDto processCourse(CourseDto course) { course.setCover(ImageFile.largeUrl(course.getCover())); processLargeImgs(course.getImgs()); processCourseBook(course.getBook()); return course; } private CourseBookDto processCourseBook(CourseBookDto book) { if (book == null) return null; List<String> imgs = new ArrayList<String>(); List<String> largeImgs = new ArrayList<String>(); for (String img : book.getImgs()) { imgs.add(ImageFile.smallUrl(img)); largeImgs.add(ImageFile.url(img)); } book.setImgs(imgs); book.setLargeImgs(largeImgs); return book; } private List<TeacherDto> processTeachers(List<TeacherDto> teachers) { for (TeacherDto teacher : teachers) { teacher.setAvatar(ImageFile.smallUrl(teacher.getAvatar())); } return teachers; } @RequestMapping(value = "/detail", method = RequestMethod.GET) public MomiaHttpResponse detail(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(courseServiceApi.detail(id)); } @RequestMapping(value = "/book", method = RequestMethod.GET) public MomiaHttpResponse book(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<String> book = courseServiceApi.book(id, start, Configuration.getInt("PageSize.BookImg")); processImgs(book.getList()); return MomiaHttpResponse.SUCCESS(book); } @RequestMapping(value = "/teacher", method = RequestMethod.GET) public MomiaHttpResponse teacher(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<TeacherDto> teachers = courseServiceApi.queryTeachers(id, start, Configuration.getInt("PageSize.Teacher")); processTeachers(teachers.getList()); return MomiaHttpResponse.SUCCESS(teachers); } @RequestMapping(value = "/institution", method = RequestMethod.GET) public MomiaHttpResponse institution(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; InstitutionDto institution = courseServiceApi.institution(id); institution.setCover(ImageFile.largeUrl(institution.getCover())); return MomiaHttpResponse.SUCCESS(institution); } @RequestMapping(value = "/sku/week", method = RequestMethod.GET) public MomiaHttpResponse listWeekSkus(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(courseServiceApi.listWeekSkus(id)); } @RequestMapping(value = "/sku/month", method = RequestMethod.GET) public MomiaHttpResponse listWeekSkus(@RequestParam long id, @RequestParam int month) { if (id <= 0 || month <= 0 || month > 12) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(courseServiceApi.listMonthSkus(id, month)); } @RequestMapping(value = "/booking", method = RequestMethod.POST) public MomiaHttpResponse booking(@RequestParam String utoken, @RequestParam(value = "pid") long packageId, @RequestParam(value = "sid") long skuId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (packageId <= 0 || skuId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!courseServiceApi.booking(utoken, packageId, skuId)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/cancel", method = RequestMethod.POST) public MomiaHttpResponse cancel(@RequestParam String utoken, @RequestParam(value = "bid") long bookingId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (bookingId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!courseServiceApi.cancel(utoken, bookingId)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/favor", method = RequestMethod.POST) public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!courseServiceApi.favor(user.getId(), id)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/unfavor", method = RequestMethod.POST) public MomiaHttpResponse unfavor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!courseServiceApi.unfavor(user.getId(), id)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS; } }
package net.jonp.sorm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; /** * Provides {@link SormSession}s. */ public class SormContext { private static final Logger LOG = Logger.getLogger(SormContext.class); private final Dialect _dialect; private final String _server; private final String _user; private final String _passwd; private boolean _closed = false; private final Map<Thread, SormSession> _sessions = new HashMap<Thread, SormSession>(); private final ThreadLocal<SormSession> _session = new ThreadLocal<SormSession>(); /** * Construct a new {@link SormContext}. * * @param dialect The dialect to use. * @param server The name of the server to connect to. If the server * requires a non-standard port number, or a more complex URL, * make sure to include it all in this (for example, * <code>my.server.net:1234/path/on/server</code>). * @param user The user name, or <code>null</code> to not pass a user * name/password. * @param passwd The password, or <code>null</code> to not pass a user * name/password. * @throws ClassNotFoundException If unable to load the driver for the * specified dialect. */ public SormContext(final Dialect dialect, final String server, final String user, final String passwd) throws ClassNotFoundException { _dialect = dialect; _server = server; _user = user; _passwd = passwd; Class.forName(_dialect.getDriver()); } /** * Get the dialect of this context. * * @return The dialect. */ public Dialect getDialect() { return _dialect; } /** * Wrapper around {@link #getSession(CacheMode)} with * {@link CacheMode#Immediate}. */ public SormSession getSession() throws SQLException { return getSession(CacheMode.Immediate); } /** * Get the session for this thread, constructing one if necessary. If your * thread will not live long, use {@link #getTransientSession()} and make * sure to close the session when you are finished. * * @param cacheMode The cache mode for the session. If this thread already * has a session, but the cache mode does not match, that session * will be closed and a new session opened. * @return The session for this thread. * @throws SQLException If there was a problem creating a new connection. */ public SormSession getSession(final CacheMode cacheMode) throws SQLException { if (_closed) { throw new IllegalStateException(getClass().getSimpleName() + " is closed"); } SormSession session = _session.get(); if (null != session && null != cacheMode && session.getCacheMode() != cacheMode) { session.close(); session = null; } if (null == session) { LOG.info("Building a new session for a new thread"); session = makeSession(cacheMode); _session.set(session); synchronized (_sessions) { _sessions.put(Thread.currentThread(), session); } } return session; } /** * Call this when your thread is dying or you want the next call from this * thread to {@link #getSession(CacheMode)} to construct a new session. */ public void dispose() { final SormSession session = _session.get(); if (null != session) { LOG.info("Disposing of session due to thread request"); _session.remove(); synchronized (_sessions) { _sessions.remove(Thread.currentThread()); } try { session.close(); } catch (final SQLException sqle) { LOG.debug("Error closing session", sqle); } } } /** * Wrapper around {@link #getTransientSession(CacheMode)} with * {@link CacheMode#Immediate}. */ public SormSession getTransientSession() throws SQLException { return getTransientSession(CacheMode.Immediate); } /** * Construct a new session intended for a brief usage. * * @param cacheMode The cache mode to use. * @return A new session. Make sure to close this when you are finished with * it. * @throws SQLException If there was a problem creating a new connection. */ public SormSession getTransientSession(final CacheMode cacheMode) throws SQLException { if (_closed) { throw new IllegalStateException(getClass().getSimpleName() + " is closed"); } final SormSession session = makeSession(cacheMode); return session; } /** * Closes all pooled database connections. Threaded connections are not * touched, as we cannot access them. */ public void close() { synchronized (this) { if (!_closed) { _closed = true; synchronized (_sessions) { LOG .info("Closing " + _sessions.size() + " per-thread sessions due to " + getClass().getSimpleName() + " close"); final Iterator<SormSession> itSessions = _sessions.values().iterator(); while (itSessions.hasNext()) { final SormSession session = itSessions.next(); itSessions.remove(); try { session.close(); } catch (final SQLException sqle) { // Ignore it } } } } } } /** * Construct a new connection to the database and return a * {@link SormSession} wrapped around it. * * @param cacheMode The cache mode. * @return A new {@link SormSession}. * @throws SQLException If there was a problem connecting to the database. */ private SormSession makeSession(final CacheMode cacheMode) throws SQLException { final Connection connection; if (null == _user || null == _passwd) { connection = DriverManager.getConnection(getDialect().getProtocol() + _server); } else { connection = DriverManager.getConnection(getDialect().getProtocol() + _server, _user, _passwd); } final SormSession session = new SormSession(connection, getDialect().getName(), cacheMode); return session; } }
package com.akiban.cserver.store; import static com.akiban.cserver.store.RowCollector.SCAN_FLAGS_DEEP; import static com.akiban.cserver.store.RowCollector.SCAN_FLAGS_END_AT_EDGE; import static com.akiban.cserver.store.RowCollector.SCAN_FLAGS_START_AT_EDGE; import java.nio.ByteBuffer; import java.util.*; import com.akiban.ais.model.*; import com.akiban.cserver.api.dml.ColumnSelector; import com.akiban.cserver.api.dml.scan.LegacyRowWrapper; import com.akiban.cserver.api.dml.scan.NewRow; import com.akiban.cserver.api.dml.scan.NiceRow; import com.persistit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.akiban.cserver.CServerConstants; import com.akiban.cserver.CServerUtil; import com.akiban.cserver.FieldDef; import com.akiban.cserver.IndexDef; import com.akiban.cserver.InvalidOperationException; import com.akiban.cserver.RowData; import com.akiban.cserver.RowDef; import com.akiban.cserver.RowDefCache; import com.akiban.cserver.RowType; import com.akiban.cserver.TableStatistics; import com.akiban.cserver.TableStatus; import com.akiban.cserver.message.ScanRowsRequest; import com.akiban.cserver.service.ServiceManagerImpl; import com.akiban.cserver.service.session.Session; import com.akiban.cserver.service.tree.TreeService; import com.akiban.message.ErrorCode; import com.akiban.util.Tap; import com.persistit.Management.DisplayFilter; import com.persistit.Transaction.CommitListener; import com.persistit.exception.PersistitException; import com.persistit.exception.RollbackException; import com.persistit.exception.TransactionFailedException; public class PersistitStore implements CServerConstants, Store { final static int INITIAL_BUFFER_SIZE = 1024; private static final Logger LOG = LoggerFactory.getLogger(PersistitStore.class .getName()); private static final Tap WRITE_ROW_TAP = Tap.add(new Tap.PerThread( "write: write_row")); private static final Tap UPDATE_ROW_TAP = Tap.add(new Tap.PerThread( "write: update_row")); private static final Tap DELETE_ROW_TAP = Tap.add(new Tap.PerThread( "write: delete_row")); private static final Tap TX_COMMIT_TAP = Tap.add(new Tap.PerThread( "write: tx_commit")); private static final Tap TX_RETRY_TAP = Tap.add(new Tap.PerThread( "write: tx_retry", Tap.Count.class)); private static final Tap NEW_COLLECTOR_TAP = Tap.add(new Tap.PerThread( "read: new_collector")); static final int MAX_TRANSACTION_RETRY_COUNT = 10; private final static int MEGA = 1024 * 1024; private final static int MAX_ROW_SIZE = 5000000; private final static int MAX_INDEX_TRANCHE_SIZE = 10 * MEGA; private final static int KEY_STATE_SIZE_OVERHEAD = 50; private final static byte[] EMPTY_BYTE_ARRAY = new byte[0]; private boolean verbose = false; private boolean deferIndexes = false; RowDefCache rowDefCache; TreeService treeService; private SchemaManager schemaManager; private DisplayFilter originalDisplayFilter; private PersistitStoreIndexManager indexManager; private boolean forceToDisk = false; // default to "group commit" private List<CommittedUpdateListener> updateListeners = Collections .synchronizedList(new ArrayList<CommittedUpdateListener>()); private final Map<Tree, SortedSet<KeyState>> deferredIndexKeys = new HashMap<Tree, SortedSet<KeyState>>(); private int deferredIndexKeyLimit = MAX_INDEX_TRANCHE_SIZE; public synchronized void start() throws Exception { treeService = ServiceManagerImpl.get().getTreeService(); schemaManager = ServiceManagerImpl.get().getSchemaManager(); indexManager = new PersistitStoreIndexManager(this); rowDefCache = new RowDefCache(); originalDisplayFilter = getDb().getManagement().getDisplayFilter(); getDb().getManagement().setDisplayFilter( new RowDataDisplayFilter(this, treeService, originalDisplayFilter)); } public synchronized void stop() throws Exception { indexManager.shutDown(); indexManager = null; getDb().getManagement().setDisplayFilter(originalDisplayFilter); } @Override public Store cast() { return this; } @Override public Class<Store> castClass() { return Store.class; } public Persistit getDb() { return treeService.getDb(); } public Exchange getExchange(final Session session, final RowDef rowDef, final IndexDef indexDef) throws PersistitException { if (indexDef == null) { final RowDef groupRowDef = rowDef.isGroupTable() ? rowDef : rowDefCache.getRowDef(rowDef.getGroupRowDefId()); return treeService.getExchange(session, groupRowDef); } else { return treeService.getExchange(session, indexDef); } } public void releaseExchange(final Session session, final Exchange exchange) { treeService.releaseExchange(session, exchange); } // Given a RowData for a table, construct an hkey for a row in the table. // For a table that does not contain its own hkey, this method uses the parent join // columns as needed to find the hkey of the parent table. void constructHKey(Session session, Exchange hEx, RowDef rowDef, RowData rowData, boolean insertingRow) throws PersistitException, InvalidOperationException { // Initialize the hkey being constructed Key hKey = hEx.getKey(); hKey.clear(); // Metadata for the row's table UserTable table = rowDef.userTable(); FieldDef[] fieldDefs = rowDef.getFieldDefs(); // Metadata and other state for the parent table RowDef parentRowDef = null; if (rowDef.getParentRowDefId() != 0) { parentRowDef = rowDefCache.getRowDef(rowDef.getParentRowDefId()); } IndexDef.I2H[] indexToHKey = null; int i2hPosition = 0; Exchange parentPKExchange = null; boolean parentExists = false; // Nested loop over hkey metadata: All the segments of an hkey, and all the columns of a segment. List<HKeySegment> hKeySegments = table.hKey().segments(); int s = 0; while (s < hKeySegments.size()) { HKeySegment hKeySegment = hKeySegments.get(s++); // Write the ordinal for this segment RowDef segmentRowDef = rowDefCache.getRowDef(hKeySegment.table().getTableId()); hKey.append(segmentRowDef.getOrdinal()); // Iterate over the segment's columns List<HKeyColumn> hKeyColumns = hKeySegment.columns(); int c = 0; while (c < hKeyColumns.size()) { HKeyColumn hKeyColumn = hKeyColumns.get(c++); UserTable hKeyColumnTable = hKeyColumn.column().getUserTable(); if (hKeyColumnTable != table) { // Hkey column from row of parent table if (parentPKExchange == null) { // Initialize parent metadata and state assert parentRowDef != null : rowDef; IndexDef parentPK = parentRowDef.getPKIndexDef(); indexToHKey = parentPK.hkeyFields(); parentPKExchange = getExchange(session, rowDef, parentPK); constructParentPKIndexKey(parentPKExchange.getKey(), rowDef, rowData); parentExists = parentPKExchange.hasChildren(); if (parentExists) { boolean hasNext = parentPKExchange.next(true); assert hasNext : rowData; } // parent does not necessarily exist. rowData could be an orphan } IndexDef.I2H i2h = indexToHKey[i2hPosition++]; if (i2h.isOrdinalType()) { assert i2h.ordinal() == segmentRowDef.getOrdinal() : hKeyColumn; i2h = indexToHKey[i2hPosition++]; } if (parentExists) { appendKeyFieldFromKey(parentPKExchange.getKey(), hKey, i2h.indexKeyLoc()); } else { // orphan row hKey.append(null); } } else { // Hkey column from rowData Column column = hKeyColumn.column(); FieldDef fieldDef = fieldDefs[column.getPosition()]; if (insertingRow && column.isAkibanPKColumn()) { // Must be a PK-less table. Use unique id from TableStatus. TableStatus tableStatus = segmentRowDef.getTableStatus(); long rowId = tableStatus.newUniqueId(); hKey.append(rowId); // Write rowId into the value part of the row also. rowData.updateNonNullLong(fieldDef, rowId); } else { appendKeyField(hKey, fieldDef, rowData); } } } } if (parentPKExchange != null) { releaseExchange(session, parentPKExchange); } } void constructHKey(Exchange hEx, RowDef rowDef, int[] ordinals, int[] nKeyColumns, FieldDef[] hKeyFieldDefs, Object[] hKeyValues) throws Exception { final Key hkey = hEx.getKey(); hkey.clear(); int k = 0; for (int i = 0; i < ordinals.length; i++) { hkey.append(ordinals[i]); for (int j = 0; j < nKeyColumns[i]; j++) { FieldDef fieldDef = hKeyFieldDefs[k]; if (fieldDef.isPKLessTableCounter()) { // TODO: Maintain a counter elsewhere, maybe in the // FieldDef. At the end of the bulk load, // TODO: assign the counter to TableStatus. TableStatus tableStatus = fieldDef.getRowDef() .getTableStatus(); hkey.append(tableStatus.newUniqueId()); } else { appendKeyField(hkey, fieldDef, hKeyValues[k]); } k++; } } } /** * Given a RowData, the hkey where it will be stored, and an IndexDef for a * table, construct the index key. * * @param rowData * @param indexDef */ void constructIndexKey(Key iKey, RowData rowData, IndexDef indexDef, Key hKey) throws PersistitException { IndexDef.H2I[] fassoc = indexDef.indexKeyFields(); iKey.clear(); for (int index = 0; index < fassoc.length; index++) { IndexDef.H2I assoc = fassoc[index]; if (assoc.fieldIndex() >= 0) { int fieldIndex = assoc.fieldIndex(); RowDef rowDef = indexDef.getRowDef(); appendKeyField(iKey, rowDef.getFieldDef(fieldIndex), rowData); } else if (assoc.hKeyLoc() >= 0) { appendKeyFieldFromKey(hKey, iKey, assoc.hKeyLoc()); } else { throw new IllegalStateException("Invalid FA"); } } } /** * Given an index key and an indexDef, construct the corresponding hkey for * the row identified by the index key. * * @param hKey * @param indexKey * @param indexDef */ void constructHKeyFromIndexKey(final Key hKey, final Key indexKey, final IndexDef indexDef) { final IndexDef.I2H[] fassoc = indexDef.hkeyFields(); hKey.clear(); for (int index = 0; index < fassoc.length; index++) { final IndexDef.I2H fa = fassoc[index]; if (fa.isOrdinalType()) { hKey.append(fa.ordinal()); } else { final int depth = fassoc[index].indexKeyLoc(); if (depth < 0 || depth > indexKey.getDepth()) { throw new IllegalStateException( "IndexKey too shallow - requires depth=" + depth + ": " + indexKey); } appendKeyFieldFromKey(indexKey, hKey, fa.indexKeyLoc()); } } } /** * Given an indexDef, construct the corresponding hkey containing nulls. * * @param hKey * @param indexDef */ void constructHKeyFromNullIndexKey(final Key hKey, final IndexDef indexDef) { final IndexDef.I2H[] fassoc = indexDef.hkeyFields(); hKey.clear(); for (int index = 0; index < fassoc.length; index++) { final IndexDef.I2H fa = fassoc[index]; if (fa.isOrdinalType()) { hKey.append(fa.ordinal()); } else { hKey.append(null); } } } /** * Given a RowData for a table, construct an Exchange set up with a Key that * is the prefix of the parent's primary key index key. * * @param rowData */ void constructParentPKIndexKey(final Key iKey, final RowDef rowDef, final RowData rowData) { iKey.clear(); appendKeyFields(iKey, rowDef, rowData, rowDef.getParentJoinFields()); } void appendKeyFields(final Key key, final RowDef rowDef, final RowData rowData, final int[] fields) { for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { final FieldDef fieldDef = rowDef.getFieldDef(fields[fieldIndex]); appendKeyField(key, fieldDef, rowData); } } void appendKeyField(final Key key, final FieldDef fieldDef, final RowData rowData) { fieldDef.getEncoding().toKey(fieldDef, rowData, key); } private void appendKeyFieldFromKey(final Key fromKey, final Key toKey, final int depth) { fromKey.indexTo(depth); int from = fromKey.getIndex(); fromKey.indexTo(depth + 1); int to = fromKey.getIndex(); if (from >= 0 && to >= 0 && to > from) { System.arraycopy(fromKey.getEncodedBytes(), from, toKey.getEncodedBytes(), toKey.getEncodedSize(), to - from); toKey.setEncodedSize(toKey.getEncodedSize() + to - from); } } private void appendKeyField(final Key key, final FieldDef fieldDef, Object value) { fieldDef.getEncoding().toKey(fieldDef, value, key); } @Override public RowDefCache getRowDefCache() { return rowDefCache; } private static <T> T errorIfNull(String description, T object) { if (object == null) { throw new NullPointerException(description + " is null; did you call startUp()?"); } return object; } public IndexManager getIndexManager() { return errorIfNull("index manager", indexManager); } @Override public void setVerbose(final boolean verbose) { this.verbose = verbose; } @Override public boolean isVerbose() { return verbose; } /** * WRites a row * * @param rowData * the row data * @throws InvalidOperationException * if the given table is unknown or deleted; or if there's a * duplicate key error */ @Override public void writeRow(final Session session, final RowData rowData) throws InvalidOperationException, PersistitException { final int rowDefId = rowData.getRowDefId(); if (rowData.getRowSize() > MAX_ROW_SIZE) { if (LOG.isWarnEnabled()) { LOG.warn("RowData size " + rowData.getRowSize() + " is larger than current limit of " + MAX_ROW_SIZE + " bytes"); } } WRITE_ROW_TAP.in(); final RowDef rowDef = rowDefCache.getRowDef(rowDefId); Transaction transaction = null; Exchange hEx = null; try { hEx = getExchange(session, rowDef, null); transaction = treeService.getTransaction(session); int retries = MAX_TRANSACTION_RETRY_COUNT; for (;;) { transaction.begin(); try { final TableStatus ts = rowDef.getTableStatus(); // Does the heavy lifting of looking up the full hkey in // parent's primary index if necessary. constructHKey(session, hEx, rowDef, rowData, true); if (hEx.isValueDefined()) { complainAboutDuplicateKey("PRIMARY", hEx.getKey()); } packRowData(hEx, rowDef, rowData); // Store the h-row hEx.store(); if (ts.isAutoIncrement()) { final long location = rowDef.fieldLocation(rowData, rowDef.getAutoIncrementField()); if (location != 0) { final long autoIncrementValue = rowData .getIntegerValue((int) location, (int) (location >>> 32)); if (autoIncrementValue > ts.getAutoIncrementValue()) { ts.setAutoIncrementValue(autoIncrementValue); } } } ts.incrementRowCount(1); ts.written(); for (final IndexDef indexDef : rowDef.getIndexDefs()) { // Insert the index keys (except for the case of a // root table's PK index.) if (!indexDef.isHKeyEquivalent()) insertIntoIndex(session, indexDef, rowData, hEx.getKey(), deferIndexes); } // The row being inserted might be the parent of orphan rows already present. The hkeys of these // orphan rows need to be maintained. The hkeys of interest contain the PK from the inserted row, // and nulls for other hkey fields nearer the root. // TODO: optimizations // - If we knew that no descendent table had an orphan (e.g. store this info in TableStatus), // then this propagation could be skipped. hEx.clear(); Key hKey = hEx.getKey(); UserTable table = rowDef.userTable(); // LOG.error(String.format("table: %s, hKey: %s", table, table.hKey())); List<Column> pkColumns = table.getPrimaryKeyIncludingInternal().getColumns(); List<HKeySegment> hKeySegments = table.hKey().segments(); int s = 0; while (s < hKeySegments.size()) { HKeySegment segment = hKeySegments.get(s++); // LOG.error(String.format("segment: %s", segment)); RowDef segmentRowDef = rowDefCache.getRowDef(segment.table().getTableId()); // LOG.error(String.format("segmentRowDef: %s", segmentRowDef)); hKey.append(segmentRowDef.getOrdinal()); List<HKeyColumn> hKeyColumns = segment.columns(); int c = 0; while (c < hKeyColumns.size()) { HKeyColumn hKeyColumn = hKeyColumns.get(c++); // LOG.error(String.format("segment column: %s", hKeyColumn)); Column column = hKeyColumn.column(); RowDef columnTableRowDef = rowDefCache.getRowDef(column.getTable().getTableId()); if (pkColumns.contains(column)) { // LOG.error(String.format("Appending pk column %s, position %s, field def: %s", // column, column.getPosition(), columnTableRowDef.getFieldDef(column.getPosition()))); appendKeyField(hKey, columnTableRowDef.getFieldDef(column.getPosition()), rowData); } else { hKey.append(null); } // LOG.error(String.format("Orphan hkey prefix: %s", hKey)); } } propagateDownGroup(session, hEx); TX_COMMIT_TAP.in(); if (updateListeners.isEmpty()) { transaction.commit(forceToDisk); } else { final KeyState keyState = new KeyState(hEx.getKey()); transaction.commit(new CommitListener() { public void committed() { for (final CommittedUpdateListener cul : updateListeners) { cul.inserted(keyState, rowDef, rowData); } } }, forceToDisk); } break; } catch (RollbackException re) { TX_RETRY_TAP.out(); if (--retries < 0) { throw new TransactionFailedException(); } } finally { TX_COMMIT_TAP.out(); transaction.end(); } } if (deferredIndexKeyLimit <= 0) { putAllDeferredIndexKeys(session); } return; } finally { releaseExchange(session, hEx); WRITE_ROW_TAP.out(); } } private void complainAboutDuplicateKey(String indexName, Key hkey) throws InvalidOperationException { throw new InvalidOperationException( ErrorCode.DUPLICATE_KEY, "Non-unique key for index %s: %s", indexName, hkey); } @Override public void writeRowForBulkLoad(final Session session, Exchange hEx, RowDef rowDef, RowData rowData, int[] ordinals, int[] nKeyColumns, FieldDef[] hKeyFieldDefs, Object[] hKeyValues) throws Exception { /* * if (verbose && LOG.isInfoEnabled()) { LOG.info("BulkLoad writeRow: " * + rowData.toString(rowDefCache)); } */ constructHKey(hEx, rowDef, ordinals, nKeyColumns, hKeyFieldDefs, hKeyValues); packRowData(hEx, rowDef, rowData); // Store the h-row hEx.store(); /* * for (final IndexDef indexDef : rowDef.getIndexDefs()) { // Insert the * index keys (except for the case of a // root table's PK index.) if * (!indexDef.isHKeyEquivalent()) { insertIntoIndex(indexDef, rowData, * hEx.getKey(), deferIndexes); } } if (deferredIndexKeyLimit <= 0) { * putAllDeferredIndexKeys(); } */ return; } // TODO - remove - this is used only by the PersistitStoreAdapter in // bulk loader. @Override public void updateTableStats(final Session session, RowDef rowDef, long rowCount) throws Exception { schemaManager.saveTableStatusRecords(session); } @Override public void deleteRow(final Session session, final RowData rowData) throws InvalidOperationException, PersistitException { DELETE_ROW_TAP.in(); final int rowDefId = rowData.getRowDefId(); final RowDef rowDef = rowDefCache.getRowDef(rowDefId); Exchange hEx = null; try { hEx = getExchange(session, rowDef, null); final Transaction transaction = treeService.getTransaction(session); int retries = MAX_TRANSACTION_RETRY_COUNT; for (;;) { transaction.begin(); try { final TableStatus ts = rowDef.getTableStatus(); constructHKey(session, hEx, rowDef, rowData, false); hEx.fetch(); // Verify that the row exists if (!hEx.getValue().isDefined()) { throw new InvalidOperationException( ErrorCode.NO_SUCH_RECORD, "Missing record at key: %s", hEx.getKey()); } // Verify that the row hasn't changed. Note: at some point // we may want to optimize the protocol to send only PK and // FK fields in oldRowData, in which case this test will // need to change. // TODO - review. With covering indexes, that day has come. // We can no longer do this comparison when the "old" row // has only its PK fields. // final int oldStart = rowData.getInnerStart(); // final int oldSize = rowData.getInnerSize(); // if (!bytesEqual(rowData.getBytes(), oldStart, oldSize, // hEx // .getValue().getEncodedBytes(), 0, hEx.getValue() // .getEncodedSize())) { // throw new StoreException(HA_ERR_RECORD_CHANGED, // "Record changed at key " + hEx.getKey()); // Remove the h-row hEx.remove(); ts.incrementRowCount(-1); ts.deleted(); // Remove the indexes, including the PK index for (final IndexDef indexDef : rowDef.getIndexDefs()) { if (!indexDef.isHKeyEquivalent()) { deleteIndex(session, indexDef, rowDef, rowData, hEx.getKey()); } } // The row being deleted might be the parent of rows that now become orphans. The hkeys // of these rows need to be maintained. propagateDownGroup(session, hEx); if (updateListeners.isEmpty()) { transaction.commit(forceToDisk); } else { final KeyState keyState = new KeyState(hEx.getKey()); transaction.commit(new CommitListener() { public void committed() { for (final CommittedUpdateListener cul : updateListeners) { cul.deleted(keyState, rowDef, rowData); } } }, forceToDisk); } return; } catch (RollbackException re) { if (--retries < 0) { throw new TransactionFailedException(); } } finally { transaction.end(); } } } finally { releaseExchange(session, hEx); DELETE_ROW_TAP.out(); } } @Override public void updateRow(final Session session, final RowData oldRowData, final RowData newRowData, final ColumnSelector columnSelector) throws InvalidOperationException, PersistitException { final int rowDefId = oldRowData.getRowDefId(); if (newRowData.getRowDefId() != rowDefId) { throw new IllegalArgumentException( "RowData values have different rowDefId values: (" + rowDefId + "," + newRowData.getRowDefId() + ")"); } UPDATE_ROW_TAP.in(); final RowDef rowDef = rowDefCache.getRowDef(rowDefId); Exchange hEx = null; try { hEx = getExchange(session, rowDef, null); final Transaction transaction = treeService.getTransaction(session); int retries = MAX_TRANSACTION_RETRY_COUNT; for (;;) { transaction.begin(); try { final TableStatus ts = rowDef.getTableStatus(); constructHKey(session, hEx, rowDef, oldRowData, false); Key hKey = hEx.getKey(); hEx.fetch(); // Verify that the row exists if (!hEx.getValue().isDefined()) { throw new InvalidOperationException( ErrorCode.NO_SUCH_RECORD, "Missing record at key: %s", hEx.getKey()); } // Combine current version of row with the version coming in on the update request. // This is done by taking only the values of columns listed in the column selector. RowData currentRow = new RowData(EMPTY_BYTE_ARRAY); expandRowData(hEx, rowDef, currentRow); final RowData mergedRowData = columnSelector == null ? newRowData : mergeRows(rowDef, currentRow, newRowData, columnSelector); // Verify that it hasn't changed. Note: at some point we // may want to optimize the protocol to send only PK and FK // fields in oldRowData, in which case this test will need // to change. if (!fieldsEqual(rowDef, oldRowData, mergedRowData, rowDef.getPKIndexDef().getFields()) || !fieldsEqual(rowDef, oldRowData, mergedRowData, rowDef.getParentJoinFields())) { deleteRow(session, oldRowData); writeRow(session, mergedRowData); } else { packRowData(hEx, rowDef, mergedRowData); // Store the h-row hEx.store(); ts.updated(); // Update the indexes for (final IndexDef indexDef : rowDef.getIndexDefs()) { if (!indexDef.isHKeyEquivalent()) { updateIndex(session, indexDef, rowDef, oldRowData, mergedRowData, hEx.getKey()); } } } if (updateListeners.isEmpty()) { transaction.commit(forceToDisk); } else { final KeyState keyState = new KeyState(hEx.getKey()); transaction.commit(new CommitListener() { public void committed() { for (final CommittedUpdateListener cul : updateListeners) { cul.updated(keyState, rowDef, oldRowData, mergedRowData); } } }, forceToDisk); } return; } catch (RollbackException re) { if (--retries < 0) { throw new TransactionFailedException(); } } finally { transaction.end(); } } } finally { releaseExchange(session, hEx); UPDATE_ROW_TAP.out(); } } private void propagateDownGroup(Session session, Exchange exchange) throws PersistitException, InvalidOperationException { // exchange is positioned at a row R that has just been replaced by R', (because we're processing an update // that has to be implemented as delete/insert). hKey is the hkey of R. The replacement, R', is already present. // For each descendent* D of R, this method deletes and reinserts D. Reinsertion of D causes its hkey to be // recomputed. This may depend on an ancestor being updated (if part of D's hkey comes from the parent's // PK index). That's OK because updates are processed preorder, (i.e., ancestors before descendents). // This method will modify the state of exchange. // * D is a descendent of R means that D is below R in the group. I.e., hkey(R) is a prefix of hkey(D). // TODO: Optimizations // - Don't have to visit children that contain their own hkey // - Don't have to visit children whose hkey contains no changed column Key hKey = exchange.getKey(); KeyFilter filter = new KeyFilter(hKey, hKey.getDepth() + 1, Integer.MAX_VALUE); while (exchange.next(filter)) { Value value = exchange.getValue(); int descendentRowDefId = CServerUtil.getInt(value.getEncodedBytes(), RowData.O_ROW_DEF_ID - RowData.LEFT_ENVELOPE_SIZE); RowData descendentRowData = new RowData(EMPTY_BYTE_ARRAY); RowDef descendentRowDef = rowDefCache.getRowDef(descendentRowDefId); expandRowData(exchange, descendentRowDef, descendentRowData); // Delete the current row from the tree exchange.remove(); // ... and from the indexes for (IndexDef indexDef : descendentRowDef.getIndexDefs()) { if (!indexDef.isHKeyEquivalent()) { deleteIndex(session, indexDef, descendentRowDef, descendentRowData, exchange.getKey()); } } // Reinsert it, recomputing the hkey writeRow(session, descendentRowData); } } /** * Remove contents of entire group containing the specified table. TODO: * remove user table data from within a group. */ @Override public void truncateTable(final Session session, final int rowDefId) throws PersistitException, InvalidOperationException { final RowDef rowDef = rowDefCache.getRowDef(rowDefId); Transaction transaction = null; RowDef groupRowDef = rowDef.isGroupTable() ? rowDef : rowDefCache .getRowDef(rowDef.getGroupRowDefId()); transaction = treeService.getTransaction(session); int retries = MAX_TRANSACTION_RETRY_COUNT; for (;;) { transaction.begin(); try { // Remove the index trees for (final IndexDef indexDef : groupRowDef.getIndexDefs()) { if (!indexDef.isHKeyEquivalent()) { final Exchange iEx = getExchange(session, groupRowDef, indexDef); iEx.removeAll(); releaseExchange(session, iEx); } indexManager.deleteIndexAnalysis(session, indexDef); } for (final RowDef userRowDef : groupRowDef .getUserTableRowDefs()) { for (final IndexDef indexDef : userRowDef.getIndexDefs()) { indexManager.deleteIndexAnalysis(session, indexDef); } } // remove the htable tree final Exchange hEx = getExchange(session, groupRowDef, null); hEx.removeAll(); releaseExchange(session, hEx); for (int i = 0; i < groupRowDef.getUserTableRowDefs().length; i++) { final RowDef childRowDef = groupRowDef .getUserTableRowDefs()[i]; final TableStatus ts1 = childRowDef.getTableStatus(); ts1.setRowCount(0); ts1.deleted(); } final TableStatus ts0 = groupRowDef.getTableStatus(); ts0.setRowCount(0); ts0.deleted(); schemaManager.saveTableStatusRecords(session); transaction.commit(forceToDisk); return; } catch (RollbackException re) { if (--retries < 0) { throw new TransactionFailedException(); } } finally { transaction.end(); } } } // @Override // public long getAutoIncrementValue(final int rowDefId) // throws InvalidOperationException, PersistitException { // final RowDef rowDef = rowDefCache.getRowDef(rowDefId); // final Exchange exchange; // final RowDef groupRowDef = rowDef.isGroupTable() ? rowDef : rowDefCache // .getRowDef(rowDef.getGroupRowDefId()); // final String treeName = groupRowDef.getTreeName(); // switch (rowDef.getRowType()) { // case GROUP: // return -1L; // case ROOT: // exchange = db.getExchange(VOLUME_NAME, treeName, true); // exchange.append(rowDef.getOrdinal()); // break; // case CHILD: // case GRANDCHILD: // exchange = db // .getExchange(VOLUME_NAME, rowDef.getPkTreeName(), true); // break; // default: // throw new AssertionError("MissingCase"); // exchange.getKey().append(Key.AFTER); // boolean found = exchange.previous(); // long value = -1; // if (found) { // final Class<?> clazz = exchange.getKey().indexTo(-1).decodeType(); // if (clazz == Long.class) { // value = exchange.getKey().decodeLong(); // else { // UserTable uTable = // schemaManager.getAis().getUserTable(rowDef.getSchemaName(), // rowDef.getTableName()); // if (uTable != null) { // Column autoIncColumn = uTable.getAutoIncrementColumn(); // if (autoIncColumn != null) { // Long autoIncValue = autoIncColumn.getInitialAutoIncrementValue(); // if (autoIncValue != null) { // value = autoIncValue; // releaseExchange(exchange); // return value; @Override public RowCollector getSavedRowCollector(final Session session, final int tableId) throws InvalidOperationException { final List<RowCollector> list = collectorsForTableId(session, tableId); if (list.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("Nested RowCollector on tableId=" + tableId + " depth=" + (list.size() + 1)); } throw new InvalidOperationException(ErrorCode.CURSOR_IS_FINISHED, "No RowCollector for tableId=%d (depth=%d)", tableId, list.size() + 1); } return list.get(list.size() - 1); } @Override public void addSavedRowCollector(final Session session, final RowCollector rc) { final Integer tableId = rc.getTableId(); final List<RowCollector> list = collectorsForTableId(session, tableId); if (!list.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("Note: Nested RowCollector on tableId=" + tableId + " depth=" + (list.size() + 1)); } assert list.get(list.size() - 1) != rc : "Redundant call"; // This disallows the patch because we agreed not to fix the // bug. However, these changes fix a memory leak, which is // important for robustness. // throw new StoreException(122, "Bug 255 workaround is disabled"); } list.add(rc); } @Override public void removeSavedRowCollector(final Session session, final RowCollector rc) throws InvalidOperationException { final Integer tableId = rc.getTableId(); final List<RowCollector> list = collectorsForTableId(session, tableId); if (list.isEmpty()) { throw new InvalidOperationException(ErrorCode.INTERNAL_ERROR, "Attempt to remove RowCollector from empty list"); } final RowCollector removed = list.remove(list.size() - 1); if (removed != rc) { throw new InvalidOperationException(ErrorCode.INTERNAL_ERROR, "Attempt to remove the wrong RowCollector"); } } private List<RowCollector> collectorsForTableId(final Session session, final int tableId) { Map<Integer, List<RowCollector>> map = session.get("store", "collectors"); if (map == null) { map = new HashMap<Integer, List<RowCollector>>(); session.put("store", "collectors", map); } List<RowCollector> list = map.get(tableId); if (list == null) { list = new ArrayList<RowCollector>(); map.put(tableId, list); } return list; } private final RowDef checkRequest(final Session session, int rowDefId, RowData start, RowData end, int indexId, int scanFlags) throws InvalidOperationException, PersistitException { if (start != null && start.getRowDefId() != rowDefId) { throw new IllegalArgumentException( "Start and end RowData must specify the same rowDefId"); } if (end != null && end.getRowDefId() != rowDefId) { throw new IllegalArgumentException( "Start and end RowData must specify the same rowDefId"); } final RowDef rowDef = rowDefCache.getRowDef(rowDefId); if (rowDef == null) { throw new IllegalArgumentException("No RowDef for rowDefId " + rowDefId); } return rowDef; } public RowCollector newRowCollector(final Session session, ScanRowsRequest request) throws InvalidOperationException, PersistitException { NEW_COLLECTOR_TAP.in(); int rowDefId = request.getTableId(); RowData start = request.getStart(); RowData end = request.getEnd(); int indexId = request.getIndexId(); int scanFlags = request.getScanFlags(); byte[] columnBitMap = request.getColumnBitMap(); final RowDef rowDef = checkRequest(session, rowDefId, start, end, indexId, scanFlags); RowCollector rc = new PersistitStoreRowCollector(session, this, scanFlags, start, end, columnBitMap, rowDef, indexId); NEW_COLLECTOR_TAP.out(); return rc; } @Override public RowCollector newRowCollector(final Session session, final int rowDefId, int indexId, final int scanFlags, RowData start, RowData end, byte[] columnBitMap) throws InvalidOperationException, PersistitException { NEW_COLLECTOR_TAP.in(); final RowDef rowDef = checkRequest(session, rowDefId, start, end, indexId, scanFlags); final RowCollector rc = new PersistitStoreRowCollector(session, this, scanFlags, start, end, columnBitMap, rowDef, indexId); NEW_COLLECTOR_TAP.out(); return rc; } public final static long HACKED_ROW_COUNT = 2; @Override public long getRowCount(final Session session, final boolean exact, final RowData start, final RowData end, final byte[] columnBitMap) throws Exception { // TODO: Compute a reasonable value. The value "2" is a hack - // special because it's not 0 or 1, but small enough to induce // MySQL to use an index rather than full table scan. return HACKED_ROW_COUNT; // TODO: delete the HACKED_ROW_COUNT field when // this gets fixed // final int tableId = start.getRowDefId(); // final TableStatus status = tableManager.getTableStatus(tableId); // return status.getRowCount(); } @Override public TableStatistics getTableStatistics(final Session session, int tableId) throws Exception { final RowDef rowDef = rowDefCache.getRowDef(tableId); final TableStatistics ts = new TableStatistics(tableId); final TableStatus status = rowDef.getTableStatus(); if (rowDef.getRowType() == RowType.GROUP) { ts.setRowCount(2); ts.setAutoIncrementValue(-1); } else { ts.setAutoIncrementValue(status.getAutoIncrementValue()); ts.setRowCount(status.getRowCount()); } ts.setUpdateTime(Math.max(status.getLastUpdateTime(), status.getLastWriteTime())); ts.setCreationTime(status.getCreationTime()); // TODO - get correct values ts.setMeanRecordLength(100); ts.setBlockSize(8192); indexManager.populateTableStatistics(session, ts); return ts; } @Override public void analyzeTable(final Session session, final int tableId) throws Exception { final RowDef rowDef = rowDefCache.getRowDef(tableId); indexManager.analyzeTable(session, rowDef); } // FOR TESTING ONLY @Override public List<RowData> fetchRows(final Session session, final String schemaName, final String tableName, final String columnName, final Object least, final Object greatest, final String leafTableName) throws Exception { final ByteBuffer payload = ByteBuffer.allocate(65536); return fetchRows(session, schemaName, tableName, columnName, least, greatest, leafTableName, payload); } public List<RowData> fetchRows(final Session session, final String schemaName, final String tableName, final String columnName, final Object least, final Object greatest, final String leafTableName, final ByteBuffer payload) throws Exception { final List<RowData> list = new ArrayList<RowData>(); final String compoundName = schemaName + "." + tableName; final RowDef rowDef = rowDefCache.getRowDef(compoundName); if (rowDef == null) { throw new InvalidOperationException(ErrorCode.NO_SUCH_TABLE, compoundName); } final RowDef groupRowDef = rowDef.isGroupTable() ? rowDef : rowDefCache .getRowDef(rowDef.getGroupRowDefId()); final RowDef[] userRowDefs = groupRowDef.getUserTableRowDefs(); FieldDef fieldDef = null; for (final FieldDef fd : rowDef.getFieldDefs()) { if (fd.getName().equals(columnName)) { fieldDef = fd; break; } } if (fieldDef == null) { throw new InvalidOperationException(ErrorCode.NO_SUCH_COLUMN, columnName + " in " + compoundName); } IndexDef indexDef = null; for (final IndexDef id : rowDef.getIndexDefs()) { if (id.getFields()[0] == fieldDef.getFieldIndex()) { indexDef = id; if (indexDef.getFields().length == 1) { break; } } } if (indexDef == null) { throw new InvalidOperationException(ErrorCode.NO_INDEX, "on column " + columnName + " in " + compoundName); } boolean deepMode = false; RowDef leafRowDef = null; if (tableName.equals(leafTableName)) { leafRowDef = rowDef; } else if (leafTableName == null) { leafRowDef = rowDef; deepMode = true; } else for (int index = 0; index < userRowDefs.length; index++) { if (userRowDefs[index].getTableName().equals(leafTableName)) { leafRowDef = userRowDefs[index]; break; } } if (leafRowDef == null) { throw new InvalidOperationException(ErrorCode.NO_SUCH_TABLE, leafTableName + " in group"); } RowData start = null; RowData end = null; int flags = deepMode ? SCAN_FLAGS_DEEP : 0; if (least == null) { flags |= SCAN_FLAGS_START_AT_EDGE; } else { final Object[] startValues = new Object[groupRowDef.getFieldCount()]; startValues[fieldDef.getFieldIndex() + rowDef.getColumnOffset()] = least; start = new RowData(new byte[128]); start.createRow(groupRowDef, startValues); } if (greatest == null) { flags |= SCAN_FLAGS_END_AT_EDGE; } else { final Object[] endValues = new Object[groupRowDef.getFieldCount()]; endValues[fieldDef.getFieldIndex() + rowDef.getColumnOffset()] = greatest; end = new RowData(new byte[128]); end.createRow(groupRowDef, endValues); } final byte[] bitMap = new byte[(7 + groupRowDef.getFieldCount()) / 8]; for (RowDef def = leafRowDef; def != null;) { final int bit = def.getColumnOffset(); final int fc = def.getFieldCount(); for (int i = bit; i < bit + fc; i++) { bitMap[i / 8] |= (1 << (i % 8)); } if (def != rowDef && def.getParentRowDefId() != 0) { def = rowDefCache.getRowDef(def.getParentRowDefId()); } else { break; } } final RowCollector rc = newRowCollector(session, groupRowDef.getRowDefId(), indexDef.getId(), flags, start, end, bitMap); while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); for (int p = payload.position(); p < payload.limit();) { final RowData rowData = new RowData(payload.array(), p, payload.limit()); rowData.prepareRow(p); list.add(rowData); p = rowData.getRowEnd(); } } rc.close(); return list; } void insertIntoIndex(final Session session, final IndexDef indexDef, final RowData rowData, final Key hkey, final boolean deferIndexes) throws InvalidOperationException, PersistitException { final Exchange iEx = getExchange(session, indexDef.getRowDef(), indexDef); constructIndexKey(iEx.getKey(), rowData, indexDef, hkey); final Key key = iEx.getKey(); if (indexDef.isUnique()) { KeyState ks = new KeyState(key); key.setDepth(indexDef.getIndexKeySegmentCount()); if (iEx.hasChildren()) { complainAboutDuplicateKey(indexDef.getName(), key); } ks.copyTo(key); } iEx.getValue().clear(); if (deferIndexes) { synchronized (deferredIndexKeys) { SortedSet<KeyState> keySet = deferredIndexKeys.get(iEx .getTree()); if (keySet == null) { keySet = new TreeSet<KeyState>(); deferredIndexKeys.put(iEx.getTree(), keySet); } final KeyState ks = new KeyState(iEx.getKey()); keySet.add(ks); deferredIndexKeyLimit -= (ks.getBytes().length + KEY_STATE_SIZE_OVERHEAD); } } else { iEx.store(); } releaseExchange(session, iEx); } void putAllDeferredIndexKeys(final Session session) throws PersistitException { synchronized (deferredIndexKeys) { for (final Map.Entry<Tree, SortedSet<KeyState>> entry : deferredIndexKeys .entrySet()) { final Exchange iEx = treeService.getExchange(session, entry.getKey()); buildIndexAddKeys(entry.getValue(), iEx); entry.getValue().clear(); } deferredIndexKeyLimit = MAX_INDEX_TRANCHE_SIZE; } } void updateIndex(final Session session, final IndexDef indexDef, final RowDef rowDef, final RowData oldRowData, final RowData newRowData, final Key hkey) throws PersistitException { if (!fieldsEqual(rowDef, oldRowData, newRowData, indexDef.getFields())) { final Exchange oldExchange = getExchange(session, rowDef, indexDef); constructIndexKey(oldExchange.getKey(), oldRowData, indexDef, hkey); final Exchange newExchange = getExchange(session, rowDef, indexDef); constructIndexKey(newExchange.getKey(), newRowData, indexDef, hkey); oldExchange.getValue().clear(); newExchange.getValue().clear(); oldExchange.remove(); newExchange.store(); releaseExchange(session, newExchange); releaseExchange(session, oldExchange); } } void deleteIndex(final Session session, final IndexDef indexDef, final RowDef rowDef, final RowData rowData, final Key hkey) throws PersistitException { final Exchange iEx = getExchange(session, rowDef, indexDef); constructIndexKey(iEx.getKey(), rowData, indexDef, hkey); boolean removed = iEx.remove(); releaseExchange(session, iEx); } boolean bytesEqual(final byte[] a, final int aoffset, final int asize, final byte[] b, final int boffset, final int bsize) { if (asize != bsize) { return false; } for (int i = 0; i < asize; i++) { if (a[i + aoffset] != b[i + boffset]) { return false; } } return true; } boolean fieldsEqual(final RowDef rowDef, final RowData a, final RowData b, final int[] fieldIndexes) { for (int index = 0; index < fieldIndexes.length; index++) { final int fieldIndex = fieldIndexes[index]; final long aloc = rowDef.fieldLocation(a, fieldIndex); final long bloc = rowDef.fieldLocation(b, fieldIndex); if (!bytesEqual(a.getBytes(), (int) aloc, (int) (aloc >>> 32), b.getBytes(), (int) bloc, (int) (bloc >>> 32))) { return false; } } return true; } public void packRowData(final Exchange hEx, final RowDef rowDef, final RowData rowData) throws PersistitException { final int start = rowData.getInnerStart(); final int size = rowData.getInnerSize(); hEx.getValue().ensureFit(size); System.arraycopy(rowData.getBytes(), start, hEx.getValue() .getEncodedBytes(), 0, size); int storedTableId = treeService.aisToStore(rowDef, rowData.getRowDefId()); CServerUtil.putInt(hEx.getValue().getEncodedBytes(), RowData.O_ROW_DEF_ID - RowData.LEFT_ENVELOPE_SIZE, storedTableId); hEx.getValue().setEncodedSize(size); } public void expandRowData(final Exchange exchange, final RowDef rowDef, final RowData rowData) throws InvalidOperationException, PersistitException { // TODO this needs to be a more specific exception final int size = exchange.getValue().getEncodedSize(); final int rowDataSize = size + RowData.ENVELOPE_SIZE; final byte[] valueBytes = exchange.getValue().getEncodedBytes(); byte[] rowDataBytes = rowData.getBytes(); if (rowDataSize < RowData.MINIMUM_RECORD_LENGTH || rowDataSize > RowData.MAXIMUM_RECORD_LENGTH) { if (LOG.isErrorEnabled()) { LOG.error("Value at " + exchange.getKey() + " is not a valid row - skipping"); } throw new InvalidOperationException(ErrorCode.INTERNAL_CORRUPTION, "Corrupt RowData at " + exchange.getKey()); } int rowDefId = CServerUtil.getInt(valueBytes, RowData.O_ROW_DEF_ID - RowData.LEFT_ENVELOPE_SIZE); rowDefId = treeService.storeToAis(exchange.getVolume(), rowDefId); if (rowDef != null) { final int expectedRowDefId = rowDef.getRowDefId(); if (rowDefId != expectedRowDefId) { // TODO: Add code to here to evolve data to required // expectedRowDefId throw new InvalidOperationException( ErrorCode.MULTIGENERATIONAL_TABLE, "Unable to convert rowDefId " + rowDefId + " to expected rowDefId " + expectedRowDefId); } } if (rowDataSize > rowDataBytes.length) { rowDataBytes = new byte[rowDataSize + INITIAL_BUFFER_SIZE]; rowData.reset(rowDataBytes); } // Assemble the Row in a byte array to allow column // elision CServerUtil.putInt(rowDataBytes, RowData.O_LENGTH_A, rowDataSize); CServerUtil.putChar(rowDataBytes, RowData.O_SIGNATURE_A, RowData.SIGNATURE_A); System.arraycopy(valueBytes, 0, rowDataBytes, RowData.O_FIELD_COUNT, size); CServerUtil.putChar(rowDataBytes, RowData.O_SIGNATURE_B + rowDataSize, RowData.SIGNATURE_B); CServerUtil.putInt(rowDataBytes, RowData.O_LENGTH_B + rowDataSize, rowDataSize); CServerUtil.putInt(rowDataBytes, RowData.O_ROW_DEF_ID, rowDefId); rowData.prepareRow(0); } @Override public void addCommittedUpdateListener(CommittedUpdateListener listener) { updateListeners.add(listener); } @Override public void removeCommittedUpdateListener(CommittedUpdateListener listener) { updateListeners.remove(listener); } public void buildIndexes(final Session session, final String ddl) { flushIndexes(session); final Set<RowDef> userRowDefs = new HashSet<RowDef>(); final Set<RowDef> groupRowDefs = new HashSet<RowDef>(); // Find the groups containing indexes selected for rebuild. for (final RowDef rowDef : rowDefCache.getRowDefs()) { if (!rowDef.isGroupTable()) { for (final IndexDef indexDef : rowDef.getIndexDefs()) { if (isIndexSelected(indexDef, ddl)) { userRowDefs.add(rowDef); final RowDef group = rowDefCache.getRowDef(rowDef .getGroupRowDefId()); if (group != null) { groupRowDefs.add(group); } } } } } for (final RowDef rowDef : groupRowDefs) { final RowData rowData = new RowData(new byte[MAX_ROW_SIZE]); rowData.createRow(rowDef, new Object[0]); final byte[] columnBitMap = new byte[(rowDef.getFieldCount() + 7) / 8]; // Project onto all columns of selected user tables for (final RowDef user : rowDef.getUserTableRowDefs()) { if (userRowDefs.contains(user)) { for (int bit = 0; bit < user.getFieldCount(); bit++) { final int c = bit + user.getColumnOffset(); columnBitMap[c / 8] |= (1 << (c % 8)); } } } int indexKeyCount = 0; try { final PersistitStoreRowCollector rc = (PersistitStoreRowCollector) newRowCollector( session, rowDef.getRowDefId(), 0, 0, rowData, rowData, columnBitMap); // final KeyFilter hFilter = rc.getHFilter(); final Exchange hEx = rc.getHExchange(); hEx.getKey().clear(); // while (hEx.traverse(Key.GT, hFilter, Integer.MAX_VALUE)) { while (hEx.next(true)) { expandRowData(hEx, null, rowData); final int tableId = rowData.getRowDefId(); final RowDef userRowDef = rowDefCache.getRowDef(tableId); if (userRowDefs.contains(userRowDef)) { for (final IndexDef indexDef : userRowDef .getIndexDefs()) { if (isIndexSelected(indexDef, ddl)) { insertIntoIndex(session, indexDef, rowData, hEx.getKey(), true); indexKeyCount++; } } if (deferredIndexKeyLimit <= 0) { putAllDeferredIndexKeys(session); } } } } catch (Exception e) { LOG.error("Exception while trying to index group table " + rowDef.getSchemaName() + "." + rowDef.getTableName(), e); } flushIndexes(session); if (LOG.isInfoEnabled()) { LOG.info("Inserted " + indexKeyCount + " index keys into group " + rowDef.getSchemaName() + "." + rowDef.getTableName()); } } } public void flushIndexes(final Session session) { try { putAllDeferredIndexKeys(session); } catch (Exception e) { LOG.error("Exception while trying " + " to flush deferred index keys", e); } } public void deleteIndexes(final Session session, final String ddl) { for (final RowDef rowDef : rowDefCache.getRowDefs()) { if (!rowDef.isGroupTable()) { for (final IndexDef indexDef : rowDef.getIndexDefs()) { if (isIndexSelected(indexDef, ddl)) { try { final Exchange iEx = getExchange(session, rowDef, indexDef); iEx.removeAll(); } catch (Exception e) { LOG.error( "Exception while trying to remove index tree " + indexDef.getTreeName(), e); } } } } } } private boolean isIndexSelected(final IndexDef indexDef, final String ddl) { return !indexDef.isHKeyEquivalent() && (!ddl.contains("table=") || ddl.contains("table=(" + indexDef.getRowDef().getTableName() + ")")) && (!ddl.contains("index=") || ddl.contains("index=(" + indexDef.getName() + ")")); } private void buildIndexAddKeys(final SortedSet<KeyState> keys, final Exchange iEx) throws PersistitException { final long start = System.nanoTime(); for (final KeyState keyState : keys) { keyState.copyTo(iEx.getKey()); iEx.store(); } final long elapsed = System.nanoTime() - start; if (LOG.isInfoEnabled()) { LOG.info(String.format("Index builder inserted %s keys " + "into index tree %s in %,d seconds", keys.size(), iEx .getTree().getName(), elapsed / 1000000000)); } } private RowData mergeRows(RowDef rowDef, RowData currentRow, RowData newRowData, ColumnSelector columnSelector) { NewRow mergedRow = NiceRow.fromRowData(currentRow, rowDef); NewRow newRow = new LegacyRowWrapper(newRowData); int fields = rowDef.getFieldCount(); for (int i = 0; i < fields; i++) { if (columnSelector.includesColumn(i)) { mergedRow.put(i, newRow.get(i)); } } return mergedRow.toRowData(); } @Override public boolean isDeferIndexes() { return deferIndexes; } @Override public void setDeferIndexes(final boolean defer) { deferIndexes = defer; } public void traverse(Session session, RowDef rowDef, TreeRecordVisitor visitor) throws PersistitException, InvalidOperationException { assert rowDef.isGroupTable() : rowDef; Exchange exchange = getExchange(session, rowDef, null).append(Key.BEFORE); try { visitor.initialize(this, exchange); while (exchange.next(true)) { visitor.visit(); } } finally { releaseExchange(session, exchange); } } public void traverse(Session session, IndexDef indexDef, IndexRecordVisitor visitor) throws PersistitException, InvalidOperationException { Exchange exchange = getExchange(session, null, indexDef).append(Key.BEFORE); try { visitor.initialize(exchange); while (exchange.next(true)) { visitor.visit(); } } finally { releaseExchange(session, exchange); } } }
package naftoreiclag.splendidanimator; import org.lwjgl.Sys; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; public class Application { float x = 400, y = 300; float rotation = 0; long lastFrame; int fps; long lastFPS; public void run() { try { Display.setDisplayMode(new DisplayMode(800, 600)); Display.create(); } catch (Exception e) { System.err.println("Could not create display!"); e.printStackTrace(); System.exit(0); } initGL(); // init OpenGL getDelta(); // call once before loop to initialise lastFrame lastFPS = getTime(); // call before loop to initialise fps timer Display.setResizable(true); while (!Display.isCloseRequested()) { input(); int delta = getDelta(); update(delta); renderGL(); Display.update(); } Display.destroy(); } public void update(int delta) { rotation += 0.15f * delta; if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) x -= 0.35f * delta; if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) x += 0.35f * delta; if (Keyboard.isKeyDown(Keyboard.KEY_UP)) y += 0.35f * delta; if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) y -= 0.35f * delta; if (x < 0) x = 0; if (x > 800) x = 800; if (y < 0) y = 0; if (y > 600) y = 600; updateFPS(); } public int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } public void updateFPS() { if (getTime() - lastFPS > 1000) { Display.setTitle("FPS: " + fps); fps = 0; lastFPS += 1000; } fps ++; } public void initGL() { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0, 800, 0, 600, 1, -1); } public void renderGL() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glColor3f(0.5f, 0.5f, 1.0f); GL11.glPushMatrix(); GL11.glTranslatef(x, y, 0); GL11.glRotatef(rotation, 0f, 0f, 1f); GL11.glTranslatef(-x, -y, 0); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(x - 50, y - 50); GL11.glVertex2f(x + 50, y - 50); GL11.glVertex2f(x + 50, y + 50); GL11.glVertex2f(x - 50, y + 50); GL11.glEnd(); GL11.glPopMatrix(); } public void input() { if (Mouse.isButtonDown(0)) { int x = Mouse.getX(); int y = Mouse.getY(); System.out.println("mouse down x: " + x + " y: " + y); } } public static void main(String[] args) { Application application = new Application(); application.run(); } }
package com.dglapps.simuloc.geocoding; import com.dglapps.simuloc.entities.Address; import com.dglapps.simuloc.entities.AddressLocation; import com.dglapps.simuloc.entities.Position; import java.util.List; public interface Geocoding { AddressLocation addressToPosition(Address address); AddressLocation positionToAddress(Position position); List<AddressLocation> positionToAddresses(Position position); List<AddressLocation> positionToAddresses(Position position, int maxResults); }
package net.fortuna.ical4j.data; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.util.CompatibilityHints; /** * Writes an iCalendar model to an output stream. * @author Ben Fortuna */ public class CalendarOutputter { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private boolean validating; private int foldLength; /** * Default constructor. */ public CalendarOutputter() { this(true); } /** * @param validating indicates whether to validate calendar when outputting to stream */ public CalendarOutputter(final boolean validating) { this(validating, CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY) ? FoldingWriter.MAX_FOLD_LENGTH : FoldingWriter.REDUCED_FOLD_LENGTH); } /** * @param validating indicates whether to validate calendar when outputting to stream * @param foldLength maximum number of characters before a line is folded */ public CalendarOutputter(final boolean validating, final int foldLength) { this.validating = validating; this.foldLength = foldLength; } /** * Outputs an iCalender string to the specified output stream. * @param calendar calendar to write to ouput stream * @param out an output stream * @throws IOException thrown when unable to write to output stream */ public final void output(final Calendar calendar, final OutputStream out) throws IOException, ValidationException { output(calendar, new OutputStreamWriter(out, DEFAULT_CHARSET)); } /** * Outputs an iCalender string to the specified writer. * @param calendar calendar to write to writer * @param out a writer * @throws IOException thrown when unable to write to writer */ public final void output(final Calendar calendar, final Writer out) throws IOException, ValidationException { if (isValidating()) { calendar.validate(); } FoldingWriter writer = new FoldingWriter(out, foldLength); try { writer.write(calendar.toString()); } finally { writer.close(); } } /** * @return Returns the validating. */ public final boolean isValidating() { return validating; } /** * @param validating The validating to set. */ public final void setValidating(final boolean validating) { this.validating = validating; } }
package com.github.ben_lei.dncli; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import com.github.ben_lei.dncli.command.Command; import com.github.ben_lei.dncli.command.CommandDds; import com.github.ben_lei.dncli.command.CommandDnt; import com.github.ben_lei.dncli.command.CommandPak; import com.github.ben_lei.dncli.exception.InvalidDdsOutputFormatException; import java.util.Map; import static java.lang.System.exit; public class CliApplication { public static void main(String[] args) { Command command = new Command(); CommandPak pak = command.getPak(); CommandDnt dnt = command.getDnt(); CommandDds dds = command.getDds(); JCommander jc = new JCommander(command); jc.setProgramName("dncli"); // pak command setup JCommander pakJc = addCommand(jc, "pak", pak); // pak subcommand setup pakJc.addCommand("-c", pak.getCompress(), "--compress"); pakJc.addCommand("-x", pak.getExtract(), "--extract"); pakJc.addCommand("-l", pak.getDetail(), "--list"); // dnt command setup JCommander dntJc = addCommand(jc, "dnt", dnt); //dnt subcommand setup dntJc.addCommand("-q", dnt.getQuery(), "--query"); dntJc.addCommand("-b", dnt.getBuild(), "--build"); // dds command setup jc.addCommand("dds", dds); // parse args and set the params! try { jc.parse(args); } catch (ParameterException | InvalidDdsOutputFormatException e) { System.out.println(e.getMessage()); exit(1); } String parsedCommand = jc.getParsedCommand(); // if no command or help was specified, show it! if (parsedCommand == null || command.isHelp()) { jc.usage(); System.exit(0); } // find out what command is being used try { switch (parsedCommand) { case "pak": switch (pakJc.getParsedCommand()) { case "-c": case "--compress": pak.getCompress().run(); break; case "-x": case "--extract": pak.getExtract().run(); break; case "-l": case "--list": pak.getDetail().run(); break; default: throw new UnsupportedOperationException("Unknown pak command: '" + pakJc.getParsedCommand() + "'"); } break; case "dnt": switch (dntJc.getParsedCommand()) { case "-q": case "--query": dnt.getQuery().run(); break; case "-b": case "--build": dnt.getBuild().run(); break; default: throw new UnsupportedOperationException("Unknown dnt command: '" + dntJc.getParsedCommand() + "'"); } break; case "dds": dds.run(); break; default: throw new UnsupportedOperationException("Unknown command: '" + parsedCommand + "'"); } System.exit(0); } catch (Throwable t) { System.out.println(t.getMessage()); System.out.println(111); System.exit(1); } } private static JCommander addCommand(JCommander jCommander, String name, Object object) { jCommander.addCommand(name, object); Map<String, JCommander> commands = jCommander.getCommands(); return commands.get(name); } }
package net.fortuna.ical4j.model.component; import java.util.Iterator; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.ExRule; import net.fortuna.ical4j.model.property.RDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.PropertyValidator; /** * Defines an iCalendar VEVENT component. * * <pre> * 4.6.1 Event Component * * Component Name: "VEVENT" * * Purpose: Provide a grouping of component properties that describe an * event. * * Format Definition: A "VEVENT" calendar component is defined by the * following notation: * * eventc = "BEGIN" ":" "VEVENT" CRLF * eventprop *alarmc * "END" ":" "VEVENT" CRLF * * eventprop = *( * * ; the following are optional, * ; but MUST NOT occur more than once * * class / created / description / dtstart / geo / * last-mod / location / organizer / priority / * dtstamp / seq / status / summary / transp / * uid / url / recurid / * * ; either 'dtend' or 'duration' may appear in * ; a 'eventprop', but 'dtend' and 'duration' * ; MUST NOT occur in the same 'eventprop' * * dtend / duration / * * ; the following are optional, * ; and MAY occur more than once * * attach / attendee / categories / comment / * contact / exdate / exrule / rstatus / related / * resources / rdate / rrule / x-prop * * ) * </pre> * * Example 1 - Creating a new all-day event: * * <pre><code> * java.util.Calendar cal = java.util.Calendar.getInstance(); * cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); * cal.set(java.util.Calendar.DAY_OF_MONTH, 25); * * VEvent christmas = new VEvent(cal.getTime(), "Christmas Day"); * * // initialise as an all-day event.. * christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE); * * // add timezone information.. * VTimeZone tz = VTimeZone.getDefault(); * TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue()); * christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam); * </code></pre> * * Example 2 - Creating an event of one (1) hour duration: * * <pre><code> * java.util.Calendar cal = java.util.Calendar.getInstance(); * // tomorrow.. * cal.add(java.util.Calendar.DAY_OF_MONTH, 1); * cal.set(java.util.Calendar.HOUR_OF_DAY, 9); * cal.set(java.util.Calendar.MINUTE, 30); * * VEvent meeting = new VEvent(cal.getTime(), 1000 * 60 * 60, "Progress Meeting"); * * // add timezone information.. * VTimeZone tz = VTimeZone.getDefault(); * TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue()); * meeting.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam); * </code></pre> * * Example 3 - Retrieve a list of periods representing a recurring event in a * specified range: * * <pre><code> * Calendar weekday9AM = Calendar.getInstance(); * weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); * weekday9AM.set(Calendar.MILLISECOND, 0); * * Calendar weekday5PM = Calendar.getInstance(); * weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); * weekday5PM.set(Calendar.MILLISECOND, 0); * * // Do the recurrence until December 31st. * Calendar untilCal = Calendar.getInstance(); * untilCal.set(2005, Calendar.DECEMBER, 31); * untilCal.set(Calendar.MILLISECOND, 0); * * // 9:00AM to 5:00PM Rule * Recur recur = new Recur(Recur.WEEKLY, untilCal.getTime()); * recur.getDayList().add(WeekDay.MO); * recur.getDayList().add(WeekDay.TU); * recur.getDayList().add(WeekDay.WE); * recur.getDayList().add(WeekDay.TH); * recur.getDayList().add(WeekDay.FR); * recur.setInterval(3); * recur.setWeekStartDay(WeekDay.MO.getDay()); * RRule rrule = new RRule(recur); * * Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI"); * * weekdayNineToFiveEvents = new VEvent(); * weekdayNineToFiveEvents.getProperties().add(rrule); * weekdayNineToFiveEvents.getProperties().add(summary); * weekdayNineToFiveEvents.getProperties().add( * new DtStart(weekday9AM.getTime())); * weekdayNineToFiveEvents.getProperties().add( * new DtEnd(weekday5PM.getTime())); * * // Test Start 04/01/2005, End One month later. * // Query Calendar Start and End Dates. * Calendar queryStartDate = Calendar.getInstance(); * queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); * queryStartDate.set(Calendar.MILLISECOND, 0); * Calendar queryEndDate = Calendar.getInstance(); * queryEndDate.set(2005, Calendar.MAY, 1, 11, 15, 0); * queryEndDate.set(Calendar.MILLISECOND, 0); * * // This range is monday to friday every three weeks, starting from * // March 7th 2005, which means for our query dates we need * // April 18th through to the 22nd. * PeriodList periods = * weekdayNineToFiveEvents.getPeriods(queryStartDate.getTime(), * queryEndDate.getTime()); * </code></pre> * * @author Ben Fortuna */ public class VEvent extends Component { private static final long serialVersionUID = 2547948989200697335L; private ComponentList alarms; /** * Default constructor. */ public VEvent() { super(VEVENT); this.alarms = new ComponentList(); } /** * Constructor. * * @param properties * a list of properties */ public VEvent(final PropertyList properties) { super(VEVENT, properties); this.alarms = new ComponentList(); } /** * Constructor. * * @param properties * a list of properties * @param alarms * a list of alarms */ public VEvent(final PropertyList properties, final ComponentList alarms) { super(VEVENT, properties); this.alarms = alarms; } /** * Constructs a new VEVENT instance starting at the specified * time with the specified summary. * @param start the start date of the new event * @param summary the event summary */ public VEvent(final Date start, final String summary) { this(); getProperties().add(new DtStamp(new DateTime())); getProperties().add(new DtStart(start)); getProperties().add(new Summary(summary)); } /** * Constructs a new VEVENT instance starting and ending at the specified * times with the specified summary. * @param start the start date of the new event * @param end the end date of the new event * @param summary the event summary */ public VEvent(final Date start, final Date end, final String summary) { this(); getProperties().add(new DtStamp(new DateTime())); getProperties().add(new DtStart(start)); getProperties().add(new DtEnd(end)); getProperties().add(new Summary(summary)); } /** * Constructs a new VEVENT instance starting at the specified * times, for the specified duration, with the specified summary. * @param start the start date of the new event * @param duration the duration of the new event * @param summary the event summary */ public VEvent(final Date start, final Dur duration, final String summary) { this(); getProperties().add(new DtStamp(new DateTime())); getProperties().add(new DtStart(start)); getProperties().add(new Duration(duration)); getProperties().add(new Summary(summary)); } /** * Returns the list of alarms for this event. * @return a component list */ public final ComponentList getAlarms() { return alarms; } /** * @see java.lang.Object#toString() */ public final String toString() { return BEGIN + ":" + getName() + "\r\n" + getProperties() + getAlarms() + END + ":" + getName() + "\r\n"; } /** * @see net.fortuna.ical4j.model.Component#validate(boolean) */ public final void validate(final boolean recurse) throws ValidationException { // validate that getAlarms() only contains VAlarm components Iterator iterator = getAlarms().iterator(); while (iterator.hasNext()) { Component component = (Component) iterator.next(); if (!(component instanceof VAlarm)) { throw new ValidationException( "Component [" + component.getName() + "] may not occur in VEVENT"); } } /* * ; the following are optional, ; but MUST NOT occur more than once * * class / created / description / dtstart / geo / last-mod / location / * organizer / priority / dtstamp / seq / status / summary / transp / * uid / url / recurid / */ PropertyValidator.getInstance().assertOneOrLess(Property.CLASS, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.CREATED, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DESCRIPTION, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DTSTART, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.GEO, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.LAST_MODIFIED, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.LOCATION, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.ORGANIZER, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.PRIORITY, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DTSTAMP, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.SEQUENCE, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.STATUS, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.SUMMARY, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.TRANSP, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.UID, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.RECURRENCE_ID, getProperties()); Status status = (Status) getProperty(Property.STATUS); if (status != null && !Status.VEVENT_TENTATIVE.equals(status) && !Status.VEVENT_CONFIRMED.equals(status) && !Status.VEVENT_CANCELLED.equals(status)) { throw new ValidationException( "Status property [" + status.toString() + "] is not applicable for VEVENT"); } /* * ; either 'dtend' or 'duration' may appear in ; a 'eventprop', but * 'dtend' and 'duration' ; MUST NOT occur in the same 'eventprop' * * dtend / duration / */ try { PropertyValidator.getInstance().assertNone(Property.DTEND, getProperties()); } catch (ValidationException ve) { PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties()); } if (getProperty(Property.DTEND) != null) { /* * The "VEVENT" is also the calendar component used to specify an * anniversary or daily reminder within a calendar. These events have a * DATE value type for the "DTSTART" property instead of the default * data type of DATE-TIME. If such a "VEVENT" has a "DTEND" property, it * MUST be specified as a DATE value also. The anniversary type of * "VEVENT" can span more than one date (i.e, "DTEND" property value is * set to a calendar date after the "DTSTART" property value). */ DtStart start = (DtStart) getProperty(Property.DTSTART); DtEnd end = (DtEnd) getProperty(Property.DTEND); if (start != null) { Parameter value = start.getParameter(Parameter.VALUE); if (value != null && !value.equals(end.getParameter(Parameter.VALUE))) { throw new ValidationException("Property [" + Property.DTEND + "] must have the same [" + Parameter.VALUE + "] as [" + Property.DTSTART + "]"); } } } /* * ; the following are optional, ; and MAY occur more than once * * attach / attendee / categories / comment / contact / exdate / exrule / * rstatus / related / resources / rdate / rrule / x-prop */ if (recurse) { validateProperties(); } } /** * Returns a normalised list of periods representing the consumed time for this * event. * @param rangeStart * @param rangeEnd * @return a normalised list of periods representing consumed time for this event * @see VEvent#getConsumedTime(Date, Date, boolean) */ public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd) { return getConsumedTime(rangeStart, rangeEnd, true); } /** * Returns a list of periods representing the consumed time for this event * in the specified range. Note that the returned list may contain a single * period for non-recurring components or multiple periods for recurring * components. If no time is consumed by this event an empty list is returned. * @param rangeStart the start of the range to check for consumed time * @param rangeEnd the end of the range to check for consumed time * @param normalise indicate whether the returned list of periods should be * normalised * @return a list of periods representing consumed time for this event */ public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd, final boolean normalise) { PeriodList periods = new PeriodList(); // if component is transparent return empty list.. if (Transp.TRANSPARENT.equals(getProperty(Property.TRANSP))) { return periods; } DtStart start = (DtStart) getProperty(Property.DTSTART); DtEnd end = (DtEnd) getProperty(Property.DTEND); Duration duration = (Duration) getProperty(Property.DURATION); // if no start date specified return empty list.. if (start == null) { return periods; } // if an explicit event duration is not specified, derive a value for recurring // periods from the end date.. Dur rDuration; if (duration == null) { rDuration = new Dur(start.getDate(), end.getDate()); } else { rDuration = duration.getDuration(); } // adjust range start back by duration to allow for recurrences that // start before the range but finish inside.. // FIXME: See bug #1325558.. Date adjustedRangeStart = new DateTime(rangeStart); adjustedRangeStart.setTime(rDuration.negate().getTime(rangeStart).getTime()); // if start/end specified as anniversary-type (i.e. uses DATE values // rather than DATE-TIME), return empty list.. if (Value.DATE.equals(start.getParameter(Parameter.VALUE))) { return periods; } // recurrence dates.. PropertyList rDates = getProperties(Property.RDATE); for (Iterator i = rDates.iterator(); i.hasNext();) { RDate rdate = (RDate) i.next(); // only period-based rdates are applicable.. // FIXME: ^^^ not true - date-time/date also applicable.. if (Value.PERIOD.equals(rdate.getParameter(Parameter.VALUE))) { for (Iterator j = rdate.getPeriods().iterator(); j.hasNext();) { Period period = (Period) j.next(); if (period.getStart().before(rangeEnd) && period.getEnd().after(rangeStart)) { periods.add(period); } } } } // recurrence rules.. PropertyList rRules = getProperties(Property.RRULE); for (Iterator i = rRules.iterator(); i.hasNext();) { RRule rrule = (RRule) i.next(); DateList startDates = rrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE)); // DateList startDates = rrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE)); for (int j = 0; j < startDates.size(); j++) { Date startDate = (Date) startDates.get(j); periods.add(new Period(new DateTime(startDate), rDuration)); } } // exception dates.. PropertyList exDates = getProperties(Property.EXDATE); for (Iterator i = exDates.iterator(); i.hasNext();) { ExDate exDate = (ExDate) i.next(); for (Iterator j = periods.iterator(); j.hasNext();) { Period period = (Period) j.next(); // for DATE-TIME instances check for DATE-based exclusions also.. if (exDate.getDates().contains(period.getStart()) || exDate.getDates().contains(new Date(period.getStart()))) { j.remove(); } } } // exception rules.. // FIXME: exception rules should be consistent with exception dates (i.e. not use periods?).. PropertyList exRules = getProperties(Property.EXRULE); PeriodList exPeriods = new PeriodList(); for (Iterator i = exRules.iterator(); i.hasNext();) { ExRule exrule = (ExRule) i.next(); // DateList startDates = exrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE)); DateList startDates = exrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE)); for (Iterator j = startDates.iterator(); j.hasNext();) { Date startDate = (Date) j.next(); exPeriods.add(new Period(new DateTime(startDate), rDuration)); } } // apply exceptions.. if (!exPeriods.isEmpty()) { periods = periods.subtract(exPeriods); } // if periods already specified through recurrence, return.. // ..also normalise before returning. if (!periods.isEmpty()) { if (normalise) { return periods.normalise(); } else { return periods; } } // add first instance if included in range.. if (start.getDate().before(rangeEnd)) { if (end != null && end.getDate().after(rangeStart)) { periods.add(new Period(new DateTime(start.getDate()), new DateTime(end.getDate()))); } else if (duration != null) { Period period = new Period(new DateTime(start.getDate()), duration.getDuration()); if (period.getEnd().after(rangeStart)) { periods.add(period); } } } return periods; } /** * Convenience method to pull the DTSTART out of the property list. * * @return * The DtStart object representation of the start Date */ public final DtStart getStartDate() { return (DtStart) getProperty(Property.DTSTART); } /** * Convenience method to pull the DTEND out of the property list. If * DTEND was not specified, use the DTSTART + DURATION to calculate it. * * @return * The end for this VEVENT. */ public final DtEnd getEndDate() { DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND); // No DTEND? No problem, we'll use the DURATION. if (dtEnd == null) { DtStart dtStart = getStartDate(); Duration vEventDuration = (Duration) getProperty(Property.DURATION); dtEnd = new DtEnd(Dates.getInstance(vEventDuration.getDuration().getTime(dtStart.getDate()), (Value) dtStart.getParameter(Parameter.VALUE))); if (dtStart.isUtc()) { dtEnd.setUtc(true); } } return dtEnd; } /** * Returns the UID property of this component if available. * @return a Uid instance, or null if no UID property exists */ public final Uid getUid() { return (Uid) getProperty(Property.UID); } }
package com.github.rconner.util; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import java.lang.ref.WeakReference; /** * A Supplier which caches the instance retrieved from a delegate Supplier in a {@link WeakReference}. If the reference * is clear on a call to {@code get()}, it is retrieved again from the delegate. Note that the delegate Supplier cannot * return null. Instances of this class are internally thread-safe and will never invoke the delegate concurrently. * * @param <T> */ public final class CachingSupplier<T> implements Supplier<T> { private final Supplier<T> delegate; private volatile WeakReference<T> ref = new WeakReference<T>( null ); private final Object lock = new Object(); private CachingSupplier( final Supplier<T> delegate ) { this.delegate = delegate; } public static <T> Supplier<T> of( final Supplier<T> delegate ) { Preconditions.checkNotNull( delegate ); return delegate instanceof CachingSupplier ? delegate : new CachingSupplier<T>( delegate ); } @Override public T get() { T value = ref.get(); if( value == null ) { synchronized( lock ) { value = ref.get(); if( value == null ) { value = delegate.get(); Preconditions.checkState( value != null, "Value returned by delegate supplier cannot be null." ); ref = new WeakReference<T>( value ); } } } return value; } }
package com.inepex.ineForm.shared; import java.util.ArrayList; import java.util.List; import com.inepex.ineom.shared.Relation; import com.inepex.ineom.shared.assistedobject.AssistedObject; import com.inepex.ineom.shared.descriptor.CustomKVOObjectDesc; public abstract class BaseMapper<E> { public abstract E kvoToEntity(AssistedObject from, E to, CustomKVOObjectDesc... descs) throws Exception; public abstract AssistedObject entityToKvo(E entity); public abstract Relation toRelation(E entity, boolean includeKvo); public List<Relation> toRelationList(List<E> entityList){ return toRelationList(entityList, false); } public List<Relation> toRelationList(List<E> entityList, boolean includeKvo){ List<Relation> result = new ArrayList<Relation>(); for (E entity : entityList) { result.add(toRelation(entity, includeKvo)); } return result; } public ArrayList<AssistedObject> entityListToKvoList(List<E> entityList){ ArrayList<AssistedObject> result = new ArrayList<AssistedObject>(); for (E o: entityList){ result.add(entityToKvo(o)); } return result; } public ArrayList<AssistedObject> entityListToKvoList(List<E> entityList, boolean addId){ ArrayList<AssistedObject> result = new ArrayList<AssistedObject>(); Long id = 0l; for (E o: entityList){ AssistedObject kvo = entityToKvo(o); if(addId){ kvo.setId(id++); } result.add(kvo); } return result; } }
package net.fortuna.ical4j.model.component; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Iterator; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.property.Clazz; import net.fortuna.ical4j.model.property.Created; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.ExDate; import net.fortuna.ical4j.model.property.ExRule; import net.fortuna.ical4j.model.property.Geo; import net.fortuna.ical4j.model.property.LastModified; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.Priority; import net.fortuna.ical4j.model.property.RDate; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.model.property.RecurrenceId; import net.fortuna.ical4j.model.property.Sequence; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Transp; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Url; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.PropertyValidator; import net.fortuna.ical4j.util.Strings; /** * Defines an iCalendar VEVENT component. * * <pre> * 4.6.1 Event Component * * Component Name: &quot;VEVENT&quot; * * Purpose: Provide a grouping of component properties that describe an * event. * * Format Definition: A &quot;VEVENT&quot; calendar component is defined by the * following notation: * * eventc = &quot;BEGIN&quot; &quot;:&quot; &quot;VEVENT&quot; CRLF * eventprop *alarmc * &quot;END&quot; &quot;:&quot; &quot;VEVENT&quot; CRLF * * eventprop = *( * * ; the following are optional, * ; but MUST NOT occur more than once * * class / created / description / dtstart / geo / * last-mod / location / organizer / priority / * dtstamp / seq / status / summary / transp / * uid / url / recurid / * * ; either 'dtend' or 'duration' may appear in * ; a 'eventprop', but 'dtend' and 'duration' * ; MUST NOT occur in the same 'eventprop' * * dtend / duration / * * ; the following are optional, * ; and MAY occur more than once * * attach / attendee / categories / comment / * contact / exdate / exrule / rstatus / related / * resources / rdate / rrule / x-prop * * ) * </pre> * * Example 1 - Creating a new all-day event: * * <pre><code> * java.util.Calendar cal = java.util.Calendar.getInstance(); * cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER); * cal.set(java.util.Calendar.DAY_OF_MONTH, 25); * * VEvent christmas = new VEvent(cal.getTime(), &quot;Christmas Day&quot;); * * // initialise as an all-day event.. * christmas.getProperties().getProperty(Property.DTSTART).getParameters().add( * Value.DATE); * * // add timezone information.. * VTimeZone tz = VTimeZone.getDefault(); * TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID) * .getValue()); * christmas.getProperties().getProperty(Property.DTSTART).getParameters().add( * tzParam); * </code></pre> * * Example 2 - Creating an event of one (1) hour duration: * * <pre><code> * java.util.Calendar cal = java.util.Calendar.getInstance(); * // tomorrow.. * cal.add(java.util.Calendar.DAY_OF_MONTH, 1); * cal.set(java.util.Calendar.HOUR_OF_DAY, 9); * cal.set(java.util.Calendar.MINUTE, 30); * * VEvent meeting = new VEvent(cal.getTime(), 1000 * 60 * 60, &quot;Progress Meeting&quot;); * * // add timezone information.. * VTimeZone tz = VTimeZone.getDefault(); * TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID) * .getValue()); * meeting.getProperties().getProperty(Property.DTSTART).getParameters().add( * tzParam); * </code></pre> * * Example 3 - Retrieve a list of periods representing a recurring event in a specified range: * * <pre><code> * Calendar weekday9AM = Calendar.getInstance(); * weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0); * weekday9AM.set(Calendar.MILLISECOND, 0); * * Calendar weekday5PM = Calendar.getInstance(); * weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0); * weekday5PM.set(Calendar.MILLISECOND, 0); * * // Do the recurrence until December 31st. * Calendar untilCal = Calendar.getInstance(); * untilCal.set(2005, Calendar.DECEMBER, 31); * untilCal.set(Calendar.MILLISECOND, 0); * * // 9:00AM to 5:00PM Rule * Recur recur = new Recur(Recur.WEEKLY, untilCal.getTime()); * recur.getDayList().add(WeekDay.MO); * recur.getDayList().add(WeekDay.TU); * recur.getDayList().add(WeekDay.WE); * recur.getDayList().add(WeekDay.TH); * recur.getDayList().add(WeekDay.FR); * recur.setInterval(3); * recur.setWeekStartDay(WeekDay.MO.getDay()); * RRule rrule = new RRule(recur); * * Summary summary = new Summary(&quot;TEST EVENTS THAT HAPPEN 9-5 MON-FRI&quot;); * * weekdayNineToFiveEvents = new VEvent(); * weekdayNineToFiveEvents.getProperties().add(rrule); * weekdayNineToFiveEvents.getProperties().add(summary); * weekdayNineToFiveEvents.getProperties().add(new DtStart(weekday9AM.getTime())); * weekdayNineToFiveEvents.getProperties().add(new DtEnd(weekday5PM.getTime())); * * // Test Start 04/01/2005, End One month later. * // Query Calendar Start and End Dates. * Calendar queryStartDate = Calendar.getInstance(); * queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0); * queryStartDate.set(Calendar.MILLISECOND, 0); * Calendar queryEndDate = Calendar.getInstance(); * queryEndDate.set(2005, Calendar.MAY, 1, 11, 15, 0); * queryEndDate.set(Calendar.MILLISECOND, 0); * * // This range is monday to friday every three weeks, starting from * // March 7th 2005, which means for our query dates we need * // April 18th through to the 22nd. * PeriodList periods = weekdayNineToFiveEvents.getPeriods(queryStartDate * .getTime(), queryEndDate.getTime()); * </code></pre> * * @author Ben Fortuna */ public class VEvent extends CalendarComponent { private static final long serialVersionUID = 2547948989200697335L; private ComponentList alarms; /** * Default constructor. */ public VEvent() { super(VEVENT); this.alarms = new ComponentList(); getProperties().add(new DtStamp()); } /** * Constructor. * @param properties a list of properties */ public VEvent(final PropertyList properties) { super(VEVENT, properties); this.alarms = new ComponentList(); } /** * Constructor. * @param properties a list of properties * @param alarms a list of alarms */ public VEvent(final PropertyList properties, final ComponentList alarms) { super(VEVENT, properties); this.alarms = alarms; } /** * Constructs a new VEVENT instance starting at the specified time with the specified summary. * @param start the start date of the new event * @param summary the event summary */ public VEvent(final Date start, final String summary) { this(); getProperties().add(new DtStart(start)); getProperties().add(new Summary(summary)); } /** * Constructs a new VEVENT instance starting and ending at the specified times with the specified summary. * @param start the start date of the new event * @param end the end date of the new event * @param summary the event summary */ public VEvent(final Date start, final Date end, final String summary) { this(); getProperties().add(new DtStart(start)); getProperties().add(new DtEnd(end)); getProperties().add(new Summary(summary)); } /** * Constructs a new VEVENT instance starting at the specified times, for the specified duration, with the specified * summary. * @param start the start date of the new event * @param duration the duration of the new event * @param summary the event summary */ public VEvent(final Date start, final Dur duration, final String summary) { this(); getProperties().add(new DtStart(start)); getProperties().add(new Duration(duration)); getProperties().add(new Summary(summary)); } /** * Returns the list of alarms for this event. * @return a component list */ public final ComponentList getAlarms() { return alarms; } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); b.append(BEGIN); b.append(':'); b.append(getName()); b.append(Strings.LINE_SEPARATOR); b.append(getProperties()); b.append(getAlarms()); b.append(END); b.append(':'); b.append(getName()); b.append(Strings.LINE_SEPARATOR); return b.toString(); } /** * @see net.fortuna.ical4j.model.Component#validate(boolean) */ public final void validate(final boolean recurse) throws ValidationException { // validate that getAlarms() only contains VAlarm components Iterator iterator = getAlarms().iterator(); while (iterator.hasNext()) { Component component = (Component) iterator.next(); if (!(component instanceof VAlarm)) { throw new ValidationException("Component [" + component.getName() + "] may not occur in VEVENT"); } } if (!CompatibilityHints .isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) { // From "4.8.4.7 Unique Identifier": // Conformance: The property MUST be specified in the "VEVENT", "VTODO", // "VJOURNAL" or "VFREEBUSY" calendar components. PropertyValidator.getInstance().assertOne(Property.UID, getProperties()); // From "4.8.7.2 Date/Time Stamp": // Conformance: This property MUST be included in the "VEVENT", "VTODO", // "VJOURNAL" or "VFREEBUSY" calendar components. PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties()); } /* * ; the following are optional, ; but MUST NOT occur more than once class / created / description / dtstart / * geo / last-mod / location / organizer / priority / dtstamp / seq / status / summary / transp / uid / url / * recurid / */ PropertyValidator.getInstance().assertOneOrLess(Property.CLASS, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.CREATED, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DESCRIPTION, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DTSTART, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.GEO, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.LAST_MODIFIED, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.LOCATION, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.ORGANIZER, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.PRIORITY, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.DTSTAMP, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.SEQUENCE, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.STATUS, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.SUMMARY, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.TRANSP, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.UID, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties()); PropertyValidator.getInstance().assertOneOrLess(Property.RECURRENCE_ID, getProperties()); Status status = (Status) getProperty(Property.STATUS); if (status != null && !Status.VEVENT_TENTATIVE.equals(status) && !Status.VEVENT_CONFIRMED.equals(status) && !Status.VEVENT_CANCELLED.equals(status)) { throw new ValidationException("Status property [" + status.toString() + "] is not applicable for VEVENT"); } /* * ; either 'dtend' or 'duration' may appear in ; a 'eventprop', but 'dtend' and 'duration' ; MUST NOT occur in * the same 'eventprop' dtend / duration / */ try { PropertyValidator.getInstance().assertNone(Property.DTEND, getProperties()); } catch (ValidationException ve) { PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties()); } if (getProperty(Property.DTEND) != null) { /* * The "VEVENT" is also the calendar component used to specify an anniversary or daily reminder within a * calendar. These events have a DATE value type for the "DTSTART" property instead of the default data type * of DATE-TIME. If such a "VEVENT" has a "DTEND" property, it MUST be specified as a DATE value also. The * anniversary type of "VEVENT" can span more than one date (i.e, "DTEND" property value is set to a * calendar date after the "DTSTART" property value). */ DtStart start = (DtStart) getProperty(Property.DTSTART); DtEnd end = (DtEnd) getProperty(Property.DTEND); if (start != null) { Parameter startValue = start.getParameter(Parameter.VALUE); Parameter endValue = end.getParameter(Parameter.VALUE); if (startValue != null) { if(startValue.equals(Value.DATE_TIME) && endValue==null) { // DATE-TIME is the default so this is ok } else if (!startValue.equals(endValue)) { throw new ValidationException("Property [" + Property.DTEND + "] must have the same [" + Parameter.VALUE + "] as [" + Property.DTSTART + "]"); } } else if(endValue!=null) { // if DTSTART's VALUE is null then DTEND's must be DATE-TIME if(!endValue.equals(Value.DATE_TIME)) throw new ValidationException("Property [" + Property.DTEND + "] must have the same [" + Parameter.VALUE + "] as [" + Property.DTSTART + "]"); } } } /* * ; the following are optional, ; and MAY occur more than once attach / attendee / categories / comment / * contact / exdate / exrule / rstatus / related / resources / rdate / rrule / x-prop */ if (recurse) { validateProperties(); } } /** * Returns a normalised list of periods representing the consumed time for this event. * @param rangeStart * @param rangeEnd * @return a normalised list of periods representing consumed time for this event * @see VEvent#getConsumedTime(Date, Date, boolean) */ public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd) { return getConsumedTime(rangeStart, rangeEnd, true); } /** * Returns a list of periods representing the consumed time for this event in the specified range. Note that the * returned list may contain a single period for non-recurring components or multiple periods for recurring * components. If no time is consumed by this event an empty list is returned. * @param rangeStart the start of the range to check for consumed time * @param rangeEnd the end of the range to check for consumed time * @param normalise indicate whether the returned list of periods should be normalised * @return a list of periods representing consumed time for this event */ public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd, final boolean normalise) { PeriodList periods = new PeriodList(); // if component is transparent return empty list.. if (Transp.TRANSPARENT.equals(getProperty(Property.TRANSP))) { return periods; } DtStart start = (DtStart) getProperty(Property.DTSTART); DtEnd end = (DtEnd) getProperty(Property.DTEND); Duration duration = (Duration) getProperty(Property.DURATION); // if no start date or duration specified return empty list.. if (start == null || (duration == null && end == null)) { return periods; } // if an explicit event duration is not specified, derive a value for recurring // periods from the end date.. Dur rDuration; if (duration == null) { rDuration = new Dur(start.getDate(), end.getDate()); } else { rDuration = duration.getDuration(); } // adjust range start back by duration to allow for recurrences that // start before the range but finish inside.. // FIXME: See bug #1325558.. Date adjustedRangeStart = new DateTime(rangeStart); adjustedRangeStart.setTime(rDuration.negate().getTime(rangeStart) .getTime()); // recurrence dates.. PropertyList rDates = getProperties(Property.RDATE); for (Iterator i = rDates.iterator(); i.hasNext();) { RDate rdate = (RDate) i.next(); // only period-based rdates are applicable.. // FIXME: ^^^ not true - date-time/date also applicable.. if (Value.PERIOD.equals(rdate.getParameter(Parameter.VALUE))) { for (Iterator j = rdate.getPeriods().iterator(); j.hasNext();) { Period period = (Period) j.next(); if (period.getStart().before(rangeEnd) && period.getEnd().after(rangeStart)) { periods.add(period); } } } } // recurrence rules.. PropertyList rRules = getProperties(Property.RRULE); for (Iterator i = rRules.iterator(); i.hasNext();) { RRule rrule = (RRule) i.next(); DateList startDates = rrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE)); // DateList startDates = rrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) // start.getParameters().getParameter(Parameter.VALUE)); for (int j = 0; j < startDates.size(); j++) { Date startDate = (Date) startDates.get(j); periods.add(new Period(new DateTime(startDate), rDuration)); } } // add first instance if included in range.. if (start.getDate().before(rangeEnd)) { if (end != null && end.getDate().after(rangeStart)) { periods.add(new Period(new DateTime(start.getDate()), new DateTime(end.getDate()))); } else if (duration != null) { Period period = new Period(new DateTime(start.getDate()), duration.getDuration()); if (period.getEnd().after(rangeStart)) { periods.add(period); } } } // exception dates.. PropertyList exDates = getProperties(Property.EXDATE); for (Iterator i = exDates.iterator(); i.hasNext();) { ExDate exDate = (ExDate) i.next(); for (Iterator j = periods.iterator(); j.hasNext();) { Period period = (Period) j.next(); // for DATE-TIME instances check for DATE-based exclusions also.. if (exDate.getDates().contains(period.getStart()) || exDate.getDates().contains( new Date(period.getStart()))) { j.remove(); } } } // exception rules.. // FIXME: exception rules should be consistent with exception dates (i.e. not use periods?).. PropertyList exRules = getProperties(Property.EXRULE); PeriodList exPeriods = new PeriodList(); for (Iterator i = exRules.iterator(); i.hasNext();) { ExRule exrule = (ExRule) i.next(); // DateList startDates = exrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) // start.getParameters().getParameter(Parameter.VALUE)); DateList startDates = exrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE)); for (Iterator j = startDates.iterator(); j.hasNext();) { Date startDate = (Date) j.next(); exPeriods.add(new Period(new DateTime(startDate), rDuration)); } } // apply exceptions.. if (!exPeriods.isEmpty()) { periods = periods.subtract(exPeriods); } // if periods already specified through recurrence, return.. // ..also normalise before returning. if (!periods.isEmpty() && normalise) { return periods.normalise(); } return periods; } /** * @return the optional access classification property for an event */ public final Clazz getClassification() { return (Clazz) getProperty(Property.CLASS); } /** * @return the optional creation-time property for an event */ public final Created getCreated() { return (Created) getProperty(Property.CREATED); } /** * @return the optional description property for an event */ public final Description getDescription() { return (Description) getProperty(Property.DESCRIPTION); } /** * Convenience method to pull the DTSTART out of the property list. * @return The DtStart object representation of the start Date */ public final DtStart getStartDate() { return (DtStart) getProperty(Property.DTSTART); } /** * @return the optional geographic position property for an event */ public final Geo getGeographicPos() { return (Geo) getProperty(Property.GEO); } /** * @return the optional last-modified property for an event */ public final LastModified getLastModified() { return (LastModified) getProperty(Property.LAST_MODIFIED); } /** * @return the optional location property for an event */ public final Location getLocation() { return (Location) getProperty(Property.LOCATION); } /** * @return the optional organizer property for an event */ public final Organizer getOrganizer() { return (Organizer) getProperty(Property.ORGANIZER); } /** * @return the optional priority property for an event */ public final Priority getPriority() { return (Priority) getProperty(Property.PRIORITY); } /** * @return the optional date-stamp property */ public final DtStamp getDateStamp() { return (DtStamp) getProperty(Property.DTSTAMP); } /** * @return the optional sequence number property for an event */ public final Sequence getSequence() { return (Sequence) getProperty(Property.SEQUENCE); } /** * @return the optional status property for an event */ public final Status getStatus() { return (Status) getProperty(Property.STATUS); } /** * @return the optional summary property for an event */ public final Summary getSummary() { return (Summary) getProperty(Property.SUMMARY); } /** * @return the optional time transparency property for an event */ public final Transp getTransparency() { return (Transp) getProperty(Property.TRANSP); } /** * @return the optional URL property for an event */ public final Url getUrl() { return (Url) getProperty(Property.URL); } /** * @return the optional recurrence identifier property for an event */ public final RecurrenceId getRecurrenceId() { return (RecurrenceId) getProperty(Property.RECURRENCE_ID); } /** * Returns the end date of this event. Where an end date is not available it will be derived from the event * duration. * @return a DtEnd instance, or null if one cannot be derived */ public final DtEnd getEndDate() { return getEndDate(true); } /** * Convenience method to pull the DTEND out of the property list. If DTEND was not specified, use the DTSTART + * DURATION to calculate it. * @param deriveFromDuration specifies whether to derive an end date from the event duration where an end date is * not found * @return The end for this VEVENT. */ public final DtEnd getEndDate(final boolean deriveFromDuration) { DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND); // No DTEND? No problem, we'll use the DURATION. if (dtEnd == null && deriveFromDuration && getDuration() != null) { DtStart dtStart = getStartDate(); Duration vEventDuration = getDuration(); dtEnd = new DtEnd(Dates.getInstance(vEventDuration.getDuration() .getTime(dtStart.getDate()), (Value) dtStart .getParameter(Parameter.VALUE))); if (dtStart.isUtc()) { dtEnd.setUtc(true); } } return dtEnd; } /** * @return the optional Duration property */ public final Duration getDuration() { return (Duration) getProperty(Property.DURATION); } /** * Returns the UID property of this component if available. * @return a Uid instance, or null if no UID property exists */ public final Uid getUid() { return (Uid) getProperty(Property.UID); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.Component#equals(java.lang.Object) */ public boolean equals(Object arg0) { if (arg0 instanceof VEvent) { return super.equals(arg0) && ObjectUtils.equals(alarms, ((VEvent) arg0).getAlarms()); } return super.equals(arg0); } /* (non-Javadoc) * @see net.fortuna.ical4j.model.Component#hashCode() */ public int hashCode() { return new HashCodeBuilder().append(getName()).append(getProperties()) .append(getAlarms()).toHashCode(); } /** * Overrides default copy method to add support for copying alarm sub-components. * @see net.fortuna.ical4j.model.Component#copy() */ public Component copy() throws ParseException, IOException, URISyntaxException { VEvent copy = (VEvent) super.copy(); copy.alarms = new ComponentList(alarms); return copy; } }
package org.voltdb.planner; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Column; import org.voltdb.catalog.Database; import org.voltdb.catalog.Table; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.AbstractScanPlanNode; import org.voltdb.plannodes.IndexScanPlanNode; import org.voltdb.plannodes.PlanNodeTree; import org.voltdb.plannodes.SendPlanNode; import org.voltdb.types.PlanNodeType; public class plannerTester { private static PlannerTestAideDeCamp aide; private static String m_currentConfig; private static String m_testName; private static String m_pathRefPlan; private static String m_baseName; private static String m_pathDDL; private static String m_savePlanPath; // private static ArrayList<Pair<String,String>> m_partitionColumns = new ArrayList<Pair<String,String>>(); private static Map<String,String> m_partitionColumns = new HashMap<String, String>(); private static ArrayList<String> m_stmts = new ArrayList<String>(); private static int m_treeSizeDiff; private static boolean m_changedSQL; private static boolean m_isCompileSave = false; private static boolean m_isDiff = false; private static boolean m_showExpainedPlan = false; private static boolean m_showSQLStatement = false; private static ArrayList<String> m_config = new ArrayList<String>(); private static int m_numPass; private static int m_numFail; public static ArrayList<String> m_diffMessages = new ArrayList<String>(); private static String m_reportDir = "/tmp/"; private static BufferedWriter m_reportWriter; public static class diffPair { private Object m_first; private Object m_second; public diffPair( Object first, Object second ) { m_first = first; m_second = second; } @Override public String toString() { String first = ( ( m_first == null ) || ( m_first == "" ) ) ? "[]" : m_first.toString(); String second = ( m_second == null || ( m_second == "" )) ? "[]" : m_second.toString(); return "("+first+" => "+second+")"; } public boolean equals() { return m_first.equals(m_second); } public void setFirst( Object first ) { m_first = first; } public void setSecond( Object second ) { m_second = second; } public void set( Object first, Object second ) { m_first = first; m_second = second; } } //TODO maybe a more robust parser? Need to figure out how to handle config file array if using the CLIConfig below // private static class PlannerTesterConfig extends CLIConfig { // @Option(shortOpt = "d", desc = "Do the diff") // boolean isDiff = false; // @Option(shortOpt = "cs", desc = "Compile queris and save according to the config file") // boolean isCompileSave = false; // @Option(shortOpt = "C", desc = "Specify the path to the config file") // ArrayList<String> configFiles = new ArrayList<String> (); // @Override // public void validate() { // if (maxerrors < 0) // exitWithMessageAndUsage("abortfailurecount must be >=0"); // @Override // public void printUsage() { // System.out // .println("Usage: csvloader [args] tablename"); // System.out // .println(" csvloader [args] -p procedurename"); // super.printUsage(); public static void main( String[] args ) { int size = args.length; for( int i=0; i<size; i++ ) { String str = args[i]; if( str.startsWith("-C=")) { m_config.add(str.split("=")[1]); } else if( str.startsWith("-cs") ) { m_isCompileSave = true; } else if( str.startsWith("-d") ) { m_isDiff = true; } else if( str.startsWith("-r") ){ m_reportDir = str.split("=")[1]; if( !m_reportDir.endsWith("/") ) { m_reportDir += "/"; } } else if( str.startsWith("-e") ){ m_showExpainedPlan = true; } else if( str.startsWith("-s") ){ m_showSQLStatement = true; } else if( str.startsWith("-help") ){ System.out.println("-cs : Compile queries and save the plans according to the config files"); System.out.println("-d : Do the diff between plan files in baseline and currentplan"); System.out.println("-e : Output explained plan along with diff"); System.out.println("-s : Output sql statement along with diff"); System.out.println("-C=configFile : Specify the path to a config file"); System.out.println("-r=reportFileDir : Specify report file path, default will be tmp/, report file name is plannerTester.report"); System.exit(0); } } size = m_config.size(); if( m_isCompileSave ) { for( String config : m_config ) { try { setUp( config ); batchCompileSave(); } catch (Exception e) { e.printStackTrace(); } } } if( m_isDiff ) { if( !new File(m_reportDir).exists() ) { new File(m_reportDir).mkdirs(); } try { m_reportWriter = new BufferedWriter(new FileWriter( m_reportDir+"plannerTester.report" )); } catch (IOException e1) { System.out.println(e1.getMessage()); System.exit(-1); } for( String config : m_config ) { try { setUp( config ); startDiff(); } catch (Exception e) { e.printStackTrace(); } } int numTest = m_numPass + m_numFail; System.out.println("Test: "+numTest); System.out.println("Pass: "+m_numPass); System.out.println("Fail: "+m_numFail); try { m_reportWriter.write( "\nTest: "+numTest+"\n" +"Pass: "+m_numPass+"\n" +"Fail: "+m_numFail+"\n"); m_reportWriter.flush(); m_reportWriter.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Report file created at "+m_reportDir+"plannerTester.report"); } if( m_numFail == 0 ) { System.exit(0); } else { System.exit(1); } } public static void setUp( String pathConfigFile ) throws IOException { m_currentConfig = pathConfigFile; m_partitionColumns.clear(); BufferedReader reader = new BufferedReader( new FileReader( pathConfigFile ) ); String line = null; while( ( line = reader.readLine() ) != null ) { if( line.startsWith(" continue; } else if( line.equalsIgnoreCase("Name:") ) { line = reader.readLine(); m_testName = line; } else if ( line.equalsIgnoreCase("Ref:") ) { line = reader.readLine(); m_pathRefPlan = new File( line ).getCanonicalPath(); m_pathRefPlan += "/"; } else if( line.equalsIgnoreCase("DDL:")) { line = reader.readLine(); m_pathDDL = new File( line ).getCanonicalPath(); } else if( line.equalsIgnoreCase("Base Name:") ) { line = reader.readLine(); m_baseName = line; } else if( line.equalsIgnoreCase("SQL:")) { m_stmts.clear(); while( (line = reader.readLine()).length() > 6 ) { if( line.startsWith(" continue; } m_stmts.add( line ); } } else if( line.equalsIgnoreCase("Save Path:") ) { line = reader.readLine(); m_savePlanPath = new File( line ).getCanonicalPath(); m_savePlanPath += "/"; } else if( line.equalsIgnoreCase("Partition Columns:") ) { line = reader.readLine(); int index = line.indexOf("."); if( index == -1 ) { System.err.println("Config file syntax error : Partition Columns should be table.column"); } m_partitionColumns.put( line.substring(0, index).toLowerCase(), line.substring(index+1).toLowerCase()); } } try { setUpSchema(); } catch (Exception e) { e.printStackTrace(); } } public static void setUpForTest( String pathDDL, String baseName, String table, String column ) { m_partitionColumns.clear(); m_partitionColumns.put( table.toLowerCase(), column.toLowerCase()); m_pathDDL = pathDDL; m_baseName = baseName; try { setUpSchema(); } catch (Exception e) { e.printStackTrace(); } } public static void setUpSchema() throws Exception { File ddlFile = new File(m_pathDDL); aide = new PlannerTestAideDeCamp(ddlFile.toURI().toURL(), m_baseName); // Set all tables to non-replicated. Cluster cluster = aide.getCatalog().getClusters().get("cluster"); CatalogMap<Table> tmap = cluster.getDatabases().get("database").getTables(); for( String tableName : m_partitionColumns.keySet() ) { Table t = tmap.getIgnoreCase( tableName ); t.setIsreplicated(false); Column column = t.getColumns().getIgnoreCase( m_partitionColumns.get(tableName) ); t.setPartitioncolumn(column); } } public static void setTestName ( String name ) { m_testName = name; } protected void tearDown() throws Exception { aide.tearDown(); } public static List<AbstractPlanNode> compile( String sql, int paramCount, boolean singlePartition ) throws Exception { List<AbstractPlanNode> pnList = null; pnList = aide.compile(sql, paramCount, singlePartition); return pnList; } public static void writePlanToFile( AbstractPlanNode pn, String pathToDir, String fileName, String sql) { if( pn == null ) { System.err.println("the plan node is null, nothing to write"); return; } PlanNodeTree pnt = new PlanNodeTree( pn ); String prettyJson = pnt.toJSONString(); if( !new File(pathToDir).exists() ) { new File(pathToDir).mkdirs(); } try { BufferedWriter writer = new BufferedWriter( new FileWriter( pathToDir+fileName ) ); writer.write( sql ); writer.write( "\n" ); writer.write( prettyJson ); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static PlanNodeTree loadPlanFromFile( String path, ArrayList<String> getsql ) throws FileNotFoundException { PlanNodeTree pnt = new PlanNodeTree(); String prettyJson = ""; String line = null; BufferedReader reader = new BufferedReader( new FileReader( path )); try { getsql.add( reader.readLine() ); while( (line = reader.readLine() ) != null ){ line = line.trim(); prettyJson += line; } } catch (IOException e1) { e1.printStackTrace(); } JSONObject jobj; try { jobj = new JSONObject( prettyJson ); JSONArray jarray = jobj.getJSONArray("PLAN_NODES"); Database db = aide.getDatabase(); pnt.loadFromJSONArray(jarray, db); } catch (JSONException e) { e.printStackTrace(); } return pnt; } public static ArrayList< AbstractPlanNode > getJoinNodes( ArrayList<AbstractPlanNode> pnlist ) { ArrayList< AbstractPlanNode > joinNodeList = new ArrayList<AbstractPlanNode>(); for( AbstractPlanNode pn : pnlist ) { if( pn.getPlanNodeType().equals(PlanNodeType.NESTLOOP) || pn.getPlanNodeType().equals(PlanNodeType.NESTLOOPINDEX) ) { joinNodeList.add(pn); } } return joinNodeList; } public static void batchCompileSave( ) throws Exception { int size = m_stmts.size(); for( int i = 0; i < size; i++ ) { List<AbstractPlanNode> pnList = compile( m_stmts.get(i), 0, false); AbstractPlanNode pn = pnList.get(0); if( pnList.size() == 2 ){//multi partition query plan assert( pnList.get(1) instanceof SendPlanNode ); if( ! pn.reattachFragment( ( SendPlanNode) pnList.get(1) ) ) { System.err.println( "Receive plan node not found while reattachFragment." ); } } writePlanToFile(pn, m_savePlanPath, m_testName+".plan"+i, m_stmts.get(i) ); } } //parameters : path to baseline and the new plans //size : number of total files in the baseline directory public static void batchDiff( ) throws IOException { PlanNodeTree pnt1 = null; PlanNodeTree pnt2 = null; int size = m_stmts.size(); String baseStmt = null; for( int i = 0; i < size; i++ ){ ArrayList<String> getsql = new ArrayList<String>(); try { pnt1 = loadPlanFromFile( m_pathRefPlan+m_testName+".plan"+i, getsql ); baseStmt = getsql.get(0); } catch (FileNotFoundException e) { System.err.println("Plan files in"+m_pathRefPlan+m_testName+".plan"+i+" don't exist. Use -cs(batchCompileSave) to generate plans and copy base plans to baseline directory."); System.exit(1); } //if sql stmts not consistent if( !baseStmt.equalsIgnoreCase( m_stmts.get(i)) ) { diffPair strPair = new diffPair( baseStmt, m_stmts.get(i) ); m_reportWriter.write("Statement "+i+" of "+m_testName+":\n SQL statement is not consistent with the one in baseline :"+"\n"+ strPair.toString()+"\n"); m_numFail++; continue; } try{ pnt2 = loadPlanFromFile( m_savePlanPath+m_testName+".plan"+i, getsql ); } catch (FileNotFoundException e) { System.err.println("Plan files in"+m_savePlanPath+m_testName+".plan"+i+" don't exist. Use -cs(batchCompileSave) to generate and save plans."); System.exit(1); } AbstractPlanNode pn1 = pnt1.getRootPlanNode(); AbstractPlanNode pn2 = pnt2.getRootPlanNode(); if( diff( pn1, pn2, false ) ) { m_numPass++; } else { m_numFail++; m_reportWriter.write( "Statement "+i+" of "+m_testName+": \n" ); //TODO add more logic to determine which plan is better if( !m_changedSQL ){ if( m_treeSizeDiff < 0 ){ m_reportWriter.write( "Old plan might be better\n" ); } else if( m_treeSizeDiff > 0 ) { m_reportWriter.write( "New plan might be better\n" ); } } for( String msg : m_diffMessages ) { m_reportWriter.write( msg+"\n\n" ); } if( m_showSQLStatement ) { m_reportWriter.write( "SQL statement:\n"+baseStmt+"\n==>\n"+m_stmts.get(i)+"\n"); } if( m_showExpainedPlan ) { m_reportWriter.write("\nExplained plan:\n"+pn1.toExplainPlanString()+"\n==>\n"+pn2.toExplainPlanString()+"\n"); } m_reportWriter.write("Path to the config file :"+m_currentConfig+"\n" +"Path to the baseline file :"+m_pathRefPlan+m_testName+".plan"+i+"\n" +"Path to the current plan file :"+m_savePlanPath+m_testName+".plan"+i+ "\n\n } } m_reportWriter.flush(); } public static void startDiff( ) throws IOException { m_reportWriter.write( "===================================================================Begin test "+m_testName+"\n" ); batchDiff( ); m_reportWriter.write( "==================================================================="+ "End of "+m_testName+"\n"); m_reportWriter.flush(); } public static boolean diffInlineAndJoin( AbstractPlanNode oldpn1, AbstractPlanNode newpn2 ) { m_treeSizeDiff = 0; boolean noDiff = true; ArrayList<String> messages = new ArrayList<String>(); ArrayList<AbstractPlanNode> list1 = oldpn1.getPlanNodeList(); ArrayList<AbstractPlanNode> list2 = newpn2.getPlanNodeList(); int size1 = list1.size(); int size2 = list2.size(); m_treeSizeDiff = size1 - size2; diffPair intdiffPair = new diffPair(0,0); diffPair stringdiffPair = new diffPair(null,null); if( size1 != size2 ) { intdiffPair.set(size1, size2); messages.add( "Plan tree size diff: "+intdiffPair.toString() ); } Map<String,ArrayList<Integer>> planNodesPosMap1 = new LinkedHashMap<String,ArrayList<Integer>> (); Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap1 = new LinkedHashMap<String,ArrayList<AbstractPlanNode>> (); Map<String,ArrayList<Integer>> planNodesPosMap2 = new LinkedHashMap<String,ArrayList<Integer>> (); Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap2 = new LinkedHashMap<String,ArrayList<AbstractPlanNode>> (); fetchPositionInfoFromList(list1, planNodesPosMap1, inlineNodesPosMap1); fetchPositionInfoFromList(list2, planNodesPosMap2, inlineNodesPosMap2); planNodePositionDiff( planNodesPosMap1, planNodesPosMap2, messages ); inlineNodePositionDiff( inlineNodesPosMap1, inlineNodesPosMap2, messages ); //join nodes diff ArrayList<AbstractPlanNode> joinNodes1 = getJoinNodes( list1 ); ArrayList<AbstractPlanNode> joinNodes2 = getJoinNodes( list2 ); size1 = joinNodes1.size(); size2 = joinNodes2.size(); if( size1 != size2 ) { intdiffPair.set( size1 , size2); messages.add( "Join Nodes Number diff:\n"+intdiffPair.toString()+"\nSQL statement might be changed."); m_changedSQL = true; String str1 = ""; String str2 = ""; for( AbstractPlanNode pn : joinNodes1 ) { str1 = str1 + pn.toString() + ", "; } for( AbstractPlanNode pn : joinNodes2 ) { str2 = str2 + pn.toString() + ", "; } if( str1.length() > 1 ){ str1 = ( str1.subSequence(0, str1.length()-2) ).toString(); } if( str2.length() > 1 ){ str2 = ( str2.subSequence(0, str2.length()-2) ).toString(); } stringdiffPair.set( str1, str2 ); messages.add( "Join Node List diff: "+"\n"+stringdiffPair.toString()+"\n"); } else { for( int i = 0 ; i < size1 ; i++ ) { AbstractPlanNode pn1 = joinNodes1.get(i); AbstractPlanNode pn2 = joinNodes2.get(i); PlanNodeType pnt1 = pn1.getPlanNodeType(); PlanNodeType pnt2 = pn2.getPlanNodeType(); if( !pnt1.equals(pnt2) ) { stringdiffPair.set( pn1.toString(), pn2.toString() ); messages.add( "Join Node Type diff:\n"+stringdiffPair.toString()); } } } for( String msg : messages ) { if( msg.contains("diff") || msg.contains("Diff") ) { noDiff = false; break; } } m_diffMessages.addAll(messages); return noDiff; } private static void fetchPositionInfoFromList( Collection<AbstractPlanNode> list, Map<String,ArrayList<Integer>> planNodesPosMap, Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap ) { for( AbstractPlanNode pn : list ) { String nodeTypeStr = pn.getPlanNodeType().name(); if( !planNodesPosMap.containsKey(nodeTypeStr) ) { ArrayList<Integer> intList = new ArrayList<Integer>( ); intList.add( pn.getPlanNodeId() ); planNodesPosMap.put(nodeTypeStr, intList ); } else{ planNodesPosMap.get( nodeTypeStr ).add( pn.getPlanNodeId() ); } //walk inline nodes for( AbstractPlanNode inlinepn : pn.getInlinePlanNodes().values() ) { String inlineNodeTypeStr = inlinepn.getPlanNodeType().name(); if( !inlineNodesPosMap.containsKey( inlineNodeTypeStr ) ) { ArrayList<AbstractPlanNode> nodeList = new ArrayList<AbstractPlanNode>( ); nodeList.add(pn); inlineNodesPosMap.put( inlineNodeTypeStr, nodeList ); } else{ inlineNodesPosMap.get( inlineNodeTypeStr ).add( pn ); } } } } private static void planNodePositionDiff( Map<String,ArrayList<Integer>> planNodesPosMap1, Map<String,ArrayList<Integer>> planNodesPosMap2, ArrayList<String> messages ) { Set<String> typeWholeSet = new HashSet<String>(); typeWholeSet.addAll( planNodesPosMap1.keySet() ); typeWholeSet.addAll( planNodesPosMap2.keySet() ); for( String planNodeTypeStr : typeWholeSet ) { if( ! planNodesPosMap1.containsKey( planNodeTypeStr ) && planNodesPosMap2.containsKey( planNodeTypeStr ) ){ diffPair strPair = new diffPair( null, planNodesPosMap2.get(planNodeTypeStr).toString() ); messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() ); } else if( planNodesPosMap1.containsKey( planNodeTypeStr ) && !planNodesPosMap2.containsKey( planNodeTypeStr ) ) { diffPair strPair = new diffPair( planNodesPosMap1.get(planNodeTypeStr).toString(), null ); messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() ); } else{ diffPair strPair = new diffPair( planNodesPosMap1.get(planNodeTypeStr).toString(), planNodesPosMap2.get(planNodeTypeStr).toString() ); if( !strPair.equals() ) { messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() ); } } } } private static void inlineNodePositionDiff( Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap1, Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap2, ArrayList<String> messages ) { Set<String> typeWholeSet = new HashSet<String>(); typeWholeSet.addAll( inlineNodesPosMap1.keySet() ); typeWholeSet.addAll( inlineNodesPosMap2.keySet() ); for( String planNodeTypeStr : typeWholeSet ) { if( ! inlineNodesPosMap1.containsKey( planNodeTypeStr ) && inlineNodesPosMap2.containsKey( planNodeTypeStr ) ){ diffPair strPair = new diffPair( null, inlineNodesPosMap2.get(planNodeTypeStr).toString() ); messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() ); } else if( inlineNodesPosMap1.containsKey( planNodeTypeStr ) && !inlineNodesPosMap2.containsKey( planNodeTypeStr ) ) { diffPair strPair = new diffPair( inlineNodesPosMap1.get(planNodeTypeStr).toString(), null ); messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() ); } else{ diffPair strPair = new diffPair( inlineNodesPosMap1.get(planNodeTypeStr).toString(), inlineNodesPosMap2.get(planNodeTypeStr).toString() ); if( !strPair.equals() ) { messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() ); } } } } private static void scanNodeDiffModule( int leafID, AbstractScanPlanNode spn1, AbstractScanPlanNode spn2, ArrayList<String> messages ) { diffPair stringdiffPair = new diffPair("", ""); String table1 = ""; String table2 = ""; String nodeType1 = ""; String nodeType2 = ""; String index1 = ""; String index2 = ""; if( spn1 == null && spn2 != null ) { table2 = spn2.getTargetTableName(); nodeType2 = spn2.getPlanNodeType().toString(); if( nodeType2.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) { index2 = ((IndexScanPlanNode)spn2).getTargetIndexName(); } } else if( spn2 == null && spn1 != null ) { table1 = spn1.getTargetTableName(); nodeType1 = spn1.getPlanNodeType().toString(); if( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) { index1 = ((IndexScanPlanNode)spn1).getTargetIndexName(); } } //both null is not possible else{ table1 = spn1.getTargetTableName(); table2 = spn2.getTargetTableName(); nodeType1 = spn1.getPlanNodeType().toString(); nodeType2 = spn2.getPlanNodeType().toString(); if( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) { index1 = ((IndexScanPlanNode)spn1).getTargetIndexName(); } if( nodeType2.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) { index2 = ((IndexScanPlanNode)spn2).getTargetIndexName(); } } if( !table1.equals(table2) ) { stringdiffPair.set( table1.equals("") ? null : nodeType1+" on "+table1, table2.equals("") ? null : nodeType2+" on "+table2 ); messages.add( "Table diff at leaf "+leafID+":"+"\n"+stringdiffPair.toString()); } else if( !nodeType1.equals(nodeType2) ) { stringdiffPair.set(nodeType1+" on "+table1, nodeType2+" on "+table2); messages.add("Scan diff at leaf "+leafID+" :"+"\n"+stringdiffPair.toString()); } else if ( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name()) ) { if( !index1.equals(index2) ) { stringdiffPair.set( index1, index2); messages.add("Index diff at leaf "+leafID+" :"+"\n"+stringdiffPair.toString()); } else { messages.add("Same at leaf "+leafID); } } //either index scan using same index or seqscan on same table else{ messages.add("Same at leaf "+leafID); } } public static boolean diffScans( AbstractPlanNode oldpn, AbstractPlanNode newpn ){ m_changedSQL = false; boolean noDiff = true; ArrayList<AbstractScanPlanNode> list1 = oldpn.getScanNodeList(); ArrayList<AbstractScanPlanNode> list2 = newpn.getScanNodeList(); int size1 = list1.size(); int size2 = list2.size(); int max = Math.max(size1, size2); int min = Math.min(size1, size2); diffPair intdiffPair = new diffPair(0,0); ArrayList<String> messages = new ArrayList<String>(); AbstractScanPlanNode spn1 = null; AbstractScanPlanNode spn2 = null; if( max == 0 ) { messages.add("0 scan statement"); } else { if( size1 != size2 ){ intdiffPair.set(size1, size2); messages.add("Scan time diff : "+"\n"+intdiffPair.toString()+"\n"+"SQL statement might be changed"); m_changedSQL = true; for( int i = 0; i < min; i++ ) { spn1 = list1.get(i); spn2 = list2.get(i); scanNodeDiffModule(i, spn1, spn2, messages); } //lists size are different if( size2 < max ) { for( int i = min; i < max; i++ ) { spn1 = list1.get(i); spn2 = null; scanNodeDiffModule(i, spn1, spn2, messages); } } else if( size1 < max ) { for( int i = min; i < max; i++ ) { spn1 = null; spn2 = list2.get(i); scanNodeDiffModule(i, spn1, spn2, messages); } } } else { messages.add( "same leaf size" ); if( max == 1 ) { messages.add("Single scan plan"); spn1 = list1.get(0); spn2 = list2.get(0); scanNodeDiffModule(0, spn1, spn2, messages); } else { messages.add("Join query"); for( int i = 0; i < max; i++ ) { spn1 = list1.get(i); spn2 = list2.get(i); scanNodeDiffModule(i, spn1, spn2, messages); } } } } for( String msg : messages ) { if( msg.contains("diff") || msg.contains("Diff") ) { noDiff = false; break; } } m_diffMessages.addAll(messages); return noDiff; } //return true is there are no diff //false if there's any diff public static boolean diff( AbstractPlanNode oldpn, AbstractPlanNode newpn, boolean print ) { m_diffMessages.clear(); boolean noDiff1 = diffScans(oldpn, newpn); boolean noDiff2 = diffInlineAndJoin(oldpn, newpn); noDiff1 = noDiff1 && noDiff2; if( noDiff1 ) { return true; } else { if( print ) { for( String msg : m_diffMessages ) { System.out.println(msg); } } return false; } } }
package io.branch.referral; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.branch.indexing.BranchUniversalObject; import io.branch.referral.util.LinkProperties; /** * <p> * The core object required when using Branch SDK. You should declare an object of this type at * the class-level of each Activity or Fragment that you wish to use Branch functionality within. * </p> * <p/> * <p> * Normal instantiation of this object would look like this: * </p> * <p/> * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * Branch.getInstance(this.getApplicationContext()) // from an Activity * <p/> * Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment * </pre> */ public class Branch implements BranchViewHandler.IBranchViewEvents { private static final String TAG = "BranchSDK"; /** * Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that * are shared with others directly as a user action, via social media for instance. */ public static final String FEATURE_TAG_SHARE = "share"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated * with a referral program, incentivized or not. */ public static final String FEATURE_TAG_REFERRAL = "referral"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as * referral actions by users of an app using an 'invite contacts' feature for instance. */ public static final String FEATURE_TAG_INVITE = "invite"; /** * Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer. */ public static final String FEATURE_TAG_DEAL = "deal"; /** * Hard-coded {@link String} that denotes a link tagged as a gift action within a service or * product. */ public static final String FEATURE_TAG_GIFT = "gift"; /** * The code to be passed as part of a deal or gift; retrieved from the Branch object as a * tag upon initialisation. Of {@link String} format. */ public static final String REDEEM_CODE = "$redeem_code"; /** * <p>Default value of referral bucket; referral buckets contain credits that are used when users * are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p> */ public static final String REFERRAL_BUCKET_DEFAULT = "default"; /** * <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions. * Even if they are of 0 value.</p> */ public static final String REFERRAL_CODE_TYPE = "credit"; /** * Branch SDK version for the current release of the Branch SDK. */ public static final int REFERRAL_CREATION_SOURCE_SDK = 2; /** * Key value for referral code as a parameter. */ public static final String REFERRAL_CODE = "referral_code"; /** * The redirect URL provided when the link is handled by a desktop client. */ public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; /** * The redirect URL provided when the link is handled by an Android device. */ public static final String REDIRECT_ANDROID_URL = "$android_url"; /** * The redirect URL provided when the link is handled by an iOS device. */ public static final String REDIRECT_IOS_URL = "$ios_url"; /** * The redirect URL provided when the link is handled by a large form-factor iOS device such as * an iPad. */ public static final String REDIRECT_IPAD_URL = "$ipad_url"; /** * The redirect URL provided when the link is handled by an Amazon Fire device. */ public static final String REDIRECT_FIRE_URL = "$fire_url"; /** * The redirect URL provided when the link is handled by a Blackberry device. */ public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; /** * The redirect URL provided when the link is handled by a Windows Phone device. */ public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; /** * Unique identifier for the app in use. */ public static final String OG_APP_ID = "$og_app_id"; /** * {@link String} value denoting the deep link path to override Branch's default one. By * default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value, * Branch will use yourapp://'$deeplink_path'?link_click_id=12345 */ public static final String DEEPLINK_PATH = "$deeplink_path"; /** * {@link String} value indicating whether the link should always initiate a deep link action. * By default, unless overridden on the dashboard, Branch will only open the app if they are * 100% sure the app is installed. This setting will cause the link to always open the app. * Possible values are "true" or "false" */ public static final String ALWAYS_DEEPLINK = "$always_deeplink"; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user applying the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user who created the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, both the creator and applicant receive credit */ public static final int REFERRAL_CODE_LOCATION_BOTH = 3; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * the referral code can be applied continually. */ public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * a user can only apply a specific referral code once. */ public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used an * unlimited number of times. */ public static final int LINK_TYPE_UNLIMITED_USE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used only * once. After initial use, subsequent attempts will not validate. */ public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; /** * <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a * looping task before triggering an actual connection close during a session close action.</p> */ private static final int PREVENT_CLOSE_TIMEOUT = 500; /* Json object containing key-value pairs for debugging deep linking */ private JSONObject deeplinkDebugParams_; /** * <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of * the class during application runtime.</p> */ private static Branch branchReferral_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; final Object lock; private Timer closeTimer; private Timer rotateCloseTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private boolean hasNetwork_; private Map<BranchLinkData, String> linkCache_; private ScheduledFuture<?> appListingSchedule_; /* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */ private static boolean isAutoSessionMode_ = false; /* Set to true when {@link Activity} life cycle callbacks are registered. */ private static boolean isActivityLifeCycleCallbackRegistered_ = false; /* Enumeration for defining session initialisation state. */ private enum SESSION_STATE { INITIALISED, INITIALISING, UNINITIALISED } /* Holds the current Session state. Default is set to UNINITIALISED. */ private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED; /* Instance of share link manager to share links automatically with third party applications. */ private ShareLinkManager shareLinkManager_; /* The current activity instance for the application.*/ WeakReference<Activity> currentActivityReference_; /* Specifies the choice of user for isReferrable setting. used to determine the link click is referrable or not. See getAutoSession for usage */ private enum CUSTOM_REFERRABLE_SETTINGS { USE_DEFAULT, REFERRABLE, NON_REFERRABLE } /* By default assume user want to use the default settings. Update this option when user specify custom referrable settings */ private static CUSTOM_REFERRABLE_SETTINGS customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; /* Key to indicate whether the Activity was launched by Branch or not. */ private static final String AUTO_DEEP_LINKED = "io.branch.sdk.auto_linked"; /* Key for Auto Deep link param. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_KEY = "io.branch.sdk.auto_link_keys"; /* Path for $deeplink_path or $android_deeplink_path to auto deep link. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_PATH = "io.branch.sdk.auto_link_path"; /* Key for disabling auto deep link feature. Setting this to true in manifest will disable auto deep linking feature. */ private static final String AUTO_DEEP_LINK_DISABLE = "io.branch.sdk.auto_link_disable"; /*Key for defining a request code for an activity. should be added as a metadata for an activity. This is used as a request code for launching a an activity on auto deep link. */ private static final String AUTO_DEEP_LINK_REQ_CODE = "io.branch.sdk.auto_link_request_code"; /* Request code used to launch and activity on auto deep linking unless DEF_AUTO_DEEP_LINK_REQ_CODE is not specified for teh activity in manifest.*/ private static final int DEF_AUTO_DEEP_LINK_REQ_CODE = 1501; /* Sets to true when the init session params are reported to the app though call back.*/ private boolean isInitReportedThroughCallBack = false; private final ConcurrentHashMap<String, String> instrumentationExtraData_; /** * <p>The main constructor of the Branch class is private because the class uses the Singleton * pattern.</p> * <p/> * <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p> * * @param context A {@link Context} from which this call was made. */ private Branch(@NonNull Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); rotateCloseTimer = new Timer(); lock = new Object(); keepAlive_ = false; networkCount_ = 0; hasNetwork_ = true; linkCache_ = new HashMap<>(); instrumentationExtraData_ = new ConcurrentHashMap<>(); } /** * <p>Singleton method to return the pre-initialised object of the type {@link Branch}. * Make sure your app is instantiating {@link BranchApp} before calling this method * or you have created an instance of Branch already by calling getInstance(Context ctx).</p> * * @return An initialised singleton {@link Branch} object */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getInstance() { /* Check if BranchApp is instantiated. */ if (branchReferral_ == null) { Log.e("BranchSDK", "Branch instance is not created yet. Make sure you have initialised Branch. [Consider Calling getInstance(Context ctx) if you still have issue.]"); } else if (isAutoSessionMode_) { /* Check if Activity life cycle callbacks are set if in auto session mode. */ if (!isActivityLifeCycleCallbackRegistered_) { Log.e("BranchSDK", "Branch instance is not properly initialised. Make sure your Application class is extending BranchApp class. " + "If you are not extending BranchApp class make sure you are initialising Branch in your Applications onCreate()"); } } return branchReferral_; } public static Branch getInstance(@NonNull Context context, @NonNull String branchKey) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context.getApplicationContext(); if (branchKey.startsWith("key_")) { boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } else { branchReferral_.prefHelper_.setAppKey(branchKey); } return branchReferral_; } private static Branch getBranchInstance(@NonNull Context context, boolean isLive) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive); boolean isNewBranchKeySet; if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!"); isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE); } else { isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); } //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } branchReferral_.context_ = context.getApplicationContext(); /* If {@link Application} is instantiated register for activity life cycle events. */ if (context instanceof BranchApp) { isAutoSessionMode_ = true; branchReferral_.setActivityLifeCycleObserver((Application) context); } return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p/> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getInstance(@NonNull Context context) { return getBranchInstance(context, true); } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ public static Branch getTestInstance(@NonNull Context context) { return getBranchInstance(context, false); } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p/> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; boolean isLive = !BranchUtil.isTestModeEnabled(context); getBranchInstance(context, isLive); branchReferral_.setActivityLifeCycleObserver((Application) context); return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p/> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE; boolean isDebug = BranchUtil.isTestModeEnabled(context); getBranchInstance(context, !isDebug); branchReferral_.setActivityLifeCycleObserver((Application) context); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoTestInstance(@NonNull Context context) { isAutoSessionMode_ = true; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT; getBranchInstance(context, false); branchReferral_.setActivityLifeCycleObserver((Application) context); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static Branch getAutoTestInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE; getBranchInstance(context, false); branchReferral_.setActivityLifeCycleObserver((Application) context); return branchReferral_; } /** * <p>Initialises an instance of the Branch object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ private static Branch initInstance(@NonNull Context context) { return new Branch(context.getApplicationContext()); } /** * <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has * been initialised, to false - forcing re-initialisation.</p> */ public void resetUserSession() { initState_ = SESSION_STATE.UNINITIALISED; } /** * <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before * considering the request to have failed entirely. Default 5.</p> * * @param retryCount An {@link Integer} specifying the number of times to retry before giving * up and declaring defeat. */ public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount > 0) { prefHelper_.setRetryCount(retryCount); } } /** * <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request * to the Branch API. Default 3000 ms.</p> * * @param retryInterval An {@link Integer} value specifying the number of milliseconds to * wait before re-attempting a timed-out request. */ public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } /** * <p>Sets the duration in milliseconds that the system should wait for a response before considering * any Branch API call to have timed out. Default 3000 ms.</p> * <p/> * <p>Increase this to perform better in low network speed situations, but at the expense of * responsiveness to error situation.</p> * * @param timeout An {@link Integer} value specifying the number of milliseconds to wait before * considering the request to have timed out. */ public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } /** * <p>Sets the library to function in debug mode, enabling logging of all requests.</p> * <p>If you want to flag debug, call this <b>before</b> initUserSession</p> * * @deprecated use <meta-data android:name="io.branch.sdk.TestMode" android:value="true" /> in the manifest instead. */ @Deprecated public void setDebug() { prefHelper_.setExternDebug(); } /** * Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session. * This method should be called from onCreate() of activity which listens to Branch Init Session callbacks * * @param debugParams A {@link JSONObject} containing key-value pairs for debugging branch deep linking */ public void setDeepLinkDebugMode(JSONObject debugParams) { deeplinkDebugParams_ = debugParams; } /** * <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent * a list of installed apps from being returned to the Branch API.</p> */ public void disableAppList() { prefHelper_.disableExternAppListing(); } /** * <p>If there's further Branch API call happening within the two seconds, we then don't close * the session; otherwise, we close the session after two seconds.</p> * <p/> * <p>Call this method if you don't want this smart session feature and would rather manage * the session yourself.</p> * <p/> * <p><b>Note:</b> smart session - we keep session alive for two seconds</p> */ public void disableSmartSession() { prefHelper_.disableSmartSession(); } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchUniversalReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback) { initSession(callback, (Activity) null); return false; } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback) { initSession(callback, (Activity) null); return false; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchUniversalReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, Activity activity) { if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return false; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return false; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data) { return initSession(callback, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data) { return initSession(callback, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession() { return initSession((Activity) null); } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(Activity activity) { return initSession((BranchReferralInitListener) null, activity); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that * led to this * initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(@NonNull Uri data) { return initSessionWithData(data, null); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that led to this * initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession((BranchReferralInitListener) null, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable) { return initSession((BranchReferralInitListener) null, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action, and supplying the calling {@link Activity} for context.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable, @NonNull Activity activity) { return initSession((BranchReferralInitListener) null, isReferrable, activity); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data) { return initSession(callback, isReferrable, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data) { return initSession(callback, isReferrable, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, isReferrable, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, isReferrable, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity) null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Activity activity) { initUserSessionInternal(callback, activity, isReferrable); return false; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { initUserSessionInternal(callback, activity, isReferrable); return false; } private void initUserSessionInternal(BranchUniversalReferralInitListener callback, Activity activity, boolean isReferrable) { BranchUniversalReferralInitWrapper branchUniversalReferralInitWrapper = new BranchUniversalReferralInitWrapper(callback); initUserSessionInternal(branchUniversalReferralInitWrapper, activity, isReferrable); } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity, boolean isReferrable) { if (activity != null) { currentActivityReference_ = new WeakReference<>(activity); } //If already initialised if (hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED) { if (callback != null) { if (isAutoSessionMode_) { // Since Auto session mode initialise the session by itself on starting the first activity, we need to provide user // the referring params if they call init session after init is completed. Note that user wont do InitSession per activity in auto session mode. if (!isInitReportedThroughCallBack) { //Check if session params are reported already in case user call initsession form a different activity(not a noraml case) callback.onInitFinished(getLatestReferringParams(), null); isInitReportedThroughCallBack = true; } else { callback.onInitFinished(new JSONObject(), null); } } else { // Since user will do init session per activity in non auto session mode , we don't want to repeat the referring params with each initSession()call. callback.onInitFinished(new JSONObject(), null); } } clearCloseTimer(); keepAlive(); } //If uninitialised or initialising else { // In case of Auto session init will be called from Branch before user. So initialising // State also need to look for isReferrable value if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } //If initialising ,then set new callbacks. if (initState_ == SESSION_STATE.INITIALISING) { requestQueue_.setInstallOrOpenCallback(callback); } //if Uninitialised move request to the front if there is an existing request or create a new request. else { initState_ = SESSION_STATE.INITIALISING; initializeSession(callback); } } } /** * <p>Closes the current session, dependent on the state of the * {@link PrefHelper#getSmartSession()} {@link Boolean} value. If <i>true</i>, take no action. * If false, close the sesion via the {@link #executeClose()} method.</p> * <p>Note that if smartSession is enabled, closeSession cannot be called within * a 2 second time span of another Branch action. This has to do with the method that * Branch uses to keep a session alive during Activity transitions</p> */ public void closeSession() { if (isAutoSessionMode_) { /* * Ignore any session close request from user if session is managed * automatically.This is handle situation of closeSession() in * closed by developer by error while running in auto session mode. */ return; } if (prefHelper_.getSmartSession()) { if (keepAlive_) { return; } // else, real close synchronized (lock) { clearCloseTimer(); rotateCloseTimer.schedule(new TimerTask() { @Override public void run() { //Since non auto session has no lifecycle callback enabled free up the currentActivity_ if (currentActivityReference_ != null) { currentActivityReference_.clear(); } executeClose(); } }, PREVENT_CLOSE_TIMEOUT); } } else { //Since non auto session has no lifecycle callback enabled free up the currentActivity_ if (currentActivityReference_ != null) { currentActivityReference_.clear(); } executeClose(); } if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } /* Close any opened sharing dialog.*/ if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } } /* * <p>Closes the current session. Should be called by on getting the last actvity onStop() event. * </p> */ private void closeSessionInternal() { executeClose(); if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } /** * <p>Perform the state-safe actions required to terminate any open session, and report the * closed application event to the Branch API.</p> */ private void executeClose() { if (initState_ != SESSION_STATE.UNINITIALISED) { if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) { requestQueue_.dequeue(); } } else { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequestRegisterClose(context_); handleNewRequest(req); } } initState_ = SESSION_STATE.UNINITIALISED; } } private boolean readAndStripParam(Uri data, Activity activity) { // Capture the intent URI and extra for analytics in case started by external intents such as google app search try { if (data != null) { prefHelper_.setExternalIntentUri(data.toString()); } if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) { Bundle bundle = activity.getIntent().getExtras(); Set<String> extraKeys = bundle.keySet(); if (extraKeys.size() > 0) { JSONObject extrasJson = new JSONObject(); for (String key : extraKeys) { extrasJson.put(key, bundle.get(key)); } prefHelper_.setExternalIntentExtra(extrasJson.toString()); } } } catch (Exception ignore) { } //Check for any push identifier in case app is launched by a push notification if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) { try { String pushIdentifier = activity.getIntent().getExtras().getString(Defines.Jsonkey.AndroidPushNotificationKey.getKey()); // This seems producing unmarshalling errors in some corner cases if (pushIdentifier != null && pushIdentifier.length() > 0) { prefHelper_.setPushIdentifier(pushIdentifier); return false; } } catch (Exception ignore) { } } //Check for link click id or app link if (data != null && data.isHierarchical() && activity != null) { try { if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey())); String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); String uriString = null; if (activity.getIntent() != null) { uriString = activity.getIntent().getDataString(); } if (data.getQuery().length() == paramString.length()) { paramString = "\\?" + paramString; } else if (uriString != null && (uriString.length() - paramString.length()) == uriString.indexOf(paramString)) { paramString = "&" + paramString; } else { paramString = paramString + "&"; } if (uriString != null) { Uri newData = Uri.parse(uriString.replaceFirst(paramString, "")); activity.getIntent().setData(newData); } else { Log.w(TAG, "Branch Warning. URI for the launcher activity is null. Please make sure that intent data is not set to null before calling Branch#InitSession "); } return true; } else { // Check if the clicked url is an app link pointing to this app String scheme = data.getScheme(); if (scheme != null && activity.getIntent() != null) { // On Launching app from the recent apps, Android Start the app with the original intent data. So up in opening app from recent list // Intent will have App link in data and lead to issue of getting wrong parameters. (In case of link click id since we are looking for actual link click on back end this case will never happen) if ((activity.getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) && data.getHost() != null && data.getHost().length() > 0 && data.getQueryParameter(Defines.Jsonkey.AppLinkUsed.getKey()) == null) { prefHelper_.setAppLink(data.toString()); String uriString = data.toString(); uriString += uriString.contains("?") ? "&" : "?"; uriString += Defines.Jsonkey.AppLinkUsed.getKey() + "=true"; activity.getIntent().setData(Uri.parse(uriString)); return false; } } } } } catch (Exception ignore) { } } return false; } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value. No callback.</p> * * @param userId A {@link String} value containing the unique identifier of the user. */ public void setIdentity(@NonNull String userId) { setIdentity(userId, null); } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value, with a callback specified to perform a defined action upon successful * response to request.</p> * * @param userId A {@link String} value containing the unique identifier of the user. * @param callback A {@link BranchReferralInitListener} callback instance that will return * the data associated with the user id being assigned, if available. */ public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener callback) { ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } else { if (((ServerRequestIdentifyUserRequest) req).isExistingID()) { ((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_); } } } /** * Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs. * If you call setIdentity, this device will have that identity associated with this user until logout is called. * This includes persisting through uninstalls, as we track device id. * * @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity. */ public boolean isUserIdentified() { return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> */ public void logout() { logout(null); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> * * @param callback An instance of {@link io.branch.referral.Branch.LogoutStatusListener} to callback with the logout operation status. */ public void logout(LogoutStatusListener callback) { ServerRequest req = new ServerRequestLogout(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } @Deprecated public void loadActionCounts() { //noinspection deprecation loadActionCounts(null); } @Deprecated public void loadActionCounts(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetReferralCount(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p> */ public void loadRewards() { loadRewards(null); } /** * <p>Retrieves rewards for the current session, with a callback to perform a predefined * action following successful report of state change. You'll then need to call getCredits * in the callback to update the credit totals in your UX.</p> * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a referral state change. */ public void loadRewards(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetRewards(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Retrieve the number of credits available for the "default" bucket.</p> * * @return An {@link Integer} value of the number credits available in the "default" bucket. */ public int getCredits() { return prefHelper_.getCreditCount(); } /** * Returns an {@link Integer} of the number of credits available for use within the supplied * bucket name. * * @param bucket A {@link String} value indicating the name of the bucket to get credits for. * @return An {@link Integer} value of the number credits available in the specified * bucket. */ public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } @Deprecated public int getTotalCountsForAction(@NonNull String action) { return prefHelper_.getActionTotalCount(action); } @Deprecated public int getUniqueCountsForAction(@NonNull String action) { return prefHelper_.getActionUniqueCount(action); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. */ public void redeemRewards(int count) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(int count, BranchReferralStateChangedListener callback) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. */ public void redeemRewards(@NonNull final String bucket, final int count) { redeemRewards(bucket, count, null); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(@NonNull final String bucket, final int count, BranchReferralStateChangedListener callback) { ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p/> * <p>Valid choices:</p> * <p/> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p/> * <p>Valid choices:</p> * <p/> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String bucket, final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. */ public void userCompletedAction(@NonNull final String action, JSONObject metadata) { userCompletedAction(action, metadata, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". */ public void userCompletedAction(final String action) { userCompletedAction(action, null, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(final String action, BranchViewHandler.IBranchViewEvents callback) { userCompletedAction(action, null, callback); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { if (metadata != null) { metadata = BranchUtil.filterOutBadCharacters(metadata); } ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam); firstReferringParams = appendDebugParams(firstReferringParams); return firstReferringParams; } /** * <p>Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the paramters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); JSONObject latestParams = convertParamsStringToDictionary(storedParam); latestParams = appendDebugParams(latestParams); return latestParams; } /** * Append the deep link debug params to the original params * * @param originalParams A {@link JSONObject} original referrer parameters * @return A new {@link JSONObject} with debug params appended. */ private JSONObject appendDebugParams(JSONObject originalParams) { try { if (originalParams != null && deeplinkDebugParams_ != null) { if (deeplinkDebugParams_.length() > 0) { Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } Iterator<String> keys = deeplinkDebugParams_.keys(); while (keys.hasNext()) { String key = keys.next(); originalParams.put(key, deeplinkDebugParams_.get(key)); } } } catch (Exception ignore) { } return originalParams; } public JSONObject getDeeplinkDebugParams() { if (deeplinkDebugParams_ != null && deeplinkDebugParams_.length() > 0) { Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } return deeplinkDebugParams_; } @Deprecated public String getShortUrlSync() { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.stringifyAndAddSource(new JSONObject()), null, false); } @Deprecated public String getShortUrlSync(JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(null, type, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { //noinspection deprecation return generateShortLink(null, type, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false); } @Deprecated public void getShortUrl(BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.stringifyAndAddSource(new JSONObject()), callback, true); } @Deprecated public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, type, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, type, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } @Deprecated private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) { ServerRequestCreateUrl req = new ServerRequestCreateUrl(context_, alias, type, duration, tags, channel, feature, stage, params, callback, async); if (!req.constructError_ && !req.handleErrors(context_)) { if (linkCache_.containsKey(req.getLinkPost())) { String url = linkCache_.get(req.getLinkPost()); if (callback != null) { callback.onLinkCreate(url, null); } return url; } else { if (async) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } /** * <p> Generates a shorl url fot the given {@link ServerRequestCreateUrl} object </p> * * @param req An instance of {@link ServerRequestCreateUrl} with parameters create the short link. * @return A url created with the given request if the request is synchronous else null. * Note : This method can be used only internally. Use {@link BranchUrlBuilder} for creating short urls. */ public String generateShortLinkInternal(ServerRequestCreateUrl req) { if (!req.constructError_ && !req.handleErrors(context_)) { if (linkCache_.containsKey(req.getLinkPost())) { String url = linkCache_.get(req.getLinkPost()); req.onUrlAvailable(url); return url; } else { if (req.isAsync()) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } /** * <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * @see BranchLinkData * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener * @deprecated use {@link BranchReferralUrlBuilder} instead. */ @Deprecated public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } /** * <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener * @deprecated use {@link BranchReferralUrlBuilder} instead. */ @Deprecated public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } /** * <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @return A {@link String} containing the resulting referral URL. * @deprecated use {@link BranchReferralUrlBuilder} instead. */ @Deprecated public String getReferralUrlSync(String channel, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), null, false); } /** * <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @return A {@link String} containing the resulting referral URL. * @deprecated use {@link BranchReferralUrlBuilder} instead. */ @Deprecated public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), null, false); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * @see BranchLinkData * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener * @deprecated use {@link BranchContentUrlBuilder} instead. */ @Deprecated public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener * @deprecated use {@link BranchContentUrlBuilder} instead. */ @Deprecated public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { //noinspection deprecation generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous * call</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @return A {@link String} containing the resulting content URL. * @deprecated use {@link BranchContentUrlBuilder} instead. */ @Deprecated public String getContentUrlSync(String channel, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), null, false); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous * call</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * @return A {@link String} containing the resulting content URL. * @deprecated use {@link BranchContentUrlBuilder} instead. */ @Deprecated public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) { //noinspection deprecation return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), null, false); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(BranchReferralInitListener callback) { ServerRequest req = new ServerRequestGetReferralCode(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param amount An {@link Integer} value of credits associated with this referral code. * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final int amount, BranchReferralInitListener callback) { //noinspection deprecation this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be applied * to the start of a referral code. e.g. for code OFFER4867, the prefix would * be "OFFER". * @param amount An {@link Integer} value of credits associated with this referral code. * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) { //noinspection deprecation this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param amount An {@link Integer} value of credits associated with this referral code. * @param expiration Optional expiration {@link Date} of the offer code. * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code * request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) { //noinspection deprecation this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be * applied to the start of a referral code. e.g. for code OFFER4867, the * prefix would be "OFFER". * @param amount An {@link Integer} value of credits associated with this referral code. * @param expiration Optional expiration {@link Date} of the offer code. * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code * request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) { //noinspection deprecation this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be * applied to the start of a referral code. e.g. for code OFFER4867, the * prefix would be "OFFER". * @param amount An {@link Integer} value of credits associated with this referral code. * @param calculationType The type of referral calculation. i.e. * {@link #LINK_TYPE_UNLIMITED_USE} or * {@link #LINK_TYPE_ONE_TIME_USE} * @param location The user to reward for applying the referral code. * <p/> * <p>Valid options:</p> * <p/> * <ul> * <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li> * <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li> * <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li> * </ul> * @param callback A {@link BranchReferralInitListener} callback instance that will * trigger actions defined therein upon receipt of a response to a * referral code request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) { //noinspection deprecation this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to * be applied to the start of a referral code. e.g. for code OFFER4867, * the prefix would be "OFFER". * @param amount An {@link Integer} value of credits associated with this referral code. * @param expiration Optional expiration {@link Date} of the offer code. * @param bucket A {@link String} value containing the name of the referral bucket * that the code will belong to. * @param calculationType The type of referral calculation. i.e. * {@link #LINK_TYPE_UNLIMITED_USE} or * {@link #LINK_TYPE_ONE_TIME_USE} * @param location The user to reward for applying the referral code. * <p/> * <p>Valid options:</p> * <p/> * <ul> * <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li> * <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li> * <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li> * </ul> * @param callback A {@link BranchReferralInitListener} callback instance that will * trigger actions defined therein upon receipt of a response to a * referral code request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) { String date = null; if (expiration != null) date = convertDate(expiration); ServerRequest req = new ServerRequestGetReferralCode(context_, prefix, amount, date, bucket, calculationType, location, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Validates the supplied referral code on initialisation without applying it to the current * session.</p> * * @param code A {@link String} object containing the referral code supplied. * @param callback A {@link BranchReferralInitListener} callback to handle the server response * of the referral submission request. * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void validateReferralCode(final String code, BranchReferralInitListener callback) { ServerRequest req = new ServerRequestValidateReferralCode(context_, callback, code); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Applies a supplied referral code to the current user session upon initialisation.</p> * * @param code A {@link String} object containing the referral code supplied. * @param callback A {@link BranchReferralInitListener} callback to handle the server * response of the referral submission request. * @see BranchReferralInitListener * @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality. */ @Deprecated public void applyReferralCode(final String code, final BranchReferralInitListener callback) { ServerRequest req = new ServerRequestApplyReferralCode(context_, callback, code); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Creates options for sharing a link with other Applications. Creates a link with given attributes and shares with the * user selected clients.</p> * * @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link. */ private void shareLink(ShareLinkBuilder builder) { //Cancel any existing sharing in progress. if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } shareLinkManager_ = new ShareLinkManager(); shareLinkManager_.shareLink(builder); } /** * <p>Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you are * calling this method before your activity finishes inorder to prevent any window leak. </p> * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(animateClose); } } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String generateShortLinkSync(ServerRequestCreateUrl req) { if (initState_ == SESSION_STATE.INITIALISED) { ServerResponse response = null; try { int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case response = new getShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException ignore) { } String url = req.getLongUrl(); if (response != null && response.getStatusCode() == HttpURLConnection.HTTP_OK) { try { url = response.getObject().getString("url"); if (req.getLinkPost() != null) { linkCache_.put(req.getLinkPost(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { handleNewRequest(req); } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } /** * <p>Schedules a repeating threaded task to get the following details and report them to the * Branch API <b>once a week</b>:</p> * <p/> * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * int interval = 7 * 24 * 60 * 60; * appListingSchedule_ = scheduler.scheduleAtFixedRate( * periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);</pre> * <p/> * <ul> * <li>{@link SystemObserver#getOS()}</li> * <li>{@link SystemObserver#getListOfApps()}</li> * </ul> * * @see {@link SystemObserver} * @see {@link PrefHelper} */ private void scheduleListOfApps() { ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); Runnable periodicTask = new Runnable() { @Override public void run() { ServerRequest req = new ServerRequestSendAppList(context_); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } }; Date date = new Date(); Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(date); int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative if (days == 0 && hours < 0) { days = 7; } int interval = 7 * 24 * 60 * 60; appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS); } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (req != null) { //All request except Install request need a valid IdentityID if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) { Log.i("BranchSDK", "Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } //All request except open and install need a session to execute else if (!(req instanceof ServerRequestInitSession) && (!hasSession() || !hasDeviceFingerPrint())) { networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } else { BranchPostTask postTask = new BranchPostTask(req); postTask.execute(); } } else { requestQueue_.remove(null); //Inc ase there is any request nullified remove it. } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index, int statusCode) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize() - 1); } else { req = requestQueue_.peekAt(index); } handleFailure(req, statusCode); } private void handleFailure(final ServerRequest req, int statusCode) { if (req == null) return; req.handleFailure(statusCode, ""); } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals(Defines.Jsonkey.SessionID.getKey())) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals(Defines.Jsonkey.IdentityID.getKey())) { req.getPost().put(key, prefHelper_.getIdentityID()); } else if (key.equals(Defines.Jsonkey.DeviceFingerprintID.getKey())) { req.getPost().put(key, prefHelper_.getDeviceFingerPrintID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearCloseTimer() { if (rotateCloseTimer == null) return; rotateCloseTimer.cancel(); rotateCloseTimer.purge(); rotateCloseTimer = new Timer(); } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; synchronized (lock) { clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasDeviceFingerPrint() { return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) { // If there isn't already an Open / Install request, add one to the queue if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(req); } // If there is already one in the queue, make sure it's in the front. // Make sure a callback is associated with this request. This callback can // be cleared if the app is terminated while an Open/Install is pending. else { // Update the callback to the latest one in initsession call requestQueue_.setInstallOrOpenCallback(callback); requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback); } processNextQueueItem(); } private void initializeSession(BranchReferralInitListener callback) { if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) && (prefHelper_.getAppKey() == null || prefHelper_.getAppKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) { initState_ = SESSION_STATE.UNINITIALISED; //Report Key error on callback if (callback != null) { callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", RemoteInterface.NO_BRANCH_KEY_STATUS)); } Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!"); return; } else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) { Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment."); } if (hasUser()) { registerInstallOrOpen(new ServerRequestRegisterOpen(context_, callback, kRemoteInterface_.getSystemObserver()), callback); } else { registerInstallOrOpen(new ServerRequestRegisterInstall(context_, callback, kRemoteInterface_.getSystemObserver(), InstallListener.getInstallationID()), callback); } } /** * Handles execution of a new request other than open or install. * Checks for the session initialisation and adds a install/Open request in front of this request * if the request need session to execute. * * @param req The {@link ServerRequest} to execute */ public void handleNewRequest(ServerRequest req) { //If not initialised put an open or install request in front of this request(only if this needs session) if (initState_ != SESSION_STATE.INITIALISED && !(req instanceof ServerRequestInitSession)) { if ((req instanceof ServerRequestLogout)) { req.handleFailure(BranchError.ERR_NO_SESSION, ""); Log.i(TAG, "Branch is not initialized, cannot logout"); return; } if ((req instanceof ServerRequestRegisterClose)) { Log.i(TAG, "Branch is not initialized, cannot close session"); return; } else { Activity currentActivity = null; if (currentActivityReference_ != null) { currentActivity = currentActivityReference_.get(); } if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal((BranchReferralInitListener) null, currentActivity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal((BranchReferralInitListener) null, currentActivity, isReferrable); } } } requestQueue_.enqueue(req); req.onRequestQueued(); processNextQueueItem(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setActivityLifeCycleObserver(Application application) { try { BranchActivityLifeCycleObserver activityLifeCycleObserver = new BranchActivityLifeCycleObserver(); /* Set an observer for activity life cycle events. */ application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver); application.registerActivityLifecycleCallbacks(activityLifeCycleObserver); isActivityLifeCycleCallbackRegistered_ = true; } catch (NoSuchMethodError | NoClassDefFoundError Ex) { isActivityLifeCycleCallbackRegistered_ = false; isAutoSessionMode_ = false; /* LifeCycleEvents are available only from API level 14. */ Log.w(TAG, new BranchError("", BranchError.ERR_API_LVL_14_NEEDED).getMessage()); } } /** * <p>Class that observes activity life cycle events and determines when to start and stop * session.</p> */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks { private int activityCnt_ = 0; //Keep the count of live activities. @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (BranchViewHandler.getInstance().isInstallOrOpenBranchViewPending(activity.getApplicationContext())) { BranchViewHandler.getInstance().showPendingBranchView(activity); } } @Override public void onActivityStarted(Activity activity) { if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session. // Check if debug mode is set in manifest. If so enable debug. if (BranchUtil.isTestModeEnabled(context_)) { //noinspection deprecation setDebug(); } Uri intentData = null; if (activity.getIntent() != null) { intentData = activity.getIntent().getData(); } initSessionWithData(intentData, activity); // indicate starting of session. } activityCnt_++; } @Override public void onActivityResumed(Activity activity) { currentActivityReference_ = new WeakReference<>(activity); } @Override public void onActivityPaused(Activity activity) { /* Close any opened sharing dialog.*/ if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } } @Override public void onActivityStopped(Activity activity) { activityCnt_--; // Check if this is the last activity.If so stop // session. if (activityCnt_ < 1) { closeSessionInternal(); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { if (currentActivityReference_ != null && currentActivityReference_.get() == activity) { currentActivityReference_.clear(); } BranchViewHandler.getInstance().onCurrentActivityDestroyed(activity); } } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralInitListener}, defining a single method that takes a list of params in * {@link JSONObject} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONObject * @see BranchError */ public interface BranchReferralInitListener { void onInitFinished(JSONObject referringParams, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchUniversalReferralInitListener}, defining a single method that provides * {@link BranchUniversalObject}, {@link LinkProperties} and an error message of {@link BranchError} format that will be * returned on failure of the request response. * In case of an error the value for {@link BranchUniversalObject} and {@link LinkProperties} are set to null.</p> * * @see BranchUniversalObject * @see LinkProperties * @see BranchError */ public interface BranchUniversalReferralInitListener { void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralStateChangedListener}, defining a single method that takes a value of * {@link Boolean} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see Boolean * @see BranchError */ public interface BranchReferralStateChangedListener { void onStateChanged(boolean changed, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkCreateListener}, defining a single method that takes a URL * {@link String} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see String * @see BranchError */ public interface BranchLinkCreateListener { void onLinkCreate(String url, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkShareListener}, defining methods to listen for link sharing status.</p> */ public interface BranchLinkShareListener { /** * <p> Callback method to update when share link dialog is launched.</p> */ void onShareLinkDialogLaunched(); /** * <p> Callback method to update when sharing dialog is dismissed.</p> */ void onShareLinkDialogDismissed(); /** * <p> Callback method to update the sharing status. Called on sharing completed or on error.</p> * * @param sharedLink The link shared to the channel. * @param sharedChannel Channel selected for sharing. * @param error A {@link BranchError} to update errors, if there is any. */ void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error); /** * <p>Called when user select a channel for sharing a deep link. * Branch will create a deep link for the selected channel and share with it after calling this * method. On sharing complete, status is updated by onLinkShareResponse() callback. Consider * having a sharing in progress UI if you wish to prevent user activity in the window between selecting a channel * and sharing complete.</p> * * @param channelName Name of the selected application to share the link. */ void onChannelSelected(String channelName); } /** * <p>An interface class for customizing sharing properties with selected channel.</p> */ public interface IChannelProperties { /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message title for sharing the link with the selected channel */ String getSharingTitleForChannel(String channel); /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message body for sharing the link with the selected channel */ String getSharingMessageForChannel(String channel); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchListResponseListener}, defining a single method that takes a list of * {@link JSONArray} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONArray * @see BranchError */ public interface BranchListResponseListener { void onReceivingResponse(JSONArray list, BranchError error); } /** * <p> * Callback interface for listening logout status * </p> */ public interface LogoutStatusListener { /** * Called on finishing the the logout process * * @param loggedOut A {@link Boolean} which is set to true if logout succeeded * @param error An instance of {@link BranchError} to notify any error occurred during logout. * A null value is set if logout succeeded. */ void onLogoutFinished(boolean loggedOut, BranchError error); } /** * <p>enum containing the sort options for return of credit history.</p> */ public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } /** * Async Task to create a shorlink for synchronous methods */ private class getShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> { @Override protected ServerResponse doInBackground(ServerRequest... serverRequests) { return kRemoteInterface_.createCustomUrlSync(serverRequests[0].getPost()); } } /** * Asynchronous task handling execution of server requests. Execute the network task on background * thread and request are executed in sequential manner. Handles the request execution in * Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are * published in the main thread. */ private class BranchPostTask extends AsyncTask<Void, Void, ServerResponse> { int timeOut_ = 0; ServerRequest thisReq_; public BranchPostTask(ServerRequest request) { thisReq_ = request; timeOut_ = prefHelper_.getTimeout(); } @Override protected ServerResponse doInBackground(Void... voids) { //Update queue wait time addExtraInstrumentationData(thisReq_.getRequestPath() + "-" + Defines.Jsonkey.Queue_Wait_Time.getKey(), String.valueOf(thisReq_.getQueueWaitTime())); //Google ADs ID and LAT value are updated using reflection. These method need background thread //So updating them for install and open on background thread. if (thisReq_.isGAdsParamsRequired()) { thisReq_.updateGAdsParams(systemObserver_); } if (thisReq_.isGetRequest()) { return kRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getGetParams(), thisReq_.getRequestPath(), timeOut_); } else { return kRemoteInterface_.make_restful_post(thisReq_.getPostWithInstrumentationValues(instrumentationExtraData_), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_); } } @Override protected void onPostExecute(ServerResponse serverResponse) { super.onPostExecute(serverResponse); if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); hasNetwork_ = true; //If the request is not succeeded if (status != 200) { //If failed request is an initialisation request then mark session not initialised if (thisReq_ instanceof ServerRequestInitSession) { initState_ = SESSION_STATE.UNINITIALISED; } // On a bad request notify with call back and remove the request. if (status == 409) { requestQueue_.remove(thisReq_); if (thisReq_ instanceof ServerRequestCreateUrl) { ((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError(); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0, status); } } //On Network error or Branch is down fail all the pending requests in the queue except //for request which need to be replayed on failure. else { hasNetwork_ = false; //Collect all request from the queue which need to be failed. ArrayList<ServerRequest> requestToFail = new ArrayList<>(); for (int i = 0; i < requestQueue_.getSize(); i++) { requestToFail.add(requestQueue_.peekAt(i)); } //Remove the requests from the request queue first for (ServerRequest req : requestToFail) { if (req == null || !req.shouldRetryOnFail()) { // Should remove any nullified request object also from queque requestQueue_.remove(req); } } // Then, set the network count to zero, indicating that requests can be started again. networkCount_ = 0; //Finally call the request callback with the error. for (ServerRequest req : requestToFail) { if (req != null) { req.handleFailure(status, serverResponse.getFailReason()); //If request need to be replayed, no need for the callbacks if (req.shouldRetryOnFail()) req.clearCallbacks(); } } } } //If the request succeeded else { hasNetwork_ = true; //On create new url cache the url. if (thisReq_ instanceof ServerRequestCreateUrl) { if (serverResponse.getObject() != null) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(((ServerRequestCreateUrl) thisReq_).getLinkPost(), url); } } //On Logout clear the link cache and all pending requests else if (thisReq_ instanceof ServerRequestLogout) { linkCache_.clear(); requestQueue_.clear(); } requestQueue_.dequeue(); // If this request changes a session update the session-id to queued requests. if (thisReq_ instanceof ServerRequestInitSession || thisReq_ instanceof ServerRequestIdentifyUserRequest) { // Immediately set session and Identity and update the pending request with the params if (serverResponse.getObject() != null) { boolean updateRequestsInQueue = false; if (serverResponse.getObject().has(Defines.Jsonkey.SessionID.getKey())) { prefHelper_.setSessionID(serverResponse.getObject().getString(Defines.Jsonkey.SessionID.getKey())); updateRequestsInQueue = true; } if (serverResponse.getObject().has(Defines.Jsonkey.IdentityID.getKey())) { String new_Identity_Id = serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey()); if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) { //On setting a new identity Id clear the link cache linkCache_.clear(); prefHelper_.setIdentityID(serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey())); updateRequestsInQueue = true; } } if (serverResponse.getObject().has(Defines.Jsonkey.DeviceFingerprintID.getKey())) { prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString(Defines.Jsonkey.DeviceFingerprintID.getKey())); updateRequestsInQueue = true; } if (updateRequestsInQueue) { updateAllRequestsInQueue(); } if (thisReq_ instanceof ServerRequestInitSession) { initState_ = SESSION_STATE.INITIALISED; // Publish success to listeners thisReq_.onRequestSucceeded(serverResponse, branchReferral_); isInitReportedThroughCallBack = ((ServerRequestInitSession) thisReq_).hasCallBack(); if (!((ServerRequestInitSession) thisReq_).handleBranchViewIfAvailable((serverResponse))) { checkForAutoDeepLinkConfiguration(); } } else { // For setting identity just call only request succeeded thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } } else { //Publish success to listeners thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } networkCount_ = 0; if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) { processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } /** * <p>Checks if an activity is launched by Branch auto deep link feature. Branch launches activitie configured for auto deep link on seeing matching keys. * Keys for auto deep linking should be specified to each activity as a meta data in manifest.</p> * <p> * Configure your activity in your manifest to enable auto deep linking as follows * <activity android:name=".YourActivity"> * <meta-data android:name="io.branch.sdk.auto_link" android:value="DeepLinkKey1","DeepLinkKey2" /> * </activity> * </p> * * @param activity Instance of activity to check if launched on auto deep link. * @return A {Boolean} value whose value is true if this activity is launched by Branch auto deeplink feature. */ public static boolean isAutoDeepLinkLaunch(Activity activity) { return (activity.getIntent().getStringExtra(AUTO_DEEP_LINKED) != null); } private void checkForAutoDeepLinkConfiguration() { JSONObject latestParams = getLatestReferringParams(); String deepLinkActivity = null; try { //Check if the application is launched by clicking a Branch link. if (!latestParams.has(Defines.Jsonkey.Clicked_Branch_Link.getKey()) || !latestParams.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) { return; } if (latestParams.length() > 0) { // Check if auto deep link is disabled. ApplicationInfo appInfo = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData != null && appInfo.metaData.getBoolean(AUTO_DEEP_LINK_DISABLE, false)) { return; } PackageInfo info = context_.getPackageManager().getPackageInfo(context_.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA); ActivityInfo[] activityInfos = info.activities; int deepLinkActivityReqCode = DEF_AUTO_DEEP_LINK_REQ_CODE; if (activityInfos != null) { for (ActivityInfo activityInfo : activityInfos) { if (activityInfo != null && activityInfo.metaData != null && (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null || activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null)) { if (checkForAutoDeepLinkKeys(latestParams, activityInfo) || checkForAutoDeepLinkPath(latestParams, activityInfo)) { deepLinkActivity = activityInfo.name; deepLinkActivityReqCode = activityInfo.metaData.getInt(AUTO_DEEP_LINK_REQ_CODE, DEF_AUTO_DEEP_LINK_REQ_CODE); break; } } } } if (deepLinkActivity != null && currentActivityReference_ != null) { Activity currentActivity = currentActivityReference_.get(); if (currentActivity != null) { Intent intent = new Intent(currentActivity, Class.forName(deepLinkActivity)); intent.putExtra(AUTO_DEEP_LINKED, "true"); // Put the raw JSON params as extra in case need to get the deep link params as JSON String intent.putExtra(Defines.Jsonkey.ReferringData.getKey(), latestParams.toString()); // Add individual parameters in the data Iterator<?> keys = latestParams.keys(); while (keys.hasNext()) { String key = (String) keys.next(); intent.putExtra(key, latestParams.getString(key)); } currentActivity.startActivityForResult(intent, deepLinkActivityReqCode); } else { // This case should not happen. Adding a safe handling for any corner case Log.w(TAG, "No activity reference to launch deep linked activity"); } } } } catch (final PackageManager.NameNotFoundException e) { Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct!"); } catch (ClassNotFoundException e) { Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct! Error while looking for activity " + deepLinkActivity); } catch (JSONException ignore) { } } private boolean checkForAutoDeepLinkKeys(JSONObject params, ActivityInfo activityInfo) { if (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null) { String[] activityLinkKeys = activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY).split(","); for (String activityLinkKey : activityLinkKeys) { if (params.has(activityLinkKey)) { return true; } } } return false; } private boolean checkForAutoDeepLinkPath(JSONObject params, ActivityInfo activityInfo) { String deepLinkPath = null; try { if (params.has(Defines.Jsonkey.AndroidDeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.AndroidDeepLinkPath.getKey()); } else if (params.has(Defines.Jsonkey.DeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.DeepLinkPath.getKey()); } } catch (JSONException ignored) { } if (activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null && deepLinkPath != null) { String[] activityLinkPaths = activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH).split(","); for (String activityLinkPath : activityLinkPaths) { if (pathMatch(activityLinkPath.trim(), deepLinkPath)) { return true; } } } return false; } private boolean pathMatch(String templatePath, String path) { boolean matched = true; String[] pathSegmentsTemplate = templatePath.split("\\?")[0].split("/"); String[] pathSegmentsTarget = path.split("\\?")[0].split("/"); if (pathSegmentsTemplate.length != pathSegmentsTarget.length) { return false; } for (int i = 0; i < pathSegmentsTemplate.length && i < pathSegmentsTarget.length; i++) { String pathSegmentTemplate = pathSegmentsTemplate[i]; String pathSegmentTarget = pathSegmentsTarget[i]; if (!pathSegmentTemplate.equals(pathSegmentTarget) && !pathSegmentTemplate.contains("*")) { matched = false; break; } } return matched; } /** * <p> Class for building a share link dialog.This creates a chooser for selecting application for * sharing a link created with given parameters. </p> */ public static class ShareLinkBuilder { private final Activity activity_; private final Branch branch_; private String shareMsg_; private String shareSub_; private Branch.BranchLinkShareListener callback_ = null; private Branch.IChannelProperties channelPropertiesCallback_ = null; private ArrayList<SharingHelper.SHARE_WITH> preferredOptions_; private String defaultURL_; //Customise more and copy url option private Drawable moreOptionIcon_; private String moreOptionText_; private Drawable copyUrlIcon_; private String copyURlText_; private String urlCopiedMessage_; private int styleResourceID_; BranchShortLinkBuilder shortLinkBuilder_; /** * <p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with * user selected clients</p> * * @param activity The {@link Activity} to show the dialog for choosing sharing application. * @param parameters @param params A {@link JSONObject} value containing the deep link params. */ public ShareLinkBuilder(Activity activity, JSONObject parameters) { this.activity_ = activity; this.branch_ = branchReferral_; shortLinkBuilder_ = new BranchShortLinkBuilder(activity); try { Iterator<String> keys = parameters.keys(); while (keys.hasNext()) { String key = keys.next(); shortLinkBuilder_.addParameters(key, (String) parameters.get(key)); } } catch (Exception ignore) { } shareMsg_ = ""; callback_ = null; channelPropertiesCallback_ = null; preferredOptions_ = new ArrayList<>(); defaultURL_ = null; moreOptionIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_more); moreOptionText_ = "More..."; copyUrlIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_save); copyURlText_ = "Copy link"; urlCopiedMessage_ = "Copied link to clipboard!"; } /** * *<p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with * user selected clients</p> * * @param activity The {@link Activity} to show the dialog for choosing sharing application. * @param shortLinkBuilder An instance of {@link BranchShortLinkBuilder} to create link to be shared */ public ShareLinkBuilder(Activity activity, BranchShortLinkBuilder shortLinkBuilder) { this(activity, new JSONObject()); shortLinkBuilder_ = shortLinkBuilder; } /** * <p>Sets the message to be shared with the link.</p> * * @param message A {@link String} to be shared with the link * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMessage(String message) { this.shareMsg_ = message; return this; } /** * <p>Sets the subject of this message. This will be added to Email and SMS Application capable of handling subject in the message.</p> * * @param subject A {@link String} subject of this message. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setSubject(String subject) { this.shareSub_ = subject; return this; } /** * <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep * link.</p> * * @param tag A {@link String} to be added to the iterable {@link Collection} of {@link String} tags associated with a deep * link. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addTag(String tag) { this.shortLinkBuilder_.addTag(tag); return this; } /** * <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep * link.</p> * * @param tags A {@link java.util.List} of tags to be added to the iterable {@link Collection} of {@link String} tags associated with a deep * link. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addTags(ArrayList<String> tags) { this.shortLinkBuilder_.addTags(tags); return this; } /** * <p>Adds a feature that make use of the link.</p> * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setFeature(String feature) { this.shortLinkBuilder_.setFeature(feature); return this; } /** * <p>Adds a stage application or user flow associated with this link.</p> * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setStage(String stage) { this.shortLinkBuilder_.setStage(stage); return this; } /** * <p>Adds a callback to get the sharing status.</p> * * @param callback A {@link BranchLinkShareListener} instance for getting sharing status. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCallback(BranchLinkShareListener callback) { this.callback_ = callback; return this; } /** * @param channelPropertiesCallback A {@link io.branch.referral.Branch.IChannelProperties} instance for customizing sharing properties for channels. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setChannelProperties(IChannelProperties channelPropertiesCallback) { this.channelPropertiesCallback_ = channelPropertiesCallback; return this; } /** * <p>Adds application to the preferred list of applications which are shown on share dialog. * Only these options will be visible when the application selector dialog launches. Other options can be * accessed by clicking "More"</p> * * @param preferredOption A list of applications to be added as preferred options on the app chooser. * Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addPreferredSharingOption(SharingHelper.SHARE_WITH preferredOption) { this.preferredOptions_.add(preferredOption); return this; } /** * <p>Adds application to the preferred list of applications which are shown on share dialog. * Only these options will be visible when the application selector dialog launches. Other options can be * accessed by clicking "More"</p> * * @param preferredOptions A list of applications to be added as preferred options on the app chooser. * Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addPreferredSharingOptions(ArrayList<SharingHelper.SHARE_WITH> preferredOptions) { this.preferredOptions_.addAll(preferredOptions); return this; } /** * Add the given key value to the deep link parameters * * @param key A {@link String} with value for the key for the deep link params * @param value A {@link String} with deep link parameters value * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder addParam(String key, String value) { try { this.shortLinkBuilder_.addParameters(key, value); } catch (Exception ignore) { } return this; } /** * <p> Set a default url to share in case there is any error creating the deep link </p> * * @param url A {@link String} with value of default url to be shared with the selected application in case deep link creation fails. * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setDefaultURL(String url) { defaultURL_ = url; return this; } /** * <p> Set the icon and label for the option to expand the application list to see more options. * Default label is set to "More" </p> * * @param icon Drawable to set as the icon for more option. Default icon is system menu_more icon. * @param label A {@link String} with value for the more option label. Default label is "More" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMoreOptionStyle(Drawable icon, String label) { moreOptionIcon_ = icon; moreOptionText_ = label; return this; } /** * <p> Set the icon and label for the option to expand the application list to see more options. * Default label is set to "More" </p> * * @param drawableIconID Resource ID for the drawable to set as the icon for more option. Default icon is system menu_more icon. * @param stringLabelID Resource ID for String label for the more option. Default label is "More" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setMoreOptionStyle(int drawableIconID, int stringLabelID) { moreOptionIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID); moreOptionText_ = activity_.getResources().getString(stringLabelID); return this; } /** * <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p> * * @param icon Drawable to set as the icon for copy url option. Default icon is system menu_save icon * @param label A {@link String} with value for the copy url option label. Default label is "Copy link" * @param message A {@link String} with value for a toast message displayed on copying a url. * Default message is "Copied link to clipboard!" * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCopyUrlStyle(Drawable icon, String label, String message) { copyUrlIcon_ = icon; copyURlText_ = label; urlCopiedMessage_ = message; return this; } /** * <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p> * * @param drawableIconID Resource ID for the drawable to set as the icon for copy url option. Default icon is system menu_save icon * @param stringLabelID Resource ID for the string label the copy url option. Default label is "Copy link" * @param stringMessageID Resource ID for the string message to show toast message displayed on copying a url * @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance. */ public ShareLinkBuilder setCopyUrlStyle(int drawableIconID, int stringLabelID, int stringMessageID) { copyUrlIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID); copyURlText_ = activity_.getResources().getString(stringLabelID); urlCopiedMessage_ = activity_.getResources().getString(stringMessageID); return this; } public ShareLinkBuilder setAlias(String alias) { this.shortLinkBuilder_.setAlias(alias); return this; } /** * <p> Sets the amount of time that Branch allows a click to remain outstanding.</p> * * @param matchDuration A {@link Integer} value specifying the time that Branch allows a click to * remain outstanding and be eligible to be matched with a new app session. * @return This Builder object to allow for chaining of calls to set methods. */ public ShareLinkBuilder setMatchDuration(int matchDuration) { this.shortLinkBuilder_.setDuration(matchDuration); return this; } /** * <p> Set the given style to the List View showing the share sheet</p> * * @param resourceID A Styleable resource to be applied to the share sheet list view */ public void setStyleResourceID(@StyleRes int resourceID) { styleResourceID_ = resourceID; } public void setShortLinkBuilderInternal(BranchShortLinkBuilder shortLinkBuilder) { this.shortLinkBuilder_ = shortLinkBuilder; } /** * <p>Creates an application selector dialog and share a link with user selected sharing option. * The link is created with the parameters provided to the builder. </p> */ public void shareLink() { branchReferral_.shareLink(this); } public Activity getActivity() { return activity_; } public ArrayList<SharingHelper.SHARE_WITH> getPreferredOptions() { return preferredOptions_; } public Branch getBranch() { return branch_; } public String getShareMsg() { return shareMsg_; } public String getShareSub() { return shareSub_; } public BranchLinkShareListener getCallback() { return callback_; } public IChannelProperties getChannelPropertiesCallback() { return channelPropertiesCallback_; } public String getDefaultURL() { return defaultURL_; } public Drawable getMoreOptionIcon() { return moreOptionIcon_; } public String getMoreOptionText() { return moreOptionText_; } public Drawable getCopyUrlIcon() { return copyUrlIcon_; } public String getCopyURlText() { return copyURlText_; } public String getUrlCopiedMessage() { return urlCopiedMessage_; } public BranchShortLinkBuilder getShortLinkBuilder() { return shortLinkBuilder_; } public int getStyleResourceID() { return styleResourceID_; } } public void registerView(BranchUniversalObject branchUniversalObject, BranchUniversalObject.RegisterViewStatusListener callback) { if (context_ != null) { ServerRequest req; req = new ServerRequestRegisterView(context_, branchUniversalObject, systemObserver_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } } /** * Update the extra instrumentation data provided to Branch * * @param instrumentationData A {@link HashMap} with key value pairs for instrumentation data. */ public void addExtraInstrumentationData(HashMap<String, String> instrumentationData) { instrumentationExtraData_.putAll(instrumentationData); } /** * Update the extra instrumentation data provided to Branch * * @param key A {@link String} Value for instrumentation data key * @param value A {@link String} Value for instrumentation data value */ public void addExtraInstrumentationData(String key, String value) { instrumentationExtraData_.put(key, value); } @Override public void onBranchViewVisible(String action, String branchViewID) { //No Implementation on purpose } @Override public void onBranchViewAccepted(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewCancelled(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewError(int errorCode, String errorMsg, String action) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } /** * Interface for defining optional Branch view behaviour for Activities */ public interface IBranchViewControl { /** * Defines if an activity is interested to show Branch views or not. * By default activities are considered as Branch view enabled. In case of activities which are not interested to show a Branch view (Splash screen for example) * should implement this and return false. The pending Branch view will be shown with the very next Branch view enabled activity * * @return A {@link Boolean} whose value is true if the activity don't want to show any Branch view. */ boolean skipBranchViewsOnThisActivity(); } }
package org.jgroups.tests; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import junit.framework.Test; import junit.framework.TestSuite; import org.jgroups.Message; import org.jgroups.util.Util; /** * Tests correct state transfer while other members continue sending messages to * the group * * @author Bela Ban * @version $Id: StateTransferTest.java,v 1.21 2008/02/01 04:24:50 vlada Exp $ */ public class StateTransferTest extends ChannelTestBase { private static final int MSG_SEND_COUNT = 10000; private static final int APP_COUNT = 2; public StateTransferTest(String name){ super(name); } public void setUp() throws Exception { super.setUp(); CHANNEL_CONFIG = System.getProperty("channel.conf.flush", "flush-udp.xml"); } public boolean useBlocking() { return true; } public void testStateTransferWhileSending() throws Exception { StateTransferApplication[] apps = new StateTransferApplication[APP_COUNT]; // Create a semaphore and take all its permits Semaphore semaphore = new Semaphore(APP_COUNT); semaphore.acquire(APP_COUNT); int from = 0, to = MSG_SEND_COUNT; String[] names = createApplicationNames(APP_COUNT); if(isMuxChannelUsed()){ names = createMuxApplicationNames(2, 2); } for(int i = 0;i < apps.length;i++){ apps[i] = new StateTransferApplication(semaphore, names[i], from, to); from += MSG_SEND_COUNT; to += MSG_SEND_COUNT; } for(int i = 0;i < apps.length;i++){ StateTransferApplication app = apps[i]; app.start(); semaphore.release(); Util.sleep(4000); } // Make sure everyone is in sync if(isMuxChannelUsed()){ blockUntilViewsReceived(apps, getMuxFactoryCount(), 60000); }else{ blockUntilViewsReceived(apps, 60000); } Util.sleep(1000); // Reacquire the semaphore tickets; when we have them all // we know the threads are done boolean acquired = semaphore.tryAcquire( apps.length, 30, TimeUnit.SECONDS); if(!acquired){ log.warn("Most likely a bug, analyse the stack below:"); log.warn(Util.dumpThreads()); } // have we received all and the correct messages? for(int i = 0;i < apps.length;i++){ StateTransferApplication w = apps[i]; Map m = w.getMap(); log.info("map has " + m.size() + " elements"); assertEquals(MSG_SEND_COUNT * APP_COUNT, m.size()); } Set keys = apps[0].getMap().keySet(); for(int i = 0;i < apps.length;i++){ StateTransferApplication app = apps[i]; Map m = app.getMap(); Set s = m.keySet(); assertEquals(keys, s); } for(StateTransferApplication app:apps){ app.cleanup(); } } protected int getMuxFactoryCount() { // one MuxChannel per real Channel return APP_COUNT; } protected class StateTransferApplication extends PushChannelApplicationWithSemaphore { private final ReentrantLock mapLock = new ReentrantLock(); private Map map = new HashMap(MSG_SEND_COUNT * APP_COUNT); private int from, to; public StateTransferApplication(Semaphore semaphore,String name,int from,int to) throws Exception{ super(name, semaphore); this.from = from; this.to = to; } public Map getMap() { Map result = null; mapLock.lock(); result = Collections.unmodifiableMap(map); mapLock.unlock(); return result; } @Override public void receive(Message msg) { Object[] data = (Object[]) msg.getObject(); mapLock.lock(); map.put(data[0], data[1]); int num_received = map.size(); mapLock.unlock(); if(num_received % 1000 == 0) log.info("received " + num_received); // are we done? if(num_received >= MSG_SEND_COUNT * APP_COUNT) semaphore.release(); } @Override public byte[] getState() { byte[] result = null; mapLock.lock(); try{ result = Util.objectToByteBuffer(map); }catch(Exception e){ e.printStackTrace(); }finally{ mapLock.unlock(); } return result; } @Override public void setState(byte[] state) { mapLock.lock(); try{ map = (Map) Util.objectFromByteBuffer(state); }catch(Exception e){ e.printStackTrace(); }finally{ mapLock.unlock(); } log.info("received state, map has " + map.size() + " elements"); } @Override public void getState(OutputStream ostream) { ObjectOutputStream out; mapLock.lock(); try{ out = new ObjectOutputStream(ostream); out.writeObject(map); out.close(); }catch(IOException e){ e.printStackTrace(); }finally{ mapLock.unlock(); } } @Override public void setState(InputStream istream) { ObjectInputStream in; mapLock.lock(); try{ in = new ObjectInputStream(istream); map = (Map) in.readObject(); log.info("received state, map has " + map.size() + " elements"); in.close(); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }finally{ mapLock.unlock(); } } public void run() { boolean acquired = false; try{ acquired = semaphore.tryAcquire(60000L, TimeUnit.MILLISECONDS); if(!acquired){ throw new Exception(name + " cannot acquire semaphore"); } useChannel(); }catch(Exception e){ log.error(name + ": " + e.getLocalizedMessage(), e); // Save it for the test to check exception = e; } } @Override protected void useChannel() throws Exception { channel.connect("test",null,null,10000); Object[] data = new Object[2]; for(int i = from;i < to;i++){ data[0] = new Integer(i); data[1] = "Value try{ channel.send(null, null, data); if(i % 100 == 0) Util.sleep(50); if(i % 1000 == 0) log.info("sent " + i); }catch(Exception e){ e.printStackTrace(); break; } } } } public static Test suite() { return new TestSuite(StateTransferTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
package org.jetel.data; import java.lang.reflect.Array; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; /** * Description of the Class * * @author dpavlis * @since 9. prosinec 2003 * @revision $Revision$ */ public class RecordFilter { private final static int CMP_EQ = 0;// equal private final static int CMP_LT = -1;// less than private final static int CMP_GT = 1;// grater than private final static int CMP_LTEQ = -2;// less than equal private final static int CMP_GTEQ = 2;// greater than equal private final static int CMP_REGEX = 3;// regular expression compare private final static int CMP_N_EQL = 5;// not equal private final static int AND = 0; private final static int OR = 1; private final static int NOT = 2; private final static String S_CMP_EQ = "=="; private final static String S_CMP_LT = "<"; private final static String S_CMP_GT = ">"; private final static String S_CMP_LTEQ = ">="; private final static String S_CMP_GTEQ = "=<"; private final static String S_CMP_REGEX = "~"; private final static String S_CMP_N_EQL = "!="; private final static String DEFAULT_FILTER_DATE_FORMAT = "yyyy-MM-dd"; private DataRecordMetadata metadata; private FilterItem[] filterSpecs; private String filterExpression; /** *Constructor for the RecordFilter object * * @param filterExpression Description of the Parameter */ public RecordFilter(String filterExpression) { this.filterExpression = filterExpression; } /** * Description of the Method * * @param recordMetadata Description of the Parameter */ public void init(DataRecordMetadata recordMetadata) { String filterField; String filterValueStr; this.metadata = metadata; String[] filterParts = filterExpression.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); filterSpecs = new FilterItem[filterParts.length]; Map fieldNames = recordMetadata.getFieldNames(); int operatorIndex; int cmpOperator; int operatorStrLen; for (int i = 0; i < Array.getLength(filterParts); i++) { String filterPart = filterParts[i]; //Get comparison operator if ((operatorIndex = filterPart.indexOf(S_CMP_EQ)) != -1) { cmpOperator = CMP_EQ; operatorStrLen = S_CMP_EQ.length(); } else if ((operatorIndex = filterPart.indexOf(S_CMP_REGEX)) != -1) { cmpOperator = CMP_REGEX; operatorStrLen = S_CMP_REGEX.length(); } else if ((operatorIndex = filterPart.indexOf(S_CMP_LTEQ)) != -1) { cmpOperator = CMP_LTEQ; operatorStrLen = S_CMP_LTEQ.length(); } else if ((operatorIndex = filterPart.indexOf(S_CMP_GTEQ)) != -1) { cmpOperator = CMP_GTEQ; operatorStrLen = S_CMP_GTEQ.length(); } else if ((operatorIndex = filterPart.indexOf(S_CMP_N_EQL)) != -1) { cmpOperator = CMP_N_EQL; operatorStrLen = S_CMP_N_EQL.length(); } // this must go here as there otherwise <= would be reported as less not less or equal else if ((operatorIndex = filterPart.indexOf(S_CMP_GT)) != -1) { cmpOperator = CMP_GT; operatorStrLen = S_CMP_GT.length(); } else if ((operatorIndex = filterPart.indexOf(S_CMP_LT)) != -1) { cmpOperator = CMP_LT; operatorStrLen = S_CMP_LT.length(); } else { throw new RuntimeException("Unknown comparison operator: " + filterPart); } filterField = filterPart.substring(0, operatorIndex).trim(); filterValueStr = filterPart.substring(operatorIndex + operatorStrLen, filterPart.length()).trim(); DataFieldMetadata fieldMetadata = recordMetadata.getField(filterField); if (fieldMetadata == null) { throw new RuntimeException("Unknown field name: " + filterField); } Integer fieldNum = (Integer) fieldNames.get(filterField); if (fieldNum == null) { throw new RuntimeException("Unknown field name: " + filterField); } if (cmpOperator == CMP_REGEX) { try { filterSpecs[i] = new FilterItem(fieldNum.intValue(), new RegexField(filterValueStr), AND); } catch (Exception ex) { throw new RuntimeException(ex.getMessage() + " - error when populating filter's field " + filterField + " with value " + filterValueStr); } } else { DataField filterFieldValue = DataFieldFactory.createDataField(fieldMetadata.getType(), fieldMetadata); try { filterFieldValue.fromString(filterValueStr); } catch (Exception ex) { throw new RuntimeException(ex.getMessage() + " - error when populating filter's field " + filterField + " with value " + filterValueStr); } filterSpecs[i] = new FilterItem(fieldNum.intValue(), cmpOperator, filterFieldValue, AND); } } } /** * Gets the filterSpecs attribute of the RecordFilter object * * @return The filterSpecs value */ public FilterItem[] getFilterSpecs() { return filterSpecs; } /** * Description of the Method * * @param record Description of the Parameter * @return Description of the Return Value */ public boolean accepts(DataRecord record) { int fieldNo; int cmpResult; DataField field2Compare; for (int i = 0; i < filterSpecs.length; i++) { field2Compare = record.getField(filterSpecs[i].getFieldNo()); if (field2Compare == null) { // this should not happen !! throw new RuntimeException("Field (reference) to compare with is NULL !!"); } // special case for REGEX if (filterSpecs[i].getComparison() == CMP_REGEX) { cmpResult = ((RegexField) filterSpecs[i].getValue()).compareTo(field2Compare); } else { cmpResult = ((DataField) filterSpecs[i].getValue()).compareTo(field2Compare); } switch (filterSpecs[i].getComparison()) { case CMP_EQ: if (cmpResult == 0) { return true; } break;// equal case CMP_LT: if (cmpResult == -1) { return true; } break;// less than case CMP_GT: if (cmpResult == 1) { return true; } break;// grater than case CMP_LTEQ: if (cmpResult <= 0) { return true; } break;// less than equal case CMP_GTEQ: if (cmpResult >= 0) { return true; } break;// greater than equal case CMP_N_EQL: if (cmpResult != 0) { return true; } break; case CMP_REGEX: if (cmpResult == 0) { return true; } break; default: throw new RuntimeException("Unsupported cmparison operator !"); } } return false; } /** * Description of the Class * * @author dpavlis * @since * @revision $Revision$ */ private class FilterItem { int comparison; Object value; int logicalOperator; char fieldType; int fieldNo; /** *Constructor for the FilterItem object * * @param fieldNo Description of the Parameter * @param cmp Description of the Parameter * @param value Description of the Parameter * @param lOperator Description of the Parameter */ FilterItem(int fieldNo, int cmp, DataField value, int lOperator) { this.fieldNo = fieldNo; this.comparison = cmp; this.value = value; this.fieldType = value.getType(); this.logicalOperator = lOperator; } /** *Constructor for the FilterItem object * * @param fieldNo Description of the Parameter * @param value Description of the Parameter * @param lOperator Description of the Parameter */ FilterItem(int fieldNo, RegexField value, int lOperator) { this.fieldNo = fieldNo; this.comparison = CMP_REGEX; this.value = value; this.fieldType = 'X';// X for regeX this.logicalOperator = lOperator; } /** * Gets the comparison attribute of the FilterItem object * * @return The comparison value */ final int getComparison() { return comparison; } /** * Gets the value attribute of the FilterItem object * * @return The value value */ final Object getValue() { return value; } /** * Gets the logicalOperator attribute of the FilterItem object * * @return The logicalOperator value */ final int getLogicalOperator() { return logicalOperator; } /** * Gets the fieldNo attribute of the FilterItem object * * @return The fieldNo value */ final int getFieldNo() { return fieldNo; } /** * Description of the Method * * @return Description of the Return Value */ public String toString() { return fieldNo + ":" + comparison + ":" + value; } } /** * Description of the Class * * @author dpavlis * @since * @revision $Revision$ */ private class RegexField { private Pattern p; /** *Constructor for the RegexField object * * @param patternStr Description of the Parameter */ RegexField(String patternStr) { p = Pattern.compile(patternStr); } /** * Description of the Method * * @return Description of the Return Value */ public String toString() { return p.toString(); } /** * Description of the Method * * @param _str Description of the Parameter */ public void fromString(String _str) { p = Pattern.compile(_str); } /** * Description of the Method * * @param obj Description of the Parameter * @return Description of the Return Value */ public boolean equals(Object obj) { Matcher m = p.matcher(((StringDataField) obj).getCharSequence()); return m.matches(); } /** * Description of the Method * * @param obj Description of the Parameter * @return Description of the Return Value */ public int compareTo(Object obj) { return equals(obj) ? 0 : -1; } } }
package org.jasig.portal.services; import org.jasig.portal.RdbmServices; import org.jasig.portal.security.*; import org.jasig.portal.utils.XML; import org.jasig.portal.utils.ResourceLoader; import java.util.Hashtable; import java.util.Vector; import java.util.StringTokenizer; import java.util.HashSet; import java.util.Iterator; import java.sql.Driver; import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.directory.InitialDirContext; import javax.naming.NamingException; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.directory.SearchControls; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.Entity; /** * Extract eduPerson-like attributes from whatever LDAP directory or JDBC * database happens to be lying around in the IT infrastructure. * * Parameterized by uPortal/properties/PersonDirs.xml. * Original author is Howard.Gilbert@yale.edu. */ public class PersonDirectory { public PersonDirectory() { getParameters(); } static Vector sources = null; // List of PersonDirInfo objects static Hashtable drivers = new Hashtable(); // Registered JDBC drivers public static HashSet propertynames = new HashSet(); public static Iterator getPropertyNamesIterator() { return propertynames.iterator(); } /** * Parse XML file and create PersonDirInfo objects * * <p>Parameter file is uPortal/properties/PersonDirs.xml. * It contains a <PersonDirs> object with a list of * <PersonDirInfo> objects each defining an LDAP or JDBC source. * * <p>LDAP entry has format: * <pre> * <PersonDirInfo> * <url>ldap://yu.yale.edu:389/dc=itstp, dc=yale, dc=edu</url> * <logonid>cn=bogus,cn=Users,dc=itstp,dc=yale,dc=edu</logonid> * <logonpassword>foobar</logonpassword> * <uidquery>(cn={0})</uidquery> * <usercontext>cn=Users</usercontext> * <attributes>mail telephoneNumber</attributes> * </PersonDirInfo> * </pre> * * The logonid and logonpassword would be omitted for LDAP directories * that do not require a signon. The URL establishes an "initial context" * which acts like a root directory. The usercontext is a subdirectory * relative to this initial context in which to search for usernames. * In a lot of LDAP directories, the user context is "ou=People". * The username is the {0} parameter substituted into the query. The * query searches the subtree of objects under the usercontext, so if * the usercontext is the whole directory the query searches the whole * directory. * * <p>JDBC entry has format: * <pre> * <PersonDirInfo> * <url>jdbc:oracle:thin:@oracleserver.yale.edu:1521:XXXX</url> * <driver>oracle.jdbc.driver.OracleDriver</driver> * <logonid>bogus</logonid> * <logonpassword>foobar</logonpassword> * <uidquery>select * from portal_person_directory where netid=?</uidquery> * <attributes>last_name:sn first_name:givenName role</attributes> * </PersonDirInfo> * </pre> * * The SELECT can fetch any number of variables, but only the columns * named in the attributes list will be actually used. When an attribute * has two names, separated by a colon, the first name is used to find * the variable/column in the result of the query and the second is the * name used to store the value as an IPerson attribute. Generally we * recommend the use of official eduPerson names however bad they might * be (sn for "surname"). However, an institution may have local variables * that they want to include, as the Yale variable "role" that includes * distinctions like grad-student and non-ladder-faculty. This version of * this code doesn't have the ability to transform values, so if you wanted * to translate some bizzare collection of roles like Yale has to the * simpler list of eduPersonAffiliation (faculty, student, staff) then * join the query to a list-of-values table that does the translation. */ private synchronized boolean getParameters() { if (sources!=null) return true; sources= new Vector(); try { // Build a DOM tree out of uPortal/properties/PersonDirs.xml Document doc = ResourceLoader.getResourceAsDocument(this.getClass(), "/properties/PersonDirs.xml"); // Each directory source is a <PersonDirInfo> (and its contents) NodeList list = doc.getElementsByTagName("PersonDirInfo"); for (int i=0;i<list.getLength();i++) { // foreach PersonDirInfo Element dirinfo = (Element) list.item(i); PersonDirInfo pdi = new PersonDirInfo(); // Java object holding parameters for (Node param = dirinfo.getFirstChild(); param!=null; // foreach tag under the <PersonDirInfo> param=param.getNextSibling()) { if (!(param instanceof Element)) continue; // whitespace (typically \n) between tags Element pele = (Element) param; String tagname = pele.getTagName(); String value = getTextUnderElement(pele); // each tagname corresponds to an object data field if (tagname.equals("url")) { pdi.url=value; } else if (tagname.equals("logonid")) { pdi.logonid=value; } else if (tagname.equals("driver")) { pdi.driver=value; } else if (tagname.equals("logonpassword")) { pdi.logonpassword=value; } else if (tagname.equals("uidquery")) { pdi.uidquery=value; } else if (tagname.equals("fullnamequery")) { pdi.fullnamequery=value; } else if (tagname.equals("usercontext")) { pdi.usercontext=value; } else if (tagname.equals("attributes")) { NodeList anodes = pele.getElementsByTagName("attribute"); int anodecount = anodes.getLength(); if (anodecount!=0) { pdi.attributenames = new String[anodecount]; pdi.attributealiases = new String[anodecount]; for (int j =0; j<anodecount;j++) { Element anode = (Element) anodes.item(j); NodeList namenodes = anode.getElementsByTagName("name"); String aname = "$$$"; if (namenodes.getLength()!=0) aname= getTextUnderElement(namenodes.item(0)); pdi.attributenames[j]=aname; NodeList aliasnodes = anode.getElementsByTagName("alias"); if (aliasnodes.getLength()==0) { pdi.attributealiases[j]=aname; } else { pdi.attributealiases[j]=getTextUnderElement(aliasnodes.item(0)); } } } else { // The <attributes> tag contains a list of names // and optionally aliases each in the form // name[:alias] // The name is an LDAP property or database column name. // The alias, if it exists, is an eduPerson property that // corresponds to the previous LDAP or DBMS name. // If no alias is specified, the eduPerson name is also // the LDAP or DBMS column name. StringTokenizer st = new StringTokenizer(value); int n = st.countTokens(); pdi.attributenames = new String[n]; pdi.attributealiases = new String[n]; for (int k=0;k<n;k++) { String tk = st.nextToken(); int pos =tk.indexOf(':'); if (pos>0) { // There is an alias pdi.attributenames[k]=tk.substring(0,pos); pdi.attributealiases[k]=tk.substring(pos+1); } else { // There is no alias pdi.attributenames[k]=tk; pdi.attributealiases[k]=tk; } } } } else { LogService.instance().log(LogService.ERROR,"Unrecognized tag "+tagname+" in PersonDirs.xml"); } } for (int ii=0;ii<pdi.attributealiases.length;ii++) { String aa = pdi.attributealiases[ii]; propertynames.add(aa); } sources.addElement(pdi); // Add one LDAP or JDBC source to the list } } catch(Exception e) { LogService.instance().log(LogService.WARN,"properties/PersonDirs.xml is not available, directory searching disabled."); return false; } return true; } private String getTextUnderElement(Node nele) { if (!(nele instanceof Element)) return null; Element pele = (Element) nele; StringBuffer vb = new StringBuffer(); NodeList vnodes = pele.getChildNodes(); for (int j =0; j<vnodes.getLength();j++) { Node vnode = vnodes.item(j); if (vnode instanceof Text) vb.append(((Text)vnode).getData()); } return vb.toString(); } /** * Run down the list of LDAP or JDBC sources and extract info from each */ public Hashtable getUserDirectoryInformation (String username){ Hashtable attribs = new Hashtable(); for (int i=0;i<sources.size();i++) { PersonDirInfo pdi = (PersonDirInfo) sources.elementAt(i); if (pdi.disabled) continue; if (pdi.url.startsWith("ldap:")) processLdapDir(username, pdi,attribs); if (pdi.url.startsWith("jdbc:")) processJdbcDir(username, pdi,attribs); } return attribs; } public void getUserDirectoryInformation(String uid, IPerson m_Person) { java.util.Hashtable attribs = this.getUserDirectoryInformation(uid); java.util.Enumeration en = attribs.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String value = (String) attribs.get(key); m_Person.setAttribute(key,value); } } /** * Extract named attributes from a single LDAP directory * * <p>Connect to the LDAP server indicated by the URL. * An optional userid and password will be used if the LDAP server * requires logon (AD does, most directories don't). The userid given * here would establish access privileges to directory fields for the * uPortal. Connection establishes an initial context (like a current * directory in a file system) that is usually the root of the directory. * Howwever, while a file system root is simply "/", a directory root is * the global name of the directory, like "dc=yu,dc=yale,dc=edu" or * "o=Yale University",c=US". Then search a subcontext where the people * are (cn=Users in AD, ou=People sometimes, its a local convention). * */ void processLdapDir(String username, PersonDirInfo pdi, Hashtable attribs) { //JNDI boilerplate to connect to an initial context Hashtable jndienv = new Hashtable(); DirContext context = null; jndienv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); jndienv.put(Context.SECURITY_AUTHENTICATION,"simple"); jndienv.put(Context.PROVIDER_URL,pdi.url); if (pdi.logonid!=null) jndienv.put(Context.SECURITY_PRINCIPAL,pdi.logonid); if (pdi.logonpassword!=null) jndienv.put(Context.SECURITY_CREDENTIALS,pdi.logonpassword); try { context = new InitialDirContext(jndienv); } catch (NamingException nex) { return; } // Search for the userid in the usercontext subtree of the directory // Use the uidquery substituting username for {0} NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); Object [] args = new Object[] {username}; try { userlist = context.search(pdi.usercontext,pdi.uidquery,args,sc); } catch (NamingException nex) { return; } // If one object matched, extract properties from the attribute list try { if (userlist.hasMoreElements()) { SearchResult result = (SearchResult) userlist.next(); Attributes ldapattribs = result.getAttributes(); for (int i=0;i<pdi.attributenames.length;i++) { Attribute tattrib = null; if (pdi.attributenames[i] != null) tattrib = ldapattribs.get(pdi.attributenames[i]); if (tattrib!=null) { String value = tattrib.get().toString(); attribs.put(pdi.attributealiases[i],value); } } } } catch (NamingException nex) { ; } try {userlist.close();} catch (Exception e) {;} try {context.close();} catch (Exception e) {;} } /** * Extract data from a JDBC database */ void processJdbcDir(String username, PersonDirInfo pdi, Hashtable attribs) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { // Register the driver class if it has not already been registered // Not agressively synchronized, duplicate registrations are OK. if (pdi.driver!=null && pdi.driver.length()>0) { if (drivers.get(pdi.driver)==null) { try { Driver driver = (Driver) Class.forName(pdi.driver).newInstance(); DriverManager.registerDriver(driver); drivers.put(pdi.driver,driver); } catch (Exception driverproblem) { pdi.disabled=true; pdi.logged=true; LogService.instance().log(LogService.ERROR,"Cannot register driver class "+pdi.driver); return; } } } // Get a connection with URL, userid, password conn = DriverManager.getConnection(pdi.url,pdi.logonid,pdi.logonpassword); // Execute query substituting Username for parameter stmt = conn.prepareStatement(pdi.uidquery); stmt.setString(1,username); rs = stmt.executeQuery(); rs.next(); // get the first (only) row of result // Foreach attribute, put its value and alias in the hashtable for (int i=0;i<pdi.attributenames.length;i++) { try { String value = null; String attName = pdi.attributenames[i]; if (attName != null) value = rs.getString(attName); if (value!=null) { attribs.put(pdi.attributealiases[i],value); } } catch (SQLException sqle) { ; // Don't let error in a field prevent processing of others. LogService.log(LogService.DEBUG,"Error accessing JDBC field "+pdi.attributenames[i]+" "+sqle); } } } catch (Exception e) { ; // If database down or can't logon, ignore this data source // It is not clear that we want to disable the source, since the // database may be temporarily down. LogService.log(LogService.DEBUG,"Error "+e); } if (rs!=null) try {rs.close();} catch (Exception e) {;} if (stmt!=null) try {stmt.close();} catch (Exception e) {;} if (conn!=null) try {conn.close();} catch (Exception e) {;} } private class PersonDirInfo { String url; // protocol, server, and initial connection parameters String driver; // JDBC java class to register String logonid; // database userid or LDAP user DN (if needed) String logonpassword; // password String usercontext; // where are users? "OU=people" or "CN=Users" String uidquery; // SELECT or JNDI query for userid String fullnamequery; // SELECT or JNDI query using fullname String[] attributenames; String[] attributealiases; boolean disabled = false; boolean logged = false; } }
package io.branch.referral; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Semaphore; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class Branch { public static String FEATURE_TAG_SHARE = "share"; public static String FEATURE_TAG_REFERRAL = "referral"; public static String FEATURE_TAG_INVITE = "invite"; public static String FEATURE_TAG_DEAL = "deal"; public static String FEATURE_TAG_GIFT = "gift"; public static String REDEEM_CODE = "$redeem_code"; public static String REEFERRAL_BUCKET_DEFAULT = "default"; public static String REFERRAL_CODE_TYPE = "credit"; public static int REFERRAL_CREATION_SOURCE_SDK = 2; public static String REFERRAL_CODE = "referral_code"; public static int REFERRAL_CODE_LOCATION_REFERREE = 0; public static int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; public static int REFERRAL_CODE_LOCATION_BOTH = 3; public static int REFERRAL_CODE_AWARD_UNLIMITED = 1; public static int REFERRAL_CODE_AWARD_UNIQUE = 0; public static int LINK_TYPE_UNLIMITED_USE = 0; public static int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 3000; private static Branch branchReferral_; private boolean isInit_; private BranchReferralInitListener initSessionFinishedCallback_; private BranchReferralInitListener initIdentityFinishedCallback_; private BranchReferralStateChangedListener stateChangedCallback_; private BranchLinkCreateListener linkCreateCallback_; private BranchListResponseListener creditHistoryCallback_; private BranchReferralInitListener getReferralCodeCallback_; private BranchReferralInitListener validateReferralCodeCallback_; private BranchReferralInitListener applyReferralCodeCallback_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; private Timer closeTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private int retryCount_; private boolean initNotStarted_; private boolean initFinished_; private boolean initFailed_; private boolean hasNetwork_; private boolean lastRequestWasInit_; private Handler debugHandler_; private SparseArray<String> debugListenerInitHistory_; private OnTouchListener debugOnTouchListener_; private Branch(Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); kRemoteInterface_.setNetworkCallbackListener(new ReferralNetworkCallback()); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); initFinished_ = false; initFailed_ = false; lastRequestWasInit_ = true; keepAlive_ = false; isInit_ = false; initNotStarted_ = true; networkCount_ = 0; hasNetwork_ = true; debugListenerInitHistory_ = new SparseArray<String>(); debugHandler_ = new Handler(); debugOnTouchListener_ = retrieveOnTouchListener(); } public static Branch getInstance(Context context, String key) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; branchReferral_.prefHelper_.setAppKey(key); return branchReferral_; } public static Branch getInstance(Context context) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context; return branchReferral_; } private static Branch initInstance(Context context) { return new Branch(context.getApplicationContext()); } public void resetUserSession() { isInit_ = false; } public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount > 0) { prefHelper_.setRetryCount(retryCount); } } public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } // if you want to flag debug, call this before initUserSession public void setDebug() { prefHelper_.setDebug(); } public void initSession(BranchReferralInitListener callback) { initSession(callback, (Activity)null); } public void initSession(BranchReferralInitListener callback, Activity activity) { if (systemObserver_.getUpdateState() == 0 && !hasUser()) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); } public void initSession(BranchReferralInitListener callback, Uri data) { initSession(callback, data, null); } public void initSession(BranchReferralInitListener callback, Uri data, Activity activity) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, activity); } public void initSession() { initSession((Activity)null); } public void initSession(Activity activity) { initSession(null, activity); } public void initSessionWithData(Uri data) { initSessionWithData(data, null); } public void initSessionWithData(Uri data, Activity activity) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(null, activity); } public void initSession(boolean isReferrable) { initSession(null, isReferrable, (Activity)null); } public void initSession(boolean isReferrable, Activity activity) { initSession(null, isReferrable, activity); } public void initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { initSession(callback, isReferrable, data, null); } public void initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { if (data != null) { if (data.getQueryParameter("link_click_id") != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id")); } } initSession(callback, isReferrable, activity); } public void initSession(BranchReferralInitListener callback, boolean isReferrable) { initSession(callback, isReferrable, (Activity)null); } public void initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) { initSessionFinishedCallback_ = callback; lastRequestWasInit_ = true; initNotStarted_ = false; initFailed_ = false; if (!isInit_) { isInit_ = true; new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { boolean installOrOpenInQueue = requestQueue_.containsInstallOrOpen(); if (hasUser() && hasSession() && !installOrOpenInQueue) { if (callback != null) callback.onInitFinished(new JSONObject(), new BranchInitError()); keepAlive(); } else { if (!installOrOpenInQueue) { new Thread(new Runnable() { @Override public void run() { initializeSession(); } }).start(); } else { new Thread(new Runnable() { @Override public void run() { requestQueue_.moveInstallOrOpenToFront(null, networkCount_); processNextQueueItem(); } }).start(); } } } if (activity != null && activity instanceof Activity && debugListenerInitHistory_.get(Integer.valueOf(System.identityHashCode(activity))) == null) { debugListenerInitHistory_.put(Integer.valueOf(System.identityHashCode(activity)), "init"); View view = activity.getWindow().getDecorView().findViewById(android.R.id.content); if (view != null) { view.setOnTouchListener(debugOnTouchListener_); } } } private OnTouchListener retrieveOnTouchListener() { if (debugOnTouchListener_ == null) { debugOnTouchListener_ = new OnTouchListener() { class KeepDebugConnectionTask extends TimerTask { public void run() { if (!prefHelper_.keepDebugConnection()) { debugHandler_.post(_longPressed); } } } Runnable _longPressed = new Runnable() { private boolean started = false; private Timer timer; public void run() { debugHandler_.removeCallbacks(_longPressed); if (!started) { Log.i("Branch Debug","======= Start Debug Session ======="); prefHelper_.setDebug(); timer = new Timer(); timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000); } else { Log.i("Branch Debug","======= End Debug Session ======="); prefHelper_.clearDebug(); timer.cancel(); timer = null; } this.started = !this.started; } }; @Override public boolean onTouch(View v, MotionEvent ev) { int pointerCount = ev.getPointerCount(); final int actionPeformed = ev.getAction(); switch (actionPeformed & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (systemObserver_.isSimulator()) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_CANCEL: debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_UP: v.performClick(); debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_POINTER_DOWN: if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; } return true; } }; } return debugOnTouchListener_; } public void closeSession() { if (keepAlive_) { return; } // else, real close isInit_ = false; lastRequestWasInit_ = false; initNotStarted_ = true; if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) { requestQueue_.dequeue(); } } else { new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE, null); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } } public void setIdentity(String userId, BranchReferralInitListener callback) { initIdentityFinishedCallback_ = callback; setIdentity(userId); } public void setIdentity(final String userId) { if (userId == null || userId.length() == 0 || userId.equals(prefHelper_.getIdentity())) { return; } new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("identity", userId); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_IDENTIFY, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void logout() { new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("session_id", prefHelper_.getSessionID()); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_LOGOUT, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadActionCounts() { loadActionCounts(null); } public void loadActionCounts(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void loadRewards() { loadRewards(null); } public void loadRewards(BranchReferralStateChangedListener callback) { stateChangedCallback_ = callback; new Thread(new Runnable() { @Override public void run() { ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARDS, null); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public int getCredits() { return prefHelper_.getCreditCount(); } public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } public int getTotalCountsForAction(String action) { return prefHelper_.getActionTotalCount(action); } public int getUniqueCountsForAction(String action) { return prefHelper_.getActionUniqueCount(action); } public void redeemRewards(int count) { redeemRewards("default", count); } public void redeemRewards(final String bucket, final int count) { new Thread(new Runnable() { @Override public void run() { int creditsToRedeem = 0; int credits = prefHelper_.getCreditCount(bucket); if (count > credits) { creditsToRedeem = credits; Log.i("BranchSDK", "Branch Warning: You're trying to redeem more credits than are available. Have you updated loaded rewards"); } else { creditsToRedeem = count; } if (creditsToRedeem > 0) { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("bucket", bucket); post.put("amount", creditsToRedeem); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } } }).start(); } public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { creditHistoryCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("length", length); post.put("direction", order.ordinal()); if (bucket != null) { post.put("bucket", bucket); } if (afterId != null) { post.put("begin_after_id", afterId); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action, final JSONObject metadata) { new Thread(new Runnable() { @Override public void run() { retryCount_ = 0; JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("session_id", prefHelper_.getSessionID()); post.put("event", action); if (metadata != null) post.put("metadata", filterOutBadCharacters(metadata)); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION, post); requestQueue_.enqueue(req); if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void userCompletedAction(final String action) { userCompletedAction(action, null); } public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); return convertParamsStringToDictionary(storedParam); } public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); return convertParamsStringToDictionary(storedParam); } public void getShortUrl(BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, null, null, null, null, stringifyParams(null), callback); } public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), callback); } public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback); } public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback); } public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback); } public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback); } public void getReferralCode(BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void getReferralCode(final int amount, BranchReferralInitListener callback) { this.getReferralCode(null, amount, null, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(null, amount, expiration, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, expiration, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REEFERRAL_BUCKET_DEFAULT, calculationType, location, callback); } public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) { getReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("calculation_type", calculationType); post.put("location", location); post.put("type", REFERRAL_CODE_TYPE); post.put("creation_source", REFERRAL_CREATION_SOURCE_SDK); post.put("amount", amount); post.put("bucket", bucket != null ? bucket : REEFERRAL_BUCKET_DEFAULT); if (prefix != null && prefix.length() > 0) { post.put("prefix", prefix); } if (expiration != null) { post.put("expiration", convertDate(expiration)); } } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void validateReferralCode(final String code, BranchReferralInitListener callback) { validateReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } public void applyReferralCode(final String code, final BranchReferralInitListener callback) { applyReferralCodeCallback_ = callback; new Thread(new Runnable() { @Override public void run() { JSONObject post = new JSONObject(); try { post.put("app_id", prefHelper_.getAppKey()); post.put("identity_id", prefHelper_.getIdentityID()); post.put("session_id", prefHelper_.getSessionID()); post.put("referral_code", code); } catch (JSONException ex) { ex.printStackTrace(); return; } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE, post); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String stringifyParams(JSONObject params) { if (params == null) { params = new JSONObject(); } try { params.put("source", "android"); } catch (JSONException e) { e.printStackTrace(); } return params.toString(); } private void generateShortLink(final String alias, final int type, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback) { linkCreateCallback_ = callback; if (hasUser()) { new Thread(new Runnable() { @Override public void run() { JSONObject linkPost = new JSONObject(); try { linkPost.put("app_id", prefHelper_.getAppKey()); linkPost.put("identity_id", prefHelper_.getIdentityID()); if (type != 0) { linkPost.put("type", type); } if (tags != null) { JSONArray tagArray = new JSONArray(); for (String tag : tags) tagArray.put(tag); linkPost.put("tags", tagArray); } if (alias != null) { linkPost.put("alias", alias); } if (channel != null) { linkPost.put("channel", channel); } if (feature != null) { linkPost.put("feature", feature); } if (stage != null) { linkPost.put("stage", stage); } if (params != null) linkPost.put("data", params); } catch (JSONException ex) { ex.printStackTrace(); } ServerRequest req = new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL, linkPost); if (!initFailed_) { requestQueue_.enqueue(req); } if (initFinished_ || !hasNetwork_) { lastRequestWasInit_ = false; processNextQueueItem(); } else if (initFailed_ || initNotStarted_) { handleFailure(req); } } }).start(); } } private JSONObject filterOutBadCharacters(JSONObject inputObj) { JSONObject filteredObj = new JSONObject(); if (inputObj != null) { Iterator<?> keys = inputObj.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { if (inputObj.has(key) && inputObj.get(key).getClass().equals(String.class)) { filteredObj.put(key, inputObj.getString(key).replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"").replace("", "'")); } else if (inputObj.has(key)) { filteredObj.put(key, inputObj.get(key)); } } catch(JSONException ex) { } } } return filteredObj; } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { keepAlive(); } if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { kRemoteInterface_.registerInstall(PrefHelper.NO_STRING_VALUE, prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { kRemoteInterface_.registerOpen(prefHelper_.isDebug()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) && hasUser() && hasSession()) { kRemoteInterface_.getReferralCounts(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS) && hasUser() && hasSession()) { kRemoteInterface_.getRewards(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS) && hasUser() && hasSession()) { kRemoteInterface_.redeemRewards(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY) && hasUser() && hasSession()) { kRemoteInterface_.getCreditHistory(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION) && hasUser() && hasSession()) { kRemoteInterface_.userCompletedAction(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL) && hasUser() && hasSession()) { kRemoteInterface_.createCustomUrl(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY) && hasUser() && hasSession()) { kRemoteInterface_.identifyUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && hasUser() && hasSession()) { kRemoteInterface_.registerClose(); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_LOGOUT) && hasUser() && hasSession()) { kRemoteInterface_.logoutUser(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE) && hasUser() && hasSession()) { kRemoteInterface_.getReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE) && hasUser() && hasSession()) { kRemoteInterface_.validateReferralCode(req.getPost()); } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE) && hasUser() && hasSession()) { kRemoteInterface_.applyReferralCode(req.getPost()); } else if (!hasUser()) { networkCount_ = 0; Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); handleFailure(requestQueue_.getSize()-1); initSession(); } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize()-1); } else { req = requestQueue_.peekAt(index); } handleFailure(req); } private void handleFailure(final ServerRequest req) { if (req == null) return; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { if (initSessionFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } initSessionFinishedCallback_.onInitFinished(obj, new BranchInitError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetReferralsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { if (stateChangedCallback_ != null) { if (initNotStarted_) stateChangedCallback_.onStateChanged(false, new BranchNotInitError()); else stateChangedCallback_.onStateChanged(false, new BranchGetCreditsError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { if (creditHistoryCallback_ != null) { if (initNotStarted_) creditHistoryCallback_.onReceivingResponse(null, new BranchNotInitError()); else creditHistoryCallback_.onReceivingResponse(null, new BranchGetCreditHistoryError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { if (linkCreateCallback_ != null) { String failedUrl = null; if (!prefHelper_.getUserURL().equals(PrefHelper.NO_STRING_VALUE)) { failedUrl = prefHelper_.getUserURL(); } if (initNotStarted_) linkCreateCallback_.onLinkCreate(null, new BranchNotInitError()); else linkCreateCallback_.onLinkCreate(failedUrl, new BranchCreateUrlError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { if (initIdentityFinishedCallback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } if (initNotStarted_) initIdentityFinishedCallback_.onInitFinished(obj, new BranchNotInitError()); else initIdentityFinishedCallback_.onInitFinished(obj, new BranchSetIdentityError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { if (getReferralCodeCallback_ != null) { if (initNotStarted_) getReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else getReferralCodeCallback_.onInitFinished(null, new BranchGetReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { if (validateReferralCodeCallback_ != null) { if (initNotStarted_) validateReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else validateReferralCodeCallback_.onInitFinished(null, new BranchValidateReferralCodeError()); } } else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { if (applyReferralCodeCallback_ != null) { if (initNotStarted_) applyReferralCodeCallback_.onInitFinished(null, new BranchNotInitError()); else applyReferralCodeCallback_.onInitFinished(null, new BranchApplyReferralCodeError()); } } } }); } private void retryLastRequest() { retryCount_ = retryCount_ + 1; if (retryCount_ > prefHelper_.getRetryCount()) { handleFailure(0); requestQueue_.dequeue(); retryCount_ = 0; } else { try { Thread.sleep(prefHelper_.getRetryInterval()); } catch (InterruptedException e) { e.printStackTrace(); } } } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("app_id")) { req.getPost().put(key, prefHelper_.getAppKey()); } else if (key.equals("session_id")) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals("identity_id")) { req.getPost().put(key, prefHelper_.getIdentityID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; synchronized(closeTimer) { clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(String tag) { if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(new ServerRequest(tag)); } else { requestQueue_.moveInstallOrOpenToFront(tag, networkCount_); } processNextQueueItem(); } private void initializeSession() { if (hasUser()) { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN); } else { registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL); } } private void processReferralCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { JSONObject counts = resp.getObject().getJSONObject(key); int total = counts.getInt("total"); int unique = counts.getInt("unique"); if (total != prefHelper_.getActionTotalCount(key) || unique != prefHelper_.getActionUniqueCount(key)) { updateListener = true; } prefHelper_.setActionTotalCount(key, total); prefHelper_.setActionUniqueCount(key, unique); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processRewardCounts(ServerResponse resp) { boolean updateListener = false; Iterator<?> keys = resp.getObject().keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { int credits = resp.getObject().getInt(key); if (credits != prefHelper_.getCreditCount(key)) { updateListener = true; } prefHelper_.setCreditCount(key, credits); } catch (JSONException e) { e.printStackTrace(); } } final boolean finUpdateListener = updateListener; Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (stateChangedCallback_ != null) { stateChangedCallback_.onStateChanged(finUpdateListener, null); } } }); } private void processCreditHistory(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (creditHistoryCallback_ != null) { creditHistoryCallback_.onReceivingResponse(resp.getArray(), null); } } }); } private void processReferralCodeGet(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (getReferralCodeCallback_ != null) { try { JSONObject json; BranchDuplicateReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Failed to get referral code"); error = new BranchDuplicateReferralCodeError(); } else { json = resp.getObject(); } getReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeValidation(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (validateReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } validateReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } private void processReferralCodeApply(final ServerResponse resp) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (applyReferralCodeCallback_ != null) { try { JSONObject json; BranchInvalidReferralCodeError error = null; // check if a valid referral code json is returned if (!resp.getObject().has(REFERRAL_CODE)) { json = new JSONObject(); json.put("error_message", "Invalid referral code"); error = new BranchInvalidReferralCodeError(); } else { json = resp.getObject(); } applyReferralCodeCallback_.onInitFinished(json, error); } catch (JSONException e) { e.printStackTrace(); } } } }); } public class ReferralNetworkCallback implements NetworkCallback { @Override public void finished(ServerResponse serverResponse) { if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); String requestTag = serverResponse.getTag(); hasNetwork_ = true; if (status == 409) { if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(null, new BranchDuplicateUrlError()); } } }); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0); } requestQueue_.dequeue(); } else if (status >= 400 && status < 500) { if (serverResponse.getObject().has("error") && serverResponse.getObject().getJSONObject("error").has("message")) { Log.i("BranchSDK", "Branch API Error: " + serverResponse.getObject().getJSONObject("error").getString("message")); } if (lastRequestWasInit_ && !initFailed_) { initFailed_ = true; for (int i = 0; i < requestQueue_.getSize()-1; i++) { handleFailure(i); } } handleFailure(requestQueue_.getSize()-1); requestQueue_.dequeue(); } else if (status != 200) { if (status == RemoteInterface.NO_CONNECTIVITY_STATUS) { hasNetwork_ = false; handleFailure(lastRequestWasInit_ ? 0 : requestQueue_.getSize()-1); if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) { requestQueue_.dequeue(); } Log.i("BranchSDK", "Branch API Error: poor network connectivity. Please try again later."); } else { retryLastRequest(); } } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) { processReferralCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) { processRewardCounts(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) { processCreditHistory(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) { prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } else { prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); } } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } updateAllRequestsInQueue(); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE); if (serverResponse.getObject().has("identity_id")) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); } if (serverResponse.getObject().has("link_click_id")) { prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id")); } else { prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE); } if (prefHelper_.getIsReferrable() == 1) { if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setInstallParams(params); } } if (serverResponse.getObject().has("data")) { String params = serverResponse.getObject().getString("data"); prefHelper_.setSessionParams(params); } else { prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initSessionFinishedCallback_ != null) { initSessionFinishedCallback_.onInitFinished(getLatestReferringParams(), null); } } }); requestQueue_.dequeue(); initFinished_ = true; } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) { final String url = serverResponse.getObject().getString("url"); Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (linkCreateCallback_ != null) { linkCreateCallback_.onLinkCreate(url, null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_LOGOUT)) { prefHelper_.setSessionID(serverResponse.getObject().getString("session_id")); prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE); prefHelper_.setIdentity(PrefHelper.NO_STRING_VALUE); prefHelper_.clearUserValues(); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) { prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id")); prefHelper_.setUserURL(serverResponse.getObject().getString("link")); if (serverResponse.getObject().has("referring_data")) { String params = serverResponse.getObject().getString("referring_data"); prefHelper_.setInstallParams(params); } if (requestQueue_.getSize() > 0) { ServerRequest req = requestQueue_.peek(); if (req.getPost() != null && req.getPost().has("identity")) { prefHelper_.setIdentity(req.getPost().getString("identity")); } } Handler mainHandler = new Handler(context_.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (initIdentityFinishedCallback_ != null) { initIdentityFinishedCallback_.onInitFinished(getFirstReferringParams(), null); } } }); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) { processReferralCodeGet(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) { processReferralCodeValidation(serverResponse); requestQueue_.dequeue(); } else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_APPLY_REFERRAL_CODE)) { processReferralCodeApply(serverResponse); requestQueue_.dequeue(); } else { requestQueue_.dequeue(); } networkCount_ = 0; if (hasNetwork_ && !initFailed_) processNextQueueItem(); } catch (JSONException ex) { ex.printStackTrace(); } } } } public interface BranchReferralInitListener { public void onInitFinished(JSONObject referringParams, BranchError error); } public interface BranchReferralStateChangedListener { public void onStateChanged(boolean changed, BranchError error); } public interface BranchLinkCreateListener { public void onLinkCreate(String url, BranchError error); } public interface BranchListResponseListener { public void onReceivingResponse(JSONArray list, BranchError error); } public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } public class BranchInitError extends BranchError { @Override public String getMessage() { return "Trouble initializing Branch. Check network connectivity or that your app key is valid"; } } public class BranchGetReferralsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving referral counts. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditsError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credits. Check network connectivity and that you properly initialized"; } } public class BranchGetCreditHistoryError extends BranchError { @Override public String getMessage() { return "Trouble retrieving user credit history. Check network connectivity and that you properly initialized"; } } public class BranchCreateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL. Check network connectivity and that you properly initialized"; } } public class BranchDuplicateUrlError extends BranchError { @Override public String getMessage() { return "Trouble creating a URL with that alias. If you want to reuse the alias, make sure to submit the same properties for all arguments and that the user is the same owner"; } } public class BranchSetIdentityError extends BranchError { @Override public String getMessage() { return "Trouble setting the user alias. Check network connectivity and that you properly initialized"; } } public class BranchGetReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble retrieving the referral code. Check network connectivity and that you properly initialized"; } } public class BranchValidateReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble validating the referral code. Check network connectivity and that you properly initialized"; } } public class BranchInvalidReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code was invalid"; } } public class BranchDuplicateReferralCodeError extends BranchError { @Override public String getMessage() { return "That Branch referral code is already in use"; } } public class BranchApplyReferralCodeError extends BranchError { @Override public String getMessage() { return "Trouble applying the referral code. Check network connectivity and that you properly initialized"; } } public class BranchNotInitError extends BranchError { @Override public String getMessage() { return "Did you forget to call init? Make sure you init the session before making Branch calls"; } } }
package org.jfree.chart.axis.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.AxisSpace; /** * Tests for the {@link AxisSpace} class. */ public class AxisSpaceTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(AxisSpaceTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public AxisSpaceTests(String name) { super(name); } /** * Check that the equals() method can distinguish all fields. */ public void testEquals() { AxisSpace a1 = new AxisSpace(); AxisSpace a2 = new AxisSpace(); assertEquals(a1, a2); a1.setTop(1.11); assertFalse(a1.equals(a2)); a2.setTop(1.11); assertTrue(a1.equals(a2)); a1.setBottom(2.22); assertFalse(a1.equals(a2)); a2.setBottom(2.22); assertTrue(a1.equals(a2)); a1.setLeft(3.33); assertFalse(a1.equals(a2)); a2.setLeft(3.33); assertTrue(a1.equals(a2)); a1.setRight(4.44); assertFalse(a1.equals(a2)); a2.setRight(4.44); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { AxisSpace s1 = new AxisSpace(); AxisSpace s2 = new AxisSpace(); assertTrue(s1.equals(s2)); int h1 = s1.hashCode(); int h2 = s2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { AxisSpace s1 = new AxisSpace(); AxisSpace s2 = null; try { s2 = (AxisSpace) s1.clone(); } catch (CloneNotSupportedException e) { System.err.println("Failed to clone."); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gwac.job; import com.gwac.dao.FitsFileDAO; import com.gwac.dao.ImageStatusParameterDao; import com.gwac.dao.ProcessStatusDao; import com.gwac.dao.UploadFileUnstoreDao; import com.gwac.model.FitsFile; import com.gwac.model.ImageStatusParameter; import com.gwac.model.ProcessStatus; import com.gwac.model.UploadFileUnstore; import com.gwac.util.CommonFunction; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * OTOT * * @author xy */ public class ImageStatusParmServiceImpl implements ImageStatusParmService { private static final Log log = LogFactory.getLog(ImageStatusParmServiceImpl.class); private UploadFileUnstoreDao ufuDao; private FitsFileDAO ffDao; private ProcessStatusDao psDao; private ImageStatusParameterDao ispDao; private String rootPath; private static boolean running = true; private Boolean isBeiJingServer; private Boolean isTestServer; @Override public void startJob() { if (isTestServer) { return; } if (running == true) { log.debug("start job..."); running = false; } else { log.warn("job is running, jump this scheduler."); return; } long startTime = System.nanoTime(); parseImageStatusParm(); long endTime = System.nanoTime(); double time1 = 1.0 * (endTime - startTime) / 1e9; if (running == false) { running = true; log.debug("job is done."); } log.debug("job consume: parse image status parameter " + time1 + "."); } public void parseImageStatusParm() { List<UploadFileUnstore> ufus = ufuDao.getImgStatusFile(); log.debug("size=" + ufus.size()); if (ufus != null) { List<ImageStatusParameter> isps = new ArrayList<ImageStatusParameter>(); InputStream input = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss"); for (UploadFileUnstore ufu : ufus) { log.debug("ufuId=" + ufu.getUfuId()); File tfile = new File(rootPath + "/" + ufu.getStorePath(), ufu.getFileName()); log.debug(tfile.getAbsolutePath()); if (tfile.exists()) { try { input = new FileInputStream(tfile); Properties cfile = new Properties(); cfile.load(input); ImageStatusParameter isp = new ImageStatusParameter(); String tStr = cfile.getProperty("DateObsUT"); String tStr2 = cfile.getProperty("TimeObsUT"); tStr = tStr.trim(); tStr2 = tStr2.trim(); if (tStr != null && tStr2 != null && !tStr.isEmpty() && !tStr2.isEmpty()) { isp.setTimeObsUt(df.parse(tStr + " " + tStr2)); tStr = cfile.getProperty("Obj_Num"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setObjNum(Integer.parseInt(tStr.trim())); } } tStr = cfile.getProperty("bgbright"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setBgBright(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("Fwhm"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setFwhm(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("AverDeltaMag"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setS2n(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("AverLimit"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setAvgLimit(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("Extinc"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setExtinc(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("xshift"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setXshift(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("yshift"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setYshift(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("xrms"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setXrms(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("yrms"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setYrms(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("OC1"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setOt1Num(Integer.parseInt(tStr)); } } tStr = cfile.getProperty("VC1"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setVar1Num(Integer.parseInt(tStr)); } } tStr = cfile.getProperty("Image"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { tStr2 = cfile.getProperty("DirData"); FitsFile ff = new FitsFile(); ff.setFileName(tStr); ff.setStorePath(tStr2); ffDao.save(ff); isp.setFfId(ff.getFfId()); int dpmId = Integer.parseInt(tStr.substring(3, 5)); //dpmName int number = Integer.parseInt(tStr.substring(22, 26)); isp.setDpmId(dpmId); isp.setPrcNum(number); } } tStr = cfile.getProperty("ra_mount"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { if (tStr.contains(":")) { isp.setMountRa(CommonFunction.dmsToDegree(tStr)); } else { isp.setMountRa(Float.parseFloat(tStr)); } } } tStr = cfile.getProperty("dec_mount"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { if (tStr.contains(":")) { isp.setMountDec(CommonFunction.dmsToDegree(tStr)); } else { isp.setMountDec(Float.parseFloat(tStr)); } } } tStr = cfile.getProperty("State"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { ProcessStatus ps = new ProcessStatus(); ps.setPsName(tStr); psDao.save(ps); isp.setProcStageId(ps.getPsId()); } } tStr = cfile.getProperty("TimeProcess"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setProcTime(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("ellipticity"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setAvgEllipticity(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("tempset"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setTemperatureSet(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("tempact"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setTemperatureActual(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("exptime"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setExposureTime(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("ra_imgCenter"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setImgCenterRa(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("dec_imgCenter"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setImgCenterDec(Float.parseFloat(tStr)); } } tStr = cfile.getProperty("TimeProcessEnd"); if (tStr != null) { tStr = tStr.trim(); if (!tStr.isEmpty() && !tStr.equalsIgnoreCase("nan")) { isp.setProcEndTime(df2.parse(tStr)); } } isps.add(isp); ispDao.save(isp); } } catch (NumberFormatException ex) { log.error(ufu.getFileName()); log.error(ex); } catch (FileNotFoundException ex) { log.error(ufu.getFileName()); log.error(ex); } catch (IOException ex) { log.error(ufu.getFileName()); log.error(ex); } catch (ParseException ex) { log.error(ufu.getFileName()); log.error(ex); } finally { if (input != null) { try { input.close(); } catch (IOException ex) { log.error(ex); } } } } else { log.error("file not exists!"); } } if (isps.size() > 0) { try { String ip = "190.168.1.32"; //190.168.1.32 int port = 18851; Socket socket = null; DataOutputStream out = null; socket = new Socket(ip, port); out = new DataOutputStream(socket.getOutputStream()); for (ImageStatusParameter isp : isps) { if (chechStatus(isp)) { String tmsg = getFWHMMessage(isp); out.write(tmsg.getBytes()); out.flush(); log.debug("send message to " + ip + " : " + tmsg); try { Thread.sleep(100); } catch (InterruptedException ex) { log.error("sleep error!", ex); } } else { log.debug("image status do not meet send status."); } } out.close(); socket.close(); } catch (IOException ex) { log.error("send message error", ex); } } } } public Boolean chechStatus(ImageStatusParameter isp) { Boolean flag = false; if (isp != null && isp.getXrms() != null && isp.getYrms() != null && isp.getAvgEllipticity() != null && isp.getObjNum() != null && isp.getBgBright() != null && isp.getS2n() != null && isp.getAvgLimit() != null && isp.getFwhm() != null && isp.getXshift() != null) { Boolean s1 = isp.getXrms() < 0.13 && isp.getYrms() < 0.13 && isp.getAvgEllipticity() > 0 && isp.getAvgEllipticity() < 0.26 && isp.getObjNum() > 5000 && isp.getObjNum() < 30000 && isp.getBgBright() < 10000 && isp.getBgBright() > 1000 && isp.getS2n() < 0.5 && isp.getAvgLimit() > 12 && isp.getFwhm() < 10 && isp.getFwhm() > 1; Boolean s2 = (isp.getXshift() + 99) < 0.00001 && isp.getObjNum() > 5000 && isp.getObjNum() < 30000 && isp.getBgBright() < 10000 && isp.getBgBright() > 1000 && isp.getFwhm() < 10 && isp.getFwhm() > 1; //&& isp.getAvgEllipticity() > 0 && isp.getAvgEllipticity() < 0.26 flag = s1 || s2; } else { log.error("image status is null or has null porperties!"); } return flag; } public String getFWHMMessage(ImageStatusParameter isp) { int dpmId = isp.getDpmId(); String msg = "d#fwhm" + (int) Math.ceil(dpmId / 2.0); if (dpmId % 2 == 0) { msg += "N"; } else { msg += "S"; } msg += String.format("%04.0f", isp.getFwhm() * 100); msg += "%"; return msg; } /** * @param ufuDao the ufuDao to set */ public void setUfuDao(UploadFileUnstoreDao ufuDao) { this.ufuDao = ufuDao; } /** * @param ffDao the ffDao to set */ public void setFfDao(FitsFileDAO ffDao) { this.ffDao = ffDao; } /** * @param psDao the psDao to set */ public void setPsDao(ProcessStatusDao psDao) { this.psDao = psDao; } /** * @param ispDao the ispDao to set */ public void setIspDao(ImageStatusParameterDao ispDao) { this.ispDao = ispDao; } /** * @param rootPath the rootPath to set */ public void setRootPath(String rootPath) { this.rootPath = rootPath; } /** * @param isBeiJingServer the isBeiJingServer to set */ public void setIsBeiJingServer(Boolean isBeiJingServer) { this.isBeiJingServer = isBeiJingServer; } /** * @param isTestServer the isTestServer to set */ public void setIsTestServer(Boolean isTestServer) { this.isTestServer = isTestServer; } }
package cgeo.geocaching.location; import static org.assertj.core.api.Assertions.assertThat; import cgeo.CGeoTestCase; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; import org.assertj.core.data.Offset; import rx.Observable; import android.location.Address; import android.location.Geocoder; public class GeocoderTest extends CGeoTestCase { private static final String TEST_ADDRESS = "46 rue Barrault, Paris, France"; private static final double TEST_LATITUDE = 48.82677; private static final double TEST_LONGITUDE = 2.34644; private static final Geopoint TEST_COORDS = new Geopoint(TEST_LATITUDE, TEST_LONGITUDE); private static final Offset<Double> TEST_OFFSET = Offset.offset(0.00050); public static void testAndroidGeocoder() { // Some emulators don't have access to Google Android geocoder if (Geocoder.isPresent()) { final AndroidGeocoder geocoder = new AndroidGeocoder(CgeoApplication.getInstance()); testGeocoder(geocoder.getFromLocationName(TEST_ADDRESS), "Android", true); testGeocoder(geocoder.getFromLocation(TEST_COORDS), "Android reverse", true); } else { Log.i("not testing absent Android geocoder"); } } public static void testGCGeocoder() { testGeocoder(GCGeocoder.getFromLocationName(TEST_ADDRESS), "GC", false); } public static void testMapQuestGeocoder() { testGeocoder(MapQuestGeocoder.getFromLocationName(TEST_ADDRESS), "MapQuest", true); testGeocoder(MapQuestGeocoder.getFromLocation(TEST_COORDS), "MapQuest reverse", true); } public static void testGeocoder(final Observable<Address> addressObservable, final String geocoder, final boolean withAddress) { final Address address = addressObservable.toBlocking().first(); assertThat(address.getLatitude()).as(describe("latitude", geocoder)).isCloseTo(TEST_LATITUDE, TEST_OFFSET); assertThat(address.getLongitude()).as(describe("longitude", geocoder)).isCloseTo(TEST_LONGITUDE, TEST_OFFSET); if (withAddress) { assertThat(StringUtils.lowerCase(address.getAddressLine(0))).as(describe("street address", geocoder)).startsWith("46 rue barrault"); assertThat(address.getLocality()).as(describe("locality", geocoder)).isEqualTo("Paris"); assertThat(address.getCountryCode()).as(describe("country code", geocoder)).isEqualTo("FR"); // don't assert on country name, as this can be localized, e.g. with the mapquest geocoder } } private static String describe(final String field, final String geocoder) { return new StringBuilder(field).append(" for ").append(geocoder).append(" .geocoder").toString(); } }
package com.heroku.myapp.myorchestrator; import com.heroku.myapp.commons.util.content.MediawikiApiRequest; import java.net.URLEncoder; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class Develop { public Processor dev() { return (Exchange exchange) -> { Map<String, Boolean> categories = new LinkedHashMap<>(); Set<String> pages = new HashSet<>(); //categories.put("Category:", Boolean.FALSE); //categories.put("Category:", Boolean.FALSE); //categories.put("Category:", Boolean.FALSE); categories.put("Category:", Boolean.FALSE); //categories.put("Category:", Boolean.FALSE); //categories.put("Category:", Boolean.FALSE); //categories.put("Category:", Boolean.FALSE); int i = 0; Pattern p = Pattern.compile("^Category:201\\d.+$"); while (categories.values().stream().filter((b) -> !b).findFirst().isPresent()) { System.out.println(++i); categories.keySet().parallelStream() .filter((key) -> !categories.get(key)) .flatMap((key) -> { categories.put(key, Boolean.TRUE); try { return new MediawikiApiRequest() .setApiParam("action=query&list=categorymembers" + "&cmtitle=" + URLEncoder.encode(key, "UTF-8") + "&cmlimit=500" + "&cmnamespace=0|14" + "&format=xml" + "&continue=" + "&cmprop=title|ids|sortkeyprefix") .setListName("categorymembers").setMapName("cm") .setContinueElementName("cmcontinue") .getResultByMapList().stream(); } catch (Throwable t) { System.out.println("failed!!!"); throw new RuntimeException(); } }).reduce(categories, (foo, bar) -> { String title = (String) bar.get("title"); String ns = (String) bar.get("ns"); if (ns.equals("0")) { pages.add(title); } else if (!categories.containsKey(title) && p.matcher(title).find()) { categories.put(title, Boolean.FALSE); } return categories; }, (foo, bar) -> { return foo; }); } System.out.println(categories.keySet().size() + " " + pages.size()); pages.stream().forEach(System.out::println); categories.keySet().stream().forEach(System.out::println); }; } /* public Processor dev0926(){ return (Exchange exchange) -> { List<String> list = Arrays.asList(new String[]{"", "", "", "", "", "", "", "", "", "", ""}); IntStream.range(0, list.size()) .mapToObj((i) -> { Map<Integer, String> map = new LinkedHashMap<>(); map.put(i, list.get(i)); return map; }) .collect(Collectors.groupingBy((map) -> map.keySet().iterator().next() / 3)) .values().stream().map((values) -> values.stream().map((m) -> m.values().iterator().next()).collect(Collectors.toList())) .flatMap((titles) -> { Iterator<Elements> iterator = new IterableMediawikiApiRequest().setApiParam("action=query&titles=" + String.join("|", titles) + "&format=xml&redirects=true&prop=links|linkshere&plnamespace=0&lhnamespace=0&pllimit=500&lhlimit=500").setContinueElementNames(new String[]{"plcontinue", "lhcontinue"}).debug().iterator(); Spliterator<Elements> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED); return StreamSupport.stream(spliterator, false).flatMap((elements) -> elements.stream()); }) .collect(Collectors.groupingBy((element) -> element.attr("title"))) .forEach((k, v) -> { Set<String> plset = v.stream().flatMap((element) -> element.select("pl").stream()) .map((m) -> m.attr("title")) .collect(Collectors.toSet()); Set<String> mutual = v.stream().flatMap((element) -> element.select("lh").stream()) .map((m) -> m.attr("title")) .filter((str) -> plset.contains(str)) .collect(Collectors.toSet()); System.out.println(k + "\t" + mutual); }); } }*/ }
package com.hubspot.dropwizard.guice; import io.dropwizard.Bundle; import io.dropwizard.lifecycle.Managed; import io.dropwizard.servlets.tasks.Task; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import com.google.common.base.Preconditions; import com.google.inject.Injector; import org.glassfish.jersey.server.model.Resource; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Path; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; import java.util.Set; public class AutoConfig { final Logger logger = LoggerFactory.getLogger(AutoConfig.class); private Reflections reflections; public AutoConfig(String... basePackages) { Preconditions.checkArgument(basePackages.length > 0); ConfigurationBuilder cfgBldr = new ConfigurationBuilder(); FilterBuilder filterBuilder = new FilterBuilder(); for (String basePkg : basePackages) { cfgBldr.addUrls(ClasspathHelper.forPackage(basePkg)); filterBuilder.include(FilterBuilder.prefix(basePkg)); } cfgBldr.filterInputsBy(filterBuilder).setScanners( new SubTypesScanner(), new TypeAnnotationsScanner()); this.reflections = new Reflections(cfgBldr); } public void run(Environment environment, Injector injector) { addHealthChecks(environment, injector); addProviders(environment); addResources(environment); addTasks(environment, injector); addManaged(environment, injector); addParamConverterProviders(environment); } public void initialize(Bootstrap<?> bootstrap, Injector injector) { addBundles(bootstrap, injector); } private void addManaged(Environment environment, Injector injector) { Set<Class<? extends Managed>> managedClasses = reflections .getSubTypesOf(Managed.class); for (Class<? extends Managed> managed : managedClasses) { environment.lifecycle().manage(injector.getInstance(managed)); logger.info("Added managed: {}", managed); } } private void addTasks(Environment environment, Injector injector) { Set<Class<? extends Task>> taskClasses = reflections .getSubTypesOf(Task.class); for (Class<? extends Task> task : taskClasses) { environment.admin().addTask(injector.getInstance(task)); logger.info("Added task: {}", task); } } private void addHealthChecks(Environment environment, Injector injector) { Set<Class<? extends InjectableHealthCheck>> healthCheckClasses = reflections .getSubTypesOf(InjectableHealthCheck.class); for (Class<? extends InjectableHealthCheck> healthCheck : healthCheckClasses) { InjectableHealthCheck instance = injector.getInstance(healthCheck); environment.healthChecks().register(instance.getName(), instance); logger.info("Added injectableHealthCheck: {}", healthCheck); } } private void addProviders(Environment environment) { Set<Class<?>> providerClasses = reflections .getTypesAnnotatedWith(Provider.class); for (Class<?> provider : providerClasses) { environment.jersey().register(provider); logger.info("Added provider class: {}", provider); } } private void addResources(Environment environment) { Set<Class<?>> resourceClasses = reflections .getTypesAnnotatedWith(Path.class); for (Class<?> resource : resourceClasses) { if(Resource.isAcceptable(resource)) { environment.jersey().register(resource); logger.info("Added resource class: {}", resource); } } } private void addBundles(Bootstrap<?> bootstrap, Injector injector) { Set<Class<? extends Bundle>> bundleClasses = reflections .getSubTypesOf(Bundle.class); for (Class<? extends Bundle> bundle : bundleClasses) { bootstrap.addBundle(injector.getInstance(bundle)); logger.info("Added bundle class {} during bootstrap", bundle); } } private void addParamConverterProviders(Environment environment) { Set<Class<? extends ParamConverterProvider>> providerClasses = reflections .getSubTypesOf(ParamConverterProvider.class); for (Class<?> provider : providerClasses) { environment.jersey().register(provider); logger.info("Added ParamConverterProvider class: {}", provider); } } }
package com.ic.modules.user.controller; import com.ic.core.base.CoreController; import com.ic.core.config.Global; import com.ic.core.mapper.JsonMapper; import com.ic.core.model.Code; import com.ic.core.utils.MD5Util; import com.ic.modules.user.service.UserServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/api/user") public class UserCtrl extends CoreController { @Autowired private UserServiceImpl userService; @RequestMapping("/login") public void login(HttpServletRequest req, HttpServletResponse resp, HttpSession session){ Map<String, Object> param = (Map<String, Object>) req.getAttribute("param"); Map<String, Object> user = userService.getUser(param); if(user== null){ renderData(Code.FAIL, "", null); }else{ if(!user.get("user_pwd").equals(MD5Util.getMD5String(Global.getConfig("md5salt")+param.get("userPwd")))){ renderData(Code.FAIL, "/", null); }else{ renderData(Code.SUCCESS,"",user); } } } @RequestMapping("/reg") public void register(HttpServletRequest req,HttpServletResponse resp,HttpSession session){ Map<String, Object> param = (Map<String, Object>) req.getAttribute("param"); if(param.get("userName")==null || param.get("userPwd") == null) { renderData(Code.PARAMS_ERROR, "/", null); }else{ Map<String, Object> out = userService.getUser(param); String exists = (String) session.getAttribute("exists"); if ("1".equals(exists) || out != null) { renderData(Code.FAIL, "", null); } else { int rtn = userService.insertUser(param); if (rtn == 1) { renderData(Code.SUCCESS, "", null); } else { renderData(Code.FAIL, "", null); } } } } @RequestMapping("/check") public void check(HttpServletRequest req,HttpServletResponse resp,HttpSession session){ Map<String, Object> param = (Map<String, Object>) req.getAttribute("param"); if(param.get("userName")==null){ renderData(Code.PARAMS_ERROR, "", null); }else{ Map<String, Object> out = userService.getUser(param); if (out == null) { out = new HashMap<String, Object>(); out.put("exists", "0"); } else { out = new HashMap<String, Object>(); out.put("exists", "1"); } renderData(Code.SUCCESS, "", out); } } }
package org.apache.batik.swing.gvt; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.image.BufferedImage; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.JComponent; import org.apache.batik.gvt.GraphicsNode; import org.apache.batik.gvt.event.AWTEventDispatcher; import org.apache.batik.gvt.renderer.DynamicRendererFactory; import org.apache.batik.gvt.renderer.ImageRenderer; import org.apache.batik.gvt.renderer.ImageRendererFactory; /** * This class represents a component which can display a GVT tree. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class JGVTComponent extends JComponent { /** * The listener. */ protected Listener listener; /** * The GVT tree renderer. */ protected GVTTreeRenderer gvtTreeRenderer; /** * The GVT tree root. */ protected GraphicsNode gvtRoot; /** * The renderer factory. */ protected ImageRendererFactory rendererFactory = new DynamicRendererFactory(); /** * The current renderer. */ protected ImageRenderer renderer; /** * The GVT tree renderer listeners. */ protected List gvtTreeRendererListeners = Collections.synchronizedList(new LinkedList()); /** * Whether a render was requested. */ protected boolean needRender; /** * Whether to allow progressive paint. */ protected boolean progressivePaint; /** * The progressive paint thread. */ protected Thread progressivePaintThread; /** * The image to paint. */ protected BufferedImage image; /** * The initial rendering transform. */ protected AffineTransform initialTransform; /** * The transform used for rendering. */ protected AffineTransform renderingTransform; /** * The transform used for painting. */ protected AffineTransform paintingTransform; /** * The interactor list. */ protected List interactors = new LinkedList(); /** * The current interactor. */ protected Interactor interactor; /** * The overlays. */ protected List overlays = new LinkedList(); /** * The event dispatcher. */ protected AWTEventDispatcher eventDispatcher; /** * The text selection manager. */ protected TextSelectionManager textSelectionManager; /** * Whether the double buffering is enabled. */ protected boolean doubleBufferedRendering; /** * Whether the GVT tree should be reactive to mouse and key events. */ protected boolean eventsEnabled; /** * Whether the text should be selectable if eventEnabled is false, * this flag is ignored. */ protected boolean selectableText; /** * Whether to suspend interactions. */ protected boolean suspendInteractions; /** * Whether to inconditionally disable interactions. */ protected boolean disableInteractions; /** * Creates a new JGVTComponent. */ public JGVTComponent() { this(false, false); } /** * Creates a new JGVTComponent. * @param eventEnabled Whether the GVT tree should be reactive * to mouse and key events. * @param selectableText Whether the text should be selectable. * if eventEnabled is false, this flag is ignored. */ public JGVTComponent(boolean eventsEnabled, boolean selectableText) { setBackground(Color.white); this.eventsEnabled = eventsEnabled; this.selectableText = selectableText; listener = createListener(); addKeyListener(listener); addMouseListener(listener); addMouseMotionListener(listener); addGVTTreeRendererListener(listener); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { updateRenderingTransform(); scheduleGVTRendering(); } }); } /** * Returns the interactor list. */ public List getInteractors() { return interactors; } /** * Returns the overlay list. */ public List getOverlays() { return overlays; } /** * Returns the off-screen image, if any. */ public BufferedImage getOffScreen() { return image; } /** * Stops the processing of the current tree. */ public void stopProcessing() { if (gvtTreeRenderer != null) { gvtTreeRenderer.interrupt(); interruptProgressivePaintThread(); } } /** * Returns the root of the GVT tree displayed by this component, if any. */ public GraphicsNode getGraphicsNode() { return gvtRoot; } /** * Sets the GVT tree to display. */ public void setGraphicsNode(GraphicsNode gn) { setGraphicsNode(gn, true); } /** * Sets the GVT tree to display. */ protected void setGraphicsNode(GraphicsNode gn, boolean createDispatcher) { gvtRoot = gn; if (gn != null && createDispatcher) { initializeEventHandling(); } if (eventDispatcher != null) { eventDispatcher.setRootNode(gn); } computeRenderingTransform(); } /** * Initializes the event handling classes. */ protected void initializeEventHandling() { if (eventsEnabled) { eventDispatcher = new AWTEventDispatcher(rendererFactory.getRenderContext()); if (selectableText) { textSelectionManager = new TextSelectionManager(this, rendererFactory.getRenderContext(), eventDispatcher); } } } /** * Whether to enable the progressive paint. */ public void setProgressivePaint(boolean b) { if (progressivePaint != b) { progressivePaint = b; interruptProgressivePaintThread(); } } /** * Tells whether the progressive paint is enabled. */ public boolean getProgressivePaint() { return progressivePaint; } /** * Repaints immediately the component. */ public void immediateRepaint() { if (java.awt.EventQueue.isDispatchThread()) { Dimension dim = getSize(); paintImmediately(0, 0, dim.width, dim.height); } else { try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { Dimension dim = getSize(); paintImmediately(0, 0, dim.width, dim.height); } }); } catch (Exception e) { } } } /** * Paints this component. */ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; Dimension d = getSize(); g2d.setComposite(AlphaComposite.SrcOver); g2d.setPaint(getBackground()); g2d.fillRect(0, 0, d.width, d.height); if (image != null) { if (paintingTransform != null) { g2d.transform(paintingTransform); } g2d.drawRenderedImage(image, null); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); Iterator it = overlays.iterator(); while (it.hasNext()) { ((Overlay)it.next()).paint(g); } } } /** * Sets the painting transform. A null transform is the same as * an identity transform. * The next repaint will use the given transform. */ public void setPaintingTransform(AffineTransform at) { paintingTransform = at; immediateRepaint(); } /** * Returns the current painting transform. */ public AffineTransform getPaintingTransform() { return paintingTransform; } /** * Sets the rendering transform. * Calling this method causes a rendering to be performed. */ public void setRenderingTransform(AffineTransform at) { renderingTransform = at; suspendInteractions = true; if (eventDispatcher != null) { try { eventDispatcher.setBaseTransform(renderingTransform.createInverse()); } catch (NoninvertibleTransformException e) { handleException(e); } } scheduleGVTRendering(); } /** * Returns the current rendering transform. */ public AffineTransform getRenderingTransform() { return renderingTransform; } /** * Sets whether this component should use double buffering to render * SVG documents. The change will be effective during the next * rendering. */ public void setDoubleBufferedRendering(boolean b) { doubleBufferedRendering = b; } /** * Tells whether this component use double buffering to render * SVG documents. */ public boolean getDoubleBufferedRendering() { return doubleBufferedRendering; } /** * Adds a GVTTreeRendererListener to this component. */ public void addGVTTreeRendererListener(GVTTreeRendererListener l) { gvtTreeRendererListeners.add(l); } /** * Removes a GVTTreeRendererListener from this component. */ public void removeGVTTreeRendererListener(GVTTreeRendererListener l) { gvtTreeRendererListeners.remove(l); } /** * Renders the GVT tree. Used for the initial rendering and resize only. */ protected void renderGVTTree() { Dimension d = getSize(); if (gvtRoot == null || d.width <= 0 || d.height <= 0) { return; } // Renderer setup. if (renderer == null) { renderer = rendererFactory.createImageRenderer(); renderer.setTree(gvtRoot); } // Area of interest computation. AffineTransform inv; try { inv = renderingTransform.createInverse(); } catch (NoninvertibleTransformException e) { throw new InternalError(e.getMessage()); } Shape s = inv.createTransformedShape(new Rectangle(0, 0, d.width, d.height)); // Rendering thread setup. gvtTreeRenderer = new GVTTreeRenderer(renderer, renderingTransform, doubleBufferedRendering, s, d.width, d.height); gvtTreeRenderer.setPriority(Thread.MIN_PRIORITY); Iterator it = gvtTreeRendererListeners.iterator(); while (it.hasNext()) { gvtTreeRenderer.addGVTTreeRendererListener ((GVTTreeRendererListener)it.next()); } // Disable the dispatch during the rendering // to avoid concurrent access to the GVT tree. if (eventDispatcher != null) { eventDispatcher.setRootNode(null); } gvtTreeRenderer.start(); } /** * Computes the initial value of the transform used for rendering. */ protected void computeRenderingTransform() { initialTransform = new AffineTransform(); setRenderingTransform(initialTransform); } /** * Updates the value of the transform used for rendering. */ protected void updateRenderingTransform() { // Do nothing. } /** * Handles an exception. */ protected void handleException(Exception e) { // Do nothing. } /** * Releases the references to the rendering resources, */ protected void releaseRenderingReferences() { eventDispatcher = null; if (textSelectionManager != null) { overlays.remove(textSelectionManager.getSelectionOverlay()); textSelectionManager = null; } renderer = null; gvtRoot = null; } /** * Schedules a new GVT rendering. */ protected void scheduleGVTRendering() { if (gvtTreeRenderer != null) { needRender = true; gvtTreeRenderer.interrupt(); } else { renderGVTTree(); } } private void interruptProgressivePaintThread() { if (progressivePaintThread != null) { progressivePaintThread.interrupt(); progressivePaintThread = null; } } /** * Creates an instance of Listener. */ protected Listener createListener() { return new Listener(); } /** * To hide the listener methods. */ protected class Listener implements GVTTreeRendererListener, KeyListener, MouseListener, MouseMotionListener { /** * Creates a new Listener. */ protected Listener() { } // GVTTreeRendererListener ///////////////////////////////////////////// /** * Called when a rendering is in its preparing phase. */ public void gvtRenderingPrepare(GVTTreeRendererEvent e) { suspendInteractions = true; if (!progressivePaint && !doubleBufferedRendering) { image = null; immediateRepaint(); } } /** * Called when a rendering started. */ public void gvtRenderingStarted(GVTTreeRendererEvent e) { paintingTransform = null; if (progressivePaint && !doubleBufferedRendering) { image = e.getImage(); progressivePaintThread = new Thread() { public void run() { final Thread thisThread = this; try { while (!isInterrupted()) { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { if (progressivePaintThread == thisThread) { Dimension dim = getSize(); paintImmediately(0, 0, dim.width, dim.height); } } }); sleep(200); } } catch (Exception e) { } } }; progressivePaintThread.setPriority(Thread.MIN_PRIORITY + 1); progressivePaintThread.start(); } if (!doubleBufferedRendering) { suspendInteractions = false; } } /** * Called when a rendering was completed. */ public void gvtRenderingCompleted(GVTTreeRendererEvent e) { interruptProgressivePaintThread(); if (doubleBufferedRendering) { suspendInteractions = false; } gvtTreeRenderer = null; if (needRender) { renderGVTTree(); needRender = false; } else { image = e.getImage(); immediateRepaint(); } if (eventDispatcher != null) { eventDispatcher.setRootNode(gvtRoot); } } /** * Called when a rendering was cancelled. */ public void gvtRenderingCancelled(GVTTreeRendererEvent e) { renderingStopped(); } /** * Called when a rendering failed. */ public void gvtRenderingFailed(GVTTreeRendererEvent e) { renderingStopped(); } /** * The actual implementation of gvtRenderingCancelled() and * gvtRenderingFailed(). */ private void renderingStopped() { interruptProgressivePaintThread(); if (doubleBufferedRendering) { suspendInteractions = false; } gvtTreeRenderer = null; if (needRender) { renderGVTTree(); needRender = false; } else { immediateRepaint(); } } // KeyListener ////////////////////////////////////////////////////////// /** * Invoked when a key has been typed. * This event occurs when a key press is followed by a key release. */ public void keyTyped(KeyEvent e) { selectInteractor(e); if (interactor != null) { interactor.keyTyped(e); deselectInteractor(); } } /** * Invoked when a key has been pressed. */ public void keyPressed(KeyEvent e) { selectInteractor(e); if (interactor != null) { interactor.keyPressed(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.keyReleased(e); } } /** * Invoked when a key has been released. */ public void keyReleased(KeyEvent e) { selectInteractor(e); if (interactor != null) { interactor.keyReleased(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.keyReleased(e); } } // MouseListener /////////////////////////////////////////////////////// /** * Invoked when the mouse has been clicked on a component. */ public void mouseClicked(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseClicked(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseClicked(e); } } /** * Invoked when a mouse button has been pressed on a component. */ public void mousePressed(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mousePressed(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mousePressed(e); } } /** * Invoked when a mouse button has been released on a component. */ public void mouseReleased(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseReleased(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseReleased(e); } } /** * Invoked when the mouse enters a component. */ public void mouseEntered(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseEntered(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseEntered(e); } } /** * Invoked when the mouse exits a component. */ public void mouseExited(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseExited(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseExited(e); } } // MouseMotionListener ///////////////////////////////////////////////// /** * Invoked when a mouse button is pressed on a component and then * dragged. Mouse drag events will continue to be delivered to * the component where the first originated until the mouse button is * released (regardless of whether the mouse position is within the * bounds of the component). */ public void mouseDragged(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseDragged(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseDragged(e); } } /** * Invoked when the mouse button has been moved on a component * (with no buttons no down). */ public void mouseMoved(MouseEvent e) { selectInteractor(e); if (interactor != null) { interactor.mouseMoved(e); deselectInteractor(); } else if (eventDispatcher != null) { eventDispatcher.mouseMoved(e); } } /** * Selects an interactor, given an input event. */ protected void selectInteractor(InputEvent ie) { if (!disableInteractions && !suspendInteractions && interactor == null) { Iterator it = interactors.iterator(); while (it.hasNext()) { Interactor i = (Interactor)it.next(); if (i.startInteraction(ie)) { interactor = i; break; } } } } /** * Deselects an interactor, if the interaction has finished. */ protected void deselectInteractor() { if (interactor.endInteraction()) { interactor = null; } } } }
package com.j256.simplemagic.entries; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.j256.simplemagic.ContentType; import com.j256.simplemagic.ContentTypeUtil.ErrorCallBack; import com.j256.simplemagic.endian.EndianConverter; import com.j256.simplemagic.endian.EndianType; /** * Representation of a line of information from the magic (5) format. * * @author graywatson */ public class MagicEntry { private static final String UNKNOWN_NAME = "unknown"; // special lines, others are put into the extensionMap private static final String MIME_TYPE_LINE = "!:mime"; private static final String STRENGTH_LINE = "!:stength"; private List<MagicEntry> children; private final MagicEntry parent; private final String name; private final int level; private final boolean addOffset; private final int offset; private final OffsetInfo offsetInfo; private final MagicMatcher matcher; private final Long andValue; private final boolean unsignedType; // the testValue object is defined by the particular matcher private final Object testValue; private final boolean formatSpacePrefix; private final Formatter formatter; private int strength; private String mimeType; private Map<String, String> extensionMap; private MagicEntry(MagicEntry parent, String name, int level, boolean addOffset, int offset, OffsetInfo offsetInfo, MagicMatcher matcher, Long andValue, boolean unsignedType, Object testValue, boolean formatSpacePrefix, String format) { this.parent = parent; this.name = name; this.level = level; this.addOffset = addOffset; this.offset = offset; this.offsetInfo = offsetInfo; this.matcher = matcher; this.andValue = andValue; this.unsignedType = unsignedType; this.testValue = testValue; this.formatSpacePrefix = formatSpacePrefix; if (format == null) { this.formatter = null; } else { this.formatter = new Formatter(format); } this.strength = 1; } /** * Parse a line from the magic configuration file into an entry. */ public static MagicEntry parseLine(MagicEntry previous, String line, ErrorCallBack errorCallBack) { if (line.startsWith("!:")) { if (previous != null) { // we ignore it if there is no previous entry to add it to handleSpecial(previous, line, errorCallBack); } return null; } // 0[ ]string[ ]%PDF-[ ]PDF document // !:mime[ ]application/pdf // >5[ ]byte[ ]x[ ]\b, version %c // >7[ ]byte[ ]x[ ]\b.%c // unfortunately, tab is not a reliable line splitter, even though patterns and formats have spaces (sigh) String[] parts = splitLine(line, errorCallBack); if (parts == null) { return null; } // level and offset int level; int sindex = parts[0].lastIndexOf('>'); String offsetString; if (sindex < 0) { level = 0; offsetString = parts[0]; } else { level = sindex + 1; offsetString = parts[0].substring(sindex + 1); } int offset; OffsetInfo offsetInfo; if (offsetString.length() == 0) { if (errorCallBack != null) { errorCallBack.error(line, "invalid offset number:" + offsetString, null); } return null; } boolean addOffset = false; if (offsetString.charAt(0) == '&') { addOffset = true; offsetString = offsetString.substring(1); } if (offsetString.length() == 0) { if (errorCallBack != null) { errorCallBack.error(line, "invalid offset number:" + offsetString, null); } return null; } if (offsetString.charAt(0) == '(') { offset = -1; offsetInfo = OffsetInfo.parseOffset(offsetString, line, errorCallBack); if (offsetInfo == null) { return null; } } else { try { offset = Integer.decode(offsetString); offsetInfo = null; } catch (NumberFormatException e) { if (errorCallBack != null) { errorCallBack.error(line, "invalid offset number:" + offsetString, e); } return null; } } // type String typeStr = parts[1]; sindex = typeStr.indexOf('&'); // we use long because of overlaps Long andValue = null; if (sindex >= 0) { String andStr = typeStr.substring(sindex + 1); try { andValue = Long.decode(andStr); } catch (NumberFormatException e) { if (errorCallBack != null) { errorCallBack.error(line, "invalid type AND-number: " + andStr, e); } return null; } typeStr = typeStr.substring(0, sindex); } if (typeStr.length() == 0) { if (errorCallBack != null) { errorCallBack.error(line, "blank type string", null); } return null; } boolean unsignedType = false; MagicMatcher matcher = MagicType.matcherfromString(typeStr); if (matcher == null) { if (typeStr.charAt(0) == 'u') { matcher = MagicType.matcherfromString(typeStr.substring(1)); unsignedType = true; } else { int index = typeStr.indexOf('/'); if (index > 0) { matcher = MagicType.matcherfromString(typeStr.substring(0, index)); } } if (matcher == null) { if (errorCallBack != null) { errorCallBack.error(line, "unknown magic type string: " + typeStr, null); } return null; } } Object testValue; String testStr = parts[2]; if (testStr.equals("x")) { testValue = null; } else { try { testValue = matcher.convertTestString(typeStr, testStr, offset); } catch (Exception e) { if (errorCallBack != null) { errorCallBack.error(line, "could not convert magic test string: " + testStr, e); } return null; } } String format; boolean formatSpacePrefix = true; if (parts.length == 3) { format = null; } else { format = parts[3]; if (format.startsWith("\\b")) { format = format.substring(2); formatSpacePrefix = false; } } MagicEntry parent = null; if (level > 0) { if (previous == null) { // if no previous then we have to drop this return null; } // use the previous and then go up until the parent is a level lower than ours for (parent = previous; parent.level >= level; parent = parent.parent) { // none } } String name; if (format == null) { name = UNKNOWN_NAME; } else { parts = format.split("[ \t]"); if (parts.length == 0) { name = UNKNOWN_NAME; } else { name = parts[0]; } } MagicEntry entry = new MagicEntry(parent, name, level, addOffset, offset, offsetInfo, matcher, andValue, unsignedType, testValue, formatSpacePrefix, format); if (level > 0) { if (previous == null) { // if no previous then we have to drop this return null; } if (parent != null) { parent.addChild(entry); } } return entry; } /** * Returns the content type associated with the bytes or null if it does not match. */ public ContentType processBytes(byte[] bytes) { ContentInfo info = processBytes(bytes, 0, null); if (info == null || info.name == UNKNOWN_NAME) { return null; } else { return new ContentType(info.name, info.mimeType, info.sb.toString()); } } /** * Return the "level" of the rule. Level-0 rules start the matching process. Level-1 and above rules are processed * only when the level-0 matches. */ public int getLevel() { return level; } /** * Get the strength of the rule. Not well supported right now. */ public int getStrength() { return strength; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("level ").append(level); if (name != null) { sb.append(",name '").append(name).append('\''); } if (mimeType != null) { sb.append(",mime '").append(mimeType).append('\''); } if (testValue != null) { sb.append(",test '").append(testValue).append('\''); } if (formatter != null) { sb.append(",format '").append(formatter).append('\''); } return sb.toString(); } private static String[] splitLine(String line, ErrorCallBack errorCallBack) { // skip opening whitespace if any int startPos = findNonWhitespace(line, 0); if (startPos >= line.length()) { return null; } // find the level info int endPos = findWhitespaceWithoutEscape(line, startPos); if (endPos >= line.length()) { if (errorCallBack != null) { errorCallBack.error(line, "invalid number of whitespace separated fields, must be >= 4", null); } return null; } String levelStr = line.substring(startPos, endPos); // skip whitespace startPos = findNonWhitespace(line, endPos + 1); if (startPos >= line.length()) { if (errorCallBack != null) { errorCallBack.error(line, "invalid number of whitespace separated fields, must be >= 4", null); } return null; } // find the type string endPos = findWhitespaceWithoutEscape(line, startPos); if (endPos >= line.length()) { if (errorCallBack != null) { errorCallBack.error(line, "invalid number of whitespace separated fields, must be >= 4", null); } return null; } String typeStr = line.substring(startPos, endPos); // skip whitespace startPos = findNonWhitespace(line, endPos + 1); if (startPos >= line.length()) { if (errorCallBack != null) { errorCallBack.error(line, "invalid number of whitespace separated fields, must be >= 4", null); } return null; } // find the test string endPos = findWhitespaceWithoutEscape(line, startPos); // endPos can be == length String testStr = line.substring(startPos, endPos); // skip any whitespace startPos = findNonWhitespace(line, endPos + 1); // format is optional, this could return length if (startPos < line.length()) { // format is the rest of the line return new String[] { levelStr, typeStr, testStr, line.substring(startPos) }; } else { return new String[] { levelStr, typeStr, testStr }; } } private static int findNonWhitespace(String line, int startPos) { int pos; for (pos = startPos; pos < line.length(); pos++) { if (!Character.isWhitespace(line.charAt(pos))) { break; } } return pos; } private static int findWhitespaceWithoutEscape(String line, int startPos) { boolean lastEscape = false; int pos; for (pos = startPos; pos < line.length(); pos++) { char ch = line.charAt(pos); if (ch == ' ') { if (!lastEscape) { break; } lastEscape = false; } else if (Character.isWhitespace(line.charAt(pos))) { break; } else if (ch == '\\') { lastEscape = true; } else { lastEscape = false; } } return pos; } private void addChild(MagicEntry child) { if (children == null) { children = new ArrayList<MagicEntry>(); } children.add(child); } private ContentInfo processBytes(byte[] bytes, int prevOffset, ContentInfo contentInfo) { int offset = this.offset; if (offsetInfo != null) { offset = offsetInfo.getOffset(bytes); } if (addOffset) { offset = prevOffset + offset; } Object val = matcher.extractValueFromBytes(offset, bytes); if (val == null) { return null; } if (testValue != null) { val = matcher.isMatch(testValue, andValue, unsignedType, val, offset, bytes); if (val == null) { return null; } } if (contentInfo == null) { contentInfo = new ContentInfo(name, mimeType); } if (formatter != null) { // if we are appending and need a space then preprend one if (formatSpacePrefix && contentInfo.sb.length() > 0) { contentInfo.sb.append(' '); } matcher.renderValue(contentInfo.sb, val, formatter); } if (children != null) { /* * If there are children then one of them has to match otherwise the whole thing doesn't match. This is * necessary for formats that are XML but we don't want to dominate plain old XML documents. */ boolean matched = false; // we have to do this because the children's children set the name first otherwise boolean assignName = (contentInfo.name == UNKNOWN_NAME); for (MagicEntry child : children) { if (child.processBytes(bytes, offset, contentInfo) != null) { matched = true; if (assignName) { contentInfo.setName(child); } if (contentInfo.mimeType == null && child.mimeType != null) { contentInfo.mimeType = child.mimeType; } } } if (!matched) { return null; } } return contentInfo; } private static void handleSpecial(MagicEntry parent, String line, ErrorCallBack errorCallBack) { String[] parts = line.split("\\s+", 2); if (parts.length < 2) { if (errorCallBack != null) { errorCallBack.error(line, "invalid extension line has less than 2 whitespace separated fields", null); } return; } String key = parts[0]; if (key.equals(MIME_TYPE_LINE)) { parent.mimeType = parts[1]; return; } if (key.equals(STRENGTH_LINE)) { handleStrength(parent, line, parts[1], errorCallBack); return; } key = key.substring(2); if (key.length() == 0) { if (errorCallBack != null) { errorCallBack.error(line, "blank extension key", null); } return; } parent.addExtension(key, parts[1]); } private static void handleStrength(MagicEntry parent, String line, String strengthValue, ErrorCallBack errorCallBack) { String[] parts = strengthValue.split("\\s+", 2); if (parts.length == 0) { if (errorCallBack != null) { errorCallBack.error(line, "invalid strength value: " + strengthValue, null); } return; } if (parts[0].length() == 0) { if (errorCallBack != null) { errorCallBack.error(line, "invalid strength value: " + strengthValue, null); } return; } char operator = parts[0].charAt(0); String valueStr; if (parts.length == 1) { valueStr = parts[0].substring(1); } else { valueStr = parts[1]; } int value; try { value = Integer.parseInt(valueStr); } catch (NumberFormatException e) { if (errorCallBack != null) { errorCallBack.error(line, "invalid strength number value: " + valueStr, null); } return; } int strength = parent.strength; switch (operator) { case '+' : strength += value; break; case '-' : strength -= value; break; case '*' : strength *= value; break; case '/' : strength /= value; break; default : if (errorCallBack != null) { errorCallBack.error(line, "invalid strength operator: " + operator, null); } return; } parent.strength = strength; } private void addExtension(String key, String value) { if (extensionMap == null) { extensionMap = new HashMap<String, String>(); } extensionMap.put(key, value); } private static class ContentInfo { String name; int nameLevel; String mimeType; final StringBuilder sb = new StringBuilder(); private ContentInfo(String name, String mimeType) { this.name = name; this.mimeType = mimeType; } public void setName(MagicEntry entry) { if (name == UNKNOWN_NAME || (entry.name != null && entry.name != UNKNOWN_NAME && entry.level < nameLevel)) { name = entry.name; nameLevel = entry.level; } } } /** * Information about the extended offset. * * Offsets do not need to be constant, but can also be read from the file being examined. If the first character * following the last '>' is a '(' then the string after the parenthesis is interpreted as an indirect offset. That * means that the number after the parenthesis is used as an offset in the file. The value at that offset is read, * and is used again as an offset in the file. Indirect offsets are of the form: ((x[.[bislBISLm]][+-]y). The value * of x is used as an offset in the file. A byte, id3 length, short or long is read at that offset depending on the * [bislBISLm] type specifier. The capitalized types interpret the number as a big-endian value, whereas the small * letter versions interpret the number as a little-endian value; the 'm' type interprets the number as a * middle-endian (PDP-11) value. To that number the value of y is added and the result is used as an offset in the * file. The default type if one is not specified is 4-byte long. */ private static class OffsetInfo { private final static Pattern OFFSET_PATTERN = Pattern.compile("\\(([0-9x]+)\\.([bislBISLm])([+-])([0-9x]+)\\)"); final int offset; final EndianConverter converter; final boolean id3; final int size; final int add; private OffsetInfo(int offset, EndianConverter converter, boolean id3, int size, int add) { this.offset = offset; this.converter = converter; this.id3 = id3; this.size = size; this.add = add; } public static OffsetInfo parseOffset(String offsetString, String line, ErrorCallBack errorCallBack) { // (9.b+19) Matcher matcher = OFFSET_PATTERN.matcher(offsetString); if (!matcher.matches()) { return null; } int offset; try { offset = Integer.decode(matcher.group(1)); } catch (NumberFormatException e) { if (errorCallBack != null) { errorCallBack.error(line, "invalid long offset number: " + offsetString, e); } return null; } if (matcher.group(2) == null) { if (errorCallBack != null) { errorCallBack.error(line, "invalid long offset type: " + offsetString, null); } return null; } char ch; if (matcher.group(2).length() == 1) { ch = matcher.group(2).charAt(0); } else { // it will use the default ch = '\0'; } EndianConverter converter = null; boolean id3 = false; int size = 0; switch (ch) { case 'b' : converter = EndianType.LITTLE.getConverter(); size = 1; break; case 'i' : converter = EndianType.LITTLE.getConverter(); size = 4; id3 = true; break; case 's' : converter = EndianType.LITTLE.getConverter(); size = 2; break; case 'l' : converter = EndianType.LITTLE.getConverter(); size = 4; break; case 'B' : converter = EndianType.BIG.getConverter(); size = 1; break; case 'I' : converter = EndianType.BIG.getConverter(); size = 4; id3 = true; break; case 'S' : converter = EndianType.BIG.getConverter(); size = 2; break; case 'L' : converter = EndianType.BIG.getConverter(); size = 4; break; case 'm' : converter = EndianType.MIDDLE.getConverter(); size = 4; break; default : converter = EndianType.LITTLE.getConverter(); size = 4; break; } int add; try { add = Integer.decode(matcher.group(4)); } catch (NumberFormatException e) { if (errorCallBack != null) { errorCallBack.error(line, "invalid long add value: " + matcher.group(4), e); } return null; } // decode doesn't work with leading '+', grumble if ("-".equals(matcher.group(3))) { add = -add; } return new OffsetInfo(offset, converter, id3, size, add); } public Integer getOffset(byte[] bytes) { Long val; if (id3) { val = (Long) converter.convertId3(offset, bytes, size); } else { val = (Long) converter.convertNumber(offset, bytes, size); } if (val == null) { return null; } else { return (int) (val + add); } } } }
package com.jeffrodriguez.xmlwrapper; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * An {@link Element} wrapping utility class. * @author <a href="mailto:jeff@jeffrodriguez.com">Jeff Rodriguez</a> */ public class XMLElement { /** * The wrapped {@link Element}. */ private final Element element; /** * Wraps an {@link Element}. * @param element the element to wrap. */ public XMLElement(Element element) { this.element = element; } /** * @return the wrapped element. */ public Element getElement() { return element; } /** * @return the parent of this element. */ public XMLElement getParent() { return new XMLElement((Element) element.getParentNode()); } /** * Gets the tag name of the element. * @return the tag name of the element. */ public String getName() { return element.getTagName(); } /** * Creates a new child element and appends it to this one. * @param name the name of the element. * @return the new element. */ public XMLElement addChild(String name) { Element child = element.getOwnerDocument().createElement(name); element.appendChild(child); return new XMLElement(child); } public XMLElement getChild(String name) { NodeList nodes = element.getElementsByTagName(name); // Make sure there's only one if (nodes.getLength() > 1) { throw new IllegalStateException("More than one element with the name: " + name); } else if (nodes.getLength() < 1) { throw new IllegalStateException("No elements with the name: " + name); } // Get the element return new XMLElement((Element) nodes.item(0)); } /** * Gets an {@link Iterable} for the children of this element by tag name. * @param name the tag name of the children. * @return an {@link Iterable} of the children. */ public Iterable<XMLElement> getChildren(String name) { // Get the child element node list final NodeList nodes = element.getElementsByTagName(name); // Build the iterators final NodeListIterator<Element> nodeListIterator = new NodeListIterator(nodes); return new XMLElementIterator(nodeListIterator).toIterable(); } /** * Sets an attribute on the element. * @param name the name of the attribute. * @param value the value of the attribute. * @return this element */ public XMLElement setAttribute(String name, String value) { element.setAttribute(name, value); return this; } /** * Gets the value of an attribute. * @param name the name of the attribute. * @return the value of the attribute. */ public String getAttribute(String name) { return element.getAttribute(name); } /** * Sets the text content of the element. * @param value the value to set. */ public void setValue(String value) { element.setTextContent(value); } /** * Gets the element's text content. * @return the element's text content. */ public String getValue() { return element.getTextContent(); } /** * Gets the element's text content, parsed as a Long. * @return the element's text content, parsed as a {@link Long} (possibly null). */ public Long getValueAsLong() { String value = getValue(); if (value == null || value.isEmpty()) { return null; } return Long.parseLong(value); } /** * Gets the element's text content, parsed as an Integer. * @return the element's text content, parsed as an {@link Integer} (possibly null). */ public Integer getValueAsInteger() { String value = getValue(); if (value == null || value.isEmpty()) { return null; } return Integer.parseInt(value); } }
package com.logentries.jenkins; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLSocketFactory; /** * Class to write logs to logentries asynchronously * */ public class LogentriesWriter { /** Logentries API server address. */ private static final String LE_API = "api.logentries.com"; // FIXME Use ssl port /** Port number for Token logging on Logentries API server. */ private static final int LE_PORT = 20000; /** UTF-8 output character set. */ private static final Charset UTF8 = Charset.forName("UTF-8"); private static final int SHUTDOWN_TIMEOUT_SECONDS = 10; private final ExecutorService executor; private final String token; private Socket socket; private OutputStream outputStream; /** * Constructor. * // FIXME Nicer exceptions * @param token Token for logentries log. * @throws UnknownHostException If there was a problem connecting to LE_API * @throws IOException If there was a problem getting the output stream. */ public LogentriesWriter(String token) throws UnknownHostException, IOException { this.executor = Executors.newSingleThreadExecutor(); this.token = token; socket = SSLSocketFactory.getDefault().createSocket(LE_API, LE_PORT); outputStream = socket.getOutputStream(); } /** * Writes the given string to logentries.com asynchronously. It would be * possible to take an array of bytes as a parameter but we want to make * sure it is UTF8 encoded. * * @param line The line to write. */ public void writeLogentry(final String line) { executor.execute(new Runnable() { @Override public void run() { try { outputStream.write((token + line + '\n').getBytes( UTF8)); outputStream.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public void close() { try { if (!executor.awaitTermination(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { System.err .println("LogentriesWriter shutdown before finished execution"); } } catch (InterruptedException e) { e.printStackTrace(); } finally { closeStream(); closeSocket(); } } private void closeStream() { try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void closeSocket() { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.maddob.data; import io.vertx.core.shareddata.LocalMap; import java.util.List; import java.util.stream.Collectors; public class InMemoryArticleProvider implements ArticleProvider { /** actual storage for all articles **/ private final LocalMap<String, Article> articleDatabase; public InMemoryArticleProvider(LocalMap<String, Article> articleDatabase) { this.articleDatabase = articleDatabase; } @Override public List<Article> getLatestArticles(int number) { return this.articleDatabase.values().stream() .sorted((a1, a2) -> a2.getCreated().compareTo(a1.getCreated())) .limit(number).filter(article -> article.isPublished()).collect(Collectors.toList()); } @Override public List<Article> getAllArticles() { return articleDatabase.values().stream().collect(Collectors.toList()); } @Override public Article getArticleByTitle(String title) { if (title != null) { return this.articleDatabase.values().stream() .filter(article -> title.equals(article.getTitle())).findFirst().get(); } return null; } @Override public void addArticle(Article article) { articleDatabase.put(article.getId().toString(), article); } @Override public void editArticle(Article article) { articleDatabase.put(article.getId().toString(), article); } @Override public void deleteArticle(Article article) { articleDatabase.remove(article.getId().toString()); } }
package com.mdsol.skyfire; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Transition; import org.eclipse.uml2.uml.Vertex; import coverage.graph.Graph; import coverage.graph.GraphUtil; import coverage.graph.InvalidGraphException; import coverage.graph.Node; import coverage.graph.Path; import coverage.web.InvalidInputException; /** * A class that generates abstract tests (that is, test paths) based on UML models * * @author Nan Li * @version 1.0 Nov 28, 2012 * */ public class AbstractTestGenerator { private String globalDirectory = System.getProperty("user.dir"); private static final String TEMPTESTDIR = "testData/test/temp/"; private static final String TEMPTESTNAME = "tempTest"; private static Logger logger = LogManager.getLogger("AbstractTestGenerator"); // Maps a transition to the mappings private final HashMap<Transition, List<Mapping>> hashedTransitionMappings; /** * Constructs an AbstractTestGenerator with no detailed directories */ public AbstractTestGenerator() { hashedTransitionMappings = new HashMap<>(); } /** * Constructs an AbstractTestGenerator with the global directory * * @param globalDirectory * the global directory */ public AbstractTestGenerator(final String globalDirectory) { this.globalDirectory = globalDirectory; hashedTransitionMappings = new HashMap<>(); } /** * Generates test paths to satisfy the edge coverage criterion. * * @param edges * edges of a control flow graph in a String format "1 2 \n 2 3 \n" * @param initialNodes * initial nodes of a control flow graph in a String format "1 2 ... etc." * @param finalNodes * final nodes of a control flow graph in a String format "1 2 ... etc." * @param criterion * an enumeration type of {@link TestCoverageCriteria} * @return a list of {@link coverage.graph.Path} objects that satisfy edge coverage * @throws InvalidInputException * when any of edges, initialNodes, and finalNodes is in a wrong format * @throws InvalidGraphException * when the graph cannot be correctly constructed from the specified inputs */ public static List<Path> getTestPaths(final String edges, final String initialNodes, final String finalNodes, final TestCoverageCriteria criterion) throws InvalidInputException, InvalidGraphException { logger.info("Generate abstract test paths from a flat graph"); final Graph g = GraphUtil.readGraph(edges, initialNodes, finalNodes); try { g.validate(); } catch (final InvalidGraphException e) { logger.debug("The flattened generic graph is invalid"); throw new InvalidGraphException(e); } if (criterion == TestCoverageCriteria.NODECOVERAGE) { logger.info( "Node coverage is used. The number of total nodes is " + g.findNodes().size()); logger.info("The test requirements of nodes are: " + g.findNodes()); List<Path> testPaths = g.findNodeCoverage(); logger.info(testPaths.size() + " test paths are generated to satisfy node coverage. The total nodes is " + getTotalNodes(testPaths)); return testPaths; } else if (criterion == TestCoverageCriteria.EDGECOVERAGE) { final List<Path> edgeTRs = g.findEdges(); logger.info("Edge coverage is used. The number of total edges is " + edgeTRs.size()); logger.info("The test requirements of edges are: " + edgeTRs); final Graph prefix = GraphUtil.getPrefixGraph(edgeTRs); final Graph bipartite = GraphUtil.getBipartiteGraph(prefix, initialNodes, finalNodes); final List<Path> testPaths = g.splittedPathsFromSuperString( bipartite.findMinimumPrimePathCoverageViaPrefixGraphOptimized(edgeTRs).get(0), g.findTestPath()); logger.info(testPaths.size() + " test paths are generated to satisfy edge coverage. The total nodes is " + getTotalNodes(testPaths)); return testPaths; } else if (criterion == TestCoverageCriteria.EDGEPAIRCOVERAGE) { final List<Path> edgePairs = g.findEdgePairs(); logger.info("Edge-pair coverage is used. The number of total edge-pairs is " + edgePairs.size()); logger.info("The test requriements of edge-pairs are: " + edgePairs); final Graph prefix = GraphUtil.getPrefixGraph(edgePairs); final Graph bipartite = GraphUtil.getBipartiteGraph(prefix, initialNodes, finalNodes); final List<Path> testPaths = g.splittedPathsFromSuperString( bipartite.findMinimumPrimePathCoverageViaPrefixGraphOptimized(edgePairs).get(0), g.findTestPath()); logger.info(testPaths.size() + " test paths are generated to satisfy edge-pair coverage. The total nodes is " + getTotalNodes(testPaths)); return testPaths; } else { final List<Path> primePaths = g.findPrimePaths(); final Graph prefix = GraphUtil.getPrefixGraph(primePaths); final Graph bipartite = GraphUtil.getBipartiteGraph(prefix, initialNodes, finalNodes); final List<Path> testPaths = g.splittedPathsFromSuperString(bipartite .findMinimumPrimePathCoverageViaPrefixGraphOptimized(g.findPrimePaths()).get(0), g.findTestPath()); logger.info("Prime path coverage is used. The number of total prime paths is " + primePaths.size()); logger.info("The test requirements of prime paths are: " + primePaths); logger.info(testPaths.size() + " test paths are generated to satisfy prime coverage. The total nodes is " + getTotalNodes(testPaths)); return testPaths; } } /** * Transforms a {@link coverage.graph.Path} to a list of {@link org.eclipse.uml2.uml.Vertex} in * a UML state machine * * @param path * a path of a control flow graph in a String format "1, 2, 3, ... etc." * @param stateMachine * a StateMachineAccessor object * @return a list of {@link org.eclipse.uml2.uml.Vertex} */ public static List<Vertex> getPathByState(final Path path, final StateMachineAccessor stateMachine) { final List<Vertex> vertices = new ArrayList<>(); final Iterator<Node> nodes = path.getNodeIterator(); while (nodes.hasNext()) { final Node node = nodes.next(); vertices.add(stateMachine.getReversedStateMappings().get(node.toString())); } return vertices; } /** * Transforms a list of {@link org.eclipse.uml2.uml.Vertex} to a list of * {@link org.eclipse.uml2.uml.Transition}s in a UML state machine * * @param vertices * a list of {@link org.eclipse.uml2.uml.Vertex} * @return a list of {@link org.eclipse.uml2.uml.Transition}s */ public static final List<Transition> convertVerticesToTransitions(final List<Vertex> vertices) { final List<Transition> transitions = new ArrayList<>(); for (int i = 0; i < vertices.size(); i++) { int sourceIndex = i; final Vertex sourceVertex = vertices.get(sourceIndex); if (i == vertices.size() - 1) { break; } int targetIndex = sourceIndex + 1; final Vertex targetVertex = vertices.get(targetIndex); for (final Transition transition : sourceVertex.getOutgoings()) { if (transition.getTarget() == null) { logger.error(transition.getName() + " has no target state"); } // Now the first right transition is used // but there may be more than one transition between two vertices // this issue will be taken care of later if (transition.getTarget().getName().equals(targetVertex.getName())) { transitions.add(transition); // a bug is fixed; without break statement, extra transitions may be added break; } } } return transitions; } /** * Generates tests from the paths of a graph * * @param paths * a list of {@link coverage.graph.Path} * @param modelAccessor * a {@link StateMachineAccessor} object * @return a list of {@link edu.gmu.swe.taf.Test} objects */ public final List<Test> generateTests(final List<Path> paths, final ModelAccessor modelAccessor) { final List<Test> tests = new ArrayList<>(); for (int i = 0; i < paths.size(); i++) { Test test = null; if (modelAccessor instanceof StateMachineAccessor) { convertVerticesToTransitions( getPathByState(paths.get(i), (StateMachineAccessor) modelAccessor)); final String testComment = "/** The test path is: " + paths.get(i).toString() + "**/"; test = new Test("test" + i, testComment); } tests.add(test); } return tests; } /** * Adds preconditions, state invariants, and postconditions of an element to the mappings. * * @param element * a {@link Element} object that owns the constraints * @param finalMappings * a list of {@link Mapping} objects that represents the path of the abstract test * @param constraints * a list of {@link Mapping} objects that represents preconditions, state invariants, * and postconditions * @return a list of {@link Element} objects */ public final List<Mapping> addPreconditionStateInvariantMappings(final Element element, final List<Mapping> finalMappings, final List<Mapping> constraints) { List<Mapping> mappings = finalMappings; if (element instanceof Vertex) { for (final Mapping precondition : constraints) { if (precondition.getIdentifiableElementName().equals(((Vertex) element).getName()) && precondition.getType() == IdentifiableElementType.PRECONDITION) { mappings.add(precondition); } } for (final Mapping stateinvariant : constraints) { if (stateinvariant.getIdentifiableElementName().equals(((Vertex) element).getName()) && stateinvariant.getType() == IdentifiableElementType.STATEINVARIANT) { mappings.add(stateinvariant); } } } if (element instanceof Transition) { for (final Mapping precondition : constraints) { if (precondition.getIdentifiableElementName() .equals(((Transition) element).getName()) && precondition.getType() == IdentifiableElementType.PRECONDITION) { mappings.add(precondition); } } for (final Mapping stateinvariant : constraints) { if (stateinvariant.getIdentifiableElementName() .equals(((Transition) element).getName()) && stateinvariant.getType() == IdentifiableElementType.STATEINVARIANT) { mappings.add(stateinvariant); } } } return mappings; } /** * Adds postconditions of an element to the mappings. * * @param element * a {@link Element} object that owns the constraints * @param finalMappings * a list of {@link Mapping} objects that represents the path of the abstract test * @param constraints * a list of {@link Mapping} objects that represents postconditions * @return a list of {@link Element} objects */ public final List<Mapping> addPostconditionMappings(final Element element, final List<Mapping> finalMappings, final List<Mapping> constraints) { if (element instanceof Vertex) { for (final Mapping postcondition : constraints) { if (postcondition.getIdentifiableElementName().equals(((Vertex) element).getName()) && postcondition.getType() == IdentifiableElementType.POSTCONDITION) { finalMappings.add(postcondition); } } } if (element instanceof Transition) { for (final Mapping postcondition : constraints) { if (postcondition.getIdentifiableElementName() .equals(((Transition) element).getName()) && postcondition.getType() == IdentifiableElementType.POSTCONDITION) { finalMappings.add(postcondition); } } } return finalMappings; } /** * Gets all constraints from the XML file and creates precondition, stateinvariant, * postcondition mappings. * * @param constraints * a list of {@link ConstraintMapping} objects * @return a list of {@link Mapping} objects */ public static final List<Mapping> getConstraints(final List<ConstraintMapping> constraints) { // a list of mappings to be returned: precondition, stateinvariant, postcondition mappings List<Mapping> mappings = new ArrayList<>(); if (constraints == null) return mappings; for (final ConstraintMapping constraint : constraints) { // add precondition mappings if (constraint.getPreconditions() != null && constraint.getPreconditions().size() > 0) { mappings = addPreconditions(mappings, constraint); } // add state invariant mappings if (constraint.getStateinvariants() != null && constraint.getStateinvariants().size() > 0) { mappings = addStateInvariants(mappings, constraint); } // add postcondition mappings if (constraint.getPostconditions() != null && constraint.getPostconditions().size() > 0) { mappings = addPostconditions(mappings, constraint); } } return mappings; } /** * Adds pre-conditions to the mappings * * @param mappings * the specified mappings that do not have pre-conditions * @param constraint * the constraint mapping * @return a list of Mapping objects that have pre-conditions */ private static List<Mapping> addPreconditions(final List<Mapping> mappings, final ConstraintMapping constraint) { List<Mapping> newMappings = mappings; for (final String precondition : constraint.getPreconditions()) { newMappings.add(new Mapping(constraint.getName(), IdentifiableElementType.PRECONDITION, precondition, constraint.getTestCode(), constraint.getRequiredMappings(), constraint.getParameters(), constraint.getCallers(), constraint.getReturnObjects())); } return newMappings; } /** * Adds state invariants to the mappings * * @param mappings * the specified mappings that do not have state invariants * @param constraint * the constraint mapping * @return a list of Mapping objects that have state invariants */ private static List<Mapping> addStateInvariants(final List<Mapping> mappings, final ConstraintMapping constraint) { List<Mapping> newMappings = mappings; for (final String stateinvariant : constraint.getStateinvariants()) { newMappings .add(new Mapping(constraint.getName(), IdentifiableElementType.STATEINVARIANT, stateinvariant, constraint.getTestCode(), constraint.getRequiredMappings(), constraint.getParameters(), constraint.getCallers(), constraint.getReturnObjects())); } return newMappings; } /** * Adds post-conditions to the mappings * * @param mappings * the specified mappings that do not have post-conditions * @param constraint * the constraint mapping * @return a list of Mapping objects that have post-conditions */ private static List<Mapping> addPostconditions(final List<Mapping> mappings, final ConstraintMapping constraint) { List<Mapping> newMappings = mappings; for (final String postcondition : constraint.getPostconditions()) { newMappings.add(new Mapping(constraint.getName(), IdentifiableElementType.POSTCONDITION, postcondition, constraint.getTestCode(), constraint.getRequiredMappings(), constraint.getParameters(), constraint.getCallers(), constraint.getReturnObjects())); } return newMappings; } /** * Calculates the total number of nodes in all the test paths * * @param testPaths * a list of {@link coverage.graph.Path} objects * @return the total number of nodes in the specified test paths */ public static int getTotalNodes(final List<Path> testPaths) { int totalNumber = 0; if (testPaths == null) { return totalNumber; } else { for (Path p : testPaths) { totalNumber += p.size(); } } return totalNumber; } /** * @return the globalDirectory */ public final String getGlobalDirectory() { return globalDirectory; } /** * Sets the globalDirectory * * @param globalDirectory * the globalDirectory */ public final void setGlobalDirectory(final String globalDirectory) { this.globalDirectory = globalDirectory; } /** * @return the tempTestDirectory */ public final String getTempTestDirectory() { return TEMPTESTDIR; } /** * @return the tempTestName */ public final String getTempTestName() { return TEMPTESTNAME; } /** * @return the hashedTransitionMappings */ public final Map<Transition, List<Mapping>> getHashedTransitionMappings() { return hashedTransitionMappings; } }
package com.microsoft.sqlserver.jdbc; import java.text.MessageFormat; /** * This class holds information regarding the basetype of a sql_variant data. * */ /** * Enum for valid probBytes for different TDSTypes * */ enum SqlVariant_ProbBytes { INTN (0), INT8 (0), INT4 (0), INT2 (0), INT1 (0), FLOAT4 (0), FLOAT8 (0), DATETIME4 (0), DATETIME8 (0), MONEY4 (0), MONEY8 (0), BITN (0), GUID (0), DATEN (0), TIMEN (1), DATETIME2N (1), DECIMALN (2), NUMERICN (2), BIGBINARY (2), BIGVARBINARY (2), BIGCHAR (7), BIGVARCHAR (7), NCHAR (7), NVARCHAR (7); private final int intValue; private static final int MAXELEMENTS = 23; private static final SqlVariant_ProbBytes valuesTypes[] = new SqlVariant_ProbBytes[MAXELEMENTS]; int intValue() { return intValue; } private SqlVariant_ProbBytes(int intValue) { this.intValue = intValue; } static SqlVariant_ProbBytes valueOf(int intValue) throws IllegalArgumentException { SqlVariant_ProbBytes tdsType; if (!(0 <= intValue && intValue < valuesTypes.length) || null == (tdsType = valuesTypes[intValue])) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unknownSSType")); Object[] msgArgs = {new Integer(intValue)}; throw new IllegalArgumentException(form.format(msgArgs)); } return tdsType; } } public class SqlVariant { private int baseType; private int cbPropsActual; private int properties; private int value; private int precision; private int scale; private int maxLength; // for Character basetypes in sqlVariant private SQLCollation collation; //for Character basetypes in sqlVariant private boolean isBaseTypeTime = false; //we need this when we need to read time as timestamp (for instance in bulkcopy) private JDBCType baseJDBCType; /** * Check if the basetype for variant is of time value * @return */ boolean isBaseTypeTimeValue(){ return this.isBaseTypeTime; } void setIsBaseTypeTimeValue(boolean isBaseTypeTime){ this.isBaseTypeTime = isBaseTypeTime; } /** * Constructor for sqlVariant */ SqlVariant(int baseType) { this.baseType = baseType; } /** * store the base type for sql-variant * @param baseType */ void setBaseType(int baseType){ this.baseType = baseType; } /** * retrieves the base type for sql-variant * @return */ int getBaseType(){ return this.baseType; } /** * Store the basetype as jdbc type * @param baseJDBCType */ void setBaseJDBCType(JDBCType baseJDBCType){ this.baseJDBCType = baseJDBCType; } /** * retrieves the base type as jdbc type * @return */ JDBCType getBaseJDBCType() { return this.baseJDBCType; } /** * stores the scale if applicable * @param scale */ void setScale(int scale){ this.scale = scale; } /** * stores the precision if applicable * @param precision */ void setPrecision(int precision){ this.precision = precision; } /** * retrieves the precision * @return */ int getPrecision(){ return this.precision; } /** * retrieves the scale * @return */ int getScale() { return this.scale; } /** * stores the collation if applicable * @param collation */ void setCollation (SQLCollation collation){ this.collation = collation; } /** * Retrieves the collation * @return */ SQLCollation getCollation(){ return this.collation; } /** * stores the maximum length * @param maxLength */ void setMaxLength(int maxLength){ this.maxLength = maxLength; } /** * retrieves the maximum length * @return */ int getMaxLength(){ return this.maxLength; } }
package com.molina.cvmfs.client; import com.molina.cvmfs.repository.Repository; import net.fusejna.*; import net.fusejna.util.FuseFilesystemAdapterFull; import java.nio.ByteBuffer; /** * @author Jose Molina Colmenero * * This interface cannot handle inodes, so some operations are not * identical to the original CernVM-FS. Concretely lookup and forget functions * are not supported */ public class CvmfsFileSystem extends FuseFilesystemAdapterFull { private Repository repository; private String cachePath; public CvmfsFileSystem(String cachePath) { this.cachePath = cachePath; } public CvmfsFileSystem() { this.cachePath = "~/.cvmfs-java-cache"; } public FuseFilesystem log() { return super.log(true); } private int printIlegalOperationMessage() { System.err.println("Read-only file system!"); return ErrorCodes.EROFS(); } @Override public void init() { } @Override public void destroy() { } @Override public int getattr(String path, StructStat.StatWrapper stat) { return 0; } @Override public int readlink(String path, ByteBuffer buffer, long size) { return 0; } @Override public int open(String path, StructFuseFileInfo.FileInfoWrapper info) { return 0; } @Override public int read(String path, ByteBuffer buffer, long size, long offset, StructFuseFileInfo.FileInfoWrapper info) { return 0; } @Override public int release(String path, StructFuseFileInfo.FileInfoWrapper info) { return 0; } @Override public int opendir(String path, StructFuseFileInfo.FileInfoWrapper info) { return 0; } @Override public int readdir(String path, DirectoryFiller filler) { return 0; } @Override public int releasedir(String path, StructFuseFileInfo.FileInfoWrapper info) { return 0; } @Override public int statfs(String path, StructStatvfs.StatvfsWrapper wrapper) { return 0; } @Override public int getxattr(String path, String xattr, XattrFiller filler, long size, long position) { // NOTE: not handle at the moment return super.getxattr(path, xattr, filler, size, position); } @Override public int listxattr(String path, XattrListFiller filler) { // NOTE: not handle at the moment return super.listxattr(path, filler); } }
package com.soasta.jenkins; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.tasks.Builder; import hudson.util.ArgumentListBuilder; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.QuotedStringTokenizer; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import java.io.IOException; public class iOSSimulatorLauncher extends Builder { /** * URL of {@link CloudTestServer}. */ private final String url; private final String app, sdk, family, agentURL; @DataBoundConstructor public iOSSimulatorLauncher(String url, String app, String sdk, String family, String agentURL) { this.url = url; this.app = app; this.sdk = sdk; this.family = family; this.agentURL = agentURL; } public String getUrl() { return url; } public String getApp() { return app; } public String getSdk() { return sdk; } public String getFamily() { return family; } public String getAgentURL() { return agentURL; } public CloudTestServer getServer() { return CloudTestServer.get(url); } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ArgumentListBuilder args = new ArgumentListBuilder(); EnvVars envs = build.getEnvironment(listener); CloudTestServer s = getServer(); if (s==null) throw new AbortException("No TouchTest server is configured in the system configuration."); FilePath bin = new iOSAppInstallerInstaller(s).ios_sim_launcher(build.getBuiltOn(), listener); args.add(bin) .add("--app", envs.expand(app)); if (sdk != null && !sdk.trim().isEmpty()) args.add("--sdk", envs.expand(sdk)); if (family != null && !family.trim().isEmpty()) args.add("--family", envs.expand(family)); if (agentURL != null && !agentURL.trim().isEmpty()) args.add("--agenturl", envs.expand(agentURL)); int r = launcher.launch().cmds(args).pwd(build.getWorkspace()).stdout(listener).join(); return r==0; } @Extension public static class DescriptorImpl extends AbstractCloudTestBuilderDescriptor { @Override public String getDisplayName() { return "Run App in iOS Simulator"; } public ListBoxModel doFillFamilyItems() { ListBoxModel items = new ListBoxModel(); items.add("iPhone", "iphone"); items.add("iPhone (Retina)", "iphone_retina"); items.add("iPad", "ipad"); items.add("iPad (Retina)", "ipad_retina"); return items; } public FormValidation doCheckApp(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) { return FormValidation.error("App directory is required."); } else { // TODO: Check if the actual directory is present. return FormValidation.ok(); } } } }
package com.socrata.balboa.server; import com.socrata.balboa.metrics.config.Configuration; import com.socrata.balboa.metrics.data.DateRange; import com.socrata.balboa.metrics.messaging.Receiver; import com.socrata.balboa.metrics.messaging.ReceiverFactory; import com.socrata.balboa.server.exceptions.HttpException; import com.socrata.balboa.server.exceptions.InternalException; import com.socrata.balboa.server.exceptions.InvalidRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.PropertyConfigurator; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; 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.util.Date; import java.util.HashMap; import java.util.Map; public class BalboaServlet extends HttpServlet { private static Log log = LogFactory.getLog(BalboaServlet.class); private static final long REQUEST_TIME_WARN_THRESHOLD = 2000; /** * Not used, but assigned so that the receiver doesn't get garbage * collected. */ Receiver receiver; Thread writer; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); String requestInfo = "Servicing request '" + request.getPathInfo() + "'.\n"; requestInfo += "\tParameters {\n"; for (Object k : request.getParameterMap().keySet()) { requestInfo += "\t\t" + k + " => " + request.getParameter((String)k) + "\n"; } requestInfo += "\t}"; log.info(requestInfo); // We're always JSON, no matter what. response.setContentType("application/json; charset=utf-8"); try { String entityId = request.getPathInfo().replaceFirst("/", ""); if (!"GET".equals(request.getMethod())) { throw new InvalidRequestException("Unsupported method '" + request.getMethod() + "'."); } log.debug("Request path info: " + request.getPathInfo()); Object result = fulfillGet(entityId, ServiceUtils.getParameters(request)); // Write the response out. ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); mapper.writeValue(response.getOutputStream(), result); } catch (HttpException e) { // Write out any "expected" errors. log.warn("Unable to fullfil request because there was an HTTP error.", e); response.setStatus(e.getStatus()); response.getOutputStream().write(e.getMessage().getBytes()); } catch (Throwable e) { // Any other problems were things we weren't expecting. log.fatal("Unexpected exception handling a request.", e); response.setStatus(500); Map<String, Object> error = new HashMap<String, Object>(); error.put("error", true); error.put("message", "Internal error."); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); mapper.writeValue(response.getOutputStream(), error); } finally { long requestTime = System.currentTimeMillis() - startTime; log.debug("Fulfilled request " + requestTime + " (ms)"); if (requestTime > REQUEST_TIME_WARN_THRESHOLD) { log.warn("Slow request (" + request.getPathInfo() + ")."); } } } @Override public void init(ServletConfig config) throws ServletException { super.init(config); try { // Initialize the configuration so that we set any log4j or external // configuration values properly. Configuration properties = Configuration.get(); PropertyConfigurator.configure(properties); } catch (IOException e) { throw new ServletException("Unable to load the configuration.", e); } // Initialize our receiver and it will automatically connect. String readOnly = System.getProperty("socrata.readonly"); if (!"true".equals(readOnly)) { try { Runnable r = new Runnable() { @Override public void run() { receiver = ReceiverFactory.get(); } }; writer = new Thread(r); writer.start(); } catch (InternalException e) { log.warn("Unable to create an ActiveMQReceiver. New items will not be consumed."); } } else { log.warn("System set to read only, Not starting a receiver thread."); } } Object range(String id, Map<String, String> params) throws InvalidRequestException, IOException { MetricsService service = new MetricsService(); ServiceUtils.validateRequired(params, new String[] {"start", "end"}); Date start = ServiceUtils.parseDate(params.get("start")); Date end = ServiceUtils.parseDate(params.get("end")); DateRange range = new DateRange(start, end); if (params.containsKey("field")) { return service.range(id, (String)params.get("field"), range); } else if (params.containsKey("combine")) { String[] fields = ((String)params.get("combine")).split(","); return service.range(id, fields, range); } else { return service.range(id, range); } } Object single(String id, Map<String, String> params) throws InvalidRequestException, IOException { MetricsService service = new MetricsService(); ServiceUtils.validateRequired(params, new String[] {"period", "date"}); DateRange.Period period = DateRange.Period.valueOf(params.get("period")); Date date = ServiceUtils.parseDate(params.get("date")); if (date == null) { throw new InvalidRequestException("Unrecognized date format '" + params.get("date") + "'."); } DateRange range = DateRange.create(period, date); if (params.containsKey("field")) { return service.get(id, period, (String)params.get("field"), range); } else if (params.containsKey("combine")) { String[] fields = ((String)params.get("combine")).split(","); return service.get(id, period, fields, range); } else { return service.get(id, period, range); } } Object series(String id, Map<String, String> params) throws InvalidRequestException, IOException { MetricsService service = new MetricsService(); ServiceUtils.validateRequired(params, new String[] {"series", "start", "end"}); DateRange.Period period = DateRange.Period.valueOf(params.get("series")); Date nominalStart = ServiceUtils.parseDate(params.get("start")); Date nominalEnd = ServiceUtils.parseDate(params.get("end")); DateRange range = new DateRange( DateRange.create(period, nominalStart).start, DateRange.create(period, nominalEnd).end ); if (params.containsKey("field")) { return service.series(id, period, (String)params.get("field"), range); } else if (params.containsKey("combine")) { String[] fields = ((String)params.get("combine")).split(","); return service.series(id, period, fields, range); } else { return service.series(id, period, range); } } Object fulfillGet(String id, Map<String, String> params) throws IOException, InvalidRequestException { if (params.containsKey("series")) { return series(id, params); } else if (params.containsKey("range")) { return range(id, params); } else { return single(id, params); } } }
package com.solr2activemq; import org.apache.lucene.queryParser.ParseException; import org.apache.solr.handler.component.ResponseBuilder; import org.apache.solr.handler.component.SearchComponent; import org.apache.solr.handler.component.SearchHandler; import org.apache.solr.request.SolrQueryRequest; import java.util.Arrays; import java.util.List; public class SolrToActiveMQHandler extends SearchHandler { public void handleRequestBody(SolrQueryRequest req, org.apache.solr.response.SolrQueryResponse rsp) throws Exception, ParseException, InstantiationException, IllegalAccessException { try { super.handleRequestBody(req,rsp); } catch(Exception e){ // Call the solrToActiveMQComponent directly and pass the exception SearchComponent solrToActiveMQComponent = new SolrToActiveMQComponent(); List<SearchComponent> singleComponent = Arrays.asList(solrToActiveMQComponent); rsp.setException(e); ResponseBuilder rb = new ResponseBuilder(req, rsp, singleComponent); solrToActiveMQComponent.process(rb); // Finally throw the exception throw e; } } }
package com.suse.salt.netapi.calls.modules; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * salt.modules.test */ public class Test { private static final LocalCall<Boolean> PING = new LocalCall<>("test.ping", Optional.empty(), Optional.empty(), new TypeToken<Boolean>(){}); private static final LocalCall<String> MISSING_FUNC = new LocalCall<>("test.missing_func", Optional.empty(), Optional.empty(), new TypeToken<String>(){}); private static final LocalCall<VersionInformation> VERSIONS_INFORMATION = new LocalCall<>("test.versions_information", Optional.empty(), Optional.empty(), new TypeToken<VersionInformation>(){}); private static final LocalCall<ModuleReport> MODULE_REPORT = new LocalCall<>("test.module_report", Optional.empty(), Optional.empty(), new TypeToken<ModuleReport>(){}); private static final LocalCall<Map<String, String>> PROVIDERS = new LocalCall<>("test.providers", Optional.empty(), Optional.empty(), new TypeToken<Map<String, String>>(){}); /** * Availability report of all execution modules */ public static class ModuleReport { private final List<String> functions; private final List<String> modules; @SerializedName("missing_subs") private final List<String> missingSubs; @SerializedName("missing_attrs") private final List<String> missingAttrs; @SerializedName("function_subs") private final List<String> functionSubs; @SerializedName("module_attrs") private final List<String> moduleAttrs; @SerializedName("function_attrs") private final List<String> functionAttrs; public ModuleReport(List<String> functions, List<String> modules, List<String> missingSubs, List<String> missingAttrs, List<String> functionSubs, List<String> moduleAttrs, List<String> functionAttrs) { this.functions = functions; this.modules = modules; this.missingSubs = missingSubs; this.missingAttrs = missingAttrs; this.functionSubs = functionSubs; this.moduleAttrs = moduleAttrs; this.functionAttrs = functionAttrs; } public List<String> getFunctions() { return functions; } public List<String> getModules() { return modules; } public List<String> getMissingSubs() { return missingSubs; } public List<String> getMissingAttrs() { return missingAttrs; } public List<String> getFunctionSubs() { return functionSubs; } public List<String> getModuleAttrs() { return moduleAttrs; } public List<String> getFunctionAttrs() { return functionAttrs; } } /** * Version report of dependent and system software */ public static class VersionInformation { @SerializedName("Salt Version") private final Map<String, String> salt; @SerializedName("System Versions") private final Map<String, String> system; @SerializedName("Dependency Versions") private final Map<String, Optional<String>> dependencies; public VersionInformation(Map<String, String> salt, Map<String, String> system, Map<String, Optional<String>> dependencies) { this.salt = salt; this.system = system; this.dependencies = dependencies; } public Map<String, Optional<String>> getDependencies() { return dependencies; } public Map<String, String> getSalt() { return salt; } public Map<String, String> getSystem() { return system; } } public static LocalCall<Boolean> ping() { return PING; } public static LocalCall<Boolean> ping(Optional<Integer> timeout, Optional<Integer> gatherJobTimeout) { return new LocalCall<>("test.ping", Optional.empty(), Optional.empty(), new TypeToken<Boolean>() {}, timeout, gatherJobTimeout); } public static LocalCall<VersionInformation> versionsInformation() { return VERSIONS_INFORMATION; } public static LocalCall<ModuleReport> moduleReport() { return MODULE_REPORT; } public static LocalCall<Map<String, String>> providers() { return PROVIDERS; } public static LocalCall<String> provider(String module) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); args.put("module", module); return new LocalCall<>("test.provider", Optional.empty(), Optional.of(args), new TypeToken<String>() {}); } public static LocalCall<String> randStr(Optional<Integer> size, Optional<HashType> hashType) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); size.ifPresent(sz -> args.put("size", sz)); hashType.ifPresent(ht -> args.put("hash_type", ht.getHashType())); return new LocalCall<>("test.rand_str", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); } public static LocalCall<String> exception(String message) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); args.put("message", message); return new LocalCall<>("test.exception", Optional.empty(), Optional.of(args), new TypeToken<String>() {}); } public static LocalCall<Boolean> sleep(Duration duration) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); args.put("length", duration.getSeconds()); return new LocalCall<>("test.sleep", Optional.empty(), Optional.of(args), new TypeToken<Boolean>() {}); } public static LocalCall<String> echo(String text) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); args.put("text", text); return new LocalCall<>("test.echo", Optional.empty(), Optional.of(args), new TypeToken<String>() {}); } public static LocalCall<String> missingFunc() { return MISSING_FUNC; } }
package com.transloadit.sdk.async; import com.transloadit.sdk.Assembly; import com.transloadit.sdk.Transloadit; import com.transloadit.sdk.exceptions.LocalOperationException; import com.transloadit.sdk.exceptions.RequestException; import com.transloadit.sdk.response.AssemblyResponse; import io.tus.java.client.ProtocolException; import io.tus.java.client.TusExecutor; import io.tus.java.client.TusUploader; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; public class AsyncAssembly extends Assembly { private AssemblyProgressListener listener; private long uploadedBytes; private long totalUploadSize; private TusUploader lastTusUploader; @Nullable private String url; enum State { INIT, UPLOADING, PAUSED, UPLOAD_COMPLETE, FINISHED // this state is never really used, but it makes the flow more definite. } State state; protected AsyncAssemblyExecutor executor; public AsyncAssembly(Transloadit transloadit, AssemblyProgressListener listener) { super(transloadit); this.listener = listener; state = State.INIT; uploadedBytes = 0; totalUploadSize = 0; lastTusUploader = null; url = null; } public AssemblyProgressListener getListener() { return listener; } /** * Pauses the file upload. This is a blocking function that would wait till the assembly file uploads * have actually been paused. * * @throws LocalOperationException if the method is called while no upload is going on. */ public void pauseUpload() throws LocalOperationException { if (state == State.UPLOADING) { setState(State.PAUSED); executor.hardStop(); } else { throw new LocalOperationException("Attempt to pause upload while assembly is not uploading"); } } /** * Resumes the paused upload. * * @throws LocalOperationException if the upload hasn't been paused. */ public void resumeUpload() throws LocalOperationException { if (state == State.PAUSED) { startExecutor(); } else { throw new LocalOperationException("Attempt to resume un-paused upload"); } } synchronized private void setState(State state) { this.state = state; } /** * Runs intermediate check on the Assembly status until it is finished executing, * then returns it as a response. * * @return {@link AssemblyResponse} * @throws LocalOperationException if something goes wrong while running non-http operations. * @throws RequestException if request to transloadit server fails. */ protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException { AssemblyResponse response; do { response = getClient().getAssemblyByUrl(url); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new LocalOperationException(e); } } while (!response.isFinished()); setState(State.FINISHED); return response; } /** * Does the actual uploading of files (when tus is enabled) * * @throws IOException when there's a failure with file retrieval * @throws ProtocolException when there's a failure with tus upload */ @Override protected void uploadTusFiles() throws IOException, ProtocolException { setState(State.UPLOADING); while (uploads.size() > 0) { final TusUploader tusUploader; // don't recreate uploader if it already exists. // this is to avoid multiple connections being open. And to avoid some connections left unclosed. if (lastTusUploader != null) { tusUploader = lastTusUploader; lastTusUploader = null; } else { tusUploader = tusClient.resumeOrCreateUpload(uploads.get(0)); } TusExecutor tusExecutor = new TusExecutor() { @Override protected void makeAttempt() throws ProtocolException, IOException { while (state == State.UPLOADING && tusUploader.uploadChunk() > 0) { uploadedBytes += tusUploader.getOffset(); listener.onUploadPogress(uploadedBytes, totalUploadSize); } } }; tusExecutor.makeAttempts(); if (state != State.UPLOADING) { // if upload is paused, save the uploader so it can be reused on resume, then leave the method early. lastTusUploader = tusUploader; return; } // remove upload instance from list uploads.remove(0); tusUploader.finish(); } setState(State.UPLOAD_COMPLETE); } /** * If tus uploads are enabled, this method would be called by {@link Assembly#save()} to handle the file uploads * * @param response {@link AssemblyResponse} * @throws IOException when there's a failure with file retrieval. * @throws ProtocolException when there's a failure with tus upload. */ @Override protected void handleTusUpload(AssemblyResponse response) throws IOException, ProtocolException { url = response.getSslUrl(); totalUploadSize = getTotalUploadSize(); processTusFiles(url); startExecutor(); } /** * Starts the executor that would manage the asynchronous submission of the assembly. */ protected void startExecutor() { executor = new AsyncAssemblyExecutorImpl(new AssemblyRunnable()); executor.execute(); } class AssemblyRunnable implements Runnable { private AsyncAssemblyExecutorImpl executor; void setExecutor(AsyncAssemblyExecutorImpl executor) { this.executor = executor; } @Override public void run() { try { uploadTusFiles(); } catch (ProtocolException e) { getListener().onUploadFailed(e); executor.stop(); return; } catch (IOException e) { getListener().onUploadFailed(e); executor.stop(); return; } if (state == State.UPLOAD_COMPLETE) { getListener().onUploadFinished(); try { getListener().onAssemblyFinished(watchStatus()); } catch (LocalOperationException e) { getListener().onAssemblyStatusUpdateFailed(e); } catch (RequestException e) { getListener().onAssemblyStatusUpdateFailed(e); } finally { executor.stop(); } } } } // used for upload progress private long getTotalUploadSize() throws IOException { long size = 0; for (Map.Entry<String, File> entry : files.entrySet()) { size += entry.getValue().length(); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { size += entry.getValue().available(); } return size; } }
package de.jano1.sponge.regions_api; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; public interface RegionShape { /** * Test if this Shape contains a Location * @param location The Location to test * @return True if this shape contains the location, false if not */ public boolean contains(Location location); /** * Add a vertice to the Shape * @param location */ public void addVertice(Location<World> location); /** * Removes a vertice in the shape * @param location */ public void removeVertice(Location<World> location); }
package de.lessvoid.nifty.render; import java.io.IOException; import java.util.Hashtable; import java.util.Map; import java.util.logging.Logger; import de.lessvoid.nifty.NiftyMouse; import de.lessvoid.nifty.spi.input.InputSystem; import de.lessvoid.nifty.spi.render.MouseCursor; import de.lessvoid.nifty.spi.render.RenderDevice; public class NiftyMouseImpl implements NiftyMouse { private Logger log = Logger.getLogger(NiftyMouseImpl.class.getName()); private RenderDevice renderDevice; private InputSystem inputSystem; private Map < String, MouseCursor > registeredMouseCursors = new Hashtable < String, MouseCursor >(); private String currentId; public NiftyMouseImpl(final RenderDevice renderDevice, final InputSystem inputSystem) { this.renderDevice = renderDevice; this.inputSystem = inputSystem; } @Override public void registerMouseCursor(final String id, final String filename, final int hotspotX, final int hotspotY) throws IOException { MouseCursor mouseCursor = renderDevice.createMouseCursor(filename, hotspotX, hotspotY); if (mouseCursor == null) { log.warning("Your RenderDevice does not support the createMouseCursor() method. Mouse cursors can't be changed."); return; } registeredMouseCursors.put(id, mouseCursor); } @Override public String getCurrentId() { return currentId; } @Override public void unregisterAll() { for (MouseCursor cursor : registeredMouseCursors.values()) { cursor.dispose(); } registeredMouseCursors.clear(); } @Override public void resetMouseCursor() { currentId = null; renderDevice.disableMouseCursor(); } @Override public void enableMouseCursor(final String id) { if (id == null) { resetMouseCursor(); return; } if (id.equals(currentId)) { return; } renderDevice.enableMouseCursor(registeredMouseCursors.get(id)); currentId = id; } @Override public void setMousePosition(final int x, final int y) { inputSystem.setMousePosition(x, y); } }
package dk.in2isoft.commons.lang; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.Lists; public class StringSearcher { private static Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]"); private static String[] WHITESPACE = { /* dummy empty string for homogeneity */ "\\u0009", // CHARACTER TABULATION "\\u000A", // LINE FEED (LF) "\\u000B", // LINE TABULATION "\\u000C", // FORM FEED (FF) "\\u000D", // CARRIAGE RETURN (CR) "\\u0020", // SPACE "\\u0085", // NEXT LINE (NEL) "\\u00A0", // NO-BREAK SPACE "\\u1680", // OGHAM SPACE MARK "\\u180E", // MONGOLIAN VOWEL SEPARATOR "\\u2000", // EN QUAD "\\u2001", // EM QUAD "\\u2002", // EN SPACE "\\u2003", // EM SPACE "\\u2004", // THREE-PER-EM SPACE "\\u2005", // FOUR-PER-EM SPACE "\\u2006", // SIX-PER-EM SPACE "\\u2007", // FIGURE SPACE "\\u2008", // PUNCTUATION SPACE "\\u2009", // THIN SPACE "\\u200A", // HAIR SPACE "\\u2028", // LINE SEPARATOR "\\u2029", // PARAGRAPH SEPARATOR "\\u202F", // NARROW NO-BREAK SPACE "\\u205F", // MEDIUM MATHEMATICAL SPACE "\\u3000" // IDEOGRAPHIC SPACE }; String search; String replace; public StringSearcher() { search = "[\\n\\t, "; replace = "[\\\\n\\\\t, "; for (String chr : WHITESPACE) { search+=chr; replace+="\\"+chr; } search+="]+"; replace+="]*"; } public List<Result> search(String find, String text) { List<Result> results = Lists.newArrayList(); String query = SPECIAL_REGEX_CHARS.matcher(find).replaceAll("\\\\$0");; query = query.replaceAll(search, replace); //query = query.replaceAll("[\\n\\t ]+", "[\\\\n\\\\t ]*"); Pattern pattern = Pattern.compile(query); Matcher matcher = pattern.matcher(text); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String str = matcher.group(); results.add(new Result(start,end,str)); } return results; } public List<Result> findWords(String find, String text) { List<Result> results = Lists.newArrayList(); String query = SPECIAL_REGEX_CHARS.matcher(find).replaceAll("\\\\$0");; query = "\\b" + query + "\\b"; Pattern pattern = Pattern.compile(query); Matcher matcher = pattern.matcher(text); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String str = matcher.group(); results.add(new Result(start,end,str)); } return results; } public class Result { private int from; private int to; private String text; protected Result(int from, int to, String text) { this.from = from; this.to = to; this.text = text; } public int getFrom() { return from; } public int getTo() { return to; } public String getText() { return text; } } }
package edu.howest.breakout.editor; import edu.howest.breakout.game.Database; import edu.howest.breakout.game.entity.Entity; import edu.howest.breakout.game.entity.EntityBlock; import edu.howest.breakout.game.info.Level; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class EditorPannel extends JPanel implements ListSelectionListener, ChangeListener { private EditorGame game; private JList<Entity> componentList; private JButton addButton; private JButton removeButton; private JPanel RootPannel; private JPanel AddPannel; private JLabel xlabel; private JLabel ylabel; private JLabel widthLabel; private JLabel lengthLabel; private JComboBox comboBox1; private JSpinner yValue; private JSpinner xValue; private JSpinner widthValue; private JSpinner heightValue; private JTextField LevelName; private JButton storeLevelbutton; private JButton removeLevelButton; private JList LevelList; private JButton newLevelButton; private JButton loadLevelButton; private boolean canchange = true; private Database database; public EditorPannel(final EditorGame game, final Database database){ setVisible(true); this.game = game; this.database = database; this.componentList.setModel(game.getListModel()); this.componentList.addListSelectionListener(this); this.componentList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); updateLevels(); this.yValue.addChangeListener(this); this.xValue.addChangeListener(this); this.widthValue.setValue(50); this.heightValue.setValue(50); add(RootPannel); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (componentList.getSelectedValue() != null) for (Entity entity : componentList.getSelectedValuesList()) game.remove(entity); } }); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.add(new EntityBlock(getInteger(yValue), getInteger(xValue), getInteger(widthValue), getInteger(heightValue), Color.black)); canchange = false; yValue.setValue(getInteger(yValue) + getInteger(widthValue) + 2); canchange = true; } }); loadLevelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!LevelList.isSelectionEmpty()) game.loadLevel((Level) LevelList.getSelectedValue()); } }); newLevelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.clearEntities(); } }); storeLevelbutton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { database.addLevel(game.getLevel(LevelName.getText())); updateLevels(); } }); removeLevelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!LevelList.isSelectionEmpty()) database.removeLevel((Level) LevelList.getSelectedValue()); updateLevels(); } }); } private void updateLevels() { this.LevelList.setListData(database.getLevels().toArray()); } public void newLevel(){ game.getEntities().clear(); } public void select(Entity entity, boolean ctrlDown){ if (ctrlDown) { System.out.println("more"); int index = game.getListModel().indexOf(entity); componentList.getSelectionModel().addSelectionInterval(index, index); } else { componentList.clearSelection(); componentList.setSelectedValue(entity, true); } } @Override public void valueChanged(ListSelectionEvent e) { this.canchange = false; if (!componentList.isSelectionEmpty()) { yValue.setValue(componentList.getSelectedValue().getX()); xValue.setValue(componentList.getSelectedValue().getY()); widthValue.setValue(componentList.getSelectedValue().getWidth()); heightValue.setValue(componentList.getSelectedValue().getHeight()); } repaint(); this.canchange = true; } @Override public void stateChanged(ChangeEvent e) { if (!componentList.isSelectionEmpty() && canchange == true) { moveSelection(getInteger(xValue), getInteger(yValue)); resizeSelection(getInteger(widthValue), getInteger(heightValue)); } } private void resizeSelection(int width, int heigth) { for (Entity entity : componentList.getSelectedValuesList()) { entity.setWidth(width); entity.setHeight(heigth); } } private int getInteger(JSpinner spinner){ return ((SpinnerNumberModel) spinner.getModel()).getNumber().intValue(); } public void moveSelection(int x2, int y2){ int x1 = (int) componentList.getSelectedValue().getX(); int y1 = (int) componentList.getSelectedValue().getY(); if (!componentList.isSelectionEmpty()) { for (Entity entity : componentList.getSelectedValuesList()) { int dx = (int) (entity.getX() - x1); int dy = (int) (entity.getY() - y1); entity.setX(x2 + dx); entity.setY(y2 + dy); } } } public Entity getSelectedValue(){ return componentList.getSelectedValue(); } }
package fi.solita.utils.codegen; import static fi.solita.utils.functional.Collections.newMap; import static fi.solita.utils.functional.Collections.newSet; import static fi.solita.utils.functional.Functional.takeWhile; import static fi.solita.utils.functional.Predicates.equalTo; import static fi.solita.utils.functional.Predicates.not; import java.io.Serializable; import java.io.Writer; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Generated; import javax.annotation.processing.Filer; import javax.tools.FileObject; import fi.solita.utils.functional.Option; public class ClassFileWriter { private static final Pattern IMPORTS = Pattern.compile(Pattern.quote("{${") + "(([a-zA-Z0-9_]+\\.)*([a-zA-Z0-9_$]+))" + Pattern.quote("}$}")); private static final String SERIALIZABLE = Serializable.class.getSimpleName(); private static final String GENERATED = Generated.class.getSimpleName(); private static final String LINE_SEP = System.getProperty("line.separator"); public static void writeClassFile(String packageName, String classSimpleName, Option<String> extendedClassName, Iterable<String> contentLines, Class<?> generator, Filer filer) { Map<String,String> toImport = newMap(); toImport.put(GENERATED, "javax.annotation.Generated"); toImport.put(SERIALIZABLE, "java.io.Serializable"); StringBuffer content = new StringBuffer(); for (String line: contentLines) { Matcher m = IMPORTS.matcher(line); while (m.find()) { String qualifiedName = takeWhile(not(equalTo('$')), m.group(1)); String simpleName = m.group(3).replaceAll("[$]", "."); String alreadyImported = toImport.get(simpleName); if (alreadyImported == null || alreadyImported.equals(qualifiedName)) { toImport.put(simpleName, qualifiedName); m.appendReplacement(content, simpleName); } else { m.appendReplacement(content, qualifiedName); } } m.appendTail(content); content.append(LINE_SEP); } try { String extend = extendedClassName.isDefined() ? " extends " + extendedClassName.get() : ""; FileObject fo = filer.createSourceFile((packageName.isEmpty() ? "" : packageName + ".") + classSimpleName); Writer pw = fo.openWriter(); if (!packageName.isEmpty()) { pw.append("package ") .append(packageName) .append(';') .append(LINE_SEP); } for (String qualifiedName: newSet(toImport.values())) { pw.append("import ") .append(qualifiedName) .append(";") .append(LINE_SEP); } pw.append(LINE_SEP) .append('@') .append(GENERATED) .append("(\"") .append(generator.getName()) .append("\")") .append(LINE_SEP) .append("public class ") .append(classSimpleName) .append(extend) .append(" implements ") .append(SERIALIZABLE) .append(" {") .append(LINE_SEP) .append(LINE_SEP) .append(content) .append('}'); pw.close(); } catch (Exception e) { throw new RuntimeException(e); } } }
package foodtruck.geolocation; import java.util.logging.Level; import java.util.logging.Logger; import com.google.inject.Inject; import foodtruck.dao.ConfigurationDAO; import foodtruck.model.Configuration; import foodtruck.model.Location; import foodtruck.util.Clock; /** * @author aviolette@gmail.com * @since 4/11/12 */ public class OrderedGeolocator implements GeoLocator { private GoogleGeolocator googleGeolocator; private YahooGeolocator yahooGeolocator; private ConfigurationDAO configurationDAO; private static final Logger log = Logger.getLogger(OrderedGeolocator.class.getName()); private final Clock clock; @Inject public OrderedGeolocator(GoogleGeolocator googleGeolocator, YahooGeolocator yahooGeolocator, ConfigurationDAO configurationDAO, Clock clock) { this.googleGeolocator = googleGeolocator; this.yahooGeolocator = yahooGeolocator; this.configurationDAO = configurationDAO; this.clock = clock; } @Override public Location locate(String location, GeolocationGranularity granularity) { Configuration config = configurationDAO.findSingleton(); if (config.isGoogleGeolocationEnabled() && !config.isGoogleThrottled(clock.now())) { try { Location loc = googleGeolocator.locate(location, granularity); if (loc != null) { return loc; } } catch (OverQueryLimitException oqle) { log.warning("Received OVER_QUERY_LIMIT from Google"); } } else { log.log(Level.INFO, "Skipping google for geolocation. Throttle value: {0}", config.getThrottleGoogleUntil()); } if (config.isYahooGeolocationEnabled()) { return yahooGeolocator.locate(location, granularity); } return null; } @Override public String reverseLookup(Location location, String defaultValue) { Configuration config = configurationDAO.findSingleton(); if (config.isGoogleGeolocationEnabled() && !config.isGoogleThrottled(clock.now())) { log.log(Level.INFO, "Looking up location: {0}", location); try { return googleGeolocator.reverseLookup(location, defaultValue); } catch (OverQueryLimitException e) { log.warning("Received OVER_QUERY_LIMIT from Google"); } } return defaultValue; } }
package info.freelibrary.util; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; import java.util.ResourceBundle; public class XMLResourceBundle extends ResourceBundle { private Properties myProperties; XMLResourceBundle(InputStream stream) throws IOException { myProperties = new Properties(); myProperties.loadFromXML(stream); } protected Object handleGetObject(String key) { return myProperties.getProperty(key); } public Enumeration<String> getKeys() { final Enumeration<?> enumeration = myProperties.elements(); return new Enumeration<String>() { public boolean hasMoreElements() { return enumeration.hasMoreElements(); } public String nextElement() { return (String) enumeration.nextElement(); } }; } public String get(String aMessage, String[] aDetailsArray) { return StringUtils.formatMessage(super.getString(aMessage), aDetailsArray); } public String get(String aMessage, String aDetail) { return StringUtils.formatMessage(super.getString(aMessage), new String[] { aDetail }); } public String get(String aMessage) { return getString(aMessage); } }
package io.magicthegathering.javasdk.api; import io.magicthegathering.javasdk.exception.HttpRequestFailedException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * Base class for using the magicthegathering.io APIs. * * @author thechucklingatom * @author nniklas */ public abstract class MTGAPI { protected static String ENDPOINT = "https://api.magicthegathering.io/v1"; protected static OkHttpClient CLIENT = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build(); private static String DELIM_LINK = ","; private static String DELIM_LINK_PARAM = ";"; /** * Make an HTTP GET request to the given path and map the object under the * given key in the JSON of the response to the Java {@link Class} of type * {@link TYPE}. * * @param path Controlled by what is calling the function, currently "sets" or "cards" * depending on the calling class. * @param key The key for the JSON element we are looking for. * @param expectedClass The class type we are expecting to get back. * @return Object of the requested type if found. */ protected static <TYPE> TYPE get(String path, String key, Class<TYPE> expectedClass) { Gson deserializer = new GsonBuilder().create(); JsonObject jsonObject = getJsonObject(path, deserializer).get(0); return deserializer.fromJson(jsonObject.get(key), expectedClass); } /** * Make an HTTP GET request to the given path and map the array under the * given key in the JSON of the response to a {@link List} of type * {@link TYPE}. * * @param path Controlled by what is calling the function, currently "sets" or "cards" * depending on the calling class. * @param key The key for the JSON element we are looking for. * @param expectedClass The class type we are expecting to get back. * @return a {@link List} of {@link TYPE} */ protected static <TYPE> List<TYPE> getList(String path, String key, Class<TYPE> expectedClass) { Gson deserializer = new GsonBuilder().create(); List<TYPE> toReturn = new ArrayList<>(); List<JsonObject> jsonObjectList = getJsonObject(path, deserializer); for(JsonObject jsonObject : jsonObjectList) { for (JsonElement jsonElement : jsonObject.get(key).getAsJsonArray()) { toReturn.add(deserializer.fromJson( jsonElement, expectedClass)); } } return toReturn; } /** * Deserialize the object to the type expected. * * @param path Controlled by what is calling the function, currently "sets" or "cards" * depending on the calling class. * @param deserializer {@link Gson} object that will be used to deserialize the JSON returned * from the web API. * @return The parsed {@link JsonObject} */ private static List<JsonObject> getJsonObject(String path, Gson deserializer) { String url = String.format("%s/%s", ENDPOINT, path); Request request = new Request.Builder().url(url).build(); Response response; try { response = CLIENT.newCall(request).execute(); ArrayList<JsonObject> objectList = new ArrayList<>(); String linkHeader = response.headers().get("Link"); if (linkHeader == null || linkHeader.isEmpty() || path.contains("page=")) { objectList.add(deserializer.fromJson(response.body() .string(), JsonObject.class)); return objectList; } else { int numberOfPages = 0; String[] linkStrings = linkHeader.split(DELIM_LINK); List<String[]> paramList = new ArrayList<>(); for (String link : linkStrings) { paramList.add(link.split(DELIM_LINK_PARAM)); } for (String[] params : paramList) { if (params[1].contains("last")) { Matcher matcher = Pattern.compile("page=[0-9]+").matcher(params[0]); numberOfPages = (matcher.find()) ? Integer.parseInt(matcher.group().substring(5)) : 0; } } objectList.add(deserializer.fromJson(response.body().string(), JsonObject.class)); if (!url.contains("?")) { url += "?"; } for(int i = 2; i <= numberOfPages; i++){ request = new Request.Builder().url(url + "&page=" + i).build(); response = CLIENT.newCall(request).execute(); objectList.add(deserializer.fromJson(response.body().string(), JsonObject.class)); } return objectList; } } catch (IOException e) { throw new HttpRequestFailedException(e); } } protected static <TYPE> List<TYPE> getList(String path, String key, Class<TYPE> expectedClass, List<String> filters) { StringBuilder tempPath = new StringBuilder(path); tempPath.append("?"); for (String filter : filters) { tempPath.append(filter).append('&'); } return getList(tempPath.substring(0, tempPath.length() - 1), key, expectedClass); } }
package com.marverenic.music; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.audiofx.AudioEffect; import android.media.audiofx.Equalizer; import android.net.Uri; import android.os.PowerManager; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import com.crashlytics.android.Crashlytics; import com.marverenic.music.activity.NowPlayingActivity; import com.marverenic.music.instances.Song; import com.marverenic.music.utils.ManagedMediaPlayer; import com.marverenic.music.utils.Prefs; import com.marverenic.music.utils.Util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.util.Random; import java.util.Scanner; public class Player implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, AudioManager.OnAudioFocusChangeListener { public static final String UPDATE_BROADCAST = "marverenic.jockey.player.REFRESH"; // Sent to refresh views that use up-to-date player information private static final String TAG = "Player"; private static final String QUEUE_FILE = ".queue"; public static final String PREFERENCE_SHUFFLE = "prefShuffle"; public static final String PREFERENCE_REPEAT = "prefRepeat"; // Instance variables private ManagedMediaPlayer mediaPlayer; private Equalizer equalizer; private Context context; private MediaSessionCompat mediaSession; private HeadsetListener headphoneListener; // Queue information private ArrayList<Song> queue; private ArrayList<Song> queueShuffled = new ArrayList<>(); private int queuePosition; private int queuePositionShuffled; // MediaFocus variables private boolean active = false; // If we currently have audio focus private boolean shouldResumeOnFocusGained = false; // If we should play music when focus is returned // Shufle & Repeat options private boolean shuffle; // Shuffle status public static final short REPEAT_NONE = 0; public static final short REPEAT_ALL = 1; public static final short REPEAT_ONE = 2; private short repeat; // Repeat status private Bitmap art; // The art for the current song /** * A {@link Properties} object used as a hashtable for saving play and skip counts. * See {@link Player#logPlayCount(long, boolean)} * * Keys are stored as strings in the form "song_id" * Values are stored as strings in the form "play,skip,lastPlayDateAsUtcTimeStamp" */ private Properties playCountHashtable; /** * Create a new Player Object, which manages a {@link MediaPlayer} * @param context A {@link Context} that will be held for the lifetime of the Player */ public Player(Context context) { this.context = context; // Initialize the media player mediaPlayer = new ManagedMediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnCompletionListener(this); // Initialize the queue queue = new ArrayList<>(); queuePosition = 0; // Load preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); shuffle = prefs.getBoolean(PREFERENCE_SHUFFLE, false); repeat = (short) prefs.getInt(PREFERENCE_REPEAT, REPEAT_NONE); initMediaSession(); if (Util.hasEqualizer()) { initEqualizer(); } // Attach a HeadsetListener to respond to headphone events headphoneListener = new HeadsetListener(this); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_BUTTON); filter.addAction(Intent.ACTION_HEADSET_PLUG); context.registerReceiver(headphoneListener, filter); } /** * Reload the last queue saved by the Player */ public void reload() { try { File save = new File(context.getExternalFilesDir(null), QUEUE_FILE); Scanner scanner = new Scanner(save); final int currentPosition = scanner.nextInt(); if (shuffle) { queuePositionShuffled = scanner.nextInt(); } else { queuePosition = scanner.nextInt(); } int queueLength = scanner.nextInt(); int[] queueIDs = new int[queueLength]; for (int i = 0; i < queueLength; i++) { queueIDs[i] = scanner.nextInt(); } queue = Library.buildSongListFromIds(queueIDs, context); int[] shuffleQueueIDs; if (scanner.hasNextInt()) { shuffleQueueIDs = new int[queueLength]; for (int i = 0; i < queueLength; i++) { shuffleQueueIDs[i] = scanner.nextInt(); } queueShuffled = Library.buildSongListFromIds(shuffleQueueIDs, context); } else if (shuffle) { queuePosition = queuePositionShuffled; shuffleQueue(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.seekTo(currentPosition); updateNowPlaying(); mp.setOnPreparedListener(Player.this); } }); art = Util.fetchFullArt(getNowPlaying()); mediaPlayer.setDataSource(getNowPlaying().location); mediaPlayer.prepareAsync(); } catch (Exception e){ queuePosition = 0; queuePositionShuffled = 0; queue.clear(); queueShuffled.clear(); } } /** * Reload all equalizer settings from SharedPreferences */ private void initEqualizer() { SharedPreferences prefs = Prefs.getPrefs(context); String eqSettings = prefs.getString(Prefs.EQ_SETTINGS, null); boolean enabled = Prefs.getPrefs(context).getBoolean(Prefs.EQ_ENABLED, false); equalizer = new Equalizer(0, mediaPlayer.getAudioSessionId()); if (eqSettings != null) { try { equalizer.setProperties(new Equalizer.Settings(eqSettings)); } catch (IllegalArgumentException|UnsupportedOperationException e) { Crashlytics.logException(new RuntimeException( "Failed to load equalizer settings: " + eqSettings, e)); } } equalizer.setEnabled(enabled); // If the built in equalizer is off, bind to the system equalizer if one is available if (!enabled) { final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); context.sendBroadcast(intent); } } /** * Writes a player state to disk. Contains information about the queue (both unshuffled and shuffled), * current queuePosition within this list, and the current queuePosition of the song * @throws IOException */ public void saveState(@NonNull final String nextCommand) throws IOException { // Anticipate the outcome of a command so that if we're killed right after it executes, // we can restore to the proper state int reloadSeekPosition; int reloadQueuePosition = (shuffle)? queuePositionShuffled : queuePosition; switch (nextCommand) { case PlayerService.ACTION_NEXT: if (reloadQueuePosition + 1 < queue.size()) { reloadSeekPosition = 0; reloadQueuePosition++; } else{ reloadSeekPosition = mediaPlayer.getDuration(); } break; case PlayerService.ACTION_PREV: if (mediaPlayer.getDuration() < 5000 && reloadQueuePosition - 1 > 0){ reloadQueuePosition } reloadSeekPosition = 0; break; default: reloadSeekPosition = mediaPlayer.getCurrentPosition(); break; } final String currentPosition = Integer.toString(reloadSeekPosition); final String queuePosition = Integer.toString(reloadQueuePosition); final String queueLength = Integer.toString(queue.size()); String queue = ""; for (Song s : this.queue){ queue += " " + s.songId; } String queueShuffled = ""; for (Song s : this.queueShuffled){ queueShuffled += " " + s.songId; } String output = currentPosition + " " + queuePosition + " " + queueLength + queue + queueShuffled; File save = new File(context.getExternalFilesDir(null), QUEUE_FILE); FileOutputStream stream = new FileOutputStream(save); stream.write(output.getBytes()); stream.close(); } /** * Release the player. Call when finished with an instance */ public void finish (){ ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this); context.unregisterReceiver(headphoneListener); // Unbind from the system audio effects final Intent intent = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION); intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); context.sendBroadcast(intent); if (equalizer != null) equalizer.release(); active = false; mediaPlayer.stop(); mediaPlayer.release(); mediaSession.release(); mediaPlayer = null; context = null; } /** * Initiate a MediaSession to allow the Android system to interact with the player */ private void initMediaSession() { mediaSession = new MediaSessionCompat(context, TAG, null, null); mediaSession.setCallback(new MediaSessionCompat.Callback() { @Override public void onPlay() { play(); } @Override public void onSkipToQueueItem(long id) { changeSong((int) id); } @Override public void onPause() { pause(); } @Override public void onSkipToNext() { skip(); } @Override public void onSkipToPrevious() { previous(); } @Override public void onStop() { stop(); } @Override public void onSeekTo(long pos) { seek((int) pos); } }); mediaSession.setSessionActivity( PendingIntent.getActivity( context, 0, new Intent(context, NowPlayingActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_CANCEL_CURRENT)); mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder() .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) .setState(PlaybackStateCompat.STATE_NONE, 0, 0f); mediaSession.setPlaybackState(state.build()); mediaSession.setActive(true); } @Override public void onAudioFocusChange(int focusChange) { shouldResumeOnFocusGained = isPlaying() || shouldResumeOnFocusGained; switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: pause(); break; case AudioManager.AUDIOFOCUS_LOSS: stop(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: mediaPlayer.setVolume(0.5f, 0.5f); break; case AudioManager.AUDIOFOCUS_GAIN: mediaPlayer.setVolume(1f, 1f); if (shouldResumeOnFocusGained) play(); shouldResumeOnFocusGained = false; break; default: break; } updateNowPlaying(); } @Override public void onCompletion(MediaPlayer mp) { logPlayCount(getNowPlaying().songId, false); if(repeat == REPEAT_ONE){ mediaPlayer.seekTo(0); play(); } else { skip(); } updateUi(); } @Override public void onPrepared(MediaPlayer mp) { if(!isPreparing()) { mediaPlayer.start(); updateUi(); updateNowPlaying(); } } /** * Change the queue and shuffle it if necessary * @param newQueue An {@link ArrayList} of {@link Song}s to become the new queue * @param newPosition The queuePosition in the list to start playback from */ public void setQueue(final ArrayList<Song> newQueue, final int newPosition) { queue = newQueue; queuePosition = newPosition; if (shuffle) shuffleQueue(); updateNowPlaying(); } /** * Replace the contents of the queue without affecting playback * @param newQueue An {@link ArrayList} of {@link Song}s to become the new queue * @param newPosition The queuePosition in the list to start playback from */ public void editQueue(final ArrayList<Song> newQueue, final int newPosition) { if (shuffle){ queueShuffled = newQueue; queuePositionShuffled = newPosition; } else { queue = newQueue; queuePosition = newPosition; } updateNowPlaying(); } /** * Begin playback of a new song. Call this method after changing the queue or now playing track */ public void begin() { if (getNowPlaying() != null && getFocus()) { mediaPlayer.stop(); mediaPlayer.reset(); art = Util.fetchFullArt(getNowPlaying()); try { mediaPlayer.setDataSource(context, Uri.parse(getNowPlaying().location)); mediaPlayer.prepareAsync(); } catch (IOException e) { Crashlytics.logException(e); } } } /** * Update the main thread and Android System about this player instance. This method also calls * {@link PlayerService#notifyNowPlaying()}. */ public void updateNowPlaying() { PlayerService.getInstance().notifyNowPlaying(); updateMediaSession(); } /** * Update the MediaSession to keep the Android system up to date with player information */ public void updateMediaSession() { if (getNowPlaying() != null) { MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder(); Song nowPlaying = getNowPlaying(); metadataBuilder .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, nowPlaying.songName) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, nowPlaying.songName) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, nowPlaying.albumName) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, nowPlaying.artistName) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, getDuration()) .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, art); mediaSession.setMetadata(metadataBuilder.build()); PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions( PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS); switch (mediaPlayer.getState()) { case STARTED: state.setState(PlaybackStateCompat.STATE_PLAYING, getCurrentPosition(), 1f); break; case PAUSED: state.setState(PlaybackStateCompat.STATE_PAUSED, getCurrentPosition(), 1f); break; case STOPPED: state.setState(PlaybackStateCompat.STATE_STOPPED, getCurrentPosition(), 1f); break; default: state.setState(PlaybackStateCompat.STATE_NONE, getCurrentPosition(), 1f); } mediaSession.setPlaybackState(state.build()); mediaSession.setActive(active); } } /** * Called to notify the UI thread to refresh any player data when the player changes states * on its own (Like when a song finishes) */ public void updateUi() { context.sendBroadcast(new Intent(UPDATE_BROADCAST), null); } /** * Get the song at the current queuePosition in the queue or shuffled queue * @return The now playing {@link Song} (null if nothing is playing) */ public Song getNowPlaying() { if (shuffle) { if (queueShuffled.size() == 0 || queuePositionShuffled >= queueShuffled.size() || queuePositionShuffled < 0) { return null; } return queueShuffled.get(queuePositionShuffled); } if (queue.size() == 0 || queuePosition >= queue.size() || queuePosition < 0) { return null; } return queue.get(queuePosition); } // MEDIA CONTROL METHODS /** * Toggle between playing and pausing music */ public void togglePlay() { if (isPlaying()) { pause(); } else { play(); } } /** * Resume playback. Starts playback over if at the end of the last song in the queue */ public void play() { if (!isPlaying() && getFocus()) { if (shuffle) { if (queuePositionShuffled + 1 == queueShuffled.size() && mediaPlayer.isComplete()) { queuePositionShuffled = 0; begin(); } else { mediaPlayer.start(); updateNowPlaying(); } } else { if (queuePosition + 1 == queue.size() && mediaPlayer.isComplete()) { queuePosition = 0; begin(); } else { mediaPlayer.start(); updateNowPlaying(); } } } } /** * Pauses playback. The same as calling {@link MediaPlayer#pause()} and {@link Player#updateNowPlaying()} */ public void pause() { if (isPlaying()) { mediaPlayer.pause(); updateNowPlaying(); } shouldResumeOnFocusGained = false; } /** * Pauses playback and releases audio focus from the system */ public void stop() { if (isPlaying()) { pause(); } ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this); active = false; updateMediaSession(); } /** * Gain Audio focus from the system if we don't already have it * @return whether we have gained focus (or already had it) */ private boolean getFocus() { if (!active) { AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); active = (audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED); } return active; } /** * Skip to the previous track if less than 5 seconds in, otherwise restart this song from the beginning */ public void previous() { if (!isPreparing()) { if (shuffle) { if (mediaPlayer.getCurrentPosition() > 5000 || queuePositionShuffled < 1) { mediaPlayer.seekTo(0); updateNowPlaying(); } else { queuePositionShuffled begin(); } } else { if (mediaPlayer.getCurrentPosition() > 5000 || queuePosition < 1) { mediaPlayer.seekTo(0); updateNowPlaying(); } else { queuePosition begin(); } } } } /** * Skip to the next track in the queue */ public void skip() { if (!isPreparing()) { if (!mediaPlayer.isComplete() && getNowPlaying() != null) { if (mediaPlayer.getCurrentPosition() > 24000 || mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) { logPlayCount(getNowPlaying().songId, false); } else if (getCurrentPosition() < 20000) { logPlayCount(getNowPlaying().songId, true); } } if (shuffle && queuePositionShuffled + 1 < queueShuffled.size()) { queuePositionShuffled++; begin(); } else if (!shuffle && queuePosition + 1 < queue.size()) { queuePosition++; begin(); } else if (repeat == REPEAT_ALL) { if (shuffle) { queuePositionShuffled = 0; } else { queuePosition = 0; } begin(); } else { mediaPlayer.complete(); updateNowPlaying(); } } } /** * Seek to a different queuePosition in the current track * @param position The queuePosition to seek to (in milliseconds) */ public void seek(int position) { if (position <= mediaPlayer.getDuration() && getNowPlaying() != null) { mediaPlayer.seekTo(position); mediaSession.setPlaybackState(new PlaybackStateCompat.Builder() .setState( isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED, (long) mediaPlayer.getCurrentPosition(), isPlaying() ? 1f : 0f) .build()); } } /** * Change the current song to a different song in the queue * @param newPosition The index of the song to start playing */ public void changeSong(int newPosition) { if (!mediaPlayer.isComplete()) { if (mediaPlayer.getCurrentPosition() > 24000 || mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) { logPlayCount(getNowPlaying().songId, false); } else if (getCurrentPosition() < 20000) { logPlayCount(getNowPlaying().songId, true); } } if (shuffle) { if (newPosition < queueShuffled.size() && newPosition != queuePositionShuffled) { queuePositionShuffled = newPosition; begin(); } } else { if (newPosition < queue.size() && queuePosition != newPosition) { queuePosition = newPosition; begin(); } } } // QUEUE METHODS /** * Add a song to the queue so it plays after the current track. If shuffle is enabled, then the * song will also be added to the end of the unshuffled queue. * @param song the {@link Song} to add */ public void queueNext(final Song song) { if (queue.size() != 0) { if (shuffle) { queueShuffled.add(queuePositionShuffled + 1, song); queue.add(song); } else { queue.add(queuePosition + 1, song); } } else { ArrayList<Song> newQueue = new ArrayList<>(); newQueue.add(song); setQueue(newQueue, 0); begin(); } } /** * Add a song to the end of the queue. If shuffle is enabled, then the song will also be added * to the end of the unshuffled queue. * @param song the {@link Song} to add */ public void queueLast(final Song song) { if (queue.size() != 0) { if (shuffle) { queueShuffled.add(queueShuffled.size(), song); } queue.add(queue.size(), song); } else { ArrayList<Song> newQueue = new ArrayList<>(); newQueue.add(song); setQueue(newQueue, 0); begin(); } } /** * Add songs to the queue so they play after the current track. If shuffle is enabled, then the * songs will also be added to the end of the unshuffled queue. * @param songs an {@link ArrayList} of {@link Song}s to add */ public void queueNext(final ArrayList<Song> songs) { if (queue.size() != 0) { if (shuffle) { queueShuffled.addAll(queuePositionShuffled + 1, songs); queue.addAll(songs); } else { queue.addAll(queuePosition + 1, songs); } } else { ArrayList<Song> newQueue = new ArrayList<>(); newQueue.addAll(songs); setQueue(newQueue, 0); begin(); } } /** * Add songs to the end of the queue. If shuffle is enabled, then the songs will also be added * to the end of the unshuffled queue. * @param songs an {@link ArrayList} of {@link Song}s to add */ public void queueLast(final ArrayList<Song> songs) { if (queue.size() != 0) { if (shuffle) { queueShuffled.addAll(queueShuffled.size(), songs); queue.addAll(queue.size(), songs); } else { queue.addAll(queue.size(), songs); } } else { ArrayList<Song> newQueue = new ArrayList<>(); newQueue.addAll(songs); setQueue(newQueue, 0); begin(); } } // SHUFFLE & REPEAT METHODS /** * Shuffle the queue and put it into {@link Player#queueShuffled}. The current song will always * be placed first in the list */ private void shuffleQueue() { queueShuffled.clear(); if (queue.size() > 0) { queuePositionShuffled = 0; queueShuffled.add(queue.get(queuePosition)); ArrayList<Song> randomHolder = new ArrayList<>(); for (int i = 0; i < queuePosition; i++) { randomHolder.add(queue.get(i)); } for (int i = queuePosition + 1; i < queue.size(); i++) { randomHolder.add(queue.get(i)); } Collections.shuffle(randomHolder, new Random(System.nanoTime())); queueShuffled.addAll(randomHolder); } } public void setPrefs(boolean shuffleSetting, short repeatSetting){ // Because SharedPreferences doesn't work with multiple processes (thanks Google...) // we actually have to be told what the new settings are in order to avoid the service // and UI doing the opposite of what they should be doing and to prevent the universe // from exploding. It's fine to initialize the SharedPreferences by reading them like we // do in the constructor since they haven't been modified, but if something gets written // in one process the SharedPreferences in the other process won't be updated. // I really wish someone had told me this earlier. if (shuffle != shuffleSetting){ shuffle = shuffleSetting; if (shuffle) { shuffleQueue(); } else if (queueShuffled.size() > 0){ queuePosition = queue.indexOf(queueShuffled.get(queuePositionShuffled)); queueShuffled = new ArrayList<>(); } } repeat = repeatSetting; updateNowPlaying(); } // PLAY & SKIP COUNT LOGGING /** * Initializes {@link Player#playCountHashtable} * @throws IOException */ private void openPlayCountFile() throws IOException{ File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME); if (!file.exists()) //noinspection ResultOfMethodCallIgnored file.createNewFile(); InputStream is = new FileInputStream(file); try { playCountHashtable = new Properties(); playCountHashtable.load(is); } finally { is.close(); } } /** * Writes {@link Player#playCountHashtable} to disk * @throws IOException */ private void savePlayCountFile() throws IOException{ OutputStream os = new FileOutputStream(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME); try { playCountHashtable.store(os, Library.PLAY_COUNT_FILE_COMMENT); } finally { os.close(); } } /** * Record a play or skip for a certain song * @param songId the ID of the song written in the {@link android.provider.MediaStore} * @param skip Whether the song was skipped (true if skipped, false if played) */ public void logPlayCount(long songId, boolean skip){ try { if (playCountHashtable == null) openPlayCountFile(); final String originalValue = playCountHashtable.getProperty(Long.toString(songId)); int playCount = 0; int skipCount = 0; int playDate = 0; if (originalValue != null && !originalValue.equals("")) { final String[] originalValues = originalValue.split(","); playCount = Integer.parseInt(originalValues[0]); skipCount = Integer.parseInt(originalValues[1]); // Preserve backwards compatibility with play count files written with older // versions of Jockey that didn't save this data if (originalValues.length > 2) { playDate = Integer.parseInt(originalValues[2]); } } if (skip) { skipCount++; } else { playDate = (int) (System.currentTimeMillis() / 1000); playCount++; } playCountHashtable.setProperty( Long.toString(songId), playCount + "," + skipCount + "," + playDate); savePlayCountFile(); } catch (Exception e){ e.printStackTrace(); Crashlytics.logException(e); } } // ACCESSOR METHODS public Bitmap getArt() { return art; } public boolean isPlaying() { return mediaPlayer.getState() == ManagedMediaPlayer.status.STARTED; } public boolean isPreparing() { return mediaPlayer.getState() == ManagedMediaPlayer.status.PREPARING; } public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); } public int getDuration() { return mediaPlayer.getDuration(); } public ArrayList<Song> getQueue() { if (shuffle) return new ArrayList<>(queueShuffled); return new ArrayList<>(queue); } public int getQueuePosition() { if (shuffle) return queuePositionShuffled; return queuePosition; } public int getAudioSessionId() { return mediaPlayer.getAudioSessionId(); } /** * Receives headphone connect and disconnect intents so that music may be paused when headphones * are disconnected */ public static class HeadsetListener extends BroadcastReceiver { Player instance; public HeadsetListener(Player instance){ this.instance = instance; } @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG) && intent.getIntExtra("state", -1) == 0 && instance.isPlaying()){ instance.pause(); } } } }
package me.joshuamarquez.sails.io; import io.socket.client.Ack; import io.socket.client.IO; import io.socket.client.Socket; import org.json.JSONObject; import java.net.URISyntaxException; import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; public class SailsIOClient { public final static String SDK_VERSION_KEY = "__sails_io_sdk_version"; public final static String SDK_VERSION_VALUE = "0.13.7"; private SailsSocket sailsSocket; private static SailsIOClient instance; // Global Socket url private AtomicReference<String> url = new AtomicReference<>(); // Global Socket options private AtomicReference<IO.Options> options = new AtomicReference<>(new IO.Options()); // Global headers private Map<String, String> headers = Collections.emptyMap(); private SailsIOClient() { /* No args constructor */ } public synchronized static SailsIOClient getInstance() { if (instance == null) { instance = new SailsIOClient(); } return instance; } public synchronized SailsSocket socket() { if (url.get() == null) { throw new RuntimeException("Url must be initialized"); } if (sailsSocket == null) { sailsSocket = new SailsSocket(url.get(), options.get()); } return sailsSocket; } /** * Get HTTP headers to be sent in every request for all sockets. */ public Map<String, String> getHeaders() { return headers; } /** * @param headers HTTP headers to be sent in every request for all sockets. */ public void setHeaders(Map<String, String> headers) { if (headers != null && !headers.isEmpty()) { this.headers = headers; } } /** * @return url to connect socket */ public String getUrl() { return url.get(); } /** * @param url to connect socket */ public void setUrl(String url) { if (sailsSocket != null && sailsSocket.isConnected()) { throw new RuntimeException("Can not change url while socket is connected"); } if (url != null) this.url.set(url); } /** * @return initial socket {@link IO.Options} */ public IO.Options getOptions() { return options.get(); } /** * @param options initial socket {@link IO.Options} */ public void setOptions(IO.Options options) { if (sailsSocket != null && sailsSocket.isConnected()) { throw new RuntimeException("Can not change options while socket is connected"); } if (options != null) this.options.set(options); } /** * Private method used by {@link SailsSocket#request} * * @param request {@link SailsSocketRequest} */ void emitFrom(Socket socket, SailsSocketRequest request) { // Name of the appropriate socket.io listener on the server String sailsEndpoint = request.getMethod(); // Since Listener is embedded in request, retrieve it. SailsSocketResponse.Listener listener = request.getListener(); socket.emit(sailsEndpoint, request.toJSONObject(), new Ack() { @Override public void call(Object... args) { // Send back jsonWebSocketResponse if (listener != null) { listener.onResponse(new JWR((JSONObject) args[0])); } } }); } }
package fr.neamar.kiss; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.TypedValue; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; import java.util.ArrayList; import fr.neamar.kiss.adapter.RecordAdapter; import fr.neamar.kiss.pojo.Pojo; import fr.neamar.kiss.result.Result; import fr.neamar.kiss.searcher.ApplicationsSearcher; import fr.neamar.kiss.searcher.HistorySearcher; import fr.neamar.kiss.searcher.NullSearcher; import fr.neamar.kiss.searcher.QueryInterface; import fr.neamar.kiss.searcher.QuerySearcher; import fr.neamar.kiss.searcher.Searcher; public class MainActivity extends ListActivity implements QueryInterface { public static final String START_LOAD = "fr.neamar.summon.START_LOAD"; public static final String LOAD_OVER = "fr.neamar.summon.LOAD_OVER"; public static final String FULL_LOAD_OVER = "fr.neamar.summon.FULL_LOAD_OVER"; /** * IDS for the favorites buttons */ private final int[] favsIds = new int[]{R.id.favorite0, R.id.favorite1, R.id.favorite2, R.id.favorite3}; /** * Number of favorites to retrieve. * We need to pad this number to account for removed items still in history */ private final int tryToRetrieve = favsIds.length + 2; /** * InputType with spellecheck and swiping */ private final int spellcheckEnabledType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT; /** * Adapter to display records */ public RecordAdapter adapter; /** * Store user preferences */ private SharedPreferences prefs; private BroadcastReceiver mReceiver; /** * View for the Search text */ private EditText searchEditText; private final Runnable displayKeyboardRunnable = new Runnable() { @Override public void run() { showKeyboard(); } }; /** * Menu button */ private View menuButton; /** * Kiss bar */ private View kissBar; /** * Task launched on text change */ private Searcher searcher; /** * Called when the activity is first created. */ @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { // Initialize UI prefs = PreferenceManager.getDefaultSharedPreferences(this); String theme = prefs.getString("theme", "light"); if (theme.equals("dark")) { setTheme(R.style.AppThemeDark); } else if (theme.equals("transparent")) { setTheme(R.style.AppThemeTransparent); } else if (theme.equals("semi-transparent")) { setTheme(R.style.AppThemeSemiTransparent); } else if (theme.equals("semi-transparent-dark")) { setTheme(R.style.AppThemeSemiTransparentDark); } super.onCreate(savedInstanceState); IntentFilter intentFilter = new IntentFilter(START_LOAD); IntentFilter intentFilterBis = new IntentFilter(LOAD_OVER); IntentFilter intentFilterTer = new IntentFilter(FULL_LOAD_OVER); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(LOAD_OVER)) { updateRecords(searchEditText.getText().toString()); } else if (intent.getAction().equalsIgnoreCase(FULL_LOAD_OVER)) { displayLoader(false); } else if (intent.getAction().equalsIgnoreCase(START_LOAD)) { displayLoader(true); } } }; this.registerReceiver(mReceiver, intentFilter); this.registerReceiver(mReceiver, intentFilterBis); this.registerReceiver(mReceiver, intentFilterTer); KissApplication.initDataHandler(this); // Initialize preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, false); prefs = PreferenceManager.getDefaultSharedPreferences(this); // Lock launcher into portrait mode // Do it here (before initializing the view) to make the transition as smooth as possible if (prefs.getBoolean("force-portrait", true)) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } setContentView(R.layout.main); // Create adapter for records adapter = new RecordAdapter(this, this, R.layout.item_app, new ArrayList<Result>()); setListAdapter(adapter); searchEditText = (EditText) findViewById(R.id.searchEditText); // Listen to changes searchEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { // Auto left-trim text. if (s.length() > 0 && s.charAt(0) == ' ') s.delete(0, 1); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { updateRecords(s.toString()); displayClearOnInput(); } }); // On validate, launch first record searchEditText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { RecordAdapter adapter = ((RecordAdapter) getListView().getAdapter()); adapter.onClick(adapter.getCount() - 1, null); return true; } }); searchEditText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (prefs.getBoolean("history-hide", false) && prefs.getBoolean("history-onclick", false)) { //show history only if no search text is added if (((EditText) v).getText().toString().isEmpty()) { searcher = new HistorySearcher(MainActivity.this); searcher.execute(); } } } }); kissBar = findViewById(R.id.main_kissbar); menuButton = findViewById(R.id.menuButton); registerForContextMenu(menuButton); getListView().setLongClickable(true); getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) { ((RecordAdapter) parent.getAdapter()).onLongClick(pos, v); return true; } }); // Enable swiping if (prefs.getBoolean("enable-spellcheck", false)) { searchEditText.setInputType(spellcheckEnabledType); } // Hide the "X" after the text field, instead displaying the menu button displayClearOnInput(); // Apply effects depending on current Android version applyDesignTweaks(); } /** * Apply some tweaks to the design, depending on the current SDK version */ private void applyDesignTweaks() { final int[] tweakableIds = new int[]{ R.id.menuButton, // Barely visible on the clearbutton, since it disappears instant. Can be seen on long click though R.id.clearButton, R.id.launcherButton, R.id.favorite0, R.id.favorite1, R.id.favorite2, R.id.favorite3, }; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { TypedValue outValue = new TypedValue(); getTheme().resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true); for (int id : tweakableIds) { findViewById(id).setBackgroundResource(outValue.resourceId); } } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { TypedValue outValue = new TypedValue(); getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); for (int id : tweakableIds) { findViewById(id).setBackgroundResource(outValue.resourceId); } } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); adapter.onClick(position, v); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_settings, menu); } @Override public boolean onContextItemSelected(MenuItem item) { return onOptionsItemSelected(item); } /** * Empty text field on resume and show keyboard */ protected void onResume() { if (prefs.getBoolean("require-layout-update", false)) { // Restart current activity to refresh view, since some preferences // may require using a new UI prefs.edit().putBoolean("require-layout-update", false).commit(); Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION); finish(); overridePendingTransition(0, 0); startActivity(i); overridePendingTransition(0, 0); } if (kissBar.getVisibility() != View.VISIBLE) { updateRecords(searchEditText.getText().toString()); displayClearOnInput(); } else { displayKissBar(false); } // Activity manifest specifies stateAlwaysHidden as windowSoftInputMode // so the keyboard will be hidden by default // we may want to display it if the setting is set if (prefs.getBoolean("display-keyboard", false)) { // Display keyboard showKeyboard(); new Handler().postDelayed(displayKeyboardRunnable, 10); // For some weird reasons, keyboard may be hidden by the system // So we have to run this multiple time at different time new Handler().postDelayed(displayKeyboardRunnable, 100); new Handler().postDelayed(displayKeyboardRunnable, 500); } else { // Not used (thanks windowSoftInputMode) // unless coming back from KISS settings hideKeyboard(); } super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); // unregister our receiver this.unregisterReceiver(this.mReceiver); KissApplication.getCameraHandler().releaseCamera(); } @Override protected void onPause() { super.onPause(); KissApplication.getCameraHandler().releaseCamera(); } @Override protected void onNewIntent(Intent intent) { // Empty method, // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) } @Override public void onBackPressed() { // Is the kiss menu visible? if (menuButton.getVisibility() == View.VISIBLE) { displayKissBar(false); } else { // If no kissmenu, empty the search bar searchEditText.setText(""); } // No call to super.onBackPressed, since this would quit the launcher. } @Override public boolean onKeyDown(int keycode, @NonNull KeyEvent e) { switch (keycode) { case KeyEvent.KEYCODE_MENU: // For user with a physical menu button, we still want to display *our* contextual menu menuButton.showContextMenu(); return true; } return super.onKeyDown(keycode, e); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); return true; case R.id.wallpaper: hideKeyboard(); Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER); startActivity(Intent.createChooser(intent, getString(R.string.menu_wallpaper))); return true; case R.id.preferences: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_settings, menu); return true; } /** * Display menu, on short or long press. * * @param menuButton "kebab" menu (3 dots) */ public void onMenuButtonClicked(View menuButton) { // When the kiss bar is displayed, the button can still be clicked in a few areas (due to favorite margin) // To fix this, we discard any click event occurring when the kissbar is displayed if (kissBar.getVisibility() != View.VISIBLE) menuButton.showContextMenu(); } /** * Clear text content when touching the cross button */ @SuppressWarnings("UnusedParameters") public void onClearButtonClicked(View clearButton) { searchEditText.setText(""); } /** * Display KISS menu */ public void onLauncherButtonClicked(View launcherButton) { // Display or hide the kiss bar, according to current view tag (showMenu / hideMenu). displayKissBar(launcherButton.getTag().equals("showMenu")); } public void onFavoriteButtonClicked(View favorite) { // Favorites handling Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve) .get(Integer.parseInt((String) favorite.getTag())); final Result result = Result.fromPojo(MainActivity.this, pojo); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { result.fastLaunch(MainActivity.this); } }, KissApplication.TOUCH_DELAY); } private void displayClearOnInput() { final View clearButton = findViewById(R.id.clearButton); if (searchEditText.getText().length() > 0) { clearButton.setVisibility(View.VISIBLE); menuButton.setVisibility(View.INVISIBLE); } else { clearButton.setVisibility(View.INVISIBLE); menuButton.setVisibility(View.VISIBLE); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) private void displayLoader(Boolean display) { final View loaderBar = findViewById(R.id.loaderBar); final View launcherButton = findViewById(R.id.launcherButton); int animationDuration = getResources().getInteger( android.R.integer.config_longAnimTime); if (!display) { launcherButton.setVisibility(View.VISIBLE); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Animate transition from loader to launch button launcherButton.setAlpha(0); launcherButton.animate() .alpha(1f) .setDuration(animationDuration) .setListener(null); loaderBar.animate() .alpha(0f) .setDuration(animationDuration) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { loaderBar.setVisibility(View.GONE); loaderBar.setAlpha(1); } }); } else { loaderBar.setVisibility(View.GONE); } } else { launcherButton.setVisibility(View.INVISIBLE); loaderBar.setVisibility(View.VISIBLE); } } private void displayKissBar(Boolean display) { final ImageView launcherButton = (ImageView) findViewById(R.id.launcherButton); // get the center for the clipping circle int cx = (launcherButton.getLeft() + launcherButton.getRight()) / 2; int cy = (launcherButton.getTop() + launcherButton.getBottom()) / 2; // get the final radius for the clipping circle int finalRadius = Math.max(kissBar.getWidth(), kissBar.getHeight()); if (display) { // Display the app list if (searcher != null) { searcher.cancel(true); } searcher = new ApplicationsSearcher(MainActivity.this); searcher.execute(); // Reveal the bar if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, 0, finalRadius); kissBar.setVisibility(View.VISIBLE); anim.start(); } else { // No animation before Lollipop kissBar.setVisibility(View.VISIBLE); } // Retrieve favorites. Try to retrieve more, since some favorites can't be displayed (e.g. search queries) retrieveFavorites(); hideKeyboard(); } else { // Hide the bar if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, finalRadius, 0); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { kissBar.setVisibility(View.GONE); super.onAnimationEnd(animation); } }); anim.start(); } else { // No animation before Lollipop kissBar.setVisibility(View.GONE); } searchEditText.setText(""); } } public void retrieveFavorites() { ArrayList<Pojo> favoritesPojo = KissApplication.getDataHandler(MainActivity.this) .getFavorites(tryToRetrieve); if (favoritesPojo.size() == 0) { Toast toast = Toast.makeText(MainActivity.this, getString(R.string.no_favorites), Toast.LENGTH_SHORT); toast.show(); } // Don't look for items after favIds length, we won't be able to display them for (int i = 0; i < Math.min(favsIds.length, favoritesPojo.size()); i++) { Pojo pojo = favoritesPojo.get(i); ImageView image = (ImageView) findViewById(favsIds[i]); Result result = Result.fromPojo(MainActivity.this, pojo); Drawable drawable = result.getDrawable(MainActivity.this); if (drawable != null) image.setImageDrawable(drawable); image.setVisibility(View.VISIBLE); image.setContentDescription(pojo.displayName); } // Hide empty favorites (not enough favorites yet) for (int i = favoritesPojo.size(); i < favsIds.length; i++) { findViewById(favsIds[i]).setVisibility(View.GONE); } } /** * This function gets called on changes. It will ask all the providers for * data * * @param query the query on which to search */ private void updateRecords(String query) { if (searcher != null) { searcher.cancel(true); } if (query.length() == 0) { if (prefs.getBoolean("history-hide", false)) { searcher = new NullSearcher(this); //Hide default scrollview findViewById(R.id.main_empty).setVisibility(View.INVISIBLE); } else { searcher = new HistorySearcher(this); //Show default scrollview findViewById(R.id.main_empty).setVisibility(View.VISIBLE); } } else { searcher = new QuerySearcher(this, query); } searcher.execute(); } public void resetTask() { searcher = null; } /** * Call this function when we're leaving the activity We can't use * onPause(), since it may be called for a configuration change */ public void launchOccurred(int index, Result result) { // We selected an item on the list, // now we can cleanup the filter: if (!searchEditText.getText().toString().equals("")) { searchEditText.setText(""); hideKeyboard(); } } private void hideKeyboard() { // Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } private void showKeyboard() { searchEditText.requestFocus(); InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT); } public int getFavIconsSize() { return favsIds.length; } }
package me.newyith.fortress.command; import me.newyith.fortress.rune.generator.GeneratorRune; import me.newyith.fortress.main.FortressPlugin; import me.newyith.fortress.main.FortressesManager; import me.newyith.fortress.util.Cuboid; import me.newyith.fortress.util.Point; import me.newyith.fortress.util.Blocks; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.util.*; public class StuckPlayer { private Player player; private World world; private Point startPoint; private double maxHealthOnRecord; private long startTimestamp; private Map<Integer, String> messages; private final int distBeyondFortress = 10; //how far outside combinedCuboid to teleport private final int stuckDelayMs = FortressPlugin.config_stuckDelayMs; private final int cancelDistance = FortressPlugin.config_stuckCancelDistance; private Set<GeneratorRune> nearbyGeneratorRunes; public StuckPlayer(Player player) { this.player = player; this.world = player.getWorld(); this.startPoint = new Point(player.getLocation()); this.maxHealthOnRecord = player.getHealth(); this.startTimestamp = new Date().getTime(); this.messages = new HashMap<>(); int ms; ms = 1*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 2*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 3*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 4*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 5*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 10*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 15*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 30*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."); ms = 1*60*1000; this.messages.put(ms, "/stuck teleport in 1 minute."); for (int i = 2; i*60*1000 < this.stuckDelayMs; i++) { ms = i*60*1000; this.messages.put(ms, "/stuck teleport in " + String.valueOf(ms/(1000*60)) + " minutes."); } //remove messages that would be shown later than or at stuckDelayMs List<Integer> displayTimes = new ArrayList<>(this.messages.keySet()); for (int displayTime : displayTimes) { if (displayTime >= this.stuckDelayMs) { this.messages.remove(displayTime); } } nearbyGeneratorRunes = FortressesManager.forWorld(world).getGeneratorRunesNear(startPoint); } public void considerSendingMessage() { int remaining = this.getRemainingMs(); List<Integer> displayTimes = new ArrayList<>(this.messages.keySet()); Collections.sort(displayTimes); Collections.reverse(displayTimes); for (int displayTime : displayTimes) { if (remaining <= displayTime) { //time to display the message String msg = this.messages.get(displayTime); this.messages.remove(displayTime); sendMessage(msg); break; } } } public boolean considerCancelling() { boolean cancel = false; Point p = new Point(player.getLocation()); double changeInX = Math.abs(p.x() - startPoint.x()); double changeInY = Math.abs(p.y() - startPoint.y()); double changeInZ = Math.abs(p.z() - startPoint.z()); if (nearbyGeneratorRunes.size() == 0) { //player is too far from any fortress cancel = true; sendMessage("/stuck failed because you are too far from any fortress."); } if (changeInX > cancelDistance || changeInY > cancelDistance || changeInZ > cancelDistance) { //player moved too far away cancel = true; sendMessage("/stuck cancelled because you moved too far away."); } double health = this.player.getHealth(); if (health < this.maxHealthOnRecord) { //player took damage cancel = true; sendMessage("/stuck cancelled because you took damage."); } else if (health > this.maxHealthOnRecord) { //player healed this.maxHealthOnRecord = this.player.getHealth(); } return cancel; } public void sendStartMessage() { String msgLine1 = "/stuck will cancel if you move " + cancelDistance + "+ blocks away or take damage."; String msgLine2 = ""; int ms = this.stuckDelayMs; if (ms <= 5*1000) { //first natural message will be soon enough } else if (ms < 60*1000) { //less than a minute delay msgLine2 = "/stuck teleport in " + String.valueOf(ms/1000) + " seconds."; } else { msgLine2 = "/stuck teleport in " + String.valueOf(ms/(1000*60)) + " minutes."; } this.sendMessage(msgLine1); if (msgLine2.length() > 0) { this.sendMessage(msgLine2); } } public void sendBePatientMessage() { int remainingSeconds = this.getRemainingMs() / 1000; String msg = "/stuck teleport in " + String.valueOf(remainingSeconds) + " seconds... be patient."; this.sendMessage(msg); } private void sendMessage(String msg) { msg = ChatColor.AQUA + msg; player.sendMessage(msg); } public boolean isPlayer(Player otherPlayer) { return player.getPlayer().getUniqueId() == otherPlayer.getPlayer().getUniqueId(); } public boolean isDoneWaiting() { return this.getElapsedMs() > this.stuckDelayMs; } private int getElapsedMs() { long now = new Date().getTime(); int elapsed = (int) (now - this.startTimestamp); return elapsed; } private int getRemainingMs() { return this.stuckDelayMs - this.getElapsedMs(); } public void stuckTeleport() { boolean teleported = false; int attemptLimit = 50; List<Point> nearbyPoints = getRandomNearbyPoints(attemptLimit); for (Point p : nearbyPoints) { p = getValidTeleportDest(world, p); if (p != null) { p = p.add(0.5F, 0, 0.5F); teleportPlayer(player, p); teleported = true; break; } } if (!teleported) { //fallback to player's bed Location bedLoc = player.getBedSpawnLocation(); if (bedLoc != null) { player.teleport(bedLoc); teleported = true; } } if (!teleported) { this.sendMessage("/stuck failed because no suitable destination was found."); } } private List<Point> getRandomNearbyPoints(int limit) { List<Point> nearbyPoints = new ArrayList<>(); if (nearbyGeneratorRunes.size() > 0) { //set combinedCuboid (cuboid enclosing all nearby generators) List<Cuboid> runeCuboids = new ArrayList<>(); nearbyGeneratorRunes.stream().forEach(nearbyRune -> { runeCuboids.add(nearbyRune.getFortressCuboid()); }); Cuboid combinedCuboid = Cuboid.fromCuboids(runeCuboids, world); //set outerCuboid (same as combinedCuboid except distBeyondFortress bigger in all directions) Point outerMin = combinedCuboid.getMin().add(-1 * distBeyondFortress, -1 * distBeyondFortress, -1 * distBeyondFortress); Point outerMax = combinedCuboid.getMax().add(distBeyondFortress, distBeyondFortress, distBeyondFortress); Cuboid outerCuboid = new Cuboid(outerMin, outerMax, world); //set combinedSheet and outerSheet double y = combinedCuboid.getMax().y(); Set<Point> combinedSheet = combinedCuboid.getPointsAtHeight(y); Set<Point> outerSheet = outerCuboid.getPointsAtHeight(y); //set nearbyPoints nearbyPoints.addAll(outerSheet); nearbyPoints.removeAll(combinedSheet); Collections.shuffle(nearbyPoints); //nearbyPoints = first limit points in nearbyPoints nearbyPoints = new ArrayList<>(nearbyPoints.subList(0, Math.min(limit, nearbyPoints.size() - 1))); //creating new list allows garbage collection of old list } return nearbyPoints; } // static // private static void teleportPlayer(Player player, Point target) { World world = player.getWorld(); Location playerLoc = player.getLocation(); Location targetLoc = target.toLocation(world); targetLoc = faceLocationToward(targetLoc, playerLoc); player.teleport(targetLoc); } public static boolean teleport(Player player) { World world = player.getWorld(); Point playerPoint = new Point(player.getLocation()); int radius = 16; boolean teleported = false; int attemptLimit = 50; List<Point> nearbyPoints = getNearbyPoints(world, playerPoint, radius, attemptLimit); for (Point p : nearbyPoints) { p = getValidTeleportDest(world, p); if (p != null) { p = p.add(0.5F, 0, 0.5F); teleportPlayer(player, p); teleported = true; break; } } if (!teleported) { //fallback to player's bed Location bedLoc = player.getBedSpawnLocation(); if (bedLoc != null) { player.teleport(bedLoc); teleported = true; } } return teleported; } private static List<Point> getNearbyPoints(World world, Point center, int radius, int attemptLimit) { int r = radius; Point a = center.add(r, r, r); Point b = center.add(-1 * r, -1 * r, -1 * r); Cuboid cuboid = new Cuboid(a, b, world); List<Point> nearbyPoints = new ArrayList<>(cuboid.getPointsAtHeight(a.y())); Collections.shuffle(nearbyPoints); //nearbyPoints = first attemptLimit points in nearbyPoints nearbyPoints = new ArrayList<>(nearbyPoints.subList(0, Math.min(attemptLimit, nearbyPoints.size() - 1))); //creating new list allows garbage collection of old list return nearbyPoints; } private static Point getValidTeleportDest(World world, Point p) { Point validDest = null; if (p != null) { //p = highest non air block at p.x, p.z int maxHeight = world.getMaxHeight(); for (int y = maxHeight-2; y >= 0; y p = new Point(p.xInt(), y, p.zInt()); if (!Blocks.isAiry(p, world)) { //first non airy block break; } } //check if valid teleport destination if (p.getBlock(world).getType().isSolid()) { Point dest = p.add(0, 1, 0); Point aboveDest = dest.add(0, 2, 0); if (Blocks.isAiry(dest, world) && Blocks.isAiry(aboveDest, world)) { validDest = dest; } } } return validDest; } public static Location faceLocationToward(Location loc, Location lookat) { //Clone the loc to prevent applied changes to the input loc loc = loc.clone(); // Values of change in distance (make it relative) double dx = lookat.getX() - loc.getX(); double dy = lookat.getY() - loc.getY(); double dz = lookat.getZ() - loc.getZ(); // Set yaw if (dx != 0) { // Set yaw start value based on dx if (dx < 0) { loc.setYaw((float) (1.5 * Math.PI)); } else { loc.setYaw((float) (0.5 * Math.PI)); } loc.setYaw((float) loc.getYaw() - (float) Math.atan(dz / dx)); } else if (dz < 0) { loc.setYaw((float) Math.PI); } // Get the distance from dx/dz double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); // Set pitch loc.setPitch((float) -Math.atan(dy / dxz)); // Set values, convert to degrees (invert the yaw since Bukkit uses a different yaw dimension format) loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI); loc.setPitch(loc.getPitch() * 180f / (float) Math.PI); return loc; } }
package io.r_a_d.radio; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.support.v7.app.NotificationCompat; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.LoadControl; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.extractor.ExtractorsFactory; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; public class RadioService extends Service { private static final String ACTION_PLAY = "io.r_a_d.radio.PLAY"; private static final String ACTION_PAUSE = "io.r_a_d.radio.PAUSE"; private static final String ACTION_NPAUSE = "io.r_a_d.radio.NPAUSE"; private static final String ACTION_MUTE = "io.r_a_d.radio.MUTE"; private static final String ACTION_UNMUTE = "io.r_a_d.radio.UNMUTE"; private PowerManager powerManager; private PowerManager.WakeLock wakeLock; private WifiManager wifiManager; private WifiManager.WifiLock wifiLock; private SimpleExoPlayer sep; private Notification notification; private TelephonyManager mTelephonyManager; private AudioManager am; private MediaSessionCompat mMediaSession; private final PhoneStateListener mPhoneListener = new PhoneStateListener() { public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); if (state != TelephonyManager.CALL_STATE_IDLE) { mutePlayer(); } else { unmutePlayer(); } } }; private AudioManager.OnAudioFocusChangeListener focusChangeListener = new AudioManager.OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { switch (focusChange) { case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) : sep.setVolume(0.2f); break; case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) : mutePlayer(); break; case (AudioManager.AUDIOFOCUS_LOSS) : stopPlaying(); break; case (AudioManager.AUDIOFOCUS_GAIN) : unmutePlayer(); break; default: break; } } }; private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)/* || (action.equals(AudioManager.ACTION_HEADSET_PLUG) && (intent.getIntExtra("state", 0) == 0))*/) { Intent i = new Intent(context, RadioService.class); i.putExtra("action", "io.r_a_d.radio.PAUSE"); context.startService(i); } } }; private String radio_url = "https://stream.r-a-d.io/main.mp3"; public RadioService() { } @Override public void onCreate() { super.onCreate(); powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KilimDankLock"); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "KilimDankWifiLock"); createMediaPlayer(); am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); // This stuff is for the broadcast receiver IntentFilter filter = new IntentFilter(); // filter.addAction(AudioManager.ACTION_HEADSET_PLUG); filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(receiver, filter); // This stuff is for allowing bluetooth tags if (mMediaSession == null) { mMediaSession = new MediaSessionCompat(this, "RadioServiceMediaSession"); mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); mMediaSession.setActive(true); } } private void maybeUpdateBluetooth(String title, String artist, long duration, long position) { if (am.isBluetoothA2dpOn()) { MediaMetadataCompat metadata = new MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration) .build(); mMediaSession.setMetadata(metadata); PlaybackStateCompat state = new PlaybackStateCompat.Builder() .setActions(PlaybackStateCompat.ACTION_PLAY) .setState(PlaybackStateCompat.STATE_PLAYING, position, 1.0f, SystemClock.elapsedRealtime()) .build(); mMediaSession.setPlaybackState(state); } } public void mutePlayer() { sep.setVolume(0); } public void unmutePlayer() { sep.setVolume(1.0f); } public void setupMediaPlayer() { DataSource.Factory dsf = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "R/a/dio-Android-App")); ExtractorsFactory extractors = new DefaultExtractorsFactory(); MediaSource audioSource = new ExtractorMediaSource(Uri.parse(radio_url), dsf, extractors, null, null); sep.prepare(audioSource); } public void createNotification() { Intent notificationIntent = new Intent(this, ActivityMain.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); /*RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_layout); contentView.setImageViewResource(R.id.notification_image, R.drawable.normal_logo); contentView.setTextViewText(R.id.notification_title, "My custom notification title"); contentView.setTextViewText(R.id.notification_text, "My custom notification text"); builder.setContent(contentView);*/ builder.setContentTitle("R/a/dio is streaming"); builder.setContentText("Touch to return to app"); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setSmallIcon(R.drawable.lollipop_logo); builder.setColor(0xFFDF4C3A); } else { builder.setSmallIcon(R.drawable.normal_logo); } if ( android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } builder.setContentIntent(pendingIntent); Intent intent = new Intent(this, RadioService.class); NotificationCompat.Action action; if(PlayerState.CURRENTLY_PLAYING) { intent.putExtra("action", RadioService.ACTION_NPAUSE); PendingIntent pendingButtonIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); action = new NotificationCompat.Action.Builder(R.drawable.exo_controls_pause, "Pause", pendingButtonIntent).build(); } else { intent.putExtra("action", RadioService.ACTION_PLAY); PendingIntent pendingButtonIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); action = new NotificationCompat.Action.Builder(R.drawable.exo_controls_play, "Play", pendingButtonIntent).build(); } builder.addAction(action); notification = builder.build(); } public void beginPlaying() { int result = am.requestAudioFocus(focusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { PlayerState.CURRENTLY_PLAYING = true; createNotification(); setupMediaPlayer(); sep.setPlayWhenReady(true); acquireWakeLocks(); startForeground(1, notification); } } public void stopPlaying () { PlayerState.CURRENTLY_PLAYING = false; sep.stop(); releaseWakeLocks(); stopForeground(true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent == null || intent.getStringExtra("action") == null)return super.onStartCommand(intent, flags, startId); if (intent.getStringExtra("action").equals(ACTION_PLAY)) { beginPlaying(); } else if (intent.getStringExtra("action").equals(ACTION_PAUSE)){ stopPlaying(); } else if (intent.getStringExtra("action").equals(ACTION_NPAUSE)){ PlayerState.CURRENTLY_PLAYING = false; createNotification(); sep.stop(); releaseWakeLocks(); startForeground(1, notification); stopForeground(false); } else if (intent.getStringExtra("action").equals(ACTION_MUTE)){ mutePlayer(); } else if (intent.getStringExtra("action").equals(ACTION_UNMUTE)){ unmutePlayer(); } return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); sep.stop(); sep.release(); sep = null; releaseWakeLocks(); mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE); unregisterReceiver(receiver); mMediaSession.release(); } @Override public void onTaskRemoved(Intent rootIntent) { if(!PlayerState.CURRENTLY_PLAYING) { stopSelf(); } super.onTaskRemoved(rootIntent); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } public void acquireWakeLocks() { wakeLock.acquire(); wifiLock.acquire(); } public void releaseWakeLocks() { if(wakeLock.isHeld()) wakeLock.release(); if(wifiLock.isHeld()) wifiLock.release(); } public void createMediaPlayer() { TrackSelector tSelector = new DefaultTrackSelector(); LoadControl lc = new DefaultLoadControl(); sep = ExoPlayerFactory.newSimpleInstance(this, tSelector, lc); } }
package model.clustering; import model.ModelDatabase; import model.clustering.strategies.CompleteLinkageStrategy; import model.clustering.strategies.LinkageStrategy; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class HierarchicalClustering { private PreparedStatement stSimilaritiesCondensed; //The statement that retrieves all document vs document similarities as a condensed matrix private HashMap<String, Cluster> documents; //A HashMap that contains the document clusters, and indexed by their document names private LinkageStrategy linkageStrategy; //the strategy object that will be use to recalculate similarities public HierarchicalClustering(Connection connection) throws SQLException{ stSimilaritiesCondensed = connection.prepareStatement("SELECT i2.idDoc, SUM((i1.weight*i2.weight)/SQRT((SELECT SUM(i11.weight) FROM (SELECT weight FROM SPATIA.INVERTEDINDEX WHERE idDoc=?) i11)*(SELECT SUM(i22.weight) FROM SPATIA.INVERTEDINDEX i22 WHERE i2.idDoc=i22.idDoc))) as sim " + "FROM (SELECT term, weight FROM SPATIA.INVERTEDINDEX WHERE idDoc=?) AS i1, " + " SPATIA.INVERTEDINDEX i2 " + "WHERE i2.term=i1.term AND i2.idDoc>? " + "GROUP BY i2.idDoc " + "ORDER BY i2.idDoc"); //The default linkage strategy is the Complete linkage linkageStrategy = new CompleteLinkageStrategy(); } /** * Reads the database and extracts the similarities between every document in it * Saves the condensed matrix of similarities into an array * Starts the clustering if everything was correctly obtained from the database * @throws SQLException if there's a problem executing the stSimilaritiesCondensed query */ public void beginClustering() throws SQLException{ //Initialize arrays ArrayList<String> documentsList = new ArrayList<>(); ArrayList<Double> similarities = new ArrayList<>(); //Obtain the number of documents in the database int numDocs = ModelDatabase.instance().opDocuments.countDocuments(); //As we know we have consecutive document ids in the database from 1 to numDocs, obtain the data from every id until the number of documents for(int i=1; i<=numDocs; i++){ documentsList.add("D"+i); //Add the name of the document as "D"+id System.out.println("Processing document " + i); //Set the parameters for the query (AKA the document id) stSimilaritiesCondensed.setInt(1, i); stSimilaritiesCondensed.setInt(2, i); stSimilaritiesCondensed.setInt(3, i); ResultSet rs = stSimilaritiesCondensed.executeQuery(); int lastDoc = i; while (rs.next()) { double sim = rs.getDouble(2); //Get the similarity between the documents evaluated //Add the missing documents if they exist before the currently being added and the last added if(rs.getInt(1)!=(lastDoc+1)){ for(int k=lastDoc+1; k<rs.getInt(1); k++){ similarities.add(0.0); lastDoc++; } } //The last document added is the currently being added lastDoc++; similarities.add(sim); } //Add the missing documents if they exist after the ones added if(lastDoc!=numDocs){ for(int k=lastDoc+1; k<=numDocs; k++){ similarities.add(0.0); lastDoc++; } } } //Security checks before start clustering if(documentsList.size()==0){ //If we don't have documents, don't cluster JOptionPane.showMessageDialog(null, "The are no documents"); } else if(similarities.size()==0){ //If we don't have similarities, we cannot cluster JOptionPane.showMessageDialog(null, "The are no similarities in the matrix"); } else if(similarities.size() != documentsList.size()*(documentsList.size()-1)/2){ //If we dont have enough similarities for the number of documents, we cannot cluster JOptionPane.showMessageDialog(null, "The similarities array doesn't have the expected size for the number of documents"); } else { //We execute the clustering if all checks have passed performClustering(similarities, documentsList); } } /** * Initialize the creation of the clusters * @param similarities a condensed matrix containing the similarities between documents * @param documentNames an array containing the document names * @return the root of the cluster hierarchy */ private void performClustering(ArrayList<Double> similarities, ArrayList<String> documentNames) { //We must ensure the existence of a linkage strategy if (linkageStrategy == null) { JOptionPane.showMessageDialog(null, "Undefined linkage strategy"); return; } documents = new HashMap<>(); //Initialize the documents HashMap List<Cluster> clusters = beginClustering(documentNames); //Create the base clusters based on the documents array SimilarityMap linkages = createLinkages(similarities, clusters); //Create the first links between clusters using the similarity condensed matrix //Give the hierarchy builder the initial clusters with the similarity map HierarchyBuilder builder = new HierarchyBuilder(clusters, linkages); //While there is more than one cluster, keep making clusters while (!builder.isTreeComplete()) { builder.agglomerate(linkageStrategy); } System.out.println(); printChildrens(builder.getRootCluster(), null); } /** * Creates the similarity map based on the given similarities condensed matrix * @param similarities the similarities condensed matrix * @param clusters the list of initial clusters that have their similarities in the previous matrix * @return the built similarity map */ private SimilarityMap createLinkages(ArrayList<Double> similarities, List<Cluster> clusters) { SimilarityMap linkages = new SimilarityMap(); for (int col = 0; col < clusters.size(); col++) { Cluster cluster_col = clusters.get(col); for (int row = col + 1; row < clusters.size(); row++) { ClusterPair link = new ClusterPair(); Double d = similarities.get(accessFunction(row, col, clusters.size())); link.setLinkSimilarity(d); link.setlCluster(cluster_col); link.setrCluster(clusters.get(row)); linkages.add(link); } } return linkages; } /** * Create the initial clusters array based on the document names * @param clusterNames the names of the documents * @return the array containing the created clusters */ private ArrayList<Cluster> beginClustering(ArrayList<String> clusterNames) { ArrayList<Cluster> clusters = new ArrayList<>(); for (String clusterName : clusterNames) { Cluster cluster = new Cluster(clusterName); clusters.add(cluster); documents.put(clusterName, cluster); } return clusters; } /** * A method to convert from normal matrix coordinates to the position in a condensed matrix on an array * @param i the row of the matrix * @param j the column of the matrix * @param n the N of an NxN matrix * @return the position of the element in the condensed matrix array */ private int accessFunction(int i, int j, int n) { return n*j - j*(j+1)/2 + i-1-j; } /** * Recursively prints the clusters and their children on the console * @param cluster the cluster currently being printed * @param parent the parent of the cluster */ private void printChildrens(Cluster cluster, Cluster parent){ if(parent!=null) System.out.println( "Child of " + parent.getCode() + ", name: " + cluster.getCode()); else System.out.println("Name: " + cluster.getCode() + " (root)"); if(cluster.isLeaf()){ return; } if(cluster.getLeftChild()!=null){ printChildrens(cluster.getLeftChild(), cluster); } if(cluster.getRightChild()!=null){ printChildrens(cluster.getRightChild(), cluster); } } /** * A method to get the corresponding CLuster for a document ID * @param id the document ID * @return the Cluster that corresponds to the searched document */ public Cluster getDocumentCluster(int id){ return documents.get("D"+id); } /** * Linkage strategy setter */ public void setLinkageStrategy(LinkageStrategy linkageStrategy) { this.linkageStrategy = linkageStrategy; } }
package io.xjhub.samplecontacts; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; final class Api { // Prevents accidentally instantiating this class private Api() {} static final String URL = "https://inloop-contacts.appspot.com/_ah/api"; static final String CONTACT_ENDPOINT = "/contactendpoint/v1/"; static final String ORDER_ENDPOINT = "/orderendpoint/v1/"; static class ContactWrapper { final List<Contact> items; public ContactWrapper(List<Contact> items) { this.items = items; } } static class Contact { final Long id; final String name; final String phone; final String pictureUrl; final String kind; public Contact(Long id, String name, String phone, String pictureUrl, String kind) { this.id = id; this.name = name; this.phone = phone; this.pictureUrl = pictureUrl; this.kind = kind; } public Contact(String name, String phone) { this.id = null; this.name = name; this.phone = phone; this.pictureUrl = null; this.kind = null; } } static class OrderWrapper { final List<Order> items; public OrderWrapper(List<Order> items) { this.items = items; } } static class Order { final String name; final int count; final String kind; public Order(String name, int count, String kind) { this.name = name; this.count = count; this.kind = kind; } } interface ContactService { @GET("contact") Call<ContactWrapper> listContacts(); @POST("contact") Call<Contact> createContact(@Body Contact contact); @GET("order/{id}") Call<OrderWrapper> listOrders(@Path("id") long contactId); } }
package mousio.etcd4j.transport; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.util.concurrent.DefaultPromise; import mousio.etcd4j.promises.EtcdResponsePromise; import mousio.etcd4j.requests.EtcdKeyRequest; import mousio.etcd4j.requests.EtcdRequest; import mousio.etcd4j.requests.EtcdVersionRequest; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.util.Map; /** * Netty client for the requests and responses */ public class EtcdNettyClient implements EtcdClientImpl { private final Bootstrap bootstrap; private final NioEventLoopGroup eventLoopGroup; private final URI[] uris; protected int lastWorkingUriIndex = 0; /** * Constructor * * @param sslContext SSL context if connecting with SSL. Null if not connecting with SSL. * @param uri to connect to */ public EtcdNettyClient(SslContext sslContext, URI... uri) { this.eventLoopGroup = new NioEventLoopGroup(); this.uris = uri; // Configure the client. this.bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 300) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslContext != null) { p.addLast(sslContext.newHandler(ch.alloc())); } p.addLast("codec", new HttpClientCodec()); p.addLast("aggregate", new HttpObjectAggregator(1024 * 100)); } }); } /** * Send a request and get a future. * * @param etcdRequest Etcd Request to send * @return Promise for the request. */ public <R> EtcdResponsePromise<R> send(EtcdRequest<R> etcdRequest) throws IOException { if (etcdRequest.getPromise() == null) { EtcdResponsePromise<R> responsePromise = new EtcdResponsePromise<>(); etcdRequest.setPromise(responsePromise); } connect(etcdRequest); return etcdRequest.getPromise(); } /** * Connect * * @param request to connect with * @param <R> Type of response * @throws IOException if connection fails */ public <R> void connect(EtcdRequest<R> request) throws IOException { connect(request, request.getUri()); } /** * Connect * * @param request to request with * @param url relative url to read resource at * @param <R> Type of response * @throws IOException if request could not be sent. */ public <R> void connect(EtcdRequest<R> request, String url) throws IOException { final ConnectionCounter counter = new ConnectionCounter(); counter.uriIndex = lastWorkingUriIndex; connect(request, counter, url); } /** * Connect to server * * @param etcdRequest to request with * @param counter for retries * @param url relative url to read resource at * @param <R> Type of response * @throws IOException if request could not be sent. */ protected <R> void connect(EtcdRequest<R> etcdRequest, ConnectionCounter counter, String url) throws IOException { // Start the connection attempt. ChannelFuture connectFuture = bootstrap.clone() .connect(uris[counter.uriIndex].getHost(), uris[counter.uriIndex].getPort()); Channel channel = connectFuture.channel(); etcdRequest.getPromise().attachNettyPromise( new DefaultPromise<>(connectFuture.channel().eventLoop()) ); connectFuture.addListener((ChannelFuture f) -> { if (!f.isSuccess()) { counter.uriIndex++; if (counter.uriIndex >= uris.length) { if (counter.retryCount >= 3) { etcdRequest.getPromise().getNettyPromise().setFailure(f.cause()); return; } counter.retryCount++; counter.uriIndex = 0; } connect(etcdRequest, counter, url); return; } lastWorkingUriIndex = counter.uriIndex; modifyPipeLine(etcdRequest, f.channel().pipeline()); HttpRequest httpRequest = createHttpRequest(url, etcdRequest); // send request channel.writeAndFlush(httpRequest); }); } /** * Modify the pipeline for the request * * @param req to process * @param pipeline to modify * @param <R> Type of Response */ @SuppressWarnings("unchecked") private <R> void modifyPipeLine(EtcdRequest<R> req, ChannelPipeline pipeline) { if (req.getTimeout() != -1) { pipeline.addFirst(new ReadTimeoutHandler(req.getTimeout(), req.getTimeoutUnit())); } if (req instanceof EtcdKeyRequest) { pipeline.addLast( new EtcdKeyResponseHandler(this, (EtcdKeyRequest) req) ); } else if (req instanceof EtcdVersionRequest) { pipeline.addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { (((EtcdVersionRequest) req).getPromise()).getNettyPromise() .setSuccess( msg.content().toString(Charset.defaultCharset())); } }); } else { throw new RuntimeException("Unknown request type " + req.getClass().getName()); } pipeline.addLast(new ChannelHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { req.getPromise().getNettyPromise().setFailure(cause); } }); } /** * Get HttpRequest belonging to etcdRequest * * @param uri to send request to * @param etcdRequest to send * @param <R> Response type * @return HttpRequest * @throws IOException if request could not be created */ public static <R> HttpRequest createHttpRequest(String uri, EtcdRequest<R> etcdRequest) throws IOException { HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, etcdRequest.getMethod(), uri); httpRequest.headers().add("Connection", "keep-alive"); try { httpRequest = setRequestParameters(etcdRequest, httpRequest); } catch (Exception e) { throw new IOException(e); } return httpRequest; } /** * Set parameters on request * * @param etcdRequest to send * @param httpRequest to send * @return Http Request * @throws Exception on fail */ private static HttpRequest setRequestParameters(EtcdRequest<?> etcdRequest, HttpRequest httpRequest) throws Exception { // Set possible key value pairs Map<String, String> keyValuePairs = etcdRequest.getRequestParams(); if (keyValuePairs != null && !keyValuePairs.isEmpty()) { if (etcdRequest.getMethod() == HttpMethod.POST) { HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(httpRequest, false); for (Map.Entry<String, String> entry : keyValuePairs.entrySet()) { bodyRequestEncoder.addBodyAttribute(entry.getKey(), entry.getValue()); } httpRequest = bodyRequestEncoder.finalizeRequest(); bodyRequestEncoder.close(); } else { String getLocation = ""; for (Map.Entry<String, String> entry : keyValuePairs.entrySet()) { if (!getLocation.isEmpty()) { getLocation += "&"; } getLocation += entry.getKey() + "=" + entry.getValue(); } httpRequest.setUri(etcdRequest.getUri().concat("?").concat(getLocation)); } } return httpRequest; } /** * Close netty */ public void close() { eventLoopGroup.shutdownGracefully(); } /** * Counts connection retries and current connection index */ protected class ConnectionCounter { public int uriIndex; public int retryCount; } }
package net.aeronica.mods.mxtune.util; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; public class ModLogger { private static Logger logger; public static void setLogger(Logger logger) { if (ModLogger.logger != null) { throw new IllegalStateException("Attempt to replace logger"); } ModLogger.logger = logger; } public static void log(Level level, String format, Object... data) { logger.printf(level, format, data); } public static void info(String format, Object... data){ log(Level.INFO, format, data); } public static void debug(String format, Object... data){ log(Level.DEBUG, format, data); } public static void warning(String format, Object... data){ log(Level.WARN, format, data); } public static void error(String format, Object... data){ log(Level.ERROR, format, data); } public static void fatal(String format, Object... data){ log(Level.FATAL, format, data); } public static <T extends Exception> void error(T e) { logger.error(e.getStackTrace()); } }
package net.doubledoordev.torchtools; import cpw.mods.fml.client.config.IConfigElement; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.doubledoordev.d3core.D3Core; import net.doubledoordev.d3core.util.ID3Mod; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.network.play.server.S2FPacketSetSlot; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import org.apache.logging.log4j.Logger; import java.util.List; import static net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK; /** * Main mod file * * Thanks for the idea Tinkers Construct * * @author Dries007 * @author DoubleDoorDevelopment */ @Mod(modid = TorchTools.MODID, name = TorchTools.MODID) public class TorchTools implements ID3Mod { public static final String MODID = "TorchTools"; @Mod.Instance(MODID) public static TorchTools instance; private Logger logger; private int[] slots = {8, 2, 3, 4, 5, 6, 7, 8, -1}; private Configuration configuration; private boolean disableTE = true; public TorchTools() { MinecraftForge.EVENT_BUS.register(this); } @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); configuration = new Configuration(event.getSuggestedConfigurationFile()); syncConfig(); } /** * This method is the mod. Everything else is extra */ @SubscribeEvent public void playerInteractEventHandler(PlayerInteractEvent event) { // Server side and on block only. if (event.isCanceled() || event.world.isRemote || event.action != RIGHT_CLICK_BLOCK) return; ItemStack heldItem = event.entityPlayer.inventory.getCurrentItem(); // Only tools, not null if (heldItem == null || !(heldItem.getItem() instanceof ItemTool)) return; // disableTE code if (disableTE && event.world.getTileEntity(event.x, event.y, event.z) != null) return; // Save old slot id int oldSlot = event.entityPlayer.inventory.currentItem; // Avoid invalid array indexes if (oldSlot < 0 || oldSlot > 8) return; // Get the new slot id int newSlot = slots[oldSlot]; // Avoid invalid slots indexes if (newSlot < 0 || newSlot > 8) return; // Get new item ItemStack slotStack = event.entityPlayer.inventory.getStackInSlot(newSlot); // No null please if (slotStack == null) return; // Set current slot to new slot to fool Minecraft event.entityPlayer.inventory.currentItem = newSlot; // Debug info if (D3Core.debug()) logger.info("Player: " + event.entityPlayer.getDisplayName() + "\tOldSlot: " + oldSlot + "\tOldStack: " + slotStack); // Fake right click Oh look fake values :p boolean b = ((EntityPlayerMP) event.entityPlayer).theItemInWorldManager.activateBlockOrUseItem(event.entityPlayer, event.world, slotStack, event.x, event.y, event.z, event.face, 0.5f, 0.5f, 0.5f); // Remove empty stacks if (slotStack.stackSize <= 0) slotStack = null; // Debug info if (D3Core.debug()) logger.info("Player: " + event.entityPlayer.getDisplayName() + "\tNewSlot: " + newSlot + "\tNewStack: " + slotStack + "\tResult: " + b); // Set old slot back properly event.entityPlayer.inventory.currentItem = oldSlot; // Update client event.entityPlayer.inventory.setInventorySlotContents(newSlot, slotStack); ((EntityPlayerMP) event.entityPlayer).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(0, newSlot + 36, slotStack)); // Prevent derpy doors event.setCanceled(true); } @Override public void syncConfig() { disableTE = configuration.getBoolean("disableTE", MODID.toLowerCase(), disableTE, "This prevents the place effect from occurring when you are right clicking on a tileentity. Use for dupe glitches."); if (configuration.hasChanged()) configuration.save(); } @Override public void addConfigElements(List<IConfigElement> configElements) { configElements.add(new ConfigElement(configuration.getCategory(MODID.toLowerCase()))); } }
package net.iponweb.disthene.reader.graph; import net.iponweb.disthene.reader.beans.TimeSeries; import net.iponweb.disthene.reader.beans.TimeSeriesOption; import net.iponweb.disthene.reader.exceptions.LogarithmicScaleNotAllowed; import net.iponweb.disthene.reader.handler.parameters.ImageParameters; import net.iponweb.disthene.reader.handler.parameters.RenderParameters; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.Seconds; import org.joda.time.format.DateTimeFormat; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.*; import java.util.List; /** * @author Andrei Ivanov * <p/> * This class and those below in hierarchy are pure translations from graphite-web Python code. * This will probably changed some day. But for now reverse engineering the logic is too comaplicated. */ public abstract class Graph { final static Logger logger = Logger.getLogger(Graph.class); private static final double[] PRETTY_VALUES = {0.1, 0.2, 0.25, 0.5, 1.0, 1.2, 1.25, 1.5, 2.0, 2.25, 2.5}; protected ImageParameters imageParameters; protected RenderParameters renderParameters; protected List<DecoratedTimeSeries> data = new ArrayList<>(); protected List<DecoratedTimeSeries> dataLeft = new ArrayList<>(); protected List<DecoratedTimeSeries> dataRight = new ArrayList<>(); protected boolean secondYAxis = false; protected int xMin; protected int xMax; protected int yMin; protected int yMax; protected int graphWidth; protected int graphHeight; protected long startTime = Long.MAX_VALUE; protected long endTime = Long.MIN_VALUE; protected DateTime startDateTime; protected DateTime endDateTime; protected double yStep; protected double yBottom; protected double yTop; protected double ySpan; protected double yScaleFactor; protected double yStepL; protected double yStepR; protected double yBottomL; protected double yBottomR; protected double yTopL; protected double yTopR; protected double ySpanL; protected double ySpanR; protected double yScaleFactorL; protected double yScaleFactorR; protected List<Double> yLabelValues; protected List<String> yLabels; protected int yLabelWidth; protected List<Double> yLabelValuesL; protected List<Double> yLabelValuesR; protected List<String> yLabelsL; protected List<String> yLabelsR; protected int yLabelWidthL; protected int yLabelWidthR; protected double xScaleFactor; protected XAxisConfig xAxisConfig; protected long xLabelStep; protected long xMinorGridStep; protected long xMajorGridStep; protected BufferedImage image; protected Graphics2D g2d; public Graph(RenderParameters renderParameters, List<TimeSeries> data) { this.renderParameters = renderParameters; this.imageParameters = renderParameters.getImageParameters(); for (TimeSeries ts : data) { this.data.add(new DecoratedTimeSeries(ts)); } xMin = imageParameters.getMargin() + 10; xMax = imageParameters.getWidth() - imageParameters.getMargin(); yMin = imageParameters.getMargin(); yMax = imageParameters.getHeight() - imageParameters.getMargin(); image = new BufferedImage(imageParameters.getWidth(), imageParameters.getHeight(), BufferedImage.TYPE_INT_ARGB); g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g2d.setPaint(imageParameters.getBackgroundColor()); g2d.fillRect(0, 0, imageParameters.getWidth(), imageParameters.getHeight()); } public abstract byte[] drawGraph() throws LogarithmicScaleNotAllowed; protected byte[] getBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); return baos.toByteArray(); } catch (IOException e) { logger.error(e); return new byte[0]; } } protected void drawText(int x, int y, String text, HorizontalAlign horizontalAlign, VerticalAlign verticalAlign) { drawText(x, y, text, imageParameters.getFont(), imageParameters.getForegroundColor(), horizontalAlign, verticalAlign, 0); } protected void drawText(int x, int y, String text, Font font, Color color, HorizontalAlign horizontalAlign, VerticalAlign verticalAlign) { drawText(x, y, text, font, color, horizontalAlign, verticalAlign, 0); } protected void drawText(int x, int y, String text, Font font, Color color, HorizontalAlign horizontalAlign, VerticalAlign verticalAlign, int rotate) { g2d.setPaint(color); g2d.setFont(font); FontMetrics fontMetrics = g2d.getFontMetrics(font); int textWidth = fontMetrics.stringWidth(text); int horizontal, vertical; switch (horizontalAlign) { case RIGHT: horizontal = textWidth; break; case CENTER: horizontal = textWidth / 2; break; default: horizontal = 0; break; } switch (verticalAlign) { case MIDDLE: vertical = fontMetrics.getHeight() / 2 - fontMetrics.getDescent(); break; case BOTTOM: vertical = -fontMetrics.getDescent(); break; case BASELINE: vertical = 0; break; default: vertical = fontMetrics.getAscent(); } double angle = Math.toRadians(rotate); AffineTransform orig = g2d.getTransform(); g2d.rotate(angle, x, y); g2d.drawString(text, x - horizontal, y + vertical); g2d.setTransform(orig); } protected void drawTitle() { int y = yMin; int x = imageParameters.getWidth() / 2; Font font = new Font(imageParameters.getFont().getName(), imageParameters.getFont().getStyle(), (int) (imageParameters.getFont().getSize() + Math.log(imageParameters.getFont().getSize()))); FontMetrics fontMetrics = g2d.getFontMetrics(font); int lineHeight = fontMetrics.getHeight(); String[] split = imageParameters.getTitle().split("\n"); for (String line : split) { drawText(x, y, line, font, imageParameters.getForegroundColor(), HorizontalAlign.CENTER, VerticalAlign.TOP); y += lineHeight; } if (imageParameters.getyAxisSide().equals(ImageParameters.Side.RIGHT)) { yMin = y; } else { yMin = y + imageParameters.getMargin(); } } protected void drawLegend(List<String> legends, List<Color> colors, List<Boolean> secondYAxes, boolean uniqueLegend) { // remove duplicate names List<String> legendsUnique = new ArrayList<>(); List<Color> colorsUnique = new ArrayList<>(); List<Boolean> secondYAxesUnique = new ArrayList<>(); if (uniqueLegend) { for (int i = 0; i < legends.size(); i++) { if (!legendsUnique.contains(legends.get(i))) { legendsUnique.add(legends.get(i)); colorsUnique.add(colors.get(i)); secondYAxesUnique.add(secondYAxes.get(i)); } } legends = legendsUnique; colors = colorsUnique; secondYAxes = secondYAxesUnique; } FontMetrics fontMetrics = g2d.getFontMetrics(imageParameters.getFont()); // Check if there's enough room to use two columns boolean rightSideLabels = false; int padding = 5; String longestLegend = Collections.max(legends, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } }); // Double it to check if there's enough room for 2 columns String testSizeName = longestLegend + " " + longestLegend; int testBoxSize = fontMetrics.getHeight() - 1; int testWidth = fontMetrics.stringWidth(testSizeName) + 2 * (testBoxSize + padding); if (testWidth + 50 < imageParameters.getWidth()) { rightSideLabels = true; } if (secondYAxis && rightSideLabels) { int boxSize = fontMetrics.getHeight() - 1; int lineHeight = fontMetrics.getHeight() + 1; int labelWidth = fontMetrics.stringWidth(longestLegend) + 2 * (boxSize + padding); int columns = (int) Math.max(1, Math.floor((imageParameters.getWidth() - xMin) / labelWidth)); if (columns < 1) columns = 1; int numRight = 0; for (Boolean b : secondYAxes) { if (b) numRight++; } int numberOfLines = Math.max(legends.size() - numRight, numRight); columns = (int) Math.floor(columns / 2.0); int legendHeight = Math.max(1, (numberOfLines / columns)) * (lineHeight + padding); yMax -= legendHeight; int x = xMin; int y = yMax + 2 * padding; int n = 0; int xRight = xMax - xMin; int yRight = y; int nRight = 0; for (int i = 0; i < legends.size(); i++) { g2d.setPaint(colors.get(i)); if (secondYAxes.get(i)) { nRight++; g2d.fillRect(xRight - padding, yRight, boxSize, boxSize); g2d.setPaint(ColorTable.DARK_GRAY); g2d.drawRect(xRight - padding, yRight, boxSize, boxSize); drawText(xRight - boxSize, yRight, legends.get(i), imageParameters.getFont(), imageParameters.getForegroundColor(), HorizontalAlign.RIGHT, VerticalAlign.TOP); xRight -= labelWidth; if (nRight % columns == 0) { xRight = xMax - xMin; yRight += lineHeight; } } else { n++; g2d.fillRect(x, y, boxSize, boxSize); g2d.setPaint(ColorTable.DARK_GRAY); g2d.drawRect(x, y, boxSize, boxSize); drawText(x + boxSize + padding, y, legends.get(i), imageParameters.getFont(), imageParameters.getForegroundColor(), HorizontalAlign.LEFT, VerticalAlign.TOP); x += labelWidth; if (n % columns == 0) { x = xMin; y += lineHeight; } } } } else { int boxSize = fontMetrics.getHeight() - 1; int lineHeight = fontMetrics.getHeight() + 1; int labelWidth = fontMetrics.stringWidth(longestLegend) + 2 * (boxSize + padding); int columns = (int) Math.floor(imageParameters.getWidth() / labelWidth); if (columns < 1) columns = 1; int numberOfLines = (int) Math.ceil((double) legends.size() / columns); int legendHeight = numberOfLines * (lineHeight + padding); yMax -= legendHeight; g2d.setStroke(new BasicStroke(1f)); int x = xMin; int y = yMax + (2 * padding); for (int i = 0; i < legends.size(); i++) { if (secondYAxes.get(i)) { g2d.setPaint(colors.get(i)); g2d.fillRect(x + labelWidth + padding, y, boxSize, boxSize); g2d.setPaint(ColorTable.DARK_GRAY); g2d.drawRect(x + labelWidth + padding, y, boxSize, boxSize); drawText(x + labelWidth, y, legends.get(i), imageParameters.getFont(), imageParameters.getForegroundColor(), HorizontalAlign.RIGHT, VerticalAlign.TOP); x += labelWidth; } else { g2d.setPaint(colors.get(i)); g2d.fillRect(x, y, boxSize, boxSize); g2d.setPaint(ColorTable.DARK_GRAY); g2d.drawRect(x, y, boxSize, boxSize); drawText(x + boxSize + padding, y, legends.get(i), imageParameters.getFont(), imageParameters.getForegroundColor(), HorizontalAlign.LEFT, VerticalAlign.TOP); x += labelWidth; } if ((i + 1) % columns == 0) { x = xMin; y += lineHeight; } } } } protected void consolidateDataPoints() { int numberOfPixels = (int) (xMax - xMin - imageParameters.getLineWidth() - 1); graphWidth = (int) (xMax - xMin - imageParameters.getLineWidth() - 1); for (DecoratedTimeSeries ts : data) { double numberOfDataPoints = ts.getValues().length; double divisor = ts.getValues().length; double bestXStep = numberOfPixels / divisor; if (bestXStep < imageParameters.getMinXStep()) { int drawableDataPoints = numberOfPixels / imageParameters.getMinXStep(); double pointsPerPixel = Math.ceil(numberOfDataPoints / drawableDataPoints); ts.setValuesPerPoint((int) pointsPerPixel); ts.setxStep((numberOfPixels * pointsPerPixel) / numberOfDataPoints); } else { ts.setxStep(bestXStep); } } } protected void setupTwoYAxes() throws LogarithmicScaleNotAllowed { List<DecoratedTimeSeries> seriesWithMissingValuesL = new ArrayList<>(); List<DecoratedTimeSeries> seriesWithMissingValuesR = new ArrayList<>(); for (DecoratedTimeSeries ts : dataLeft) { for (Double value : ts.getValues()) { if (value == null) { seriesWithMissingValuesL.add(ts); break; } } } for (DecoratedTimeSeries ts : dataRight) { for (Double value : ts.getValues()) { if (value == null) { seriesWithMissingValuesR.add(ts); break; } } } double yMinValueL = Double.POSITIVE_INFINITY; double yMinValueR = Double.POSITIVE_INFINITY; double yMaxValueL; double yMaxValueR; if (imageParameters.isDrawNullAsZero() && seriesWithMissingValuesL.size() > 0) { yMinValueL = 0; } else { for (DecoratedTimeSeries ts : dataLeft) { if (!ts.hasOption(TimeSeriesOption.DRAW_AS_INFINITE)) { double mm = GraphUtils.safeMin(ts); yMinValueL = mm < yMinValueL ? mm : yMinValueL; } } } if (imageParameters.isDrawNullAsZero() && seriesWithMissingValuesR.size() > 0) { yMinValueR = 0; } else { for (DecoratedTimeSeries ts : dataRight) { if (!ts.hasOption(TimeSeriesOption.DRAW_AS_INFINITE)) { double mm = GraphUtils.safeMin(ts); yMinValueR = mm < yMinValueR ? mm : yMinValueR; } } } yMaxValueL = GraphUtils.safeMax(dataLeft); yMaxValueR = GraphUtils.safeMax(dataRight); /* if (getStackedData(dataLeft).size() > 0) { yMaxValueL = GraphUtils.maxSum(dataLeft); } else { yMaxValueL = GraphUtils.safeMax(dataLeft); } */ /* if (getStackedData(dataRight).size() > 0) { yMaxValueR = GraphUtils.maxSum(dataRight); } else { yMaxValueR = GraphUtils.safeMax(dataRight); } */ if (yMinValueL == Double.POSITIVE_INFINITY) { yMinValueL = 0.0; } if (yMinValueR == Double.POSITIVE_INFINITY) { yMinValueR = 0.0; } if (imageParameters.getyMaxLeft() < Double.POSITIVE_INFINITY) { yMaxValueL = imageParameters.getyMaxLeft(); } if (imageParameters.getyMaxRight() < Double.POSITIVE_INFINITY) { yMaxValueR = imageParameters.getyMaxRight(); } if (imageParameters.getyMinLeft() > Double.NEGATIVE_INFINITY) { yMinValueL = imageParameters.getyMinLeft(); } if (imageParameters.getyMinRight() > Double.NEGATIVE_INFINITY) { yMinValueR = imageParameters.getyMinRight(); } if (yMaxValueL <= yMinValueL) { yMaxValueL = yMinValueL + 1; } if (yMaxValueR <= yMinValueR) { yMaxValueR = yMinValueR + 1; } double yVarianceL = yMaxValueL - yMinValueL; double yVarianceR = yMaxValueR - yMinValueR; double orderL = Math.log10(yVarianceL); double orderR = Math.log10(yVarianceR); double orderFactorL = Math.pow(10, Math.floor(orderL)); double orderFactorR = Math.pow(10, Math.floor(orderR)); double vL = yVarianceL / orderFactorL; double vR = yVarianceR / orderFactorR; double distance = Double.POSITIVE_INFINITY; double prettyValueL = PRETTY_VALUES[0]; double prettyValueR = PRETTY_VALUES[0]; for (int i = 0; i < imageParameters.getyDivisors().size(); i++) { double q = vL / imageParameters.getyDivisors().get(i); double p = GraphUtils.closest(q, PRETTY_VALUES); if (Math.abs(q - p) < distance) { distance = Math.abs(q - p); prettyValueL = p; } } distance = Double.POSITIVE_INFINITY; for (int i = 0; i < imageParameters.getyDivisors().size(); i++) { double q = vR / imageParameters.getyDivisors().get(i); double p = GraphUtils.closest(q, PRETTY_VALUES); if (Math.abs(q - p) < distance) { distance = Math.abs(q - p); prettyValueR = p; } } yStepL = prettyValueL * orderFactorL; yStepR = prettyValueR * orderFactorR; if (imageParameters.getyStepLeft() < Double.POSITIVE_INFINITY) { yStepL = imageParameters.getyStepLeft(); } if (imageParameters.getyStepRight() < Double.POSITIVE_INFINITY) { yStepR = imageParameters.getyStepRight(); } yBottomL = yStepL * Math.floor(yMinValueL / yStepL); yBottomR = yStepR * Math.floor(yMinValueR / yStepR); yTopL = yStepL * Math.ceil(yMaxValueL / yStepL); yTopR = yStepR * Math.ceil(yMaxValueR / yStepR); if (imageParameters.getLogBase() != 0 && yMaxValueL > 0) { yBottomL = Math.pow(imageParameters.getLogBase(), Math.floor(Math.log(yMinValueL) / Math.log(imageParameters.getLogBase()))); yTopL = Math.pow(imageParameters.getLogBase(), Math.ceil(Math.log(yMaxValueL) / Math.log(imageParameters.getLogBase()))); } else if (imageParameters.getLogBase() != 0 && yMinValueL <= 0) { throw new LogarithmicScaleNotAllowed("Logarithmic scale specified with a dataset with a minimum value less than or equal to zero"); } if (imageParameters.getLogBase() != 0 && yMaxValueR > 0) { yBottomR = Math.pow(imageParameters.getLogBase(), Math.floor(Math.log(yMinValueR) / Math.log(imageParameters.getLogBase()))); yTopR = Math.pow(imageParameters.getLogBase(), Math.ceil(Math.log(yMaxValueR) / Math.log(imageParameters.getLogBase()))); } else if (imageParameters.getLogBase() != 0 && yMinValueR <= 0) { throw new LogarithmicScaleNotAllowed("Logarithmic scale specified with a dataset with a minimum value less than or equal to zero"); } if (imageParameters.getyMaxLeft() < Double.POSITIVE_INFINITY) { yTopL = imageParameters.getyMaxLeft(); } if (imageParameters.getyMaxRight() < Double.POSITIVE_INFINITY) { yTopR = imageParameters.getyMaxRight(); } if (imageParameters.getyMinLeft() > Double.NEGATIVE_INFINITY) { yBottomL = imageParameters.getyMinLeft(); } if (imageParameters.getyMinRight() > Double.NEGATIVE_INFINITY) { yBottomR = imageParameters.getyMinRight(); } ySpanL = yTopL - yBottomL; ySpanR = yTopR - yBottomR; if (ySpanL == 0) { yTopL++; ySpanL++; } if (ySpanR == 0) { yTopR++; ySpanR++; } graphHeight = yMax - yMin; yScaleFactorL = graphHeight / ySpanL; yScaleFactorR = graphHeight / ySpanR; yLabelValuesL = getYLabelValues(yBottomL, yTopL, yStepL); yLabelValuesR = getYLabelValues(yBottomR, yTopR, yStepR); FontMetrics fontMetrics = g2d.getFontMetrics(imageParameters.getFont()); yLabelsL = new ArrayList<>(); yLabelsR = new ArrayList<>(); for (Double value : yLabelValuesL) { String label = makeLabel(value, yStepL, ySpanL); yLabelsL.add(label); if (fontMetrics.stringWidth(label) > yLabelWidthL) yLabelWidthL = fontMetrics.stringWidth(label); } for (Double value : yLabelValuesR) { String label = makeLabel(value, yStepR, ySpanR); yLabelsR.add(label); if (fontMetrics.stringWidth(label) > yLabelWidthR) yLabelWidthR = fontMetrics.stringWidth(label); } int xxMin = (int) (imageParameters.getMargin() + (yLabelWidthL * 1.15)); if (xMin < xxMin) { xMin = xxMin; } int xxMax = (int) (imageParameters.getWidth() - (yLabelWidthR * 1.15)); if (xMax >= xxMax) { xMax = xxMax; } } protected void setupYAxis() throws LogarithmicScaleNotAllowed { List<DecoratedTimeSeries> seriesWithMissingValues = new ArrayList<>(); for (DecoratedTimeSeries ts : data) { for (Double value : ts.getValues()) { if (value == null) { seriesWithMissingValues.add(ts); break; } } } double yMinValue = Double.POSITIVE_INFINITY; for (DecoratedTimeSeries ts : data) { if (!ts.hasOption(TimeSeriesOption.DRAW_AS_INFINITE)) { double mm = GraphUtils.safeMin(ts); yMinValue = mm < yMinValue ? mm : yMinValue; } } if (yMinValue > 0 && imageParameters.isDrawNullAsZero() && seriesWithMissingValues.size() > 0) { yMinValue = 0; } double yMaxValue; yMaxValue = GraphUtils.safeMax(data); /* if (getStackedData(data).size() > 0) { yMaxValue = GraphUtils.maxSum(data); } else { yMaxValue = GraphUtils.safeMax(data); } */ if (yMaxValue < 0 && imageParameters.isDrawNullAsZero() && seriesWithMissingValues.size() > 0) { yMaxValue = 0; } if (yMinValue == Double.POSITIVE_INFINITY) { yMinValue = 0; } if (yMaxValue == Double.NEGATIVE_INFINITY) { yMaxValue = 0; } if (imageParameters.getyMax() != Double.POSITIVE_INFINITY) { yMaxValue = imageParameters.getyMax(); } if (imageParameters.getyMin() != Double.NEGATIVE_INFINITY) { yMinValue = imageParameters.getyMin(); } if (yMaxValue <= yMinValue) { yMaxValue = yMinValue + 1; } double yVariance = yMaxValue - yMinValue; double order; double orderFactor; order = Math.log10(yVariance); orderFactor = Math.pow(10, Math.floor(order)); double v = yVariance / orderFactor; double distance = Double.POSITIVE_INFINITY; double prettyValue = PRETTY_VALUES[0]; for (int i = 0; i < imageParameters.getyDivisors().size(); i++) { double q = v / imageParameters.getyDivisors().get(i); double p = GraphUtils.closest(q, PRETTY_VALUES); if (Math.abs(q - p) < distance) { distance = Math.abs(q - p); prettyValue = p; } } yStep = prettyValue * orderFactor; if (imageParameters.getyStep() < Double.POSITIVE_INFINITY) { yStep = imageParameters.getyStep(); } yBottom = yStep * Math.floor(yMinValue / yStep); yTop = yStep * Math.ceil(yMaxValue / yStep); if (imageParameters.getLogBase() != 0 && yMaxValue > 0) { yBottom = Math.pow(imageParameters.getLogBase(), Math.floor(Math.log(yMinValue) / Math.log(imageParameters.getLogBase()))); yTop = Math.pow(imageParameters.getLogBase(), Math.ceil(Math.log(yMaxValue) / Math.log(imageParameters.getLogBase()))); } else if (imageParameters.getLogBase() != 0 && yMinValue <= 0) { throw new LogarithmicScaleNotAllowed("Logarithmic scale specified with a dataset with a minimum value less than or equal to zero"); } if (imageParameters.getyMax() != Double.POSITIVE_INFINITY) { yTop = imageParameters.getyMax(); } if (imageParameters.getyMin() != Double.NEGATIVE_INFINITY) { yBottom = imageParameters.getyMin(); } ySpan = yTop - yBottom; if (ySpan == 0) { yTop++; ySpan++; } graphHeight = yMax - yMin; yScaleFactor = graphHeight / ySpan; if (!imageParameters.isHideAxes()) { yLabelValues = getYLabelValues(yBottom, yTop, yStep); yLabels = new ArrayList<>(); yLabelWidth = 0; FontMetrics fontMetrics = g2d.getFontMetrics(imageParameters.getFont()); for (Double value : yLabelValues) { String label = makeLabel(value); yLabels.add(label); if (fontMetrics.stringWidth(label) > yLabelWidth) yLabelWidth = fontMetrics.stringWidth(label); } if (!imageParameters.isHideYAxis()) { if (imageParameters.getyAxisSide().equals(ImageParameters.Side.LEFT)) { int xxMin = (int) (imageParameters.getMargin() + yLabelWidth * 1.15); if (xMin < xxMin) { xMin = xxMin; } } else { int xxMax = (int) (imageParameters.getMargin() - yLabelWidth * 1.15); if (xMax >= xxMax) { xMax = xxMax; } } } } else { yLabelValues = new ArrayList<>(); yLabels = new ArrayList<>(); yLabelWidth = 0; } } protected void setupXAxis() { startDateTime = new DateTime(startTime * 1000, renderParameters.getTz()); endDateTime = new DateTime(endTime * 1000, renderParameters.getTz()); double secondsPerPixel = (endTime - startTime) / graphWidth; xScaleFactor = (double) graphWidth / (endTime - startTime); xAxisConfig = XAxisConfigProvider.getXAxisConfig(secondsPerPixel, endTime - startTime); xLabelStep = xAxisConfig.getLabelUnit() * xAxisConfig.getLabelStep(); xMinorGridStep = (long) (xAxisConfig.getMinorGridUnit() * xAxisConfig.getMinorGridStep()); xMajorGridStep = xAxisConfig.getMajorGridUnit() * xAxisConfig.getMajorGridStep(); } protected void drawLabels() { // Draw the Y-labels if (!imageParameters.isHideYAxis()) { if (!secondYAxis) { for (int i = 0; i < yLabelValues.size(); i++) { int x; if (imageParameters.getyAxisSide().equals(ImageParameters.Side.LEFT)) { x = (int) (xMin - (yLabelWidth * 0.15)); } else { x = (int) (xMax + (yLabelWidth * 0.15)); } int y = getYCoord(yLabelValues.get(i)); if (y < 0) y = 0; if (imageParameters.getyAxisSide().equals(ImageParameters.Side.LEFT)) { drawText(x, y, yLabels.get(i), HorizontalAlign.RIGHT, VerticalAlign.MIDDLE); } else { drawText(x, y, yLabels.get(i), HorizontalAlign.LEFT, VerticalAlign.MIDDLE); } } } else { for (int i = 0; i < yLabelValuesL.size(); i++) { int x = (int) (xMin - (yLabelWidthL * 0.15)); int y = getYCoordLeft(yLabelValuesL.get(i)); if (y < 0) y = 0; drawText(x, y, yLabelsL.get(i), HorizontalAlign.RIGHT, VerticalAlign.MIDDLE); } for (int i = 0; i < yLabelValuesR.size(); i++) { int x = (int) (xMax + (yLabelWidthR * 0.15)); int y = getYCoordRight(yLabelValuesR.get(i)); if (y < 0) y = 0; drawText(x, y, yLabelsR.get(i), HorizontalAlign.LEFT, VerticalAlign.MIDDLE); } } } // Draw the X-labels long labelDt = 0; long labelDelta = 1; if (xAxisConfig.getLabelUnit() == XAxisConfigProvider.SEC) { labelDt = startTime - startTime % xAxisConfig.getLabelStep(); labelDelta = (long) xAxisConfig.getLabelStep(); } else if (xAxisConfig.getLabelUnit() == XAxisConfigProvider.MIN) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); labelDt = tdt.withSecondOfMinute(0).withMinuteOfHour(tdt.getMinuteOfHour() - (tdt.getMinuteOfHour() % xAxisConfig.getLabelStep())).getMillis() / 1000; labelDelta = (long) xAxisConfig.getLabelStep() * 60; } else if (xAxisConfig.getLabelUnit() == XAxisConfigProvider.HOUR) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); labelDt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(tdt.getHourOfDay() - (tdt.getHourOfDay() % xAxisConfig.getLabelStep())).getMillis() / 1000; labelDelta = (long) xAxisConfig.getLabelStep() * 60 * 60; } else if (xAxisConfig.getLabelUnit() == XAxisConfigProvider.DAY) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); labelDt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(0).getMillis() / 1000; labelDelta = (long) xAxisConfig.getLabelStep() * 60 * 60 * 24; } while (labelDt < startTime) labelDt += labelDelta; DateTime ddt = new DateTime(labelDt * 1000, renderParameters.getTz()); FontMetrics fontMetrics = g2d.getFontMetrics(imageParameters.getFont()); while (ddt.isBefore(endDateTime)) { String label = ddt.toString(DateTimeFormat.forPattern(xAxisConfig.getFormat())); int x = (int) (xMin + (Seconds.secondsBetween(startDateTime, ddt).getSeconds() * xScaleFactor)); int y = yMax + fontMetrics.getMaxAscent(); drawText(x, y, label, HorizontalAlign.CENTER, VerticalAlign.TOP); ddt = ddt.plusSeconds((int) labelDelta); } } protected void drawGridLines() { g2d.setStroke(new BasicStroke(0f)); //Horizontal grid lines int leftSide = xMin; int rightSide = xMax; List<Double> labelValues = secondYAxis ? yLabelValuesL : yLabelValues; for (int i = 0; i < labelValues.size(); i++) { g2d.setColor(imageParameters.getMajorGridLineColor()); int y = secondYAxis ? getYCoordLeft(labelValues.get(i)) : getYCoord(labelValues.get(i)); if (y < 0) continue; g2d.drawLine(leftSide, y, rightSide, y); // draw minor gridlines if this isn't the last label g2d.setColor(imageParameters.getMinorGridLineColor()); if (imageParameters.getMinorY() >= 1 && i < (labelValues.size() - 1)) { double distance = ((labelValues.get(i + 1) - labelValues.get(i)) / (1 + imageParameters.getMinorY())); for (int minor = 0; minor < imageParameters.getMinorY(); minor++) { double minorValue = (labelValues.get(i) + ((1 + minor) * distance)); int yTopFactor = imageParameters.getLogBase() != 0 ? (int) (imageParameters.getLogBase() * imageParameters.getLogBase()) : 1; if (secondYAxis) { if (minorValue > yTopFactor * yTopL) continue; } else { if (minorValue > yTopFactor * yTop) continue; } int yMinor = secondYAxis ? getYCoordLeft(minorValue) : getYCoord(minorValue); if (yMinor < 0) continue; g2d.drawLine(leftSide, yMinor, rightSide, yMinor); } } } // Vertical grid lines int top = yMin; int bottom = yMax; long dt = 0; long delta = 1; if (xAxisConfig.getMinorGridUnit() == XAxisConfigProvider.SEC) { dt = startTime - (long) (startTime % xAxisConfig.getMinorGridStep()); delta = (long) xAxisConfig.getMinorGridStep(); } else if (xAxisConfig.getMinorGridUnit() == XAxisConfigProvider.MIN) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); dt = tdt.withSecondOfMinute(0).withMinuteOfHour((int) (tdt.getMinuteOfHour() - (tdt.getMinuteOfHour() % xAxisConfig.getMinorGridStep()))).getMillis() / 1000; delta = (long) xAxisConfig.getMinorGridStep() * 60; } else if (xAxisConfig.getMinorGridUnit() == XAxisConfigProvider.HOUR) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); dt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay((int) (tdt.getHourOfDay() - (tdt.getHourOfDay() % xAxisConfig.getMinorGridStep()))).getMillis() / 1000; delta = (long) xAxisConfig.getMinorGridStep() * 60 * 60; } else if (xAxisConfig.getMinorGridUnit() == XAxisConfigProvider.DAY) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); dt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(0).getMillis() / 1000; delta = (long) xAxisConfig.getMinorGridStep() * 60 * 60 * 24; } while (dt < startTime) dt += delta; DateTime ddt = new DateTime(dt * 1000, renderParameters.getTz()); g2d.setColor(imageParameters.getMinorGridLineColor()); while (ddt.isBefore(endDateTime)) { int x = (int) (xMin + (Seconds.secondsBetween(startDateTime, ddt).getSeconds() * xScaleFactor)); if (x < xMax) { g2d.drawLine(x, bottom, x, top); } ddt = ddt.plusSeconds((int) delta); } // Now we do the major grid lines g2d.setColor(imageParameters.getMajorGridLineColor()); long majorDt = 0; long majorDelta = 1; if (xAxisConfig.getMajorGridUnit() == XAxisConfigProvider.SEC) { majorDt = startTime - startTime % xAxisConfig.getMajorGridStep(); majorDelta = (long) xAxisConfig.getMajorGridStep(); } else if (xAxisConfig.getMajorGridUnit() == XAxisConfigProvider.MIN) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); majorDt = tdt.withSecondOfMinute(0).withMinuteOfHour(tdt.getMinuteOfHour() - (tdt.getMinuteOfHour() % xAxisConfig.getMajorGridStep())).getMillis() / 1000; majorDelta = (long) xAxisConfig.getMajorGridStep() * 60; } else if (xAxisConfig.getMajorGridUnit() == XAxisConfigProvider.HOUR) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); majorDt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(tdt.getHourOfDay() - (tdt.getHourOfDay() % xAxisConfig.getMajorGridStep())).getMillis() / 1000; majorDelta = (long) xAxisConfig.getMajorGridStep() * 60 * 60; } else if (xAxisConfig.getMajorGridUnit() == XAxisConfigProvider.DAY) { DateTime tdt = new DateTime(startTime * 1000, renderParameters.getTz()); majorDt = tdt.withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(0).getMillis() / 1000; majorDelta = (long) xAxisConfig.getMajorGridStep() * 60 * 60 * 24; } while (majorDt < startTime) majorDt += majorDelta; ddt = new DateTime(majorDt * 1000, renderParameters.getTz()); while (ddt.isBefore(endDateTime)) { int x = (int) (xMin + (Seconds.secondsBetween(startDateTime, ddt).getSeconds() * xScaleFactor)); if (x < xMax) { g2d.drawLine(x, bottom, x, top); } ddt = ddt.plusSeconds((int) majorDelta); } //Draw side borders for our graph area g2d.drawLine(xMax, bottom, xMax, top); g2d.drawLine(xMin, bottom, xMin, top); } private void drawLines(List<DecoratedTimeSeries> timeSeriesList) { for (DecoratedTimeSeries ts : timeSeriesList) { g2d.setStroke(getStroke(ts)); g2d.setColor(getColor(ts)); GeneralPath path = new GeneralPath(); double x = xMin; double previousX = xMin; int y = yMin; int previousY = -1; Double[] values = ts.getConsolidatedValues(); int consecutiveNulls = 0; boolean allNullsSoFar = true; for (Double value : values) { Double adjustedValue = value; if (adjustedValue == null && imageParameters.isDrawNullAsZero()) adjustedValue = 0.; if (value == null) { if (consecutiveNulls == 0) { path.lineTo(x, y); } x += ts.getxStep(); consecutiveNulls++; continue; } if (secondYAxis) { if (ts.hasOption(TimeSeriesOption.SECOND_Y_AXIS)) { y = getYCoordRight(adjustedValue); } else { y = getYCoordLeft(adjustedValue); } } else { y = getYCoord(adjustedValue); } y = y < 0 ? 0 : y; if (path.getCurrentPoint() == null) { path.moveTo(x, y); } if (ts.hasOption(TimeSeriesOption.DRAW_AS_INFINITE) && adjustedValue > 0) { path.moveTo((int) x, yMax); path.lineTo((int) x, yMin); // g2d.drawLine((int) x, yMax, (int) x, yMin); x += ts.getxStep(); continue; } previousX = previousX < 0 ? x : previousX; previousY = previousY < 0 ? y : previousY; if (imageParameters.getLineMode().equals(ImageParameters.LineMode.SLOPE)) { if (consecutiveNulls > 0) { path.moveTo(x, y); } path.lineTo(x, y); } else if (imageParameters.getLineMode().equals(ImageParameters.LineMode.STAIRCASE)) { if (consecutiveNulls > 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } path.lineTo(x + ts.getxStep(), y); } else if (imageParameters.getLineMode().equals(ImageParameters.LineMode.CONNECTED)) { if (consecutiveNulls > imageParameters.getConnectedLimit() || allNullsSoFar) { path.moveTo(x, y); allNullsSoFar = false; } path.lineTo((int) x, y); } consecutiveNulls = 0; previousX = x; previousY = y; x += ts.getxStep(); } g2d.draw(path); } } private void drawStacked(List<DecoratedTimeSeries> timeSeriesList) { if (timeSeriesList.size() == 0) return; Shape savedClip = g2d.getClip(); g2d.clip(new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin)); for (DecoratedTimeSeries ts : timeSeriesList) { // We will be constructing general path for each time series GeneralPath path = new GeneralPath(); path.moveTo(xMin, yMax); g2d.setPaint(getColor(ts)); double x = xMin; double startX = x; int y = yMin; Double[] values = ts.getConsolidatedValues(); int consecutiveNulls = 0; boolean allNullsSoFar = true; for (Double value : values) { Double adjustedValue = value; if (value == null && imageParameters.isDrawNullAsZero()) adjustedValue = 0.; if (adjustedValue == null) { if (consecutiveNulls == 0) { path.lineTo(x, y); if (secondYAxis) { if (ts.hasOption(TimeSeriesOption.SECOND_Y_AXIS)) { fillAreaAndClip(path, x, startX, getYCoordRight(0)); } else { fillAreaAndClip(path, x, startX, getYCoordLeft(0)); } } else { fillAreaAndClip(path, x, startX, getYCoord(0)); } } x += ts.getxStep(); consecutiveNulls++; } else { if (secondYAxis) { if (ts.hasOption(TimeSeriesOption.SECOND_Y_AXIS)) { y = getYCoordRight(adjustedValue); } else { y = getYCoordLeft(adjustedValue); } } else { y = getYCoord(adjustedValue); } y = y < 0 ? 0 : y; if (consecutiveNulls > 0) startX = x; if (imageParameters.getLineMode().equals(ImageParameters.LineMode.STAIRCASE)) { if (consecutiveNulls > 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } x += ts.getxStep(); path.lineTo(x, y); } else if (imageParameters.getLineMode().equals(ImageParameters.LineMode.SLOPE)) { if (consecutiveNulls > 0) { path.moveTo(x, y); } path.lineTo(x, y); x += ts.getxStep(); } else if (imageParameters.getLineMode().equals(ImageParameters.LineMode.CONNECTED)) { if (consecutiveNulls > imageParameters.getConnectedLimit() || allNullsSoFar) { path.moveTo(x, y); allNullsSoFar = false; } path.lineTo(x, y); x += ts.getxStep(); } consecutiveNulls = 0; } } double xPos; if (imageParameters.getLineMode().equals(ImageParameters.LineMode.STAIRCASE)) { xPos = x; } else { xPos = x - ts.getxStep(); } if (secondYAxis) { if (ts.hasOption(TimeSeriesOption.SECOND_Y_AXIS)) { fillAreaAndClip(path, xPos, startX, getYCoordRight(0)); } else { fillAreaAndClip(path, xPos, startX, getYCoordLeft(0)); } } else { fillAreaAndClip(path, xPos, startX, getYCoord(0)); } } g2d.setClip(savedClip); } protected void fillAreaAndClip(GeneralPath path, double x, double startX, int yTo) { GeneralPath pattern = new GeneralPath(path); path.lineTo(x, yTo); path.lineTo(startX, yTo); path.closePath(); g2d.fill(path); pattern.lineTo(x, yTo); pattern.lineTo(xMax, yTo); pattern.lineTo(xMax, yMin); pattern.lineTo(xMin, yMin); pattern.lineTo(startX, yTo); pattern.lineTo(x, yTo); pattern.lineTo(xMax, yTo); pattern.lineTo(xMax, yMax); pattern.lineTo(xMin, yMax); pattern.lineTo(xMin, yTo); pattern.lineTo(startX, yTo); pattern.closePath(); g2d.clip(pattern); } protected void drawData() { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); drawStacked(getStackedData(data)); drawLines(getLineData(data)); } private List<DecoratedTimeSeries> getLineData(List<DecoratedTimeSeries> data) { List<DecoratedTimeSeries> result = new ArrayList<>(); for (DecoratedTimeSeries ts : data) { if (!ts.hasOption(TimeSeriesOption.STACKED)) { result.add(ts); } } return result; } protected List<DecoratedTimeSeries> getStackedData(List<DecoratedTimeSeries> data) { List<DecoratedTimeSeries> result = new ArrayList<>(); for (DecoratedTimeSeries ts : data) { if (ts.hasOption(TimeSeriesOption.STACKED)) { result.add(ts); } } return result; } private int getYCoordRight(double value) { double highestValue = Collections.max(yLabelValuesR); double lowestValue = Collections.min(yLabelValuesR); int pixelRange = yMax - yMin; double relativeValue = value - lowestValue; double valueRange = highestValue - lowestValue; if (imageParameters.getLogBase() != 0) { if (value < 0) { return -1; } relativeValue = Math.log(value) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); valueRange = Math.log(highestValue) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); } double pixelToValueRatio = pixelRange / valueRange; double valueInPixels = pixelToValueRatio * relativeValue; return (int) (yMax - valueInPixels); } private int getYCoordLeft(double value) { double highestValue = Collections.max(yLabelValuesL); double lowestValue = Collections.min(yLabelValuesL); int pixelRange = yMax - yMin; double relativeValue = value - lowestValue; double valueRange = highestValue - lowestValue; if (imageParameters.getLogBase() != 0) { if (value < 0) { return -1; } relativeValue = Math.log(value) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); valueRange = Math.log(highestValue) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); } double pixelToValueRatio = pixelRange / valueRange; double valueInPixels = pixelToValueRatio * relativeValue; return (int) (yMax - valueInPixels); } private int getYCoord(double value) { double highestValue = Collections.max(yLabelValues); double lowestValue = Collections.min(yLabelValues); int pixelRange = yMax - yMin; double relativeValue = value - lowestValue; double valueRange = highestValue - lowestValue; if (imageParameters.getLogBase() != 0) { if (value < 0) { return -1; } relativeValue = Math.log(value) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); valueRange = Math.log(highestValue) / Math.log(imageParameters.getLogBase()) - Math.log(lowestValue) / Math.log(imageParameters.getLogBase()); } double pixelToValueRatio = pixelRange / valueRange; double valueInPixels = pixelToValueRatio * relativeValue; return (int) (yMax - valueInPixels); } private List<Double> getYLabelValues(double min, double max, double step) { if (imageParameters.getLogBase() != 0) { return logRange(imageParameters.getLogBase(), min, max); } else { return fRange(step, min, max); } } protected String makeLabel(double value, double step, double span) { double tmpValue = formatUnitValue(value, step); String prefix = formatUnitPrefix(value, step); double ySpan = formatUnitValue(span, step); String spanPrefix = formatUnitPrefix(span, step); value = tmpValue; if (value < 0.1) { return value + " " + prefix; } else if (value < 1.0) { return String.format("%.2f %s", value, prefix); } if (ySpan > 10 || !spanPrefix.equals(prefix)) { return String.format("%.1f %s", value, prefix); } else if (ySpan > 3) { return String.format("%.1f %s", value, prefix); } else if (ySpan > 0.1) { return String.format("%.2f %s", value, prefix); } else { return value + prefix; } } protected String makeLabel(double value) { return makeLabel(value, yStep, ySpan); } private String formatUnitPrefix(double value, double step) { for (ImageParameters.Unit unit : imageParameters.getyUnitSystem().getPrefixes()) { if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) { return unit.getPrefix(); } } return ""; } private double formatUnitValue(double value, double step) { // Firstly, round the value a bit if (value > 0 && value < 1.0) { value = new BigDecimal(value).setScale(2 - (int) Math.log10(value), BigDecimal.ROUND_HALF_DOWN).doubleValue(); } for (ImageParameters.Unit unit : imageParameters.getyUnitSystem().getPrefixes()) { if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) { double v2 = value / unit.getValue(); if (v2 - Math.floor(v2) < 0.00000000001 && value > 1) { v2 = Math.floor(v2); } return v2; } } if (value - Math.floor(value) < 0.00000000001 && value > 1) { return Math.floor(value); } return value; } private List<Double> logRange(double base, double min, double max) { List<Double> result = new ArrayList<>(); double current = min; if (min > 0) { current = Math.floor(Math.log(min) / Math.log(base)); } double factor = current; while (current < max) { current = Math.pow(base, factor); result.add(current); factor++; } return result; } private List<Double> fRange(double step, double min, double max) { List<Double> result = new ArrayList<>(); double f = min; while (f <= max) { result.add(f); f += step; if (f == min) { result.add(max); break; } } return result; } private Color getColor(DecoratedTimeSeries timeSeries) { if (timeSeries.hasOption(TimeSeriesOption.INVISIBLE)) { return ColorTable.INVISIBLE; } Color c = (Color) timeSeries.getOption(TimeSeriesOption.COLOR); return new Color(c.getRed(), c.getGreen(), c.getBlue(), timeSeries.hasOption(TimeSeriesOption.ALPHA) ? (int) ((Float) timeSeries.getOption(TimeSeriesOption.ALPHA) * 255) : 255); } private Stroke getStroke(DecoratedTimeSeries timeSeries) { float lineWidth = 1.2f; if (timeSeries.hasOption(TimeSeriesOption.LINE_WIDTH)) { lineWidth = (float) timeSeries.getOption(TimeSeriesOption.LINE_WIDTH); } boolean isDashed = false; float dashLength = 0f; if (timeSeries.hasOption(TimeSeriesOption.DASHED)) { isDashed = true; dashLength = (float) timeSeries.getOption(TimeSeriesOption.DASHED); } if (isDashed) { return new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{dashLength, dashLength}, 0.0f); } else { return new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); } } protected enum HorizontalAlign { LEFT, CENTER, RIGHT } protected enum VerticalAlign { TOP, MIDDLE, BOTTOM, BASELINE } }
package net.openhft.chronicle.core; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.*; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ClassMetrics { private final int offset; private final int length; public ClassMetrics(int offset, int length) { this.offset = offset; this.length = length; } public int offset() { return offset; } public int length() { return length; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassMetrics that = (ClassMetrics) o; return offset == that.offset && length == that.length; } @Override public int hashCode() { return Objects.hash(offset, length); } @Override public String toString() { return "ClassMetrics{" + "offset=" + offset + ", length=" + length + '}'; } public static void updateJar(final String jarToUpdate, String sourceFile, String fileNameInJar) throws IOException { Map<String, String> env = new HashMap<>(); env.put("create", "true"); URI uri = URI.create("jar:" + new File(jarToUpdate).toURI()); try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { Path externalFile = new File(sourceFile).toPath(); Path pathInZipfile = zipfs.getPath(fileNameInJar); // copy a file into the zip file Files.copy(externalFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING); } } }
package com.cloud.api.commands; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.response.ListResponse; import com.cloud.api.response.TemplateResponse; import com.cloud.async.AsyncJobVO; import com.cloud.dc.DataCenterVO; import com.cloud.host.HostVO; import com.cloud.storage.GuestOS; import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.VMTemplateDao.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.UserContext; @Implementation(method="listIsos", description="Lists all available ISO files.") public class ListIsosCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); private static final String s_name = "listisosresponse"; //////////////// API parameters ///////////////////// @Parameter(name="account", type=CommandType.STRING) private String accountName; @Parameter(name="bootable", type=CommandType.BOOLEAN) private Boolean bootable; @Parameter(name="domainid", type=CommandType.LONG) private Long domainId; @Parameter(name="id", type=CommandType.LONG) private Long id; @Parameter(name="ispublic", type=CommandType.BOOLEAN) private Boolean publicIso; @Parameter(name="isready", type=CommandType.BOOLEAN) private Boolean ready; @Parameter(name="isofilter", type=CommandType.STRING) private String isoFilter = TemplateFilter.selfexecutable.toString(); @Parameter(name="name", type=CommandType.STRING) private String isoName; @Parameter(name="zoneid", type=CommandType.LONG) private Long zoneId; /////////////////// Accessors /////////////////////// public String getAccountName() { return accountName; } public Boolean isBootable() { return bootable; } public Long getDomainId() { return domainId; } public Long getId() { return id; } public Boolean isPublic() { return publicIso; } public Boolean isReady() { return ready; } public String getIsoFilter() { return isoFilter; } public String getIsoName() { return isoName; } public Long getZoneId() { return zoneId; } /////////////// API Implementation/////////////////// @Override public String getName() { return s_name; } @Override @SuppressWarnings("unchecked") public ListResponse<TemplateResponse> getResponse() { TemplateFilter isoFilterObj = null; try { if (isoFilter == null) { isoFilterObj = TemplateFilter.selfexecutable; } else { isoFilterObj = TemplateFilter.valueOf(isoFilter); } } catch (IllegalArgumentException e) { // how did we get this far? The request should've been rejected already before the response stage... isoFilterObj = TemplateFilter.selfexecutable; } boolean isAdmin = false; boolean isAccountSpecific = true; Account account = (Account)UserContext.current().getAccountObject(); if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { isAdmin = true; if ((accountName == null) || (domainId == null)) { isAccountSpecific = false; } } boolean onlyReady = (isoFilterObj == TemplateFilter.featured) || (isoFilterObj == TemplateFilter.selfexecutable) || (isoFilterObj == TemplateFilter.sharedexecutable) || (isoFilterObj == TemplateFilter.executable && isAccountSpecific) || (isoFilterObj == TemplateFilter.community); List<VMTemplateVO> isos = (List<VMTemplateVO>)getResponseObject(); Map<Long, List<VMTemplateHostVO>> isoHostsMap = new HashMap<Long, List<VMTemplateHostVO>>(); for (VMTemplateVO iso : isos) { // TODO: implement List<VMTemplateHostVO> isoHosts = ApiDBUtils.listTemplateHostBy(iso.getId(), zoneId); if (iso.getName().equals("xs-tools.iso")) { List<Long> xstoolsZones = new ArrayList<Long>(); // the xs-tools.iso is a special case since it will be available on every computing host in the zone and we want to return it once per zone List<VMTemplateHostVO> xstoolsHosts = new ArrayList<VMTemplateHostVO>(); for (VMTemplateHostVO isoHost : isoHosts) { // TODO: implement HostVO host = ApiDBUtils.findHostById(isoHost.getHostId()); if (!xstoolsZones.contains(Long.valueOf(host.getDataCenterId()))) { xstoolsZones.add(Long.valueOf(host.getDataCenterId())); xstoolsHosts.add(isoHost); } } isoHostsMap.put(iso.getId(), xstoolsHosts); } else { isoHostsMap.put(iso.getId(), isoHosts); } } ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>(); List<TemplateResponse> isoResponses = new ArrayList<TemplateResponse>(); for (VMTemplateVO iso : isos) { List<VMTemplateHostVO> isoHosts = isoHostsMap.get(iso.getId()); for (VMTemplateHostVO isoHost : isoHosts) { if (onlyReady && isoHost.getDownloadState() != Status.DOWNLOADED) { continue; } TemplateResponse isoResponse = new TemplateResponse(); isoResponse.setId(iso.getId()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); isoResponse.setCreated(isoHost.getCreated()); isoResponse.setReady(isoHost.getDownloadState() == Status.DOWNLOADED); isoResponse.setBootable(iso.isBootable()); isoResponse.setFeatured(iso.isFeatured()); isoResponse.setCrossZones(iso.isCrossZones()); // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { isoResponse.setOsTypeId(os.getId()); isoResponse.setOsTypeName(os.getDisplayName()); } else { isoResponse.setOsTypeId(-1L); isoResponse.setOsTypeName(""); } // add account ID and name Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); if (owner != null) { isoResponse.setAccount(owner.getAccountName()); isoResponse.setDomainId(owner.getDomainId()); // TODO: implement isoResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } // Add the zone ID // TODO: implement HostVO host = ApiDBUtils.findHostById(isoHost.getHostId()); DataCenterVO datacenter = ApiDBUtils.findZoneById(host.getDataCenterId()); isoResponse.setZoneId(host.getDataCenterId()); isoResponse.setZoneName(datacenter.getName()); // If the user is an admin, add the template download status if (isAdmin || account.getId() == iso.getAccountId()) { // add download status if (isoHost.getDownloadState()!=Status.DOWNLOADED) { String isoStatus = "Processing"; if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { isoStatus = "Download Complete"; } else if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { if (isoHost.getDownloadPercent() == 100) { isoStatus = "Installing ISO"; } else { isoStatus = isoHost.getDownloadPercent() + "% Downloaded"; } } else { isoStatus = isoHost.getErrorString(); } isoResponse.setStatus(isoStatus); } else { isoResponse.setStatus("Successfully Installed"); } } long isoSize = isoHost.getSize(); if (isoSize > 0) { isoResponse.setSize(isoSize); } AsyncJobVO asyncJob = ApiDBUtils.findInstancePendingAsyncJob("vm_template", iso.getId()); if(asyncJob != null) { isoResponse.setJobId(asyncJob.getId()); isoResponse.setJobStatus(asyncJob.getStatus()); } isoResponse.setResponseName("iso"); isoResponses.add(isoResponse); } } response.setResponses(isoResponses); response.setResponseName(getName()); return response; } }
package com.genymobile.scrcpy; import android.util.Log; /** * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal * directly). */ public final class Ln { private static final String TAG = "scrcpy"; private static final String PREFIX = "[server] "; enum Level { VERBOSE, DEBUG, INFO, WARN, ERROR } private static Level threshold = Level.INFO; private Ln() { // not instantiable } /** * Initialize the log level. * <p> * Must be called before starting any new thread. * * @param level the log level */ public static void initLogLevel(Level level) { threshold = level; } public static boolean isEnabled(Level level) { return level.ordinal() >= threshold.ordinal(); } public static void v(String message) { if (isEnabled(Level.VERBOSE)) { Log.v(TAG, message); System.out.println(PREFIX + "VERBOSE: " + message); } } public static void d(String message) { if (isEnabled(Level.DEBUG)) { Log.d(TAG, message); System.out.println(PREFIX + "DEBUG: " + message); } } public static void i(String message) { if (isEnabled(Level.INFO)) { Log.i(TAG, message); System.out.println(PREFIX + "INFO: " + message); } } public static void w(String message, Throwable throwable) { if (isEnabled(Level.WARN)) { Log.w(TAG, message, throwable); System.out.println(PREFIX + "WARN: " + message); if (throwable != null) { throwable.printStackTrace(); } } } public static void w(String message) { w(message, null); } public static void e(String message, Throwable throwable) { if (isEnabled(Level.ERROR)) { Log.e(TAG, message, throwable); System.out.println(PREFIX + "ERROR: " + message); if (throwable != null) { throwable.printStackTrace(); } } } public static void e(String message) { e(message, null); } }
// Events.java package imagej.event; import org.bushe.swing.event.EventBus; /** * Simple utility class for subscribing to ImageJ events, * as well as publishing them. * * @author Curtis Rueden * @author Grant Harris */ public final class Events { private Events() { // prevent instantiation of utility class } public static <E extends ImageJEvent> void publish(final E e) { EventBus.publish(e); } public static <E extends ImageJEvent> void subscribe( final Class<E> c, final EventSubscriber<E> subscriber) { EventBus.subscribe(c, subscriber); } public static <E extends ImageJEvent> void unsubscribe( final Class<E> c, final EventSubscriber<E> subscriber) { EventBus.unsubscribe(c, subscriber); } public static <E extends ImageJEvent> java.util.List<E> getSubscribers(final Class<E> c) { return EventBus.getSubscribers(c); } }
package imagej.data; import net.imglib2.img.ImgPlus; import net.imglib2.meta.AxisType; import net.imglib2.meta.Metadata; import net.imglib2.type.numeric.RealType; /** * Dataset is the primary image data structure in ImageJ. A Dataset wraps an * ImgLib {@link ImgPlus}. It also provides a number of convenience methods, * such as the ability to access pixels on a plane-by-plane basis, and create * new Datasets of various types easily. * * @author Curtis Rueden * @author Barry DeZonia */ public interface Dataset extends Data, Metadata { /** TODO */ boolean isDirty(); /** TODO */ void setDirty(boolean value); /** TODO */ ImgPlus<? extends RealType<?>> getImgPlus(); /** TODO */ <T extends RealType<T>> ImgPlus<T> typedImg(T t); /** TODO */ void setImgPlus(final ImgPlus<? extends RealType<?>> imgPlus); /** * gets a plane of data from the Dataset. The representation of the plane is * determined by the native ImgLib container. This method will create a copy * of the original data if it cannot obtain a direct reference. */ Object getPlane(final int planeNumber); /** * gets a plane of data from the Dataset. The representation of the plane is * determined by the native ImgLib container. The behavior of this method when * a reference to the actual data cannot be obtained depends upon the value of * the input copyOK boolean. If copyOK is true a copy of the data is created * and returned. If copyOK is false null is returned. */ Object getPlane(final int planeNumber, boolean copyOK); /** * sets a plane of data within the dataset. generates an update event if the * plane reference differs from the current plane reference associated with * the given plane number. returns true if the reference was changed or false * if it was not. This method only works with PlanarAccess backed Img's. */ boolean setPlane(final int planeNum, final Object newPlane); /** * sets a plane of data within the dataset. NEVER generates update events. if * the plane reference differs from the current plane reference associated * with the given plane number returns true else false. This method only works * with PlanarAccess backed Img's. */ boolean setPlaneSilently(final int planeNum, final Object newPlane); /** TODO */ RealType<?> getType(); /** TODO */ boolean isSigned(); /** TODO */ boolean isInteger(); /** Gets a short string description of the dataset's pixel type. */ String getTypeLabelShort(); /** Gets the full string description of the dataset's pixel type. */ String getTypeLabelLong(); /** Creates a copy of the dataset. */ Dataset duplicate(); /** Creates a copy of the dataset, but without copying any pixel values. */ Dataset duplicateBlank(); /** Copies the dataset's pixels into the given target dataset. */ void copyInto(final Dataset target); // TODO - eliminate legacy layer specific functionality in favor of a // generic properties system (setProperty(String, Object), // getProperty(String)) for storing arbitrary key/value pairs about the data. // The property system can be part of Data, and implemented in AbstractData. /** * For use in legacy layer only, this flag allows the various legacy layer * image translators to support color images correctly. */ void setRGBMerged(final boolean rgbMerged); /** * For use in legacy layer only, this flag allows the various legacy layer * image translators to support color images correctly. */ boolean isRGBMerged(); /** TODO */ void typeChange(); /** TODO */ void rgbChange(); /** * Changes a Dataset's internal data and metadata to match that from a given * Dataset. Only its name stays the same. Written to allow nonplanar * representations to copy data from other Datasets as needed to get around * the fact that its data is not being shared by reference. */ void copyDataFrom(final Dataset other); double getBytesOfInfo(); // TODO - move into Imglib void setAxes(AxisType[] axes); }
package org.benchmarks.berkeleydb; import org.bdb.*; import org.bdbLevel1.*; import org.generic.env.*; import org.toolza.*; public class TestManyNodes { private final static String END = "END"; private final static String START = "START"; private final static String MIDDLE = "MIDDLE"; private final static String ROOT_LIST = "ROOT_LIST"; // 10000 to 20k seems optimal private static final int HOWMANY_PER_TRANSACTION = 30000; private static final int HOWMANY_RELATIONSHIPS_FOR_ONE = 1000000; private final GenericEnvironment env; private GenericNode list; private GenericNode middleElement; private GenericNode headElement; private GenericNode tailElement; public TestManyNodes( final GenericEnvironment _env ) { assert null != _env; env = _env; } private static void showMem() { System.out.println( "usedmem=" + ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) ); } public static void main( final String[] args ) { showMem(); final boolean deleteFirst = true; final TestManyNodes t2 = new TestManyNodes( new BDBEnvironment( JUnitConstants.BDB_ENVIRONMENT_STORE_DIR, deleteFirst ) ); showMem(); t2.init(); showMem(); t2.run(); showMem(); t2.shutdown(); showMem(); Runtime.getRuntime().gc(); showMem(); } public void init() { GenericTransaction txn = env.beginTransaction(); try { list = env.getNode( ROOT_LIST ); middleElement = env.getNode( MIDDLE ); headElement = env.getNode( START ); tailElement = env.getNode( END ); if ( null == list ) { assert null == middleElement; System.out.println( env.getClass() ); list = env.createOrGetNode( ROOT_LIST ); tailElement = env.createOrGetNode( END ); headElement = env.createOrGetNode( START ); middleElement = env.createOrGetNode( MIDDLE ); env.makeVector( list, headElement ); System.out.println( "first time creating the relationships..." ); final int half = HOWMANY_RELATIONSHIPS_FOR_ONE / 2; t3.start(); int i = 0; try { for ( i = 0; i < half; i++ ) { env.makeVector( list, env.createNewUniqueNode() ); if ( ( i % HOWMANY_PER_TRANSACTION ) == 0 ) { txn.success(); txn.finish(); txn = env.beginTransaction(); System.out.println( "new txn at " + i ); } if ( i == ( half / 2 ) ) { env.makeVector( list, middleElement ); } }// for } finally { System.out.println( i ); } t3.stop(); System.out.println( "just created " + A.number( half ) + " rels, took=" + t3.getDeltaPrintFriendly() ); showMem(); System.out.println( "first time creating more relationships..." ); t3.start(); for ( i = 0; i < half; i++ ) { env.makeVector( env.createNewUniqueNode(), tailElement ); if ( ( i % HOWMANY_PER_TRANSACTION ) == 0 ) { txn.success(); txn.finish(); txn = env.beginTransaction(); } if ( i == ( half / 2 ) ) { env.makeVector( list, tailElement ); } } t3.stop(); System.out.println( "just created another bunch of " + A.number( half ) + " rels, took=" + t3.getDeltaPrintFriendly() ); showMem(); } else { assert null != middleElement; assert null != headElement; assert null != tailElement; } txn.success(); } finally { txn.finish(); System.out.println( "closed transaction" ); } } public void run() { final GenericTransaction t = env.beginTransaction(); try { System.out.println( "run for `" + env.getClass() + "`" ); System.out.println( "trying isVector():" ); int repeat = 10; do { goFind2( list, headElement ); goFind2( list, middleElement ); goFind2( list, tailElement ); } while ( --repeat > 0 ); showMem(); t.success(); } finally { t.finish(); } } public void shutdown() { env.shutdown( false );// no need to be in finally, it's already on shutdownhook } private final Timer t3 = new Timer( Timer.TYPE.MILLIS ); private void goFind2( final GenericNode initialNode, final GenericNode terminalNode ) { t3.start(); final boolean ret = env.isVector( initialNode, terminalNode ); assert ret; t3.stop(); System.out.printf( "%10s -> %10s %10s%n", env.getName( initialNode ), env.getName( terminalNode ), t3.getDeltaPrintFriendly() ); } }
package org.clubrockisen.common; import static com.alexrnl.commons.translation.Translator.HIERARCHY_SEPARATOR; import com.alexrnl.commons.translation.GUIElement; import com.alexrnl.commons.translation.StandardDialog; /** * The Translation file key structure. * @author Alex */ public final class TranslationKeys { /** * Constructor #1.<br /> * Build the key structure. */ private TranslationKeys () { super(); } /** * The translations for the entities. * @author Alex */ public static final class Entity { /** The key to the entity structure */ private final String entityKey = "entity"; /** * Constructor #1.<br /> * Build the entity structure. */ private Entity () { super(); } @Override public String toString () { return entityKey; } /** * The translations for the member entity. * @author Alex */ public static final class Member { /** The key to the member structure */ private final String memberKey; /** * Constructor #1.<br /> * Build the member structure. * @param parentKey * the key from the parent category. */ private Member (final String parentKey) { super(); this.memberKey = parentKey + HIERARCHY_SEPARATOR + "member"; } @Override public String toString () { return memberKey; } /** * The member name. * @return The translation for the name field. */ public String name () { return memberKey + HIERARCHY_SEPARATOR + "name"; } /** * The member gender. * @return The translation for the gender field. */ public String gender () { return memberKey + HIERARCHY_SEPARATOR + "gender"; } /** * The member entry number. * @return The translation for the entry field. */ public String entries () { return memberKey + HIERARCHY_SEPARATOR + "entries"; } /** * The member credit. * @return The translation for the credit field. */ public String credit () { return memberKey + HIERARCHY_SEPARATOR + "credit"; } /** * The member status. * @return The translation for the status field. */ public String status () { return memberKey + HIERARCHY_SEPARATOR + "status"; } } /** * Access to the member translations. * @return the member translations. */ public Member member () { return new Member(entityKey); } /** * The translations for the party entity. * @author Alex */ public static final class Party { /** The key to the party structure */ private final String partyKey; /** * Constructor #1.<br /> * Build the party structure. * @param parentKey * the key from the parent category. */ private Party (final String parentKey) { super(); this.partyKey = parentKey + HIERARCHY_SEPARATOR + "party"; } @Override public String toString () { return partyKey; } /** * The party date. * @return the translation for the date field. */ public String date () { return partyKey + HIERARCHY_SEPARATOR + "date"; } /** * The total number of entries. * @return the translation for the total entries. */ public String entriesTotal () { return partyKey + HIERARCHY_SEPARATOR + "entriestotal"; } /** * The number of entries for the first part. * @return the translation for the first part entries. */ public String entriesFirstPart () { return partyKey + HIERARCHY_SEPARATOR + "entriesfirstpart"; } /** * The number of entries for the second part. * @return the translation for the second part entries. */ public String entriesSecondPart () { return partyKey + HIERARCHY_SEPARATOR + "entriessecondpart"; } /** * The number of entries for the new member. * @return the translation for the entries of new members. */ public String entriesNewMember () { return partyKey + HIERARCHY_SEPARATOR + "entriesnewmember"; } /** * The number of free entries. * @return the translation for the free entries. */ public String entriesFree () { return partyKey + HIERARCHY_SEPARATOR + "entriesfree"; } /** * The number of entries from males. * @return the translation for the male entries. */ public String entriesMale () { return partyKey + HIERARCHY_SEPARATOR + "entriesmale"; } /** * The number of entries from female. * @return the translation for the female entries. */ public String entriesFemale () { return partyKey + HIERARCHY_SEPARATOR + "entriesfemale"; } /** * The revenue of the party. * @return the translation for the revenue of the party. */ public String revenue () { return partyKey + HIERARCHY_SEPARATOR + "revenue"; } /** * The profit of the party. * @return the translation for the profit of the party. */ public String profit () { return partyKey + HIERARCHY_SEPARATOR + "profit"; } } /** * Access to the party translations. * @return the party translations. */ public Party party () { return new Party(entityKey); } } /** Access to the entity translations */ public static final TranslationKeys.Entity ENTITY = new Entity(); /** * The translations for the enumerations. * @author Alex */ public static final class Enum { /** The key to the enum structure */ private final String enumKey = "enum"; /** * Constructor #1.<br /> * Build the enum structure. */ private Enum () { super(); } @Override public String toString () { return enumKey; } /** * The translations for the genders. * @author Alex */ public static final class Gender { /** The key to the gender structure */ private final String genderKey; /** * Constructor #1.<br /> * @param parentKey * the key from the parent category. */ private Gender (final String parentKey) { super(); this.genderKey = parentKey + HIERARCHY_SEPARATOR + "gender"; } @Override public String toString () { return genderKey; } /** * The male gender. * @return the translation for the male gender. */ public String male () { return genderKey + HIERARCHY_SEPARATOR + "male"; } /** * The female gender. * @return the translation for the female gender. */ public String female () { return genderKey + HIERARCHY_SEPARATOR + "female"; } } /** * Access to the gender translations. * @return the gender translations. */ public Enum.Gender gender () { return new Gender(enumKey); } /** * The translations for the status. * @author Alex */ public static final class Status { /** The key to the gender structure */ private final String statusKey; /** * Constructor #1.<br /> * @param parentKey * the key from the parent category. */ private Status (final String parentKey) { super(); this.statusKey = parentKey + HIERARCHY_SEPARATOR + "status"; } @Override public String toString () { return statusKey; } /** * The member status. * @return the translation for the member status. */ public String member () { return statusKey + HIERARCHY_SEPARATOR + "member"; } /** * The helper member status. * @return the translation for the helper member status. */ public String helperMember () { return statusKey + HIERARCHY_SEPARATOR + "helperMember"; } /** * The office member status. * @return the translation for the office member status. */ public String officeMember () { return statusKey + HIERARCHY_SEPARATOR + "officeMember"; } /** * The veteran status. * @return the translation for the veteran status. */ public String veteran () { return statusKey + HIERARCHY_SEPARATOR + "veteran"; } } /** * Access to the gender translations. * @return the gender translations. */ public Enum.Status status () { return new Status(enumKey); } /** * The translations for the parameters. * @author Alex */ public static final class Parameter { /** The key to the gender structure */ private final String parameterKey; /** * Constructor #1.<br /> * @param parentKey * the key from the parent category. */ private Parameter (final String parentKey) { super(); this.parameterKey = parentKey + HIERARCHY_SEPARATOR + "parameter"; } @Override public String toString () { return parameterKey; } /** * The look and feel parameter. * @return the translation for the look and feel parameter. */ public String lookAndFeel () { return parameterKey + HIERARCHY_SEPARATOR + "look_and_feel"; } /** * The time limit parameter. * @return the translation for the time limit parameter. */ public String timeLimit () { return parameterKey + HIERARCHY_SEPARATOR + "time_limit"; } /** * The entry price total parameter. * @return the translation for the entry price total parameter. */ public String entryPriceTotal () { return parameterKey + HIERARCHY_SEPARATOR + "entry_price_total"; } /** * The entry price first price parameter. * @return the translation for the entry price first price parameter. */ public String entryPriceFirstPart () { return parameterKey + HIERARCHY_SEPARATOR + "entry_price_first_part"; } /** * The entry price second price parameter. * @return the translation for the entry price second price parameter. */ public String entryPriceSecondPart () { return parameterKey + HIERARCHY_SEPARATOR + "entry_price_second_part"; } /** * The free entry frequency parameter. * @return the translation for the free entry frequency parameter. */ public String freeEntryFrequency () { return parameterKey + HIERARCHY_SEPARATOR + "free_entry_frequency"; } /** * The minimum credit parameter. * @return the translation for the minimum credit parameter. */ public String minCredit () { return parameterKey + HIERARCHY_SEPARATOR + "min_credit"; } /** * The maximum credit parameter. * @return the translation for the maximum credit parameter. */ public String maxCredit () { return parameterKey + HIERARCHY_SEPARATOR + "max_credit"; } } /** * Access to the parameters translations. * @return the parameters translations. */ public Enum.Parameter parameter () { return new Parameter(enumKey); } } /** Access to the enumeration translations */ public static final TranslationKeys.Enum ENUM = new Enum(); /** * The formats translation * @author Alex */ public static final class Formats { /** The key to the format structure */ private final String formatsKey = "formats"; /** * Constructor #1.<br /> * Build the formats structure. */ private Formats () { super(); } /** * The old file format. * @return the translation for the old file format. */ public String oldFileFormat () { return formatsKey + HIERARCHY_SEPARATOR + "oldFileFormat"; } } /** Access to the formats translations */ public static final TranslationKeys.Formats FORMATS = new Formats(); /** * The GUI related translations * @author Alex */ public static final class Gui { /** The key to the GUI structure */ private final String guiKey = "gui"; /** * Constructor #1.<br /> * Build the GUI structure. */ private Gui () { super(); } @Override public String toString () { return guiKey; } /** * The title of the application. * @return the translation for the application's title. */ public String title () { return guiKey + HIERARCHY_SEPARATOR + "title"; } /** * The menu translation. * @author Alex */ public static final class Menu { /** The key to the menu structure */ private final String menuKey; /** * Constructor #1.<br /> * Build the menu structure. * @param parentKey * the key from the parent category. */ private Menu (final String parentKey) { super(); menuKey = parentKey + HIERARCHY_SEPARATOR + "menu"; } @Override public String toString () { return menuKey; } /** * The file menu translation. * @author Alex */ public static final class File { /** The key to the file menu */ private final String fileKey; /** * Constructor #1.<br /> * Build the file menu structure. * @param parentKey * the key from the parent category. */ private File (final String parentKey) { super(); fileKey = parentKey + HIERARCHY_SEPARATOR + "file"; } @Override public String toString () { return fileKey; } /** * The parameters item. * @return the translation for the parameters item. */ public GUIElement parameters () { return new GUIElement(fileKey + HIERARCHY_SEPARATOR + "parameters"); } /** * The quit item. * @return the translation for the quit item. */ public GUIElement quit () { return new GUIElement(fileKey + HIERARCHY_SEPARATOR + "quit"); } } /** * Access to the file menu translations. * @return the file menu translations. */ public Menu.File file () { return new File(menuKey); } /** * The database menu translation. * @author Alex */ public static final class Database { /** The key to the file menu */ private final String databaseKey; /** * Constructor #1.<br /> * Build the database menu structure. * @param parentKey * the key from the parent category. */ private Database (final String parentKey) { super(); databaseKey = parentKey + HIERARCHY_SEPARATOR + "database"; } @Override public String toString () { return databaseKey; } /** * The see members item. * @return the translation for the see members item. */ public GUIElement seeMembers () { return new GUIElement(databaseKey + HIERARCHY_SEPARATOR + "seeMembers"); } /** * The see attendees item. * @return the translation for the see attendees item. */ public GUIElement seeAttendees () { return new GUIElement(databaseKey + HIERARCHY_SEPARATOR + "seeAttendees"); } /** * The import data item. * @return the translation for the import data item. */ public GUIElement importData () { return new GUIElement(databaseKey + HIERARCHY_SEPARATOR + "importData"); } /** * The export data item. * @return the translation for the export data item. */ public GUIElement exportData () { return new GUIElement(databaseKey + HIERARCHY_SEPARATOR + "exportData"); } } /** * Access to the database menu translations. * @return the database menu translations. */ public Menu.Database database () { return new Database(menuKey); } /** * The member menu translation. * @author Alex */ public static final class Member { /** The key to the member menu */ private final String memberKey; /** * Constructor #1.<br /> * Build the member menu structure. * @param parentKey * the key from the parent category. */ private Member (final String parentKey) { super(); memberKey = parentKey + HIERARCHY_SEPARATOR + "member"; } @Override public String toString () { return memberKey; } /** * The new member item. * @return the translation for the new member item. */ public GUIElement newMember () { return new GUIElement(memberKey + HIERARCHY_SEPARATOR + "newMember"); } /** * The delete member item. * @return the translation for the delete member item. */ public GUIElement deleteMember () { return new GUIElement(memberKey + HIERARCHY_SEPARATOR + "deleteMember"); } /** * The update member item. * @return the translation for the update member item. */ public GUIElement updateMember () { return new GUIElement(memberKey + HIERARCHY_SEPARATOR + "updateMember"); } } /** * Access to the member menu translations. * @return the member menu translations. */ public Menu.Member member () { return new Member(menuKey); } /** * The help menu translation. * @author Alex */ public static final class Help { /** The key to the help menu */ private final String helpKey; /** * Constructor #1.<br /> * Build the help menu structure. * @param parentKey * the key from the parent category. */ public Help (final String parentKey) { super(); helpKey = parentKey + HIERARCHY_SEPARATOR + "help"; } @Override public String toString () { return helpKey; } /** * The help item. * @return the translation for the help item. */ public GUIElement help () { return new GUIElement(helpKey + HIERARCHY_SEPARATOR + "help"); } /** * The about item. * @return the translation for the about item. */ public GUIElement about () { return new GUIElement(helpKey + HIERARCHY_SEPARATOR + "about"); } } /** * Access to the help menu translations. * @return the help menu translations. */ public Menu.Help help () { return new Help(menuKey); } } /** * Access to the menu translations. * @return the menu translations. */ public Menu menu () { return new Menu(guiKey); } /** * The parameters manager panel. * @author Alex */ public static final class Parameters { /** The key to parameters panel */ private final String parametersKey; /** * Constructor #1.<br /> * Build the structure for the parameter's panel translations. * @param parentKey * the key from the parent category. */ private Parameters (final String parentKey) { super(); parametersKey = parentKey + HIERARCHY_SEPARATOR + "parameters"; } @Override public String toString () { return parametersKey; } /** * The title of the panel. * @return the translation for the panel. */ public String title () { return parametersKey + HIERARCHY_SEPARATOR + "title"; } } /** * Access to the parameters manager translations. * @return the parameters manager translations. */ public Parameters parameters () { return new Parameters(guiKey); } /** * The buttons translations. * @author Alex */ public static final class Buttons { /** The key to the buttons translations */ private final String buttonsKey; /** * Constructor #1.<br /> * Build the buttons structure. * @param parentKey * the key from the parent category. */ public Buttons (final String parentKey) { super(); buttonsKey = parentKey + HIERARCHY_SEPARATOR + "buttons"; } /** * The enter button. * @return the text of the enter button. */ public String enter () { return buttonsKey + HIERARCHY_SEPARATOR + "enter"; } /** * The update button. * @return the text of the update button. */ public String update () { return buttonsKey + HIERARCHY_SEPARATOR + "update"; } @Override public String toString () { return buttonsKey; } } /** * Access to the translations for the buttons. * @return the buttons translation. */ public Buttons buttons () { return new Buttons(guiKey); } /** * The dialog translations. * @author Alex */ public static final class Dialog { /** The key to dialogs */ private final String dialogKey; /** * Constructor #1.<br /> * Build the dialog structure. * @param parentKey * the key from the parent category. */ private Dialog (final String parentKey) { super(); dialogKey = parentKey + HIERARCHY_SEPARATOR + "dialog"; } @Override public String toString () { return dialogKey; } /** * Access to the translations for the about dialog. * @param author * the author of the application. * @return the about dialog translations. */ public StandardDialog about (final String author) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "about", author); } /** * Access to the translations for the not selected member dialog. * @return the not selected member dialog translations. */ public StandardDialog notSelectedMember () { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "notSelectedMember"); } /** * Access to the translations for the not persisted member. * @return the not selected member dialog translations. */ public StandardDialog notPersistedMember () { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "notPersistedMember"); } /** * Access to the translations for the not persisted parameter. * @return the not persisted parameter dialog translations. */ public StandardDialog notPersistedParameter () { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "notPersistedParameter"); } /** * Access to the translations for the unparsable date dialog. * @param date * the date which could not be parsed. * @return the unparsable date dialog translations. */ public StandardDialog unparsableDate (final String date) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "unparsableDate", date); } /** * Access to the translations for the help not displayable dialog. * @return the help not displayable dialog translations. */ public StandardDialog helpNotDisplayable () { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "helpNotFound"); } /** * Access to the translations for the confirm dialog on member deletion. * @param memberName * the name of the member to delete. * @return the delete member dialog translations. */ public StandardDialog deleteMember (final String memberName) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "deleteMember", memberName); } /** * Access to the file import successful dialog. * @param fileName * the name of the file imported. * @param memberImported * the number of member successfully imported. * @return the file import successful dialog. */ public StandardDialog fileImportSuccessful (final String fileName, final int memberImported) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "fileImportSucceed", fileName, memberImported); } /** * Access to the file import failed dialog. * @param fileName * the name of the file imported. * @return the file import failed dialog. */ public StandardDialog fileImportFailed (final String fileName) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "fileImportFailed", fileName); } /** * Access to the choose format dialog. * @return the choose format dialog. */ public StandardDialog chooseFormat () { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "chooseFormat"); } /** * Access to the file export successful dialog. * @param fileName * the name of the file imported. * @return the file export successful dialog. */ public StandardDialog fileExportSuccessful (final String fileName) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "fileExportSucceed", fileName); } /** * Access to the file export failed dialog. * @param fileName * the name of the file exported. * @return the file export failed dialog. */ public StandardDialog fileExportFailed (final String fileName) { return new StandardDialog(dialogKey + HIERARCHY_SEPARATOR + "fileExportFailed", fileName); } /** * Access to the free entry dialog. * @param memberName * the name of the member whose entry is free. * @return the free entry dialog. */ public StandardDialog freeEntry (final String memberName) { return new StandardDialog (dialogKey + HIERARCHY_SEPARATOR + "freeEntry", memberName); } /** * Access to the entry price dialog. * @param memberName * the name of the member whose entry is free. * @param price * the price the member has to pay. * @return the entry price dialog. */ public StandardDialog entryPrice (final String memberName, final double price) { return new StandardDialog (dialogKey + HIERARCHY_SEPARATOR + "entryPrice", memberName, price); } /** * Access to the member entry dialog. * @param memberName * the name of the member whose entry is free. * @return the member entry dialog. */ public StandardDialog memberEntry (final String memberName) { return new StandardDialog (dialogKey + HIERARCHY_SEPARATOR + "memberEntry", memberName); } /** * Access to the member entry failed dialog. * @param memberName * the name of the member whose entry is free. * @return the member entry failed dialog. */ public StandardDialog memberEntryFailed (final String memberName) { return new StandardDialog (dialogKey + HIERARCHY_SEPARATOR + "memberEntryFailed", memberName); } } /** * Access to the translations for the dialog. * @return the dialog translations. */ public Gui.Dialog dialog () { return new Dialog(guiKey); } } /** Access to the GUI related translations. */ public static final TranslationKeys.Gui GUI = new Gui(); /** * The miscellaneous translations. * @author Alex */ public static final class Misc { /** The key to the miscellaneous */ private final String miscKey = "misc"; /** * Constructor #1.<br /> * Build the miscellaneous structure. */ private Misc () { super(); } @Override public String toString () { return miscKey; } /** * The field / value separator. * @return the translation for the field / value separator. */ public String fieldValueSeparator () { return miscKey + HIERARCHY_SEPARATOR + "fieldValueSeparator"; } /** * The currency symbol to use. * @return the translation for the currency symbol. */ public String currencySymbol () { return miscKey + HIERARCHY_SEPARATOR + "currencySymbol"; } /** * The plural letter of the language. * @return the plural letter of the language. */ public String pluralLetter () { return miscKey + HIERARCHY_SEPARATOR + "pluralLetter"; } /** * The 'OK' text to use. * @return the translation for the OK. */ public String ok () { return miscKey + HIERARCHY_SEPARATOR + "ok"; } /** * The 'cancel' text to use. * @return the translation for the cancel. */ public String cancel () { return miscKey + HIERARCHY_SEPARATOR + "cancel"; } /** * The 'apply' text to use. * @return the translation for the apply. */ public String apply () { return miscKey + HIERARCHY_SEPARATOR + "apply"; } } /** Access to the miscellaneous translations. */ public static final TranslationKeys.Misc MISC = new Misc(); }
package org.elasticsearch.datagen; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import org.elasticsearch.action.WriteConsistencyLevel; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.support.replication.ReplicationType; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import com.fasterxml.jackson.databind.ObjectMapper; public class DataGenerator { private static Random rand = new Random(); private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); private static ObjectMapper mapper = new ObjectMapper(); private static final String[] CATEGORIES = { "Home", "Grocery", "Outdoor", "Hardware", "Plumbing", "Clothing" }; private static final float[] PRICES = { 23.99f, 99.99f, 50f, 100f, 299.95f, 88.50f, 37.25f, 5.77f }; private static final String[] DESCRIPTIONS = { "Bottle Opener", "Toilet Paper (single-ply)", "Toilet Paper (2-ply)", "Paper Plates (500x)", "Paper Plates (150x)", "PVC Pipe - L-joint - 3.25\"", "Paint - White", "Lawn Chair", "Screwdriver", "Polo Shirt", "Pepperoni Pizza" }; private static final int[] UNITS = { 1, 2, 3, 5, 17, 25, 99 }; public static void main(String[] args) throws Exception { new DataGenerator().run(); } private static Client getClient() { String clusterName = getProperty("es.cluster.name", "elasticsearch"); Settings settings = ImmutableSettings .settingsBuilder() .put("cluster.name", clusterName) .build(); String[] hosts = getProperty("es.unicast.hosts", "localhost").split(","); int port = getProperty("es.unicast.port", 9300); TransportClient client = new TransportClient(settings); for (String host : hosts) { client.addTransportAddress(new InetSocketTransportAddress(host, port)); } return client; } private static BulkRequestBuilder getRequest(Client client) { return client.prepareBulk() .setConsistencyLevel(WriteConsistencyLevel.DEFAULT) .setReplicationType(ReplicationType.SYNC) .setRefresh(false) .setTimeout("30s"); } private void run() throws Exception { String index = getProperty("es.index.name", "items"); String mapping = getProperty("es.mapping.name", "purchases"); Client client = getClient(); BulkRequestBuilder request = getRequest(client); int durationMinutes = getProperty("es.duration", 30); int volPerSec = getProperty("es.volume", 50); long now = System.currentTimeMillis(); long then = now - (durationMinutes * 60 * 1000l); for (long x = then; x <= now; x += 1000) { for (int y = 0, r = rand.nextInt(volPerSec) + 1; y < r; y++) { String descr = rand(DESCRIPTIONS); String cat = rand(CATEGORIES); int units = rand(UNITS); float price = rand(PRICES); float total = price * units; Date date = new Date(x); // System.out.printf("%-35s %-40s %-12s $%7.2f %5d $%9.2f", date.toString(), descr, cat, price, units, total); // System.out.println(); Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("timestamp", df.format(date)); map.put("description", descr); map.put("category", cat); map.put("units", units); map.put("price", price); map.put("total", total); String json = mapper.writeValueAsString(map); // System.out.println(json); request.add(client.prepareIndex(index, mapping).setSource(json)); } request.execute().actionGet(); request = getRequest(client); } client.close(); } private static String rand(String[] elems) { int index = rand.nextInt(elems.length); return elems[index]; } private static float rand(float[] elems) { int index = rand.nextInt(elems.length); return elems[index]; } private static int rand(int[] elems) { int index = rand.nextInt(elems.length); return elems[index]; } private static String getProperty(String key, String defaultValue) { return System.getProperty(key, defaultValue); } private static int getProperty(String key, int defaultValue) { int intValue = defaultValue; try { String value = System.getProperty(key); if (value != null) { intValue = Integer.parseInt(value); } } catch (NumberFormatException ignored) { } return intValue; } }
package org.formula.swing.binding; import java.util.ArrayList; import java.util.List; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableModel; import org.formula.binding.FormBinder; import org.formula.binding.PropertyMap; import org.formula.converter.Converter; import org.formula.swing.table.FormulaTableModel; /** * TODO: This binding is read only for now. That needs to change eventually. */ public class JTableBinding extends SwingFormFieldBinding<JTable> implements ListSelectionListener { private String selectionProperty; public JTableBinding(JTable jTable, FormBinder formBinder, PropertyMap propertyMap, String property, String[] labelProperties, String optionsProperty, String selectionProperty, boolean required, boolean errorIndicator, Converter converter) { super(jTable, formBinder, propertyMap, property, labelProperties, optionsProperty, required, errorIndicator, converter); if (!selectionProperty.isEmpty()) { getPropertyMap().put(selectionProperty, null); jTable.getSelectionModel().addListSelectionListener(this); this.selectionProperty = selectionProperty; } } @Override @SuppressWarnings("unchecked") protected void doRead() { if (getPropertyValue() != null) { if (getView().getModel() instanceof FormulaTableModel) { FormulaTableModel formulaTableModel = (FormulaTableModel) getView().getModel(); formulaTableModel.setObjects((List) getPropertyValue()); } else { getView().setModel((TableModel) getPropertyValue()); } } } @Override protected void doReadLabel() { } @Override protected void doReadOptions() { } @Override public void enable(boolean enable) { getView().setEnabled(enable); } @Override public void focus() { getView().requestFocusInWindow(); } @SuppressWarnings("unchecked") protected void doWriteSelection() { if (getView().getModel() instanceof FormulaTableModel) { FormulaTableModel formulaTabelModel = (FormulaTableModel) getView().getModel(); List selectedObjects = new ArrayList(); int[] selectedRows = getView().getSelectedRows(); for (int row : selectedRows) { selectedObjects.add(formulaTabelModel.getObjects().get(row)); } if (getView().getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) { getPropertyMap().put(this.selectionProperty, selectedObjects.get(0)); } else { getPropertyMap().put(this.selectionProperty, selectedObjects); } getFormBinder().commitProperty(this.selectionProperty); } } @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && this.selectionProperty != null) { doWriteSelection(); } } }
package org.jenkinsci.backend.ircbot; import com.atlassian.jira.rest.client.domain.AssigneeType; import hudson.plugins.jira.soap.JiraSoapService; import hudson.plugins.jira.soap.JiraSoapServiceServiceLocator; import hudson.plugins.jira.soap.RemoteIssue; import hudson.plugins.jira.soap.RemoteStatus; import org.apache.axis.collections.LRUMap; import org.apache.commons.io.IOUtils; import org.jenkinsci.jira_scraper.ConnectionInfo; import org.jenkinsci.jira_scraper.JiraScraper; import org.jibble.pircbot.PircBot; import org.jibble.pircbot.User; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHOrganization.Permission; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GHTeam; import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.rpc.ServiceException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.rmi.RemoteException; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.*; /** * IRC Bot on irc.freenode.net as a means to delegate administrative work to committers. * * @author Kohsuke Kawaguchi */ public class IrcBotImpl extends PircBot { /** * Records commands that we didn't understand. */ private File unknownCommands; /** * Map from the issue number to the time it was last mentioned. * Used so that we don't repeatedly mention the same issues. */ private final Map recentIssues = Collections.synchronizedMap(new LRUMap(10)); public IrcBotImpl(File unknownCommands) { setName("jenkins-admin"); this.unknownCommands = unknownCommands; } @Override protected void onMessage(String channel, String sender, String login, String hostname, String message) { if (!channel.equals("#jenkins")) return; // not in this channel if (sender.equals("jenkinsci_builds")) return; // ignore messages from other bots message = message.trim(); String prefix = getNick() + ":"; if (!message.startsWith(prefix)) { // not send to me Matcher m = Pattern.compile("(?:hudson-|jenkins-|bug )([0-9]+)",CASE_INSENSITIVE).matcher(message); while (m.find()) { replyBugStatus(channel,m.group(1)); } return; } String payload = message.substring(prefix.length(), message.length()).trim(); // replace duplicate whitespace with a single space payload = payload.replaceAll("\\s+", " "); Matcher m; m = Pattern.compile("(?:create|make|add) (\\S+)(?: repository)? (?:on|in) github(?: for (\\S+))?",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { createGitHubRepository(channel, m.group(1), m.group(2)); return; } m = Pattern.compile("fork (\\S+)/(\\S+)(?: on github)?(?: as (\\S+))?",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { forkGitHub(channel, m.group(1),m.group(2),m.group(3)); return; } m = Pattern.compile("(?:make|give|grant|add) (\\S+)(?: as)? (?:a )?(?:committ?er|commit access) (?:of|on|to|at) (\\S+)",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { addGitHubCommitter(channel,sender,m.group(1),m.group(2)); return; } m = Pattern.compile("(?:make|give|grant|add) (\\S+)(?: as)? (a )?(committ?er|commit access).*",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { addGitHubCommitter(channel,sender,m.group(1),null); return; } m = Pattern.compile("(?:create|make|add) (\\S+)(?: component)? in (?:the )?(?:issue|bug)(?: tracker| database)? for (\\S+)",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { createComponent(channel, sender, m.group(1), m.group(2)); return; } m = Pattern.compile("(?:make|give|grant|add) (\\S+) voice(?: on irc)?",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { grantAutoVoice(channel,sender,m.group(1)); return; } m = Pattern.compile("(?:rem|remove|ungrant|del|delete) (\\S+) voice(?: on irc)?",CASE_INSENSITIVE).matcher(payload); if (m.matches()) { removeAutoVoice(channel,sender,m.group(1)); return; } if (payload.equalsIgnoreCase("version")) { version(channel); return; } if (payload.equalsIgnoreCase("help")) { help(channel); return; } if (payload.equalsIgnoreCase("refresh")) { // get the updated list sendRawLine("NAMES #jenkins"); return; } sendMessage(channel,"I didn't understand the command"); try { PrintWriter w = new PrintWriter(new FileWriter(unknownCommands, true)); w.println(payload); w.close(); } catch (IOException e) {// if we fail to write, let it be. e.printStackTrace(); } } private void replyBugStatus(String channel, String number) { Long time = (Long)recentIssues.get(number); recentIssues.put(number,System.currentTimeMillis()); if (time!=null) { if (System.currentTimeMillis()-time < 60*1000) { return; // already mentioned recently. don't repeat } } try { sendMessage(channel, getSummary(number)); } catch (Exception e) { e.printStackTrace(); } } private String getSummary(String number) throws ServiceException, IOException { JiraSoapService svc = new JiraSoapServiceServiceLocator().getJirasoapserviceV2(new URL("http://issues.jenkins-ci.org/rpc/soap/jirasoapservice-v2")); ConnectionInfo con = new ConnectionInfo(); String token = svc.login(con.userName, con.password); RemoteIssue issue = svc.getIssue(token, "JENKINS-" + number); return String.format("%s:%s (%s) %s", issue.getKey(), issue.getSummary(), findStatus(svc,token,issue.getStatus()).getName(), "http://jenkins-ci.org/issue/"+number); } private RemoteStatus findStatus(JiraSoapService svc, String token, String statusId) throws RemoteException { RemoteStatus[] statuses = svc.getStatuses(token); for (RemoteStatus s : statuses) if(s.getId().equals(statusId)) return s; return null; } /** * Is the sender respected in the channel? * * IOW, does he have a voice of a channel operator? */ private boolean isSenderAuthorized(String channel, String sender) { for (User u : getUsers(channel)) { System.out.println(u.getPrefix()+u.getNick()); if (u.getNick().equals(sender)) { String p = u.getPrefix(); if (p.contains("@") || p.contains("+")) return true; } } return false; } @Override protected void onDisconnect() { while (!isConnected()) { try { reconnect(); joinChannel("#jenkins"); } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(3000); } catch (InterruptedException _) { return; // abort } } } } private void help(String channel) { sendMessage(channel,"See http://wiki.jenkins-ci.org/display/JENKINS/IRC+Bot"); } private void version(String channel) { try { String v = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("version.txt")); sendMessage(channel,"My version is "+v); } catch (IOException e) { e.printStackTrace(); sendMessage(channel,"I don't know who I am"); } } private void insufficientPermissionError(String channel) { sendMessage(channel,"Only people with + or @ can run this command."); // I noticed that sometimes the bot just get out of sync, so ask the sender to retry sendRawLine("NAMES #jenkins"); sendMessage(channel,"I'll refresh the member list, so if you think this is an error, try again in a few seconds."); } /** * Creates an issue tracker component. */ private void createComponent(String channel, String sender, String subcomponent, String owner) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } sendMessage(channel,String.format("Adding a new subcomponent %s to the bug tracker, owned by %s",subcomponent,owner)); try { JiraScraper js = new JiraScraper(); js.createComponent("JENKINS", subcomponent, owner, AssigneeType.COMPONENT_LEAD); sendMessage(channel,"New component created"); } catch (Exception e) { sendMessage(channel,"Failed to create a new component: "+e.getMessage()); e.printStackTrace(); } } private void grantAutoVoice(String channel, String sender, String target) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } sendMessage("CHANSERV", "flags " + channel + " " + target + " +V"); sendMessage("CHANSERV", "voice " + channel + " " + target); sendMessage(channel, "Voice priviledge (+V) added for " + target); } private void removeAutoVoice(String channel, String sender, String target) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } sendMessage("CHANSERV", "flags " + channel + " " + target + " -V"); sendMessage("CHANSERV", "devoice " + channel + " " + target); sendMessage(channel, "Voice priviledge (-V) removed for " + target); } private void createGitHubRepository(String channel, String name, String collaborator) { try { GitHub github = GitHub.connect(); GHOrganization org = github.getOrganization("jenkinsci"); GHRepository r = org.createRepository(name, "", "", "Everyone", true); setupRepository(r); GHTeam t = getOrCreateRepoLocalTeam(org, r); if (collaborator!=null) t.add(github.getUser(collaborator)); sendMessage(channel,"New github repository created at "+r.getUrl()); } catch (IOException e) { sendMessage(channel,"Failed to create a repository: "+e.getMessage()); e.printStackTrace(); } } /** * Adds a new collaborator to existing repositories. * * @param justForThisRepo * Null to add to "Everyone", otherwise add him to a team specific repository. */ private void addGitHubCommitter(String channel, String sender, String collaborator, String justForThisRepo) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } try { GitHub github = GitHub.connect(); GHUser c = github.getUser(collaborator); GHOrganization o = github.getOrganization("jenkinsci"); GHTeam t = justForThisRepo==null ? o.getTeams().get("Everyone") : o.getTeams().get(justForThisRepo+" Developers"); if (t==null) { sendMessage(channel,"No team for "+justForThisRepo); return; } t.add(c); o.publicize(c); sendMessage(channel,"Added "+collaborator+" as a GitHub committer"); } catch (IOException e) { sendMessage(channel,"Failed to create a repository: "+e.getMessage()); e.printStackTrace(); } } /** * @param newName * If not null, rename a epository after a fork. */ private void forkGitHub(String channel, String owner, String repo, String newName) { try { sendMessage(channel, "Forking "+repo); GitHub github = GitHub.connect(); GHUser user = github.getUser(owner); if (user==null) { sendMessage(channel,"No such user: "+owner); return; } GHRepository orig = user.getRepository(repo); if (orig==null) { sendMessage(channel,"No such repository: "+repo); return; } GHOrganization org = github.getOrganization("jenkinsci"); GHRepository r; try { r = orig.forkTo(org); } catch (IOException e) { // we started seeing 500 errors, presumably due to time out. // give it a bit of time, and see if the repository is there System.out.println("GitHub reported that it failed to fork "+owner+"/"+repo+". But we aren't trusting"); Thread.sleep(3000); r = org.getRepository(repo); if (r==null) throw e; } if (newName!=null) r.renameTo(newName); // GitHub adds a lot of teams to this repo by default, which we don't want Set<GHTeam> legacyTeams = r.getTeams(); GHTeam t = getOrCreateRepoLocalTeam(org, r); t.add(user); // the user immediately joins this team // the Everyone group gets access to this new repository, too. GHTeam everyone = org.getTeams().get("Everyone"); everyone.add(r); setupRepository(r); sendMessage(channel, "Created https://github.com/jenkinsci/" + (newName != null ? newName : repo)); // remove all the existing teams for (GHTeam team : legacyTeams) team.remove(r); } catch (InterruptedException e) { sendMessage(channel,"Failed to fork a repository: "+e.getMessage()); e.printStackTrace(); } catch (IOException e) { sendMessage(channel,"Failed to fork a repository: "+e.getMessage()); e.printStackTrace(); } } /** * Fix up the repository set up to our policy. */ private void setupRepository(GHRepository r) throws IOException { r.setEmailServiceHook(POST_COMMIT_HOOK_EMAIL); r.enableIssueTracker(false); r.enableWiki(false); } /** * Creates a repository local team, and grants access to the repository. */ private GHTeam getOrCreateRepoLocalTeam(GHOrganization org, GHRepository r) throws IOException { String teamName = r.getName() + " Developers"; GHTeam t = org.getTeams().get(teamName); if (t==null) { t = org.createTeam(teamName, Permission.ADMIN, r); } else { t.add(r); } return t; } public static void main(String[] args) throws Exception { IrcBotImpl bot = new IrcBotImpl(new File("unknown-commands.txt")); bot.connect("irc.freenode.net"); bot.setVerbose(true); bot.joinChannel("#jenkins"); if (args.length>0) { System.out.println("Authenticating with NickServ"); bot.sendMessage("nickserv","identify "+args[0]); } } static { class TrustAllManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] x509Certificates, String s) { } public void checkServerTrusted(X509Certificate[] x509Certificates, String s) { } } try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new TrustAllManager()}, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException e) { throw new Error(e); } } static final String POST_COMMIT_HOOK_EMAIL = "jenkinsci-commits@googlegroups.com"; }
package de.eightbitboy.ecorealms; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.math.Vector3; import de.eightbitboy.ecorealms.logic.Map; import de.eightbitboy.ecorealms.world.World; public class EcoRealms extends ApplicationAdapter { private EcoRealmsConfig config; private World world; private Environment environment; private PerspectiveCamera cam; private ModelBatch modelBatch; private Control control; private Gizmo gizmo; public EcoRealms() { this.config = new EcoRealmsConfig(); } @Override public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); createWorld(); createEnvironment(); createCamera(); modelBatch = new ModelBatch(); gizmo = new Gizmo(); control = new Control(cam); Gdx.input.setInputProcessor(control); } @Override public void render() { Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); //unproject, pickray control.update(); modelBatch.begin(cam); renderModels(); modelBatch.end(); } @Override public void dispose() { modelBatch.dispose(); } @SuppressWarnings("ConstantConditions") private void renderModels() { modelBatch.render(world.getModelInstances(), environment); if (config.showGizmo) modelBatch.render(gizmo.getModelInstances(), environment); } private void createWorld() { Map map = new Map(config.WORLD_SIZE_X, config.WORLD_SIZE_Y); world = new World(map); } private void createEnvironment() { environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 1f, 0.5f, -0.8f)); } private void createCamera() { cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(-10f, -10f, 10f); cam.rotate(new Vector3(1, 0, 0), 90); cam.lookAt(0, 0, 0); cam.near = 1f; cam.far = 300f; cam.update(); } }
package cucumber.runtime; import cucumber.resources.Resources; import cucumber.runtime.transformers.Transformers; import gherkin.formatter.Argument; import gherkin.formatter.model.Step; import java.util.*; import static java.util.Arrays.asList; public class Runtime { private final Transformers transformers = new Transformers(); private final List<Step> undefinedSteps = new ArrayList<Step>(); private final List<Backend> backends; public Runtime(Backend... backends) { this.backends = asList(backends); } public Runtime(String packageName) { backends = Resources.instantiateSubclasses(Backend.class, "cucumber.runtime", packageName); } public StepDefinitionMatch stepDefinitionMatch(String uri, Step step) { List<StepDefinitionMatch> matches = stepDefinitionMatches(uri, step); if (matches.size() == 0) { undefinedSteps.add(step); return null; } if (matches.size() == 1) { return matches.get(0); } else { throw new AmbiguousStepDefinitionsException(matches); } } private List<StepDefinitionMatch> stepDefinitionMatches(String uri, Step step) { List<StepDefinitionMatch> result = new ArrayList<StepDefinitionMatch>(); for (Backend backend : backends) { for (StepDefinition stepDefinition : backend.getStepDefinitions()) { List<Argument> arguments = stepDefinition.matchedArguments(step); if (arguments != null) { result.add(new StepDefinitionMatch(arguments, stepDefinition, uri, step, this.transformers)); } } } return result; } /** * @return a list of code snippets that the developer can use to implement undefined steps. * This should be displayed after a run. */ public List<String> getSnippets() { // TODO: Convert "And" and "But" to the Given/When/Then keyword above. Collections.sort(undefinedSteps, new Comparator<Step>() { public int compare(Step a, Step b) { int keyword = a.getKeyword().compareTo(b.getKeyword()); if (keyword == 0) { return a.getName().compareTo(b.getName()); } else { return keyword; } } }); List<String> snippets = new ArrayList<String>(); for (Step step : undefinedSteps) { for (Backend backend : backends) { String snippet = backend.getSnippet(step); if (!snippets.contains(snippet)) { snippets.add(snippet); } } } return snippets; } public World newWorld(Set<String> tags) { return new World(backends, this, tags); } // XXX: should this be ctor initialized? public void addStepdefScanPath(String[] packages) { for (String packageName : packages) { if(packageName.matches("^([a-z]\\w*\\.?)+$")) backends.addAll(Resources.instantiateSubclasses(Backend.class, "cucumber.runtime", packageName)); else throw new CucumberException("Additional package isn't valid: " + packageName); } } }
package org.karaffe.compiler.util; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Objects; public class KaraffeSource implements CharSequence { private final String sourceName; private final String source; private final List<String> lines; private final CharStream charStream; private KaraffeSource(String source) { this(source, "<unknown>"); } private KaraffeSource(String source, String virtualSourceName) { this.sourceName = Objects.requireNonNull(virtualSourceName); this.source = Objects.requireNonNull(source); this.lines = Arrays.asList(source.split("\r\n|[\n\r\u2028\u2029\u0085]")); //java.util.Scanner#LINE_SEPARATOR_PATTERN this.charStream = CharStreams.fromString(source, virtualSourceName); } private KaraffeSource(Path path) throws IOException { Objects.requireNonNull(path); List<String> strings = Files.readAllLines(path, StandardCharsets.UTF_8); this.sourceName = path.toString(); this.source = strings.stream().reduce((l, r) -> l + "\n" + r).orElse(""); this.lines = Arrays.asList(source.split("\r\n|[\n\r\u2028\u2029\u0085]")); //java.util.Scanner#LINE_SEPARATOR_PATTERN this.charStream = CharStreams.fromPath(path); } public static KaraffeSource fromString(String source) { return new KaraffeSource(source); } public static KaraffeSource fromString(String source, String virtualSourceName) { return new KaraffeSource(source, virtualSourceName); } public static KaraffeSource fromPath(Path path) throws IOException { return new KaraffeSource(path); } public String getSourceName() { return this.sourceName; } public String getCodeByLine(int line) { return this.lines.get(line - 1); } @Override public int length() { return this.source.length(); } @Override public char charAt(int index) { return this.source.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.source.subSequence(start, end); } @Override public String toString() { return this.source; } public CharStream asCharStream() { return this.charStream; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; KaraffeSource that = (KaraffeSource) o; return sourceName.equals(that.sourceName) && source.equals(that.source); } @Override public int hashCode() { return Objects.hash(sourceName, source); } }
package detective.core; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import groovy.json.JsonBuilder; import groovy.json.JsonSlurper; import groovy.lang.Closure; import groovy.util.XmlSlurper; import groovy.xml.MarkupBuilder; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; import org.hamcrest.core.IsNot; import com.typesafe.config.Config; import detective.common.trace.TraceRecord; import detective.common.trace.TraceRecordBuilder; import detective.common.trace.TraceRecorder; import detective.common.trace.impl.TraceRecorderElasticSearchImpl; import detective.core.dsl.WrappedObject; import detective.core.dsl.builder.DslBuilder; import detective.core.matcher.IsEqual; import detective.core.matcher.Subset; import detective.core.runner.DslBuilderAndRun; import detective.core.services.DetectiveFactory; import detective.task.EchoTask; import detective.task.HttpClientTask; import detective.utils.StringUtils; public class Detective { private enum Recorder { INSTANCE; private final transient TraceRecorderElasticSearchImpl recorder = new TraceRecorderElasticSearchImpl(); public TraceRecorder getRecorder() { return recorder; } } public enum LogLevel{ FATAL, ERROR, WARN, INFO, DEBUG, TRACE; } public static DslBuilder story(){ return new DslBuilderAndRun(); } public static DslBuilder feature(){ return new DslBuilderAndRun(); } public static JsonBuilder jsonBuilder(){ return new JsonBuilder(); } public static JsonBuilder jsonBuilder(Closure c){ JsonBuilder builder = new JsonBuilder(); builder.call(c); return builder; } public static Object jsonParser(String json){ return (new JsonSlurper()).parseText(json); } public static MarkupBuilder xmlBuilder(Closure c){ MarkupBuilder builder = new MarkupBuilder(); return builder; } public static Object xmlParser(String xml){ try { return (new XmlSlurper()).parseText(xml); } catch (Throwable e) { throw new RuntimeException(e); } } public static TraceRecord record(TraceRecord record){ Recorder.INSTANCE.getRecorder().record(record); return record; } public static TraceRecord recordLog(LogLevel level, String message){ TraceRecord record = TraceRecordBuilder.newRecord().withSimpleDateAsHashKey().getRecord(); record.setType("log"); record.setCaption(message); return record(record); } public static TraceRecord info(String message){ return recordLog(LogLevel.INFO, message); } public static TraceRecord error(String message){ return recordLog(LogLevel.ERROR, message); } public static TraceRecord error(String message, Throwable e){ TraceRecord record = TraceRecordBuilder.newRecord() .withSimpleDateAsHashKey() .withException(e) .getRecord(); record.setType("log"); record.setCaption(message); return record(record); } public static TraceRecord debug(String message){ return recordLog(LogLevel.DEBUG, message); } public static EchoTask echoTask(){ return new EchoTask(); } public static HttpClientTask httpclientTask(){ return new HttpClientTask(); } public static <T> Matcher<T> equalTo(T operand) { return IsEqual.equalTo(operand); } public static <T> Matcher<T> subsetOf(T operand) { if (operand != null && operand instanceof WrappedObject){ operand = (T)((WrappedObject)operand).getValue(); } return Subset.subsetOf(operand); } public static <T> Matcher<T> not(T value) { return IsNot.not(equalTo(value)); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T>... matchers) { return AllOf.allOf(Arrays.asList(matchers)); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second) { return AllOf.allOf(first, second); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third) { return AllOf.allOf(first, second, third); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth) { return AllOf.allOf(first, second, third, fourth); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<? super T> fifth) { return AllOf.allOf(first, second, third, fourth, fifth); } /** * Creates a matcher that matches if the examined object matches <b>ALL</b> of the specified matchers. * <p/> * For example: * <pre>assertThat("myValue", allOf(startsWith("my"), containsString("Val")))</pre> */ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<? super T> second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<? super T> fifth, Matcher<? super T> sixth) { return AllOf.allOf(first, second, third, fourth, fifth, sixth); } public static String randomId() { return StringUtils.randomBase64UUID(); } public static Config getConfig(){ return DetectiveFactory.INSTANCE.getConfig(); } }
package org.lightmare.cache; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.jndi.JndiManager; import org.lightmare.jpa.JPAManager; import org.lightmare.jpa.datasource.DataSourceInitializer; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.utils.NamingUtils; import org.lightmare.utils.ObjectUtils; /** * Container class to cache connections * * @author levan * */ public class ConnectionContainer { // Keeps unique EntityManagerFactories builded by unit names private static final ConcurrentMap<String, ConnectionSemaphore> CONNECTIONS = new ConcurrentHashMap<String, ConnectionSemaphore>(); // Keeps unique PoolConfigs builded by unit names private static final ConcurrentMap<String, PoolConfig.PoolProviderType> POOL_CONFIG_TYPES = new ConcurrentHashMap<String, PoolConfig.PoolProviderType>(); private static final Logger LOG = Logger .getLogger(ConnectionContainer.class); public static boolean checkForEmf(String unitName) { boolean check = ObjectUtils.available(unitName); if (check) { check = CONNECTIONS.containsKey(unitName); } return check; } /** * Gets {@link ConnectionSemaphore} from cache without waiting for lock * * @param unitName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore getSemaphore(String unitName) { return CONNECTIONS.get(unitName); } private static boolean checkOnProgress(ConnectionSemaphore semaphore) { return semaphore.isInProgress() && ObjectUtils.notTrue(semaphore.isBound()); } /** * Creates and locks {@link ConnectionSemaphore} instance * * @param unitName * @return {@link ConnectionSemaphore} */ private static ConnectionSemaphore createSemaphore(String unitName) { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); ConnectionSemaphore current = null; if (semaphore == null) { semaphore = new ConnectionSemaphore(); semaphore.setUnitName(unitName); semaphore.setInProgress(Boolean.TRUE); semaphore.setCached(Boolean.TRUE); current = CONNECTIONS.putIfAbsent(unitName, semaphore); } if (current == null) { current = semaphore; } current.incrementUser(); return current; } /** * Caches {@link ConnectionSemaphore} with lock * * @param unitName * @param jndiName * @return {@link ConnectionSemaphore} */ public static ConnectionSemaphore cacheSemaphore(String unitName, String jndiName) { ConnectionSemaphore semaphore = null; if (ObjectUtils.available(unitName)) { semaphore = createSemaphore(unitName); if (ObjectUtils.available(jndiName)) { ConnectionSemaphore existent = CONNECTIONS.putIfAbsent( jndiName, semaphore); if (existent == null) { semaphore.setJndiName(jndiName); } } } return semaphore; } /** * Waits until {@link ConnectionSemaphore} is in progress (locked) * * @param semaphore */ private static void awaitConnection(ConnectionSemaphore semaphore) { synchronized (semaphore) { boolean inProgress = checkOnProgress(semaphore); while (inProgress) { try { semaphore.wait(); inProgress = checkOnProgress(semaphore); } catch (InterruptedException ex) { inProgress = Boolean.FALSE; LOG.error(ex.getMessage(), ex); } } } } /** * Checks if {@link ConnectionSemaphore#isInProgress()} for appropriated * unit name * * @param jndiName * @return <code>boolean</code> */ public static boolean isInProgress(String jndiName) { ConnectionSemaphore semaphore = CONNECTIONS.get(jndiName); boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } } return inProgress; } /** * Gets {@link ConnectionSemaphore} from cache, awaits if connection * instantiation is in progress * * @param unitName * @return {@link ConnectionSemaphore} * @throws IOException */ public static ConnectionSemaphore getConnection(String unitName) throws IOException { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } } return semaphore; } /** * Gets {@link EntityManagerFactory} from {@link ConnectionSemaphore}, * awaits if connection * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ public static EntityManagerFactory getEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); boolean inProgress = ObjectUtils.notNull(semaphore); if (inProgress) { inProgress = checkOnProgress(semaphore); if (inProgress) { awaitConnection(semaphore); } emf = semaphore.getEmf(); } else { emf = null; } return emf; } /** * Removes connection from {@link javax.naming.Context} cache * * @param semaphore */ private static void unbindConnection(ConnectionSemaphore semaphore) { String jndiName = semaphore.getJndiName(); if (ObjectUtils.notNull(jndiName) && semaphore.isBound()) { JndiManager jndiManager = new JndiManager(); try { String fullJndiName = NamingUtils.createJpaJndiName(jndiName); Object boundData = jndiManager.lookup(fullJndiName); if (ObjectUtils.notNull(boundData)) { jndiManager.unbind(fullJndiName); } } catch (IOException ex) { LOG.error(String.format( "Could not unbind jndi name %s cause %s", jndiName, ex.getMessage()), ex); } } } /** * Closes all existing {@link EntityManagerFactory} instances kept in cache */ public static void closeEntityManagerFactories() { Collection<ConnectionSemaphore> semaphores = CONNECTIONS.values(); EntityManagerFactory emf; for (ConnectionSemaphore semaphore : semaphores) { emf = semaphore.getEmf(); JPAManager.closeEntityManagerFactory(emf); } CONNECTIONS.clear(); } /** * Closes all {@link javax.persistence.EntityManagerFactory} cached * instances * * @throws IOException */ public static void closeConnections() throws IOException { ConnectionContainer.closeEntityManagerFactories(); DataSourceInitializer.closeAll(); } /** * Closes connection ({@link EntityManagerFactory}) in passed * {@link ConnectionSemaphore} * * @param semaphore */ private static void closeConnection(ConnectionSemaphore semaphore) { int users = semaphore.decrementUser(); if (users <= 0) { EntityManagerFactory emf = semaphore.getEmf(); JPAManager.closeEntityManagerFactory(emf); unbindConnection(semaphore); CONNECTIONS.remove(semaphore.getUnitName()); String jndiName = semaphore.getJndiName(); if (ObjectUtils.available(jndiName)) { CONNECTIONS.remove(jndiName); semaphore.setBound(Boolean.FALSE); semaphore.setCached(Boolean.FALSE); } } } /** * Removes {@link ConnectionSemaphore} from cache and unbinds name from * {@link javax.naming.Context} * * @param unitName */ public static void removeConnection(String unitName) { ConnectionSemaphore semaphore = CONNECTIONS.get(unitName); if (ObjectUtils.notNull(semaphore)) { awaitConnection(semaphore); closeConnection(semaphore); } } public static void setPollProviderType(String jndiName, PoolConfig.PoolProviderType type) { POOL_CONFIG_TYPES.put(jndiName, type); } public static PoolConfig.PoolProviderType getAndRemovePoolProviderType( String jndiName) { PoolConfig.PoolProviderType type = POOL_CONFIG_TYPES.get(jndiName); if (type == null) { type = new PoolConfig().getPoolProviderType(); } POOL_CONFIG_TYPES.remove(jndiName); return type; } /** * Closes all connections and data sources and clears all cached data * * @throws IOException */ public static void clear() throws IOException { closeConnections(); CONNECTIONS.clear(); POOL_CONFIG_TYPES.clear(); } }
package hudson.maven; import hudson.CopyOnWrite; import hudson.FilePath; import hudson.Util; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.DependencyGraph; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.Job; import hudson.model.Node; import hudson.triggers.Trigger; import hudson.util.DescribableList; import org.apache.maven.project.MavenProject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; /** * {@link Job} that builds projects based on Maven2. * * @author Kohsuke Kawaguchi */ public final class MavenModule extends AbstractProject<MavenModule,MavenBuild> implements DescribableList.Owner { private DescribableList<MavenReporter,Descriptor<MavenReporter>> reporters = new DescribableList<MavenReporter,Descriptor<MavenReporter>>(this); /** * Name taken from {@link MavenProject#getName()}. */ private String displayName; private transient ModuleName moduleName; private String relativePath; /** * If this module has goals specified by itself. * Otherwise leave it null to use the default goals specified in the parent. */ private String goals; /** * List of modules that this module declares direct dependencies on. */ @CopyOnWrite private Set<ModuleName> dependencies; /** * {@link Action}s contributed from {@link #triggers} and {@link MavenBuild#projectActionReporters} * from the last build. * * We don't want to persist them separately, and these actions * come and go as configuration change, so it's kept separate. */ private transient /*final*/ List<Action> transientActions = new Vector<Action>(); /*package*/ MavenModule(MavenModuleSet parent, PomInfo pom, int firstBuildNumber) throws IOException { super(parent, pom.name.toFileSystemName()); reconfigure(pom); updateNextBuildNumber(firstBuildNumber); } /** * Called to update the module with the new POM. * <p> * This method is invoked on {@link MavenModule} that has the matching * {@link ModuleName}. */ /*package*/ final void reconfigure(PomInfo pom) { this.displayName = pom.displayName; this.relativePath = pom.relativePath; this.dependencies = pom.dependencies; } protected void doSetName(String name) { moduleName = ModuleName.fromFileSystemName(name); super.doSetName(moduleName.toString()); } @Override public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent,name); if(reporters==null) reporters = new DescribableList<MavenReporter, Descriptor<MavenReporter>>(this); reporters.setOwner(this); if(dependencies==null) dependencies = Collections.emptySet(); updateTransientActions(); } /** * Relative path to this module's root directory * from {@link MavenModuleSet#getWorkspace()}. * * The path separator is normalized to '/'. */ public String getRelativePath() { return relativePath; } /** * Gets the list of goals to execute for this module. */ public String getGoals() { if(goals!=null) return goals; return getParent().getGoals(); } /** * Gets the list of goals specified by the user, * without taking inheritance and POM default goals * into account. * * <p> * This is only used to present the UI screen, and in * all the other cases {@link #getGoals()} should be used. */ public String getUserConfiguredGoals() { return goals; } @Override public FilePath getWorkspace() { return getParent().getModuleRoot().child(relativePath); } public ModuleName getModuleName() { return moduleName; } @Override public String getShortUrl() { return moduleName.toFileSystemName()+'/'; } @Override public String getDisplayName() { return displayName; } public MavenModuleSet getParent() { return (MavenModuleSet)super.getParent(); } /*package*/ void updateNextBuildNumber(int next) throws IOException { if(next>nextBuildNumber) { this.nextBuildNumber = next; saveNextBuildNumber(); } } /** * {@link MavenModule} uses the workspace of the {@link MavenModuleSet}, * so it always needs to be built on the same slave as the parent. */ public Node getAssignedNode() { return getParent().getLastBuiltOn(); } @Override public MavenBuild newBuild() throws IOException { MavenBuild lastBuild = new MavenBuild(this); builds.put(lastBuild); return lastBuild; } @Override protected MavenBuild loadBuild(File dir) throws IOException { return new MavenBuild(this,dir); } @Override protected boolean isBuildBlocked() { if(super.isBuildBlocked()) return true; // if the module set's new build is planned or in progress, // don't start a new build. Otherwise on a busy maven project // MavenModuleSet will never get a chance to run. MavenModuleSet p = getParent(); return p.isBuilding() || p.isInQueue(); } @Override public boolean isFingerprintConfigured() { return true; } protected void buildDependencyGraph(DependencyGraph graph) { if(isDisabled()) return; Map<ModuleName,MavenModule> modules = new HashMap<ModuleName,MavenModule>(); for (MavenModule m : Hudson.getInstance().getAllItems(MavenModule.class)) { if(m.isDisabled()) continue; modules.put(m.getModuleName(),m); } for (ModuleName d : dependencies) { MavenModule src = modules.get(d); if(src!=null) graph.addDependency(src,this); } } public synchronized List<Action> getActions() { // add all the transient actions, too List<Action> actions = new Vector<Action>(super.getActions()); actions.addAll(transientActions); return actions; } /*package*/ void updateTransientActions() { if(transientActions==null) transientActions = new Vector<Action>(); // happens when loaded from disk synchronized(transientActions) { transientActions.clear(); // if we just pick up the project actions from the last build, // and if the last build failed very early, then the reports that // kick in later (like test results) won't be displayed. // so pick up last successful build, too. Set<Class> added = new HashSet<Class>(); addTransientActionsFromBuild(getLastBuild(),added); addTransientActionsFromBuild(getLastSuccessfulBuild(),added); for (Trigger trigger : triggers) { Action a = trigger.getProjectAction(); if(a!=null) transientActions.add(a); } } } private void addTransientActionsFromBuild(MavenBuild build, Set<Class> added) { if(build==null) return; List<MavenReporter> list = build.projectActionReporters; if(list==null) return; for (MavenReporter step : list) { if(!added.add(step.getClass())) continue; // already added Action a = step.getProjectAction(this); if(a!=null) transientActions.add(a); } } /** * List of active {@link MavenReporter}s configured for this module. */ public DescribableList<MavenReporter, Descriptor<MavenReporter>> getReporters() { return reporters; } protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req, rsp); reporters.rebuild(req,MavenReporters.getConfigurableList(),"reporter"); goals = Util.fixEmpty(req.getParameter("goals").trim()); // dependency setting might have been changed by the user, so rebuild. Hudson.getInstance().rebuildDependencyGraph(); } protected void performDelete() throws IOException { super.performDelete(); getParent().onModuleDeleted(this); } /** * Marks this build as disabled. */ public void disable() throws IOException { if(!disabled) { disabled = true; save(); } } }
package org.lightmare.cache; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.persistence.EntityManagerFactory; /** * Container class for {@link EntityManagerFactory} with check if connection * configuration is in progress and user count * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT * @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters) * @see org.lightmare.cache.ConnectionContainer#cacheSemaphore(String, String) * @see org.lightmare.cache.ConnectionContainer#getConnection(String) */ public class ConnectionSemaphore { // Flag if connection initialization is in progress private final AtomicBoolean inProgress = new AtomicBoolean(); private String unitName; private String jndiName; private boolean cached; private boolean bound; private EntityManagerFactory emf; // Number of user using the same connection private final AtomicInteger users = new AtomicInteger(); // Check if needs configure EntityManagerFactory private final AtomicBoolean check = new AtomicBoolean(); // Default semaphore capacity public static final int MINIMAL_USERS = 1; public boolean isInProgress() { return inProgress.get(); } public void setInProgress(boolean inProgress) { this.inProgress.getAndSet(inProgress); } public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getJndiName() { return jndiName; } public void setJndiName(String jndiName) { this.jndiName = jndiName; } public boolean isCached() { return cached; } public void setCached(boolean cached) { this.cached = cached; } public boolean isBound() { return bound; } public void setBound(boolean bound) { this.bound = bound; } public EntityManagerFactory getEmf() { return emf; } public void setEmf(EntityManagerFactory emf) { this.emf = emf; } public int incrementUser() { return users.incrementAndGet(); } public int decrementUser() { return users.decrementAndGet(); } public int getUsers() { return users.get(); } public boolean isCheck() { return check.getAndSet(Boolean.TRUE); } }
package org.lightmare.jpa.datasource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.lightmare.jpa.datasource.Initializer.ConnectionConfig; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Configuration with default parameters for c3p0 connection pooling * * @author levan * */ public class PoolConfig { /** * Container for default configuration keys and values * * @author levan * */ public static enum Defaults { // Data source name property DATA_SOURCE_NAME("dataSourceName"), // Class loader properties CONTEXT_CLASS_LOADER_SOURCE("contextClassLoaderSource", "library"), // loader PRIVILEGED_SPAWNED_THREADS("privilegeSpawnedThreads", Boolean.TRUE), // threads // Pool properties MAX_POOL_SIZE("maxPoolSize", 15), // max pool size INITIAL_POOL_SIZE("initialPoolSize", 5), // initial MIN_POOL_SIZE("minPoolSize", 5), // min pool size MAX_STATEMENTS("maxStatements", 50), // statements AQUIRE_INCREMENT("acquireIncrement", 5), // increment // Pool timeout properties MAX_IDLE_TIMEOUT("maxIdleTime", 10000), // idle MAX_IDLE_TIME_EXCESS_CONN("maxIdleTimeExcessConnections", 0), // excess CHECK_OUT_TIMEOUT("checkoutTimeout", 1800), // checkout // Controller properties STAT_CACHE_NUM_DEFF_THREADS("statementCacheNumDeferredCloseThreads", "1"), // Transaction properties AUTOCOMMIT("autoCommit", "false"), // auto commit AUTOCOMMIT_ON_CLOSE("autoCommitOnClose", "false"), // on close URESOLVED_TRANSACTIONS("forceIgnoreUnresolvedTransactions", "true"), // ignore // Connection recovery properties ACQUIRE_RETRY_ATTEMPTS("acquireRetryAttempts", 0), // retry ACQUIRE_RETRY_DELAY("acquireRetryDelay", 1000), // delay BREACK_AFTER_ACQUIRE_FAILURE("breakAfterAcquireFailure", "false");// break public String key; public String value; private Defaults(String key) { this.key = key; } private Defaults(String key, Object value) { this(key); if (value instanceof String) { this.value = (String) value; } else { this.value = String.valueOf(value); } } } // Data source name property public static final String DATA_SOURCE_NAME = "dataSourceName"; // Default value for data source properties file private static final String POOL_PATH_DEF_VALUE = "META-INF/pool.properties"; private String poolPath; private Map<Object, Object> poolProperties = new HashMap<Object, Object>(); private boolean pooledDataSource; /** * Enumeration to choose which type connection pool should be in use * * @author levan * */ public static enum PoolProviderType { DBCP, C3P0, TOMCAT; } // Default pool provider type private PoolProviderType poolProviderType = PoolProviderType.C3P0; /** * Sets default connection pooling properties * * @return */ public Map<Object, Object> getDefaultPooling() { Map<Object, Object> c3p0Properties = new HashMap<Object, Object>(); Defaults[] defaults = Defaults.values(); String key; String value; for (Defaults config : defaults) { key = config.key; value = config.value; if (ObjectUtils.available(key) && ObjectUtils.available(value)) { c3p0Properties.put(key, value); } } return c3p0Properties; } private Set<Object> unsopportedKeys() throws IOException { Set<Object> keys = new HashSet<Object>(); ConnectionConfig[] usdKeys = ConnectionConfig.values(); String key; for (ConnectionConfig usdKey : usdKeys) { key = usdKey.name; if (ObjectUtils.available(key)) { keys.add(key); } } return keys; } /** * Add initialized properties to defaults * * @param defaults * @param initial */ private void fillDefaults(Map<Object, Object> defaults, Map<Object, Object> initial) { defaults.putAll(initial); } /** * Generates pooling configuration properties * * @param initial * @return {@link Map}<Object, Object> * @throws IOException */ private Map<Object, Object> configProperties(Map<Object, Object> initial) throws IOException { Map<Object, Object> propertiesMap = getDefaultPooling(); fillDefaults(propertiesMap, initial); Set<Object> keys = unsopportedKeys(); String dataSourceName = null; String property; for (Object key : keys) { property = ConnectionConfig.NAME_PROPERTY.name; if (key.equals(property)) { dataSourceName = (String) propertiesMap.get(property); } propertiesMap.remove(key); } if (ObjectUtils.available(dataSourceName)) { propertiesMap.put(DATA_SOURCE_NAME, dataSourceName); } return propertiesMap; } /** * Gets property as <code>int</int> value * * @param properties * @param key * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, Object key) { Object property = properties.get(key); Integer propertyInt; if (property == null) { propertyInt = null; } else if (property instanceof Integer) { propertyInt = (Integer) property; } else if (property instanceof String) { propertyInt = Integer.valueOf((String) property); } else { propertyInt = null; } return propertyInt; } /** * Gets property as <code>int</int> value * * @param properties * @param name * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, Defaults config) { String key = config.key; Integer propertyInt = asInt(properties, key); return propertyInt; } /** * Loads {@link Properties} from specific path * * @param path * @return {@link Properties} * @throws IOException */ public Map<Object, Object> load() throws IOException { Map<Object, Object> properties; InputStream stream; if (ObjectUtils.notAvailable(poolPath)) { ClassLoader loader = LibraryLoader.getContextClassLoader(); stream = loader.getResourceAsStream(POOL_PATH_DEF_VALUE); } else { File file = new File(poolPath); stream = new FileInputStream(file); } try { Properties propertiesToLoad; if (ObjectUtils.notNull(stream)) { propertiesToLoad = new Properties(); propertiesToLoad.load(stream); properties = new HashMap<Object, Object>(); properties.putAll(propertiesToLoad); } else { properties = null; } } finally { ObjectUtils.close(stream); } return properties; } /** * Merges passed properties, startup time passed properties and properties * loaded from file * * @param properties * @return {@link Map}<Object, Object> merged properties map * @throws IOException */ public Map<Object, Object> merge(Map<Object, Object> properties) throws IOException { Map<Object, Object> configMap = configProperties(properties); Map<Object, Object> loaded = load(); if (ObjectUtils.notNull(loaded)) { fillDefaults(configMap, loaded); } if (ObjectUtils.notNull(poolProperties)) { fillDefaults(configMap, poolProperties); } return configMap; } public String getPoolPath() { return poolPath; } public void setPoolPath(String poolPath) { this.poolPath = poolPath; } public Map<Object, Object> getPoolProperties() { return poolProperties; } public void setPoolProperties(Map<Object, Object> poolProperties) { this.poolProperties = poolProperties; } public boolean isPooledDataSource() { return pooledDataSource; } public void setPooledDataSource(boolean pooledDataSource) { this.pooledDataSource = pooledDataSource; } public PoolProviderType getPoolProviderType() { return poolProviderType; } public void setPoolProviderType(PoolProviderType poolProviderType) { this.poolProviderType = poolProviderType; } public void setPoolProviderType(String poolProviderTypeName) { this.poolProviderType = PoolProviderType.valueOf(poolProviderTypeName); } }
package org.lightmare.jpa.datasource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.lightmare.jpa.datasource.Initializer.ConnectionConfig; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Configuration with default parameters for c3p0 connection pooling * * @author levan * */ public class PoolConfig { /** * Container for default configuration keys and values * * @author levan * */ public static enum Defaults { // Data source name property DATA_SOURCE_NAME("dataSourceName"), // Class loader properties CONTEXT_CLASS_LOADER_SOURCE("contextClassLoaderSource", "library"), // loader PRIVILEGED_SPAWNED_THREADS("privilegeSpawnedThreads", Boolean.TRUE), // threads // Pool properties MAX_POOL_SIZE("maxPoolSize", 15), // max pool size INITIAL_POOL_SIZE("initialPoolSize", 5), // initial MIN_POOL_SIZE("minPoolSize", 5), // minimal pool size MAX_STATEMENTS("maxStatements", 50), // statements AQUIRE_INCREMENT("acquireIncrement", 5), // increment // Pool timeout properties MAX_IDLE_TIMEOUT("maxIdleTime", 1200), // idle MAX_IDLE_TIME_EXCESS_CONN("maxIdleTimeExcessConnections", 60), // excess CHECK_OUT_TIMEOUT("checkoutTimeout", 5000), // checkout // Controller properties STAT_CACHE_NUM_DEFF_THREADS("statementCacheNumDeferredCloseThreads", 1), // Transaction properties AUTOCOMMIT("autoCommit", Boolean.FALSE), // auto commit AUTOCOMMIT_ON_CLOSE("autoCommitOnClose", Boolean.FALSE), // on close URESOLVED_TRANSACTIONS("forceIgnoreUnresolvedTransactions", Boolean.TRUE), // ignore unresolved transactions // Connection recovery properties ACQUIRE_RETRY_ATTEMPTS("acquireRetryAttempts", 0), // retry ACQUIRE_RETRY_DELAY("acquireRetryDelay", 1000), // delay BREACK_AFTER_ACQUIRE_FAILURE("breakAfterAcquireFailure", Boolean.FALSE); // break public String key; public String value; private Defaults(String key) { this.key = key; } private Defaults(String key, Object value) { this(key); if (value instanceof String) { this.value = (String) value; } else { this.value = String.valueOf(value); } } } // Data source name property public static final String DATA_SOURCE_NAME = "dataSourceName"; // Default value for data source properties file private static final String POOL_PATH_DEF_VALUE = "META-INF/pool.properties"; private String poolPath; private Map<Object, Object> poolProperties = new HashMap<Object, Object>(); // Check is data source pooled or not private boolean pooledDataSource; /** * Enumeration to choose which type connection pool should be in use * * @author levan * */ public static enum PoolProviderType { DBCP, C3P0, TOMCAT; } // Default pool provider type private PoolProviderType poolProviderType = PoolProviderType.C3P0; /** * Sets default connection pooling properties * * @return */ public Map<Object, Object> getDefaultPooling() { Map<Object, Object> c3p0Properties = new HashMap<Object, Object>(); Defaults[] defaults = Defaults.values(); String key; String value; for (Defaults config : defaults) { key = config.key; value = config.value; if (StringUtils.validAll(key, value)) { c3p0Properties.put(key, value); } } return c3p0Properties; } private Set<Object> unsopportedKeys() throws IOException { Set<Object> keys = new HashSet<Object>(); ConnectionConfig[] usdKeys = ConnectionConfig.values(); String key; for (ConnectionConfig usdKey : usdKeys) { key = usdKey.name; if (StringUtils.valid(key)) { keys.add(key); } } return keys; } /** * Add initialized properties to defaults * * @param defaults * @param initial */ private void fillDefaults(Map<Object, Object> defaults, Map<Object, Object> initial) { defaults.putAll(initial); } /** * Generates pooling configuration properties * * @param initial * @return {@link Map}<Object, Object> * @throws IOException */ private Map<Object, Object> configProperties(Map<Object, Object> initial) throws IOException { Map<Object, Object> propertiesMap = getDefaultPooling(); fillDefaults(propertiesMap, initial); Set<Object> keys = unsopportedKeys(); String dataSourceName = null; String property; for (Object key : keys) { property = ConnectionConfig.NAME_PROPERTY.name; if (key.equals(property)) { dataSourceName = (String) propertiesMap.get(property); } propertiesMap.remove(key); } if (StringUtils.valid(dataSourceName)) { propertiesMap.put(DATA_SOURCE_NAME, dataSourceName); } return propertiesMap; } /** * Gets property as <code>int</code> value * * @param properties * @param key * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, Object key) { Object property = properties.get(key); Integer propertyInt; if (property == null) { propertyInt = null; } else if (property instanceof Integer) { propertyInt = (Integer) property; } else if (property instanceof String) { propertyInt = Integer.valueOf((String) property); } else { propertyInt = null; } return propertyInt; } /** * Gets property as <code>int</code> value * * @param properties * @param name * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, Defaults config) { String key = config.key; Integer propertyInt = asInt(properties, key); return propertyInt; } /** * Loads {@link Properties} from specific path * * @param path * @return {@link Properties} * @throws IOException */ public Map<Object, Object> load() throws IOException { Map<Object, Object> properties; InputStream stream; if (StringUtils.invalid(poolPath)) { ClassLoader loader = LibraryLoader.getContextClassLoader(); stream = loader.getResourceAsStream(POOL_PATH_DEF_VALUE); } else { File file = new File(poolPath); stream = new FileInputStream(file); } try { Properties propertiesToLoad; if (ObjectUtils.notNull(stream)) { propertiesToLoad = new Properties(); propertiesToLoad.load(stream); properties = new HashMap<Object, Object>(); properties.putAll(propertiesToLoad); } else { properties = null; } } finally { IOUtils.close(stream); } return properties; } /** * Merges passed properties, startup time passed properties and properties * loaded from file * * @param properties * @return {@link Map}<Object, Object> merged properties map * @throws IOException */ public Map<Object, Object> merge(Map<Object, Object> properties) throws IOException { Map<Object, Object> configMap = configProperties(properties); Map<Object, Object> loaded = load(); if (ObjectUtils.notNull(loaded)) { fillDefaults(configMap, loaded); } if (ObjectUtils.notNull(poolProperties)) { fillDefaults(configMap, poolProperties); } return configMap; } public String getPoolPath() { return poolPath; } public void setPoolPath(String poolPath) { this.poolPath = poolPath; } public Map<Object, Object> getPoolProperties() { return poolProperties; } public void setPoolProperties(Map<Object, Object> poolProperties) { this.poolProperties = poolProperties; } public boolean isPooledDataSource() { return pooledDataSource; } public void setPooledDataSource(boolean pooledDataSource) { this.pooledDataSource = pooledDataSource; } public PoolProviderType getPoolProviderType() { return poolProviderType; } public void setPoolProviderType(PoolProviderType poolProviderType) { this.poolProviderType = poolProviderType; } public void setPoolProviderType(String poolProviderTypeName) { this.poolProviderType = PoolProviderType.valueOf(poolProviderTypeName); } }
package org.jfree.data.general; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.EventListener; import java.util.List; import javax.swing.event.EventListenerList; import org.jfree.chart.util.ParamChecks; /** * An abstract implementation of the {@link Dataset} interface, containing a * mechanism for registering change listeners. */ public abstract class AbstractDataset implements Dataset, Cloneable, Serializable, ObjectInputValidation { /** For serialization. */ private static final long serialVersionUID = 1918768939869230744L; /** The group that the dataset belongs to. */ private DatasetGroup group; /** Storage for registered change listeners. */ private transient EventListenerList listenerList; /** * Constructs a dataset. By default, the dataset is assigned to its own * group. */ protected AbstractDataset() { this.group = new DatasetGroup(); this.listenerList = new EventListenerList(); } /** * Returns the dataset group for the dataset. * * @return The group (never <code>null</code>). * * @see #setGroup(DatasetGroup) */ @Override public DatasetGroup getGroup() { return this.group; } /** * Sets the dataset group for the dataset. * * @param group the group (<code>null</code> not permitted). * * @see #getGroup() */ @Override public void setGroup(DatasetGroup group) { ParamChecks.nullNotPermitted(group, "group"); this.group = group; } /** * Registers an object to receive notification of changes to the dataset. * * @param listener the object to register. * * @see #removeChangeListener(DatasetChangeListener) */ @Override public void addChangeListener(DatasetChangeListener listener) { this.listenerList.add(DatasetChangeListener.class, listener); } /** * Deregisters an object so that it no longer receives notification of * changes to the dataset. * * @param listener the object to deregister. * * @see #addChangeListener(DatasetChangeListener) */ @Override public void removeChangeListener(DatasetChangeListener listener) { this.listenerList.remove(DatasetChangeListener.class, listener); } /** * Returns <code>true</code> if the specified object is registered with * the dataset as a listener. Most applications won't need to call this * method, it exists mainly for use by unit testing code. * * @param listener the listener. * * @return A boolean. * * @see #addChangeListener(DatasetChangeListener) * @see #removeChangeListener(DatasetChangeListener) */ public boolean hasListener(EventListener listener) { List list = Arrays.asList(this.listenerList.getListenerList()); return list.contains(listener); } /** * Notifies all registered listeners that the dataset has changed. * * @see #addChangeListener(DatasetChangeListener) */ protected void fireDatasetChanged() { notifyListeners(new DatasetChangeEvent(this, this)); } /** * Notifies all registered listeners that the dataset has changed. * * @param event contains information about the event that triggered the * notification. * * @see #addChangeListener(DatasetChangeListener) * @see #removeChangeListener(DatasetChangeListener) */ protected void notifyListeners(DatasetChangeEvent event) { Object[] listeners = this.listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == DatasetChangeListener.class) { ((DatasetChangeListener) listeners[i + 1]).datasetChanged( event); } } } /** * Returns a clone of the dataset. The cloned dataset will NOT include the * {@link DatasetChangeListener} references that have been registered with * this dataset. * * @return A clone. * * @throws CloneNotSupportedException if the dataset does not support * cloning. */ @Override public Object clone() throws CloneNotSupportedException { AbstractDataset clone = (AbstractDataset) super.clone(); clone.listenerList = new EventListenerList(); return clone; } /** * Handles serialization. * * @param stream the output stream. * * @throws IOException if there is an I/O problem. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Restores a serialized object. * * @param stream the input stream. * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.listenerList = new EventListenerList(); stream.registerValidation(this, 10); // see comments about priority of // 10 in validateObject() } /** * Validates the object. We use this opportunity to call listeners who have * registered during the deserialization process, as listeners are not * serialized. This method is called by the serialization system after the * entire graph is read. * * This object has registered itself to the system with a priority of 10. * Other callbacks may register with a higher priority number to be called * before this object, or with a lower priority number to be called after * the listeners were notified. * * All listeners are supposed to have register by now, either in their * readObject or validateObject methods. Notify them that this dataset has * changed. * * @exception InvalidObjectException If the object cannot validate itself. */ @Override public void validateObject() throws InvalidObjectException { fireDatasetChanged(); } }
package org.lightmare.scannotation; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import org.apache.log4j.Logger; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.scannotation.archiveiterator.Filter; import org.scannotation.archiveiterator.IteratorFactory; import org.scannotation.archiveiterator.StreamIterator; /** * Extension of {@link org.scannotation.AnnotationDB} for saving Map< * {@link String}, {@link URL}> of class name and {@link URL} for its archive * * @author levan * @since 0.0.18-SNAPSHOT */ public class AnnotationDB extends org.scannotation.AnnotationDB { private static final long serialVersionUID = 1L; // To store which class in which URL is found protected Map<String, URL> classOwnersURLs = new WeakHashMap<String, URL>(); // To store which class in which File is found protected Map<String, String> classOwnersFiles = new WeakHashMap<String, String>(); // File separator and extension characters private static final char FILE_EXTEWNTION_SELIM = '.'; private static final char FILE_SEPARATOR_CHAR = '/'; // Log messages private static String SCANNING_STARTED_MESSAGE = "Started scanning for archives on @Stateless annotation"; private static String SCANNING_FINISHED_MESSAGE = "Finished scanning for archives on @Stateless annotation"; private static final String SCANNING_URL_MESSAGE = "Scanning URL "; private static final String FINISHED_URL_MESSAGE = "Finished URL scanning "; private static final Logger LOG = Logger.getLogger(AnnotationDB.class); /** * Filters java archive files * * @author levan * @since 0.0.84-SNAPSHOT */ protected class ArchiveFilter implements Filter { @Override public boolean accepts(String subFileName) { boolean valid; if (subFileName.endsWith(ArchiveUtils.CLASS_FILE_EXT)) { if (subFileName.startsWith(ArchiveUtils.FILE_SEPARATOR)) { subFileName = subFileName .substring(CollectionUtils.SECOND_INDEX); } String fileNameForCheck = subFileName.replace( FILE_SEPARATOR_CHAR, FILE_EXTEWNTION_SELIM); valid = !ignoreScan(fileNameForCheck); } else { valid = Boolean.FALSE; } return valid; } } private String getFileName(URL url) { String fileName = url.getFile(); int lastIndex = fileName.lastIndexOf(ArchiveUtils.FILE_SEPARATOR); if (lastIndex > StringUtils.NOT_EXISTING_INDEX) { ++lastIndex; fileName = fileName.substring(lastIndex); } return fileName; } private boolean ignoreScan(String intf) { boolean valid = Boolean.FALSE; String value; String ignored; int length = ignoredPackages.length; for (int i = CollectionUtils.FIRST_INDEX; ObjectUtils.notTrue(valid) && i < length; i++) { ignored = ignoredPackages[i]; value = StringUtils.concat(ignored, FILE_EXTEWNTION_SELIM); if (intf.startsWith(value)) { valid = Boolean.TRUE; } } return valid; } protected void populate(Annotation[] annotations, String className, URL url) { if (ObjectUtils.notNull(annotations)) { Set<String> classAnnotations = classIndex.get(className); String fileName; for (Annotation ann : annotations) { Set<String> classes = annotationIndex.get(ann.getTypeName()); if (classes == null) { classes = new HashSet<String>(); annotationIndex.put(ann.getTypeName(), classes); } classes.add(className); if (!classOwnersURLs.containsKey(className)) { classOwnersURLs.put(className, url); } if (!classOwnersFiles.containsKey(className)) { fileName = getFileName(url); classOwnersFiles.put(className, fileName); } classAnnotations.add(ann.getTypeName()); } } } protected void scanClass(ClassFile cf, URL url) { String className = cf.getName(); AnnotationsAttribute visible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); AnnotationsAttribute invisible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.invisibleTag); if (ObjectUtils.notNull(visible)) { populate(visible.getAnnotations(), className, url); } if (ObjectUtils.notNull(invisible)) { populate(invisible.getAnnotations(), className, url); } } public void scanClass(InputStream bits, URL url) throws IOException { DataInputStream dstream = new DataInputStream(new BufferedInputStream( bits)); ClassFile cf = null; try { cf = new ClassFile(dstream); String classFileName = cf.getName(); classIndex.put(classFileName, new HashSet<String>()); if (scanClassAnnotations) { scanClass(cf, url); } if (scanMethodAnnotations || scanParameterAnnotations) { scanMethods(cf); } if (scanFieldAnnotations) { scanFields(cf); } // create an index of interfaces the class implements String[] interfaces = cf.getInterfaces(); if (ObjectUtils.notNull(interfaces)) { Set<String> intfs = new HashSet<String>(); for (String intf : interfaces) { intfs.add(intf); } implementsIndex.put(classFileName, intfs); } } finally { IOUtils.closeAll(dstream, bits); } } @Override public void scanArchives(URL... urls) throws IOException { LOG.info(SCANNING_STARTED_MESSAGE); for (URL url : urls) { Filter filter = new ArchiveFilter(); LOG.info(StringUtils.concat(SCANNING_URL_MESSAGE, url)); StreamIterator it = IteratorFactory.create(url, filter); InputStream stream = it.next(); while (ObjectUtils.notNull(stream)) { scanClass(stream, url); stream = it.next(); } LOG.info(StringUtils.concat(FINISHED_URL_MESSAGE, url)); } LOG.info(SCANNING_FINISHED_MESSAGE); } public Map<String, URL> getClassOwnersURLs() { return classOwnersURLs; } public Map<String, String> getClassOwnersFiles() { return classOwnersFiles; } }
package net.silentchaos512.gems.recipe; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.RecipeSorter.Category; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.gems.api.SilentGemsAPI; import net.silentchaos512.gems.item.ModItems; import net.silentchaos512.gems.lib.EnumGem; import net.silentchaos512.gems.lib.Names; import net.silentchaos512.lib.registry.SRegistry; public class ModRecipes { public static void init() { // Chaos Essence creation. SilentGemsAPI.addAltarRecipe(ModItems.craftingMaterial.chaosEssence, ModItems.craftingMaterial.getStack(Names.CHAOS_ESSENCE_SHARD, 4), 240000, new ItemStack(Items.DIAMOND)); // Light <--> Dark gem conversion. ItemStack slimeBall = new ItemStack(Items.SLIME_BALL); ItemStack magmaCream = new ItemStack(Items.MAGMA_CREAM); for (int i = 0; i < 16; ++i) { EnumGem light = EnumGem.values()[i]; EnumGem dark = EnumGem.values()[i + 16]; ItemStack lightShards = new ItemStack(ModItems.gemShard, 6, light.ordinal()); ItemStack darkShards = new ItemStack(ModItems.gemShard, 6, dark.ordinal()); SilentGemsAPI.addAltarRecipe(darkShards, light.getItem(), 80000, magmaCream); SilentGemsAPI.addAltarRecipe(lightShards, dark.getItem(), 80000, slimeBall); } // Recipe handlers. SRegistry reg = SilentGems.instance.registry; String dep = "after:minecraft:shapeless"; try { reg.addRecipeHandler(RecipeMultiGemTool.class, "MultiGemTool", Category.SHAPED, dep); reg.addRecipeHandler(RecipeMultiGemShield.class, "MultiGemShield", Category.SHAPED, dep); reg.addRecipeHandler(RecipeMultiGemBow.class, "MultiGemBow", Category.SHAPED, dep); reg.addRecipeHandler(RecipeMultiGemArmor.class, "MultiGemArmor", Category.SHAPED, dep); reg.addRecipeHandler(RecipeDecorateTool.class, "DecorateTool", Category.SHAPED, dep); reg.addRecipeHandler(RecipeDecorateArmor.class, "DecorateArmor", Category.SHAPED, dep); reg.addRecipeHandler(RecipeApplyEnchantmentToken.class, "ApplyEnchantmentToken", Category.SHAPELESS, dep); reg.addRecipeHandler(RecipeNamePlate.class, "NamePlate", Category.SHAPELESS, dep); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.lightmare.scannotation; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import org.apache.log4j.Logger; import org.lightmare.utils.AbstractIOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.scannotation.archiveiterator.Filter; import org.scannotation.archiveiterator.IteratorFactory; import org.scannotation.archiveiterator.StreamIterator; /** * Extension of {@link org.scannotation.AnnotationDB} for saving Map< * {@link String}, {@link URL}> of class name and {@link URL} for its archive * * @author levan * */ public class AnnotationDB extends org.scannotation.AnnotationDB { private static final long serialVersionUID = 1L; // To store which class in which URL is found protected Map<String, URL> classOwnersURLs = new HashMap<String, URL>(); // To store which class in which File is found protected Map<String, String> classOwnersFiles = new HashMap<String, String>(); private static final char FILE_EXTEWNTION_SELIM = '.'; private static final char FILE_SEPARATOR_CHAR = '/'; private static final int NOT_EXISTING_INDEX = -1; private static final Logger LOG = Logger.getLogger(AnnotationDB.class); private String getFileName(URL url) { String fileName = url.getFile(); int lastIndex = fileName.lastIndexOf(AbstractIOUtils.FILE_SEPARATOR); if (lastIndex > NOT_EXISTING_INDEX) { ++lastIndex; fileName = fileName.substring(lastIndex); } return fileName; } private boolean ignoreScan(String intf) { String value; for (String ignored : ignoredPackages) { value = StringUtils.concat(ignored, FILE_EXTEWNTION_SELIM); if (intf.startsWith(value)) { return Boolean.TRUE; } } return Boolean.FALSE; } protected void populate(Annotation[] annotations, String className, URL url) { if (ObjectUtils.notNull(annotations)) { Set<String> classAnnotations = classIndex.get(className); String fileName; for (Annotation ann : annotations) { Set<String> classes = annotationIndex.get(ann.getTypeName()); if (classes == null) { classes = new HashSet<String>(); annotationIndex.put(ann.getTypeName(), classes); } classes.add(className); if (!classOwnersURLs.containsKey(className)) { classOwnersURLs.put(className, url); } if (!classOwnersFiles.containsKey(className)) { fileName = getFileName(url); classOwnersFiles.put(className, fileName); } classAnnotations.add(ann.getTypeName()); } } } protected void scanClass(ClassFile cf, URL url) { String className = cf.getName(); AnnotationsAttribute visible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); AnnotationsAttribute invisible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.invisibleTag); if (ObjectUtils.notNull(visible)) { populate(visible.getAnnotations(), className, url); } if (ObjectUtils.notNull(invisible)) { populate(invisible.getAnnotations(), className, url); } } public void scanClass(InputStream bits, URL url) throws IOException { DataInputStream dstream = new DataInputStream(new BufferedInputStream( bits)); ClassFile cf = null; try { cf = new ClassFile(dstream); classIndex.put(cf.getName(), new HashSet<String>()); if (scanClassAnnotations) { scanClass(cf, url); } if (scanMethodAnnotations || scanParameterAnnotations) { scanMethods(cf); } if (scanFieldAnnotations) { scanFields(cf); } // create an index of interfaces the class implements if (ObjectUtils.notNull(cf.getInterfaces())) { Set<String> intfs = new HashSet<String>(); for (String intf : cf.getInterfaces()) { intfs.add(intf); } implementsIndex.put(cf.getName(), intfs); } } finally { dstream.close(); bits.close(); } } @Override public void scanArchives(URL... urls) throws IOException { LOG.info("Started scanning for archives on @Stateless annotation"); for (URL url : urls) { Filter filter = new Filter() { public boolean accepts(String subFileName) { if (subFileName.endsWith(AbstractIOUtils.CLASS_FILE_EXT)) { if (subFileName .startsWith(AbstractIOUtils.FILE_SEPARATOR)) { subFileName = subFileName.substring(1); } if (!ignoreScan(subFileName.replace( FILE_SEPARATOR_CHAR, FILE_EXTEWNTION_SELIM))) { return Boolean.TRUE; } } return Boolean.FALSE; } }; LOG.info(String.format("Scanning URL %s ", url)); StreamIterator it = IteratorFactory.create(url, filter); InputStream stream; while (ObjectUtils.notNull((stream = it.next()))) { scanClass(stream, url); } LOG.info(String.format("Finished URL %s scanning", url)); } LOG.info("Finished scanning for archives on @Stateless annotation"); } public Map<String, URL> getClassOwnersURLs() { return classOwnersURLs; } public Map<String, String> getClassOwnersFiles() { return classOwnersFiles; } }
package org.mtransit.android.commons; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.content.res.ResourcesCompat; @SuppressWarnings({"SameParameterValue", "WeakerAccess", "unused"}) public final class ToastUtils implements MTLog.Loggable { private static final String LOG_TAG = ToastUtils.class.getSimpleName(); private static final int TOAST_MARGIN_IN_DP = 10; private static final int NAVIGATION_HEIGHT_IN_DP = 48; @NonNull @Override public String getLogTag() { return LOG_TAG; } private ToastUtils() { } public static void makeTextAndShowCentered(@Nullable Context context, @StringRes int resId) { makeTextAndShowCentered(context, resId, Toast.LENGTH_SHORT); } public static void makeTextAndShowCentered(@Nullable Context context, @StringRes int resId, int duration) { if (context == null) { return; } Toast toast = Toast.makeText(context, resId, duration); setGravityTextCenter(toast); toast.show(); } public static void makeTextAndShowCentered(@Nullable Context context, @NonNull CharSequence text) { makeTextAndShowCentered(context, text, Toast.LENGTH_SHORT); } public static void makeTextAndShowCentered(@Nullable Context context, @NonNull CharSequence text, int duration) { if (context == null) { return; } Toast toast = Toast.makeText(context, text, duration); setGravityTextCenter(toast); toast.show(); } /** * Android SDK: * <p><strong>Warning:</strong> Starting from Android {@link Build.VERSION_CODES#R}, for apps * targeting API level {@link Build.VERSION_CODES#R} or higher, this method is a no-op when * called on text toasts. */ private static void setGravityTextCenter(Toast toast) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { return; } toast.setGravity(Gravity.CENTER, 0, 0); } public static void makeTextAndShow(@Nullable Context context, @StringRes int resId) { makeTextAndShow(context, resId, Toast.LENGTH_SHORT); } public static void makeTextAndShow(@Nullable Context context, @StringRes int resId, int duration) { if (context == null) { return; } Toast toast = Toast.makeText(context, resId, duration); toast.show(); } public static void makeTextAndShow(@NonNull Context context, @NonNull CharSequence text) { makeTextAndShow(context, text, Toast.LENGTH_SHORT); } public static void makeTextAndShow(@NonNull Context context, @NonNull CharSequence text, int duration) { Toast toast = Toast.makeText(context, text, duration); toast.show(); } public static boolean showTouchableToast(@Nullable Activity activity, @Nullable PopupWindow touchableToast, @Nullable View parent) { int additionalBottomMarginInDp = 90; // smart ad banner max height return showTouchableToast(activity, touchableToast, parent, additionalBottomMarginInDp); } public static boolean showTouchableToast(@Nullable Activity activity, @Nullable PopupWindow touchableToast, @Nullable View parent, int additionalBottomMarginInDp) { return showTouchableToastPx(activity, touchableToast, parent, (int) ResourceUtils.convertDPtoPX(activity, additionalBottomMarginInDp) // additional bottom margin ); } public static boolean showTouchableToastPx(@Nullable Activity activity, @Nullable PopupWindow touchableToast, @Nullable View parent, int additionalBottomMarginInPx) { return showTouchableToastPx(activity, touchableToast, parent, (int) ResourceUtils.convertDPtoPX(activity, NAVIGATION_HEIGHT_IN_DP + TOAST_MARGIN_IN_DP) + additionalBottomMarginInPx, // bottom (int) ResourceUtils.convertDPtoPX(activity, TOAST_MARGIN_IN_DP) // left ); } public static boolean showTouchableToast(@Nullable Activity activity, @Nullable PopupWindow touchableToast, @Nullable View parent, int bottomMarginInDp, int leftMarginInDp) { if (activity == null || touchableToast == null || parent == null) { return false; } int bottomMarginInPx = (int) ResourceUtils.convertDPtoPX(activity, bottomMarginInDp); int leftMarginInPx = (int) ResourceUtils.convertDPtoPX(activity, leftMarginInDp); return showTouchableToastPx(activity, touchableToast, parent, bottomMarginInPx, leftMarginInPx); } public static boolean showTouchableToastPx(@Nullable Activity activity, @Nullable PopupWindow touchableToast, @Nullable View parent, int bottomMarginInPx, int leftMarginInPx) { if (activity == null || touchableToast == null || parent == null) { return false; } parent.post(() -> { if (activity.isFinishing()) { return; } touchableToast.showAtLocation( parent, Gravity.LEFT | Gravity.BOTTOM, leftMarginInPx, bottomMarginInPx ); } ); return true; } @Nullable public static PopupWindow getNewTouchableToast(@Nullable Context context, @StringRes int textResId) { return getNewTouchableToast(context, android.R.drawable.toast_frame, textResId); } @Nullable public static PopupWindow getNewTouchableToast(@Nullable Context context, @DrawableRes int toastResId, @StringRes int textResId) { if (context == null) { return null; } try { TextView contentView = new TextView(context); contentView.setText(textResId); contentView.setTextColor(Color.WHITE); PopupWindow newTouchableToast = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); newTouchableToast.setContentView(contentView); newTouchableToast.setTouchable(true); newTouchableToast.setBackgroundDrawable(ResourcesCompat.getDrawable(context.getResources(), toastResId, context.getTheme())); return newTouchableToast; } catch (Exception e) { MTLog.w(LOG_TAG, e, "Error while creating touchable toast!"); return null; } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.flump; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import playn.core.Image; import tripleplay.util.TexturePacker; public class Library { /** The original frame rate of movies in this library. */ public final float frameRate; /** The symbols defined in this library. */ public final Map<String,Symbol> symbols; public Library ( float frameRate, Iterable<Movie.Symbol> movies, Iterable<Texture.Symbol> textures) { this.frameRate = frameRate; // map all of our movies and textures by symbol name final Map<String,Symbol> symbols = new HashMap<String,Symbol>(); this.symbols = Collections.unmodifiableMap(symbols); for (Movie.Symbol movie : movies) { symbols.put(movie.name(), movie); } for (Texture.Symbol texture : textures) { symbols.put(texture.name(), texture); } // go through and resolve references for (Movie.Symbol movie : movies) { for (LayerData layer : movie.layers) { for (KeyframeData kf : layer.keyframes) { if (kf._symbolName != null) { Symbol symbol = symbols.get(kf._symbolName); // We would ideally check not null here, but neck deep in a triple-loop // is not a good place for an assert which is not actually culled for // production release. //Asserts.checkNotNull(symbol); if (layer._lastSymbol == null) layer._lastSymbol = symbol; else if (layer._lastSymbol != symbol) layer._multipleSymbols = true; kf._symbol = symbol; } } } } } /** Pack multiple libraries into a single group of atlases. The libraries will be modified so * that their symbols point at the new atlases. */ public static void pack (Collection<Library> libs) { List<Library> list = new ArrayList<Library>(libs); // Add all texture symbols to the packer TexturePacker packer = new TexturePacker(); for (int ii = 0, ll = list.size(); ii < ll; ++ii) { Library lib = list.get(ii); for (Symbol symbol : lib.symbols.values()) { if (symbol instanceof Texture.Symbol) { packer.add(ii+":"+symbol.name(), ((Texture.Symbol)symbol).region); } } } // Pack and update all texture symbols to the new regions Map<String,Image.Region> images = packer.pack(); for (int ii = 0, ll = list.size(); ii < ll; ++ii) { Library lib = list.get(ii); for (Symbol symbol : lib.symbols.values()) { if (symbol instanceof Texture.Symbol) { ((Texture.Symbol)symbol).region = images.get(ii+":"+symbol.name()); } } } } /** Creates an instance of a symbol, or throws if the symbol name is not in this library. */ public Instance createInstance (String symbolName) { Symbol symbol = symbols.get(symbolName); if (symbol == null) { throw new IllegalArgumentException("Missing required symbol [name=" + symbolName + "]"); } return symbol.createInstance(); } public Movie createMovie (String symbolName) { return (Movie)createInstance(symbolName); } public Texture createTexture (String symbolName) { return (Texture)createInstance(symbolName); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import pythagoras.f.Dimension; import pythagoras.f.MathUtil; import playn.core.Image; import playn.core.ImageLayer; import playn.core.ResourceCallback; import playn.core.TextFormat; import playn.core.TextLayout; import static playn.core.PlayN.graphics; import react.Slot; /** * An abstract base class for widgets that contain text. */ public abstract class TextWidget<T extends TextWidget<T>> extends Widget<T> { /** * Returns the current text displayed by this widget, or null if it has no text. */ protected abstract String text (); /** * Returns the current icon displayed by this widget, or null if it has no icon. */ protected abstract Image icon (); /** * Returns a slot that subclasses should wire up to their text {@code Value}. */ protected Slot<String> textDidChange () { return new Slot<String> () { @Override public void onEmit (String newText) { clearLayoutData(); invalidate(); } }; } /** * Returns a slot that subclasses should wire up to their icon {@code Value}. */ protected Slot<Image> iconDidChange() { return new Slot<Image>() { @Override public void onEmit (Image icon) { if (icon == null) { clearLayoutData(); invalidate(); } else { icon.addCallback(new ResourceCallback<Image>() { public void done (Image resource) { clearLayoutData(); invalidate(); } public void error (Throwable err) {} // noop! }); } } }; } @Override protected void wasAdded (Elements<?> parent) { super.wasAdded(parent); invalidate(); } @Override protected void wasRemoved () { super.wasRemoved(); _tglyph.destroy(); if (_ilayer != null) { _ilayer.destroy(); _ilayer = null; } } @Override protected LayoutData createLayoutData (float hintX, float hintY) { return new TextLayoutData(hintX, hintY); } protected class TextLayoutData extends LayoutData { public final Style.HAlign halign = resolveStyle(Style.HALIGN); public final Style.VAlign valign = resolveStyle(Style.VALIGN); public final Style.Pos iconPos = resolveStyle(Style.ICON_POS); public final int iconGap = resolveStyle(Style.ICON_GAP); public final int color = resolveStyle(Style.COLOR); public final boolean wrap = resolveStyle(Style.TEXT_WRAP); public final TextLayout text; public final EffectRenderer renderer; public TextLayoutData (float hintX, float hintY) { String curtext = text(); boolean haveText = (curtext != null && curtext.length() > 0); Image icon = icon(); if (icon != null) { // remove the icon space from our hint dimensions switch (iconPos) { case LEFT: case RIGHT: hintX -= icon.width(); if (haveText) hintX -= iconGap; break; case ABOVE: case BELOW: hintY -= icon.height(); if (haveText) hintX -= iconGap; break; } } if (haveText) { renderer = Style.createEffectRenderer(TextWidget.this); TextFormat format = Style.createTextFormat(TextWidget.this); if (hintX > 0 && wrap) format = format.withWrapWidth(hintX); // TODO: should we do something with a y-hint? text = graphics().layoutText(curtext, format); } else { renderer = null; text = null; } } @Override public Dimension computeSize (float hintX, float hintY) { Dimension size = new Dimension(); addTextSize(size); Image icon = icon(); if (icon != null) { switch (iconPos) { case LEFT: case RIGHT: size.width += icon.width(); if (text != null) size.width += iconGap; size.height = Math.max(size.height, icon.height()); break; case ABOVE: case BELOW: size.width = Math.max(size.width, icon.width()); size.height += icon.height(); if (text != null) size.height += iconGap; break; } } return size; } @Override public void layout (float left, float top, float width, float height) { float tx = left, ty = top, usedWidth = 0, usedHeight = 0; Image icon = icon(); if (icon != null && iconPos != null) { float ix = left, iy = top; float iwidth = icon.width(), iheight = icon.height(); switch (iconPos) { case LEFT: tx += iwidth + iconGap; iy += valign.offset(iheight, height); usedWidth = iwidth; break; case ABOVE: ty += iheight + iconGap; ix += halign.offset(iwidth, width); usedHeight = iheight; break; case RIGHT: ix += width - iwidth; iy += valign.offset(iheight, height); usedWidth = iwidth; break; case BELOW: iy += height - iheight; ix += halign.offset(iwidth, width); usedHeight = iheight; break; } if (_ilayer == null) layer.add(_ilayer = graphics().createImageLayer(icon)); else _ilayer.setImage(icon); _ilayer.setTranslation(ix, iy); } else if (icon == null && _ilayer != null) { layer.remove(_ilayer); _ilayer = null; } if (text != null) { updateTextGlyph(tx, ty, width-usedWidth, height-usedHeight); } else { _tglyph.destroy(); } } // this is broken out so that subclasses can extend this action protected void addTextSize (Dimension size) { if (_constraint instanceof Constraints.TextConstraint) { ((Constraints.TextConstraint)_constraint).addTextSize(size, text); } else if (text != null) { size.width += renderer.adjustWidth(text.width()); size.height += renderer.adjustHeight(text.height()); } } // this is broken out so that subclasses can extend this action protected void updateTextGlyph (float tx, float ty, float availWidth, float availHeight) { float twidth = renderer.adjustWidth(text.width()); float theight = renderer.adjustHeight(text.height()); if (twidth <= 0 || theight <= 0) return; // make sure our canvas layer is big enough to hold our text _tglyph.prepare(twidth, theight); // we do some extra fiddling here because one may want to constrain the height of a // button such that the text is actually cut off on the top and/or bottom because fonts // may have lots of whitespace above or below and you're trying to squeeze the text // snugly into your button float oy = valign.offset(theight, availHeight); if (oy >= 0) { renderer.render(_tglyph.canvas(), text, color, 0, 0); } else { renderer.render(_tglyph.canvas(), text, color, 0, oy); oy = 0; } _tglyph.layer().setTranslation(MathUtil.ifloor(tx + halign.offset(twidth, availWidth)), MathUtil.ifloor(ty + oy)); } } protected final Glyph _tglyph = new Glyph(); protected ImageLayer _ilayer; }
package net.mgsx.game.core.ui; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import com.badlogic.gdx.utils.Array; import net.mgsx.game.core.annotations.Editable; import net.mgsx.game.core.annotations.EditableComponent; import net.mgsx.game.core.annotations.EditableSystem; import net.mgsx.game.core.helpers.ReflectionHelper; public class EntityEditor extends Table { public static class EntityEvent extends Event { public Object entity; public Accessor accessor; public Object value; public EntityEvent(Object entity, Accessor accessor, Object value) { super(); this.entity = entity; this.accessor = accessor; this.value = value; } } private Array<Object> stack = new Array<Object>(); private final boolean annotationBased; public EntityEditor(Skin skin) { this(skin, false); } public EntityEditor(Skin skin, boolean annotationBased) { this(null, annotationBased, skin); } public EntityEditor(Object entity, Skin skin) { this(entity, false, skin); } public EntityEditor(Object entity, boolean annotationBased, Skin skin) { super(skin); this.annotationBased = annotationBased; setEntity(entity); } private EntityEditor(Object entity, boolean annotationBased, Skin skin, Array<Object> stack) { super(skin); this.annotationBased = annotationBased; this.stack = stack; generate(entity, this); } public void setEntity(Object entity) { stack.clear(); clearChildren(); if(entity != null) { generate(entity, this); } } public static interface Accessor { public Object get(); public void set(Object value); public String getName(); public Class getType(); } private static class VoidAccessor implements Accessor { private final Object object; private final Method method; private final String name; public VoidAccessor(Object object, Method method) { this(object, method, method.getName()); } public VoidAccessor(Object object, Method method, String name) { super(); this.object = object; this.method = method; this.name = name; } @Override public Object get() { ReflectionHelper.invoke(object, method); return null; } @Override public void set(Object value) { } @Override public String getName() { return name; } @Override public Class getType() { return void.class; } } private static class FieldAccessor implements Accessor { private Object object; private Field field; private String label; public FieldAccessor(Object object, Field field, String labelName) { super(); this.object = object; this.field = field; this.label = labelName; } public FieldAccessor(Object object, Field field) { super(); this.object = object; this.field = field; this.label = field.getName(); } public FieldAccessor(Object object, String fieldName) { super(); this.object = object; this.field = ReflectionHelper.field(object, fieldName); this.label = fieldName; } @Override public Object get() { return ReflectionHelper.get(object, field); } @Override public void set(Object value) { ReflectionHelper.set(object, field, value); } @Override public String getName() { return label; } @Override public Class getType() { return field.getType(); } } public static class MethodAccessor implements Accessor { private Object object; private String name; private Method getter; private Method setter; public MethodAccessor(Object object, String name, String getter, String setter) { super(); this.object = object; this.name = name; this.getter = ReflectionHelper.method(object.getClass(), getter); this.setter = ReflectionHelper.method(object.getClass(), setter, this.getter.getReturnType()); } public MethodAccessor(Object object, String name, Method getter, Method setter) { super(); this.object = object; this.name = name; this.getter = getter; this.setter = setter; } @Override public Object get() { return ReflectionHelper.invoke(object, getter); } @Override public void set(Object value) { ReflectionHelper.invoke(object, setter, value); } @Override public String getName() { return name; } @Override public Class getType() { return getter.getReturnType(); } } public void generate(final Object entity, final Table table) { // prevent cycles if(entity == null || stack.contains(entity, true)) return; stack.add(entity); if(annotationBased){ boolean match = false; if(entity.getClass().getAnnotation(EditableSystem.class) != null) match = true; if(entity.getClass().getAnnotation(EditableComponent.class) != null) match = true; if(!match) return; } // first scan class to get all accessors Array<Accessor> accessors = new Array<Accessor>(); // scan fields for(Field field : entity.getClass().getFields()) { if(Modifier.isStatic(field.getModifiers())) continue; if(annotationBased){ Editable editable = field.getAnnotation(Editable.class); if(editable == null){ continue; } if(editable.value().isEmpty()) accessors.add(new FieldAccessor(entity, field)); else accessors.add(new FieldAccessor(entity, field, editable.value())); } else { accessors.add(new FieldAccessor(entity, field)); } } // scan getter/setter pattern for(Method method : entity.getClass().getMethods()) { if(Modifier.isStatic(method.getModifiers())) continue; if(annotationBased){ Editable editable = method.getAnnotation(Editable.class); if(editable == null){ continue; } if(method.getReturnType() != void.class) continue; if(method.getParameterCount() > 0) continue; if(editable.value().isEmpty()) accessors.add(new VoidAccessor(entity, method)); else accessors.add(new VoidAccessor(entity, method, editable.value())); } else { if(method.getName().startsWith("set") && method.getName().length() > 3 && method.getParameterCount() == 1) { String getterName = "g" + method.getName().substring(1); Method getter = ReflectionHelper.method(entity.getClass(), getterName); if(getter == null || getter.getReturnType() != method.getParameterTypes()[0]){ // try boolean pattern setX/isX getterName = "is" + method.getName().substring(3); getter = ReflectionHelper.method(entity.getClass(), getterName); } if(getter != null && getter.getReturnType() == method.getParameterTypes()[0]){ String name = method.getName().substring(3,4).toLowerCase() + method.getName().substring(4); accessors.add(new MethodAccessor(entity, name, getter, method)); } } } } for(final Accessor accessor : accessors) { Label accessorLabel = new Label(accessor.getName(), table.getSkin()); table.add(accessorLabel).fill().left(); if(!createControl(table, entity, accessor, stack)) { // create recursively on missing type (object) // TODO background ? accessorLabel.setStyle(table.getSkin().get("tab-left", LabelStyle.class)); Table sub = new Table(getSkin()); sub.setBackground(getSkin().getDrawable("default-window-body-right")); table.add(sub).expand().fill().left(); generate(accessor.get(), sub); } table.row(); } } private static void createSlider2D(Table table, Object entity, String name, final Quaternion q) { Label ctrl = new Label("CTRL", table.getSkin()); ctrl.addListener(new DragListener(){ Quaternion m = new Quaternion(); @Override public void drag(InputEvent event, float x, float y, int pointer) { float dx = getDeltaX(); float dy = getDeltaY(); q.mul(m.setEulerAngles(dx, dy,0)); event.cancel(); } }); table.add(ctrl); } static public void createSlider(final Table table, final Object entity, final Accessor accessor){ createSlider(table, entity, accessor, entity, accessor); } static public void createSlider(final Table table, final Object rootEntity, final Accessor rootField, final Object entity, final Accessor accessor){ final Label label = new Label("", table.getSkin()){ @Override public void act(float delta) { super.act(delta); setText(String.valueOf(accessor.get())); } }; label.setText(String.valueOf(accessor.get())); table.add(label); label.addListener(new DragListener(){ @Override public void drag(InputEvent event, float x, float y, int pointer) { float value = (Float)accessor.get(); value += value == 0 ? 0.1f : -getDeltaX() * value * 0.01; accessor.set(value); label.setText(String.valueOf(value)); table.fire(new EntityEvent(rootEntity, rootField, rootField.get())); // prevent other widget (like ScrollPane) to act during dragging value label.getStage().cancelTouchFocusExcept(this, label); } @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { if(button == Input.Buttons.RIGHT){ float value = (Float)accessor.get(); value = -value; accessor.set(value); label.setText(String.valueOf(value)); table.fire(new EntityEvent(rootEntity, rootField, rootField.get())); return true; } return super.touchDown(event, x, y, pointer, button); } }); } public static Button createBoolean(Skin skin, boolean value) { final TextButton btCheck = new TextButton(String.valueOf(value), skin, "toggle"); btCheck.setChecked(value); btCheck.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { btCheck.setText(String.valueOf(btCheck.isChecked())); } }); return btCheck; } public static boolean createControl(final Table table, final Object entity, final Accessor accessor) { return createControl(table, entity, accessor, new Array<Object>()); } private static boolean createControl(final Table table, final Object entity, final Accessor accessor, Array<Object> stack) { Skin skin = table.getSkin(); if(accessor.getType() == int.class){ // TODO slider Table sub = new Table(skin); final Label label = new Label("", skin); final TextButton btPlus = new TextButton("+", skin); final TextButton btMinus = new TextButton("-", skin); sub.add(btMinus); sub.add(label).pad(4); sub.add(btPlus); label.setText(String.valueOf(accessor.get())); table.add(sub).fill(); btPlus.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { int value = 1 + (Integer)accessor.get(); accessor.set(value); label.setText(String.valueOf(value)); btPlus.fire(new EntityEvent(entity, accessor, value)); } }); btMinus.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { int value = -1 + (Integer)accessor.get(); accessor.set(value); label.setText(String.valueOf(value)); btMinus.fire(new EntityEvent(entity, accessor, value)); } }); }else if(accessor.getType() == float.class){ createSlider(table, entity, accessor, entity, accessor); }else if(accessor.getType() == String.class){ final TextField field = new TextField(String.valueOf(accessor.get()), skin); table.add(field); field.addListener(new ChangeListener(){ @Override public void changed(ChangeEvent event, Actor actor) { accessor.set(field.getText()); } }); field.addListener(new ClickListener(){ @Override public void touchDragged(InputEvent event, float x, float y, int pointer) { field.getStage().cancelTouchFocusExcept(field.getDefaultInputListener(), field); super.touchDragged(event, x, y, pointer); } @Override public boolean keyDown(InputEvent event, int keycode) { if(keycode == Input.Keys.ENTER) field.getStage().setKeyboardFocus(null); return super.keyDown(event, keycode); } }); }else if(accessor.getType() == boolean.class){ final Button btCheck = createBoolean(skin, (Boolean)accessor.get()); btCheck.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { accessor.set(btCheck.isChecked()); table.fire(new EntityEvent(entity, accessor, btCheck.isChecked())); } }); table.add(btCheck); }else if(accessor.getType() == Vector2.class){ Vector2 v = (Vector2)accessor.get(); Table sub = new Table(table.getSkin()); sub.add("("); createSlider(sub, entity, accessor, v, new FieldAccessor(v, "x")); sub.add(","); createSlider(sub, entity, accessor, v, new FieldAccessor(v, "y")); sub.add(")"); table.add(sub); }else if(accessor.getType() == Quaternion.class){ Quaternion q = (Quaternion)accessor.get(); createSlider2D(table, entity, accessor.getName(), q); }else if(accessor.getType() == Color.class){ Color c = (Color)accessor.get(); Table sub = new Table(table.getSkin()); sub.add("("); createSlider(sub, entity, accessor, c, new FieldAccessor(c, "r")); sub.add(","); createSlider(sub, entity, accessor, c, new FieldAccessor(c, "g")); sub.add(","); createSlider(sub, entity, accessor, c, new FieldAccessor(c, "b")); sub.add(","); createSlider(sub, entity, accessor, c, new FieldAccessor(c, "a")); sub.add(")"); table.add(sub); }else if(accessor.getType().isEnum()){ final SelectBox<Object> selector = new SelectBox<Object>(skin); Array<Object> values = new Array<Object>(); for(Object o : accessor.getType().getEnumConstants()) values.add(o); selector.setItems(values); selector.setSelected(accessor.get()); selector.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { accessor.set(selector.getSelected()); } }); table.add(selector); }else{ table.add(new EntityEditor(accessor.get(), false, skin, stack)).row(); // XXX return false; } return true; } }
package org.neo4j.util.index; import java.io.IOException; import java.io.Reader; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.WhitespaceTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.neo4j.api.core.EmbeddedNeo; import org.neo4j.api.core.NeoService; import org.neo4j.api.core.Node; import org.neo4j.impl.core.NotFoundException; import org.neo4j.impl.transaction.LockManager; import org.neo4j.impl.util.ArrayMap; // TODO: // o Move LuceneTransaction to its own file and do general code cleanup // o Run optimize when starting up // o Abort all writers (if any) on shutdown public class LuceneIndexService extends GenericIndexService { private final ArrayMap<String,IndexSearcher> indexSearchers = new ArrayMap<String,IndexSearcher>( 6, true, true ); private final ThreadLocal<LuceneTransaction> luceneTransactions = new ThreadLocal<LuceneTransaction>(); private final LockManager lockManager; private final TransactionManager txManager; private static class WriterLock { private final String key; WriterLock( String key ) { this.key = key; } private String getKey() { return key; } @Override public int hashCode() { return key.hashCode(); } @Override public boolean equals( Object o ) { if ( !(o instanceof WriterLock) ) { return false; } return this.key.equals( ((WriterLock) o).getKey() ); } } private class LuceneTransaction implements Synchronization { private final Set<WriterLock> writers = new HashSet<WriterLock>(); private final Map<String,Map<Object,Long[]>> txIndexed = new HashMap<String,Map<Object,Long[]>>(); private final Map<String,Map<Object,Long[]>> txRemoved = new HashMap<String,Map<Object,Long[]>>(); boolean hasWriter( WriterLock lock ) { return writers.contains( lock ); } void addWriter( WriterLock lock ) { writers.add( lock ); } void index( Node node, String key, Object value ) { delRemovedIndex( node, key, value ); Map<Object,Long[]> keyIndex = txIndexed.get( key ); if ( keyIndex == null ) { keyIndex = new HashMap<Object,Long[]>(); txIndexed.put( key, keyIndex ); } Long nodeIds[] = keyIndex.get( value ); if ( nodeIds == null ) { nodeIds = new Long[1]; nodeIds[0] = node.getId(); } else { Long newIds[] = new Long[nodeIds.length + 1 ]; boolean dupe = false; long nodeId = node.getId(); for ( int i = 0; i < nodeIds.length; i++ ) { if ( nodeIds[i] == nodeId ) { dupe = true; break; } newIds[i] = nodeIds[i]; } if ( !dupe ) { newIds[nodeIds.length] = node.getId(); nodeIds = newIds; } } keyIndex.put( value, nodeIds ); } void removeIndex( Node node, String key, Object value ) { if ( delAddedIndex( node, key, value ) ) { return; } Map<Object,Long[]> keyIndex = txRemoved.get( key ); if ( keyIndex == null ) { keyIndex = new HashMap<Object,Long[]>(); txRemoved.put( key, keyIndex ); } Long nodeIds[] = keyIndex.get( value ); if ( nodeIds == null ) { nodeIds = new Long[1]; nodeIds[0] = node.getId(); } else { Long newIds[] = new Long[nodeIds.length + 1 ]; boolean dupe = false; long nodeId = node.getId(); for ( int i = 0; i < nodeIds.length; i++ ) { if ( nodeIds[i] == nodeId ) { dupe = true; break; } newIds[i] = nodeIds[i]; } if ( !dupe ) { newIds[nodeIds.length] = node.getId(); nodeIds = newIds; } } keyIndex.put( value, nodeIds ); } boolean delRemovedIndex( Node node, String key, Object value ) { Map<Object,Long[]> keyIndex = txRemoved.get( key ); if ( keyIndex == null ) { return false; } Long nodeIds[] = keyIndex.get( value ); if ( nodeIds == null ) { return false; } Long newIds[] = new Long[nodeIds.length - 1 ]; long nodeId = node.getId(); int index = 0; for ( int i = 0; i < nodeIds.length; i++ ) { if ( i != 0 && index == newIds.length ) { // no match found return false; } if ( nodeIds[i] != nodeId ) { newIds[index++] = nodeIds[i]; } } if ( newIds.length == 0 ) { keyIndex.remove( value ); } else { keyIndex.put( value, newIds ); } return true; } boolean delAddedIndex( Node node, String key, Object value ) { Map<Object,Long[]> keyIndex = txIndexed.get( key ); if ( keyIndex == null ) { return false; } Long nodeIds[] = keyIndex.get( value ); if ( nodeIds == null ) { return false; } Long newIds[] = new Long[nodeIds.length - 1 ]; long nodeId = node.getId(); int index = 0; for ( int i = 0; i < nodeIds.length; i++ ) { if ( i != 0 && index == newIds.length ) { // no match found return false; } if ( nodeIds[i] != nodeId ) { newIds[index++] = nodeIds[i]; } } if ( newIds.length == 0 ) { keyIndex.remove( value ); } else { keyIndex.put( value, newIds ); } return true; } Set<Node> getDeletedNodesFor( String key, Object value ) { Map<Object,Long[]> keyIndex = txRemoved.get( key ); if ( keyIndex != null ) { Long[] nodeIds = keyIndex.get( value ); if ( nodeIds != null ) { Set<Node> nodes = new HashSet<Node>(); for ( long nodeId : nodeIds ) { try { nodes.add( getNeo().getNodeById( nodeId ) ); } catch ( NotFoundException e ) { // ok deleted in this tx } } return nodes; } } return Collections.EMPTY_SET; } List<Node> getNodesFor( String key, Object value ) { Map<Object,Long[]> keyIndex = txIndexed.get( key ); if ( keyIndex != null ) { Long[] nodeIds = keyIndex.get( value ); if ( nodeIds != null ) { List<Node> nodes = new LinkedList<Node>(); for ( long nodeId : nodeIds ) { try { nodes.add( getNeo().getNodeById( nodeId ) ); } catch ( NotFoundException e ) { // ok deleted in this tx } } return nodes; } } return Collections.EMPTY_LIST; } public void afterCompletion( int status ) { luceneTransactions.set( null ); for ( WriterLock lock : writers ) { String key = lock.getKey(); if ( status == Status.STATUS_COMMITTED ) { Map<Object,Long[]> deleteMap = txRemoved.get( key ); if ( deleteMap != null ) { for ( Entry<Object,Long[]> deleteEntry : deleteMap.entrySet() ) { Object value = deleteEntry.getKey(); Long[] ids = deleteEntry.getValue(); for ( Long id : ids ) { deleteDocumentUsingReader( id, key, value ); } } } IndexWriter writer = getIndexWriter( key ); Map<Object,Long[]> indexMap = txIndexed.get( key ); try { if ( indexMap != null ) { for ( Entry<Object,Long[]> indexEntry : indexMap.entrySet() ) { Object value = indexEntry.getKey(); Long[] ids = indexEntry.getValue(); for ( Long id : ids ) { indexWriter( writer, id, key, value ); } } } writer.close(); } catch ( IOException e ) { e.printStackTrace(); } IndexSearcher searcher = indexSearchers.remove( key ); if ( searcher != null ) { try { searcher.close(); } catch ( IOException e ) { e.printStackTrace(); } } } lockManager.releaseWriteLock( lock ); } } private void indexWriter( IndexWriter writer, long nodeId, String key, Object value ) { Document document = new Document(); document.add( new Field( "id", String.valueOf( nodeId ), Field.Store.YES, Field.Index.UN_TOKENIZED ) ); document.add( new Field( "index", value.toString(), Field.Store.NO, Field.Index.UN_TOKENIZED ) ); try { writer.addDocument( document ); } catch ( IOException e ) { throw new RuntimeException( e ); } } public void beforeCompletion() { } } private static class DefaultAnalyzer extends Analyzer { @Override public TokenStream tokenStream( String fieldName, Reader reader ) { return new LowerCaseFilter( new WhitespaceTokenizer( reader ) ); } } private static final Analyzer DEFAULT_ANALYZER = new DefaultAnalyzer(); public LuceneIndexService( NeoService neo ) { super ( neo ); EmbeddedNeo embeddedNeo = ((EmbeddedNeo) neo); lockManager = embeddedNeo.getConfig().getLockManager(); txManager = embeddedNeo.getConfig().getTxModule().getTxManager(); } private synchronized IndexWriter getIndexWriter( String key ) { try { Directory dir = FSDirectory.getDirectory( "var/search/" + key ); return new IndexWriter( dir, false, DEFAULT_ANALYZER ); } catch ( IOException e ) { throw new RuntimeException( e ); } } protected void indexThisTx( Node node, String key, Object value ) { LuceneTransaction luceneTx = luceneTransactions.get(); if ( luceneTx == null ) { luceneTx = new LuceneTransaction(); luceneTransactions.set( luceneTx ); try { Transaction tx = txManager.getTransaction(); tx.registerSynchronization( luceneTx ); } catch ( SystemException e ) { throw new IllegalStateException( "No transaciton running?", e ); } catch ( RollbackException e ) { throw new IllegalStateException( "Unable to register syncrhonization hook", e ); } } WriterLock lock = new WriterLock( key ); // IndexWriter writer = luceneTx.getWriterForLock( lock ); if ( !luceneTx.hasWriter( lock ) ) { lockManager.getWriteLock( lock ); // writer = getIndexWriter( key ); // luceneTx.addWriter( lock, writer ); luceneTx.addWriter( lock ); } // Document document = new Document(); // document.add( new Field( "id", // String.valueOf( node.getId() ), // Field.Store.YES, Field.Index.UN_TOKENIZED ) ); // document.add( new Field( "index", value.toString(), // Field.Store.NO, Field.Index.UN_TOKENIZED ) ); // try // writer.addDocument( document ); // catch ( IOException e ) // throw new RuntimeException( e ); luceneTx.index( node, key, value ); } private IndexSearcher getIndexSearcher( String key ) { IndexSearcher searcher = indexSearchers.get( key ); if ( searcher == null ) { try { Directory dir = FSDirectory.getDirectory( "var/search/" + key ); if ( dir.list().length == 0 ) { return null; } searcher = new IndexSearcher( dir ); } catch ( IOException e ) { throw new RuntimeException( e ); } indexSearchers.put( key, searcher ); } return searcher; } public Iterable<Node> getNodes( String key, Object value ) { IndexSearcher searcher = getIndexSearcher( key ); List<Node> nodes = new LinkedList<Node>(); LuceneTransaction luceneTx = luceneTransactions.get(); Set<Node> deletedNodes = Collections.EMPTY_SET; if ( luceneTx != null ) { // add nodes that has been indexed in this tx List<Node> txNodes = luceneTx.getNodesFor( key, value ); nodes.addAll( txNodes ); deletedNodes = luceneTx.getDeletedNodesFor( key, value ); } if ( searcher == null ) { return nodes; } else { Query query = new TermQuery( new Term( "index", value.toString() ) ); try { Hits hits = searcher.search( query ); for ( int i = 0; i < hits.length(); i++ ) { Document document = hits.doc( i ); try { nodes.add( getNeo().getNodeById( Integer.parseInt( document.getField( "id" ).stringValue() ) ) ); } catch ( NotFoundException e ) { // deleted in this tx } } } catch ( IOException e ) { throw new RuntimeException( "Unable to search for " + key + "," + value, e ); } } // remove dupes and deleted in same tx Set<Node> addedNodes = new HashSet<Node>(); Iterator<Node> nodeItr = nodes.iterator(); while ( nodeItr.hasNext() ) { Node node = nodeItr.next(); if ( !addedNodes.add( node ) || deletedNodes.contains( node ) ) { nodeItr.remove(); } } return nodes; } public Node getSingleNode( String key, Object value ) { LuceneTransaction luceneTx = luceneTransactions.get(); Set<Node> deletedNodes = Collections.EMPTY_SET; List<Node> addedNodes = Collections.EMPTY_LIST; if ( luceneTx != null ) { addedNodes = luceneTx.getNodesFor( key, value ); deletedNodes = luceneTx.getDeletedNodesFor( key, value ); Iterator<Node> nodeItr = addedNodes.iterator(); while ( nodeItr.hasNext() ) { Node addedNode = nodeItr.next(); if ( deletedNodes.contains( addedNode ) ) { nodeItr.remove(); } } } IndexSearcher searcher = getIndexSearcher( key ); if ( searcher == null ) { if ( addedNodes.isEmpty() ) { return null; } if ( addedNodes.size() == 1 ) { return addedNodes.get( 0 ); } } else { Query query = new TermQuery( new Term( "index", value.toString() ) ); try { Hits hits = searcher.search( query ); if ( hits.length() == 1 ) { Document document = hits.doc( 0 ); Node node = getNeo().getNodeById( Integer.parseInt( document.getField( "id" ).stringValue() ) ); if ( deletedNodes.contains( node ) ) { node = null; } if ( addedNodes.size() == 0 ) { return node; } if ( addedNodes.size() == 1 ) { if ( node == null ) { return addedNodes.get( 0 ); } if ( node.equals( addedNodes.get( 0 ) ) ) { return node; } } } else if ( hits.length() == 0 ) { if ( addedNodes.size() == 0 ) { return null; } if ( addedNodes.size() == 1 ) { return addedNodes.get( 0 ); } } } catch ( IOException e ) { throw new RuntimeException( "Unable to search for " + key + "," + value, e ); } } throw new RuntimeException( "More then one node found for: " + key + "," + value ); } void deleteDocumentUsingReader( long nodeId, String key, Object value ) { IndexSearcher searcher = getIndexSearcher( key ); if ( searcher == null ) { return; } Query query = new TermQuery( new Term( "index", value.toString() ) ); try { Hits hits = searcher.search( query ); for ( int i = 0; i < hits.length(); i++ ) { Document document = hits.doc( 0 ); int foundId = Integer.parseInt( document.getField( "id" ).stringValue() ); if ( nodeId == foundId ) { int docNum = hits.id( i ); searcher.getIndexReader().deleteDocument( docNum ); } } } catch ( IOException e ) { throw new RuntimeException( "Unable to delete for " + nodeId +"," + key + "," + value, e ); } } protected void removeIndexThisTx( Node node, String key, Object value ) { LuceneTransaction luceneTx = luceneTransactions.get(); if ( luceneTx == null ) { luceneTx = new LuceneTransaction(); luceneTransactions.set( luceneTx ); try { Transaction tx = txManager.getTransaction(); tx.registerSynchronization( luceneTx ); } catch ( SystemException e ) { throw new IllegalStateException( "No transaciton running?", e ); } catch ( RollbackException e ) { throw new IllegalStateException( "Unable to register syncrhonization hook", e ); } } WriterLock lock = new WriterLock( key ); // IndexWriter writer = luceneTx.getWriterForLock( lock ); if ( !luceneTx.hasWriter( lock ) ) { lockManager.getWriteLock( lock ); // writer = getIndexWriter( key ); // luceneTx.addWriter( lock, writer ); luceneTx.addWriter( lock ); } // Term term = new Term( new Long( node.getId() ).toString(), // value.toString().toLowerCase() ); // try // writer.deleteDocuments( term ); // catch ( IOException e ) // throw new RuntimeException( e ); luceneTx.removeIndex( node, key, value ); } @Override public synchronized void shutdown() { super.shutdown(); for ( IndexSearcher searcher : indexSearchers.values() ) { try { searcher.close(); } catch ( IOException e ) { e.printStackTrace(); } } } }
package org.pfaa.geologica.block; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; import org.pfaa.chemica.model.Condition; import org.pfaa.chemica.model.IndustrialMaterial; import org.pfaa.geologica.GeoMaterial; import org.pfaa.geologica.Geologica; import org.pfaa.geologica.GeoMaterial.Strength; import org.pfaa.geologica.GeologicaBlocks; import org.pfaa.geologica.processing.Aggregate; import org.pfaa.geologica.processing.Aggregate.Aggregates; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class IntactGeoBlock extends GeoBlock { private static Set<Block> stoneBlocks, clayBlocks; public IntactGeoBlock(Strength strength, Class<? extends IndustrialMaterial> composition, Material material) { super(strength, composition, material, false); } @Override public Item getItemDropped(int meta, Random random, int par3) { Item dropped = super.getItemDropped(meta, random, par3); GeoMaterial material = getGeoMaterial(meta); if (material.getComposition() instanceof Aggregate && blockMaterial == Material.rock) { dropped = dropRock(meta); } return dropped; } private Item dropRock(int meta) { Item dropped = null; GeoMaterial material = getGeoMaterial(meta); switch(material.getStrength()) { case WEAK: dropped = Item.getItemFromBlock(GeologicaBlocks.WEAK_RUBBLE); break; case MEDIUM: dropped = Item.getItemFromBlock(GeologicaBlocks.MEDIUM_COBBLE); break; case STRONG: dropped = Item.getItemFromBlock(GeologicaBlocks.STRONG_COBBLE); break; case VERY_STRONG: dropped = Item.getItemFromBlock(this); break; default: break; } return dropped; } @Override protected boolean canSilkHarvest() { return true; } @Override @SideOnly(Side.CLIENT) public IIcon getHostIcon(IndustrialMaterial host, IBlockAccess world, int x, int y, int z) { if (host == Aggregates.STONE || host == Aggregates.CLAY) { return getAdjacentHostIcon(world, x, y, z); } return null; } @SideOnly(Side.CLIENT) private static IIcon getAdjacentHostIcon(IBlockAccess world, int x, int y, int z) { if (stoneBlocks == null) { stoneBlocks = createSetForOre("stone"); clayBlocks = createSetForOre("clay"); } ItemStack host = getAdjacentStone(world, x, y, z); if (host == null) return null; Block block = ((ItemBlock)host.getItem()).field_150939_a; return block.getIcon(0, host.getItemDamage()); } private static Set createSetForOre(String key) { Set set = new HashSet(); List<ItemStack> ores = OreDictionary.getOres(key); for (ItemStack ore : ores) { Item item = ore.getItem(); if (item instanceof ItemBlock) { set.add(((ItemBlock)item).field_150939_a); } } return set; } private static ItemStack getAdjacentStone(IBlockAccess world, int x, int y, int z) { for (int ix = x - 1; ix <= x + 1; ix++) { for (int iy = y - 1; iy <= y + 1; iy++) { for (int iz = z - 1; iz <= z + 1; iz++) { Block block = world.getBlock(ix, iy, iz); if ((block.getMaterial() == Material.rock && stoneBlocks.contains(block)) || (block.getMaterial() == Material.clay && clayBlocks.contains(block))) { int meta = world.getBlockMetadata(ix, iy, iz); return new ItemStack(block, 1, meta); } } } } return null; } /* @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta) { TileEntity entity = world.getTileEntity(x, y, z); return meta; } */ }
package org.sfm.benchmark.db.jooq; import java.util.List; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.Result; import org.jooq.impl.DSL; import org.jooq.impl.DefaultConfiguration; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.db.jmh.ConnectionParam; import org.sfm.benchmark.db.jmh.DbTarget; import org.sfm.benchmark.db.jmh.LimitParam; import org.sfm.jooq.SfmRecordMapperProvider; import org.sfm.jooq.beans.tables.TestSmallBenchmarkObject; import org.sfm.jooq.beans.tables.records.TestSmallBenchmarkObjectRecord; @State(Scope.Benchmark) public class JooqBenchmark { @Param(value = "MOCK") private DbTarget db; private DSLContext dslNoSfmMapping; private DSLContext dslSfmMapping; @Setup public void init() throws Exception { ConnectionParam cp = new ConnectionParam(); cp.db = db; cp.init(); dslNoSfmMapping = DSL.using(new DefaultConfiguration().set(cp.dataSource).set( db.getSqlDialect())); dslSfmMapping = DSL. using(new DefaultConfiguration().set(cp.dataSource) .set(db.getSqlDialect()) .set(new SfmRecordMapperProvider())); } @Benchmark public void testFetchRecord(LimitParam limit, final Blackhole blackhole, ConnectionParam connectionParam) throws Exception { Result<Record> result = dslNoSfmMapping.select().from(TestSmallBenchmarkObject.TEST_SMALL_BENCHMARK_OBJECT).limit(limit.limit).fetch(); for(Record o : result) { TestSmallBenchmarkObjectRecord sbo = (TestSmallBenchmarkObjectRecord) o; blackhole.consume(sbo); } } @Benchmark public void testSqlWithJooqMapper(LimitParam limit, final Blackhole blackhole, ConnectionParam connectionParam) throws Exception { List<SmallBenchmarkObject> result = dslNoSfmMapping.select().from("test_small_benchmark_object").limit(limit.limit).fetch().into(SmallBenchmarkObject.class); for(SmallBenchmarkObject o : result) { blackhole.consume(o); } } @Benchmark public void testSqlSmfMapper(LimitParam limit, final Blackhole blackhole, ConnectionParam connectionParam) throws Exception { List<SmallBenchmarkObject> result = dslSfmMapping.select().from("test_small_benchmark_object").limit(limit.limit).fetch().into(SmallBenchmarkObject.class); for(SmallBenchmarkObject o : result) { blackhole.consume(o); } } }
// POITools.java package loci.formats; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; import loci.common.RandomAccessInputStream; import loci.common.ReflectException; import loci.common.ReflectedUniverse; public class POITools { // -- Constants -- private static final String NO_POI_MSG = "Jakarta POI is required to read Compix SimplePCI, Fluoview FV1000 OIB, " + "ImagePro IPW, and Zeiss ZVI files. Please obtain poi-loci.jar from " + "http://loci.wisc.edu/ome/formats.html"; // -- Fields -- private ReflectedUniverse r; private String id; private Vector<String> filePath; private Vector<String> fileList; private Hashtable<String, Integer> fileSizes; // -- Constructor -- public POITools(String id) throws FormatException, IOException { this.id = id; initialize(id); } public POITools(RandomAccessInputStream s) throws FormatException, IOException { id = String.valueOf(System.currentTimeMillis()); initialize(s); } // -- Document retrieval methods -- public RandomAccessInputStream getDocumentStream(String name) throws FormatException, IOException { byte[] buf = getDocumentBytes(name, getFileSize(name)); return new RandomAccessInputStream(buf); } public byte[] getDocumentBytes(String name) throws FormatException { return getDocumentBytes(name, getFileSize(name)); } public byte[] getDocumentBytes(String name, int count) throws FormatException { int availableBytes = getFileSize(name); int len = count > availableBytes ? availableBytes : count; setupFile(name); byte[] buf = new byte[len]; try { String dataVar = makeVarName("data"); r.setVar(dataVar, buf); r.exec(makeVarName("dis") + ".read(" + dataVar + ")"); } catch (ReflectException e) { throw new FormatException(e); } return buf; } public int getFileSize(String name) throws FormatException { Integer numBytes = fileSizes.get(name); return numBytes.intValue(); } public Vector<String> getDocumentList() throws FormatException { return fileList; } public void close() { try { r.exec(makeVarName("dis") + ".close()"); r.setVar(makeVarName("data"), null); r.setVar(makeVarName("dis"), null); r.setVar(makeVarName("data"), null); r.setVar(makeVarName("numBytes"), null); r.setVar(makeVarName("root"), null); r.setVar(makeVarName("file"), null); r.setVar(makeVarName("size"), null); r.setVar(makeVarName("littleEndian"), null); r.setVar(makeVarName("fis"), null); r.setVar(makeVarName("fs"), null); r.setVar(makeVarName("dir"), null); r.setVar(makeVarName("directory"), null); r.setVar(makeVarName("entry"), null); r.setVar(makeVarName("entryName"), null); r.setVar(makeVarName("tmp"), null); } catch (ReflectException e) { } } // -- Helper methods -- private void initialize(String file) throws FormatException, IOException { RandomAccessInputStream s = new RandomAccessInputStream(file); initialize(s); s.close(); } private void initialize(RandomAccessInputStream s) throws FormatException, IOException { try { r = new ReflectedUniverse(); r.exec("import loci.poi.poifs.filesystem.POIFSFileSystem"); r.exec("import loci.poi.poifs.filesystem.DirectoryEntry"); r.exec("import loci.poi.poifs.filesystem.DocumentEntry"); r.exec("import loci.poi.poifs.filesystem.DocumentInputStream"); r.exec("import loci.common.RandomAccessInputStream"); r.exec("import java.util.Iterator"); } catch (ReflectException exc) { throw new FormatException(NO_POI_MSG, exc); } s.order(true); s.seek(30); int size = (int) Math.pow(2, s.readShort()); s.seek(0); try { String sizeVar = makeVarName("size"); String fsVar = makeVarName("fs"); String fisVar = makeVarName("fis"); r.setVar(sizeVar, size); r.setVar(makeVarName("littleEndian"), true); r.setVar(fisVar, s); r.exec(fsVar + " = new POIFSFileSystem(" + fisVar + ", " + sizeVar + ")"); r.exec(makeVarName("root") + " = " + fsVar + ".getRoot()"); } catch (ReflectException e) { throw new FormatException(e); } fileList = new Vector<String>(); filePath = new Vector<String>(); try { parseFile(r.getVar(makeVarName("root")), fileList); } catch (ReflectException e) { throw new FormatException(e); } fileSizes = new Hashtable<String, Integer>(); for (String file : fileList) { setupFile(file); try { Integer numBytes = (Integer) r.getVar(makeVarName("numBytes")); fileSizes.put(file, numBytes); } catch (ReflectException e) { throw new FormatException(e); } } } private void setupFile(String name) throws FormatException { try { String directoryVar = makeVarName("directory"); r.exec(directoryVar + " = " + makeVarName("root")); StringTokenizer path = new StringTokenizer(name, "/\\"); int count = path.countTokens(); path.nextToken(); for (int i=1; i<count-1; i++) { String dir = path.nextToken(); r.setVar(makeVarName("dir"), dir); r.exec(directoryVar + " = " + directoryVar + ".getEntry(" + makeVarName("dir") + ")"); } String filenameVar = makeVarName("filename"); String fileVar = makeVarName("file"); String disVar = makeVarName("dis"); r.setVar(filenameVar, path.nextToken()); r.exec(fileVar + " = " + directoryVar + ".getEntry(" + filenameVar + ")"); r.exec(disVar + " = new DocumentInputStream(" + fileVar + ", " + makeVarName("fis") + ")"); r.exec(makeVarName("numBytes") + " = " + disVar + ".available()"); } catch (ReflectException e) { throw new FormatException(e); } } private void parseFile(Object root, Vector<String> fileList) throws FormatException { try { String dirVar = makeVarName("dir"); r.setVar(dirVar, root); r.exec(makeVarName("dirName") + " = " + dirVar + ".getName()"); r.exec(makeVarName("iter") + " = " + dirVar + ".getEntries()"); filePath.add((String) r.getVar(makeVarName("dirName"))); Iterator iter = (Iterator) r.getVar(makeVarName("iter")); String entryVar = makeVarName("entry"); while (iter.hasNext()) { r.setVar(entryVar, iter.next()); boolean isInstance = ((Boolean) r.exec(entryVar + ".isDirectoryEntry()")).booleanValue(); boolean isDocument = ((Boolean) r.exec(entryVar + ".isDocumentEntry()")).booleanValue(); if (isInstance) parseFile(r.getVar(entryVar), fileList); else if (isDocument) { r.exec(makeVarName("entryName") + " = " + entryVar + ".getName()"); StringBuffer path = new StringBuffer(); for (int i=0; i<filePath.size(); i++) { path.append((String) filePath.get(i)); path.append(File.separator); } path.append((String) r.getVar(makeVarName("entryName"))); fileList.add(path.toString()); } } filePath.removeElementAt(filePath.size() - 1); } catch (ReflectException e) { throw new FormatException(e); } } private String makeVarName(String var) { String file = id.replaceAll(" ", ""); file = file.replaceAll(".", ""); return file + "-" + var; } }
package ru.parallel.octotron.exec; import ru.parallel.octotron.core.graph.impl.GraphService; import ru.parallel.octotron.core.primitive.exception.ExceptionSystemError; import ru.parallel.octotron.impl.PersistentStorage; import ru.parallel.octotron.logic.ExecutionController; import ru.parallel.octotron.neo4j.impl.Neo4jGraph; import ru.parallel.utils.FileUtils; import ru.parallel.utils.JavaUtils; import java.io.File; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * main executable function<br> * */ public class StartOctotron { private final static Logger LOGGER = Logger.getLogger("octotron"); private static final int EXIT_ERROR = 1; private static final int PROCESS_CHUNK = 1024; // seems ok private static final int SYS_LOG_SIZE = 10*1024*1024; // 10 MB private static void ConfigLogging() { try { FileHandler file_handler = new FileHandler("log/octotron_%g.log" , SYS_LOG_SIZE, 1, true); // rotate to 1 file, allow append file_handler.setFormatter(new SimpleFormatter()); LOGGER.addHandler(file_handler); } catch(IOException e) { LOGGER.log(Level.CONFIG, "could not create log file", e); } } // for debugging private static boolean sample_mode = false; private static boolean bootstrap = false; /** * main executable function<br> * uses one input parameter from args - path to the configuration file<br> * see documentation for details about config file<br> * */ public static void main(String[] args) { ConfigLogging(); String config_fname; if(!sample_mode) { if (args.length != 1) { LOGGER.log(Level.SEVERE, "specify the config file"); System.exit(StartOctotron.EXIT_ERROR); } config_fname = args[0]; } else config_fname = "sample_src/config.json"; LOGGER.log(Level.INFO, "starting Octotron using config file: " + config_fname); GlobalSettings settings = null; try { String json_config = FileUtils.FileToString(config_fname); settings = new GlobalSettings(json_config); StartOctotron.CheckConfig(settings); } catch(ExceptionSystemError e) { LOGGER.log(Level.SEVERE, "could not load config file", e); System.exit(StartOctotron.EXIT_ERROR); } StartOctotron.Run(settings); } /** * compare hashes to check if the new config does not match the old one<br> * */ private static void CheckConfig(GlobalSettings settings) throws ExceptionSystemError { String path = settings.GetDbPath() + settings.GetDbName(); int old_hash = Integer.parseInt(FileUtils.FileToString(path + DBCreator.HASH_FILE)); if(settings.GetHash() != old_hash) LOGGER.log(Level.CONFIG, "config file has been changed since database creation consistency is not guaranteed"); } /** * created db, start main loop and shutdown, when finished<br> * all errors are printed and may be reported by special scripts<br> * */ private static void Run(GlobalSettings settings) { Neo4jGraph graph; ExecutionController exec_control = null; String path = settings.GetDbPath() + settings.GetDbName(); try { graph = new Neo4jGraph(path + "_neo4j", Neo4jGraph.Op.LOAD, bootstrap); GraphService.Init(graph); exec_control = new ExecutionController(graph, settings); PersistentStorage.INSTANCE.Load(path); StartOctotron.ProcessStart(settings); } catch(Exception start_exception) { StartOctotron.ProcessCrash(settings, start_exception, "start"); if(exec_control != null) exec_control.Finish(); return; } Exception loop_exception = StartOctotron.MainLoop(settings, exec_control); if(loop_exception != null) { StartOctotron.ProcessCrash(settings, loop_exception, "mainloop"); } Exception shutdown_exception = StartOctotron.Shutdown(settings, graph, exec_control); if(shutdown_exception != null) { StartOctotron.ProcessCrash(settings, shutdown_exception, "shutdown"); } } /** * run the main program loop<br> * if it crashes - returns exception, otherwise returns nothing<br> * */ private static Exception MainLoop(GlobalSettings settings, ExecutionController exec_control) { LOGGER.log(Level.INFO, "main loop started"); try { while(!exec_control.ShouldExit()) { exec_control.Process(StartOctotron.PROCESS_CHUNK); // it may sleep inside } StartOctotron.ProcessFinish(settings); } catch(Exception e) { return e; } return null; } /** * shutdown the graph and all execution processes<br> * */ public static Exception Shutdown(GlobalSettings settings, Neo4jGraph graph, ExecutionController exec_control) { String path = settings.GetDbPath() + settings.GetDbName(); try { if(exec_control != null) exec_control.Finish(); if(graph != null) graph.Shutdown(); PersistentStorage.INSTANCE.Save(path); } catch(Exception e) { return e; } return null; } /** * reaction to normal execution start<br> * */ private static void ProcessStart(GlobalSettings settings) throws ExceptionSystemError { String script = settings.GetScriptByKey("on_start"); if(script != null) FileUtils.ExecSilent(true, script); } /** * reaction to normal execution finish<br> * */ private static void ProcessFinish(GlobalSettings settings) throws ExceptionSystemError { String script = settings.GetScriptByKey("on_finish"); if(script != null) FileUtils.ExecSilent(true, script); } /** * reaction to an exception<br> * creates the file with exception info<br> * */ private static void ProcessCrash(GlobalSettings settings, Exception catched_exception, String suffix) { LOGGER.log(Level.SEVERE, "Octotron crashed during " + suffix, catched_exception); String error = catched_exception.getLocalizedMessage() + System.lineSeparator(); for(StackTraceElement elem : catched_exception.getStackTrace()) error += elem + System.lineSeparator(); File error_file = new File("log/crash_" + JavaUtils.GetDate() + "_" + JavaUtils.GetTimestamp() + "_" + suffix + ".txt"); String error_fname = error_file.getAbsolutePath(); try { FileUtils.SaveToFile(error_fname, error); } catch (Exception e) // giving up now - exception during exception processing.. { LOGGER.log(Level.SEVERE, "error during crash notification", e); } try { String script = settings.GetScriptByKey("on_crash"); if(script != null) FileUtils.ExecSilent(true, script, error_fname); } catch (ExceptionSystemError e) // giving up now - exception during exception processing.. { LOGGER.log(Level.SEVERE, "error during crash notification", e); } } }
package studentcapture.assignment; import javassist.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Repository; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import studentcapture.datalayer.filesystem.FilesystemConstants; import studentcapture.datalayer.filesystem.FilesystemInterface; import javax.servlet.http.HttpSession; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.Statement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; /** * Saves Assignments to the database and the filesystem. */ @Repository public class AssignmentDAO { // This template should be used to send queries to the database @Autowired protected JdbcTemplate databaseConnection; public int createAssignment(AssignmentModel assignmentModel) throws IllegalArgumentException, IOException { Integer assignmentID; // Construct query, depends on if assignment has publishDate or not. String insertQueryString = getInsertQueryString(assignmentModel.getAssignmentIntervall().getPublishedDate()); // Execute query and fetch generated AssignmentID KeyHolder keyHolder = new GeneratedKeyHolder(); databaseConnection.update( connection -> { PreparedStatement ps = connection.prepareStatement(insertQueryString, Statement.RETURN_GENERATED_KEYS); ps.setInt(1, assignmentModel.getCourseID()); ps.setString(2, assignmentModel.getTitle()); ps.setString(3, assignmentModel.getAssignmentIntervall().getStartDate()); ps.setString(4, assignmentModel.getAssignmentIntervall().getEndDate()); ps.setInt(5, assignmentModel.getVideoIntervall().getMinTimeSeconds()); ps.setInt(6, assignmentModel.getVideoIntervall().getMaxTimeSeconds()); ps.setString(7, assignmentModel.getAssignmentIntervall().getPublishedDate()); ps.setString(8, assignmentModel.getScale()); return ps; }, keyHolder); // Return generated AssignmentID //This is a work around, keyHolder has several keys which it shouldn't if (keyHolder.getKeys().size() > 1) { assignmentID = (int) keyHolder.getKeys().get("assignmentid"); } else { //If only one key assumes it is assignmentID. assignmentID = keyHolder.getKey().intValue(); } assignmentModel.setAssignmentID(assignmentID); if (!FilesystemInterface.storeAssignmentRecap(assignmentModel) || !FilesystemInterface.storeAssignmentDescription(assignmentModel)) { // If the recap or description could not be saved try { removeAssignment(assignmentModel); } catch (IOException e) { throw new IOException("Could not store assignment and " + "could not delete semi-stored assignment successfully. "); } throw new IOException("Could not store assignment successfully."); } return assignmentID; } private String getInsertQueryString(String published){ String insertQueryString; if(published == null) { insertQueryString = "INSERT INTO Assignment (AssignmentID, " + "CourseID, Title, StartDate, EndDate, MinTime, MaxTime, " + "Published, GradeScale) VALUES (DEFAULT ,?,?, " + "to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'), " + "to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'),?,?,?,?);"; } else { insertQueryString = "INSERT INTO Assignment (AssignmentID, " + "CourseID, Title, StartDate, EndDate, MinTime, MaxTime, " + "Published, GradeScale) VALUES (DEFAULT ,?,?, " + "to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'), " + "to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'),?,?," + "to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'),?);"; } return insertQueryString; } public void addAssignmentVideo(MultipartFile video, Integer courseID, String assignmentID) { FilesystemInterface.storeAssignmentVideo(courseID, assignmentID, video); } /** * Update an assignment, both in the database and in the file system. * * @param assignmentModel The assignment to update to. * @throws NotFoundException If the corresponding assignment is the database does not exist. * @throws IOException If files could not be stored successfully. */ public void updateAssignment(AssignmentModel assignmentModel) throws NotFoundException, IOException { String updateQuery = "UPDATE Assignment SET " + "CourseID=?, " + "Title=?, " + "StartDate=to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'), " + "EndDate=to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'), " + "MinTime=?, " + "MaxTime=?, " + "Published=to_timestamp(?, 'YYYY-MM-DD HH24:MI:SS'), " + "GradeScale=? " + "WHERE AssignmentID=?;"; int rowAffected = databaseConnection.update(updateQuery, assignmentModel.getCourseID(), assignmentModel.getTitle(), assignmentModel.getAssignmentIntervall().getStartDate(), assignmentModel.getAssignmentIntervall().getEndDate(), assignmentModel.getVideoIntervall().getMinTimeSeconds(), assignmentModel.getVideoIntervall().getMaxTimeSeconds(), assignmentModel.getAssignmentIntervall().getPublishedDate(), assignmentModel.getScale(), assignmentModel.getAssignmentID()); if (rowAffected == 0) { throw new NotFoundException("Assignment not found."); } // Overwrite description and recap if (!FilesystemInterface.storeAssignmentDescription(assignmentModel) || !FilesystemInterface.storeAssignmentRecap(assignmentModel)) { // if the assignment recap or description could not be saved throw new IOException("Could not store some data in the edited " + "assignment correctly. Please try again."); } } /** * Gets the video question corresponding to the specified assignment. * @param assignmentID Unique assignment identifier. * @return The video and Http status OK or Http status NOT_FOUND. */ public ResponseEntity<InputStreamResource> getAssignmentVideo(int assignmentID) { Optional<AssignmentModel> assignment = getAssignment(assignmentID); if (assignment.isPresent()) { String path = FilesystemInterface.generatePath(assignment.get()); path = path.concat(FilesystemConstants.ASSIGNMENT_VIDEO_FILENAME); return FilesystemInterface.getVideo(path); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } /** * * * Method for checking that the user is enrolled on the course where the video is received. * * @param assignmentModel the assignment model * @return true or false */ public boolean hasAccess(AssignmentModel assignmentModel) throws ParseException { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(); String userID = session.getAttribute("userid").toString(); String accessQuery = "SELECT userid FROM participant WHERE userid = ? AND courseid = ? LIMIT 1;"; List<String> total = databaseConnection.queryForList(accessQuery, new Object[] {Integer.parseInt(userID), assignmentModel.getCourseID()}, String.class); return !total.isEmpty(); } /** * Method for checking that the the current time is between the assignment allowed timespan * @param assignmentModel * @return */ public boolean canDoAssignment(AssignmentModel assignmentModel) throws ParseException { DateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currentDate = sdf1.parse(new Date().toString()); Date assignmentStartDate = sdf2.parse(assignmentModel.getAssignmentIntervall().getStartDate()); Date assignmentEndDate = sdf2.parse(assignmentModel.getAssignmentIntervall().getEndDate()); return currentDate.after(assignmentStartDate) && currentDate.before(assignmentEndDate); } public String getAssignmentID(String courseID,String assignmentTitle){ String sql = "SELECT assignmentID from Assignment WHERE courseID = ? AND Title = ?"; return databaseConnection.queryForObject(sql, new Object[]{courseID,assignmentTitle},String.class); } public String getCourseIDForAssignment(int assignmentID) { String sql = "SELECT courseID from Assignment WHERE assignmentID = ?"; return databaseConnection.queryForObject(sql, new Object[]{assignmentID},String.class); } /** * Returns a sought assignment from the database. * * @param assignmentID assignments identifier * @return sought assignment */ public Optional<AssignmentModel> getAssignment(int assignmentID) { try { String getAssignmentStatement = "SELECT * FROM " + "Assignment WHERE AssignmentId=?"; Map<String, Object> map = databaseConnection.queryForMap( getAssignmentStatement, assignmentID); AssignmentModel result = new AssignmentModel(map); return Optional.of(result); } catch (IncorrectResultSizeDataAccessException e){ return Optional.empty(); } catch (DataAccessException e1){ return Optional.empty(); } } /** * Returns a sought, published assignment from the database. * * @param assignmentID assignments identifier * @return sought assignment */ public Optional<AssignmentModel> getPublishedAssignment(int assignmentID) { try { String getPublishedAssignmentStatement = "SELECT * FROM " + "Assignment WHERE AssignmentId=? AND " + "published < current_timestamp"; Map<String, Object> map = databaseConnection.queryForMap( getPublishedAssignmentStatement, assignmentID); AssignmentModel result = new AssignmentModel(map); return Optional.of(result); } catch (IncorrectResultSizeDataAccessException e){ return Optional.empty(); } catch (DataAccessException e1){ return Optional.empty(); } } /** * Returns an AssignmentModel from the database. * * @param assignmentID Assignment identifier * @return The AssignmentModel * @throws NotFoundException If the assignment was not found. */ public Optional<AssignmentModel> getAssignmentModel(int assignmentID) throws NotFoundException { String getAssignmentStatement = "SELECT * FROM " + "Assignment WHERE AssignmentId=?;"; Object[] parameters = new Object[]{new Integer(assignmentID)}; SqlRowSet srs = databaseConnection.queryForRowSet(getAssignmentStatement, parameters); if (!srs.next()){ throw new NotFoundException("Assignment not found"); } AssignmentVideoIntervall videoInterval = new AssignmentVideoIntervall(); AssignmentDateIntervalls assignmentIntervals = new AssignmentDateIntervalls(); videoInterval.setMinTimeSeconds(srs.getInt("MinTime")); videoInterval.setMaxTimeSeconds(srs.getInt("MaxTime")); assignmentIntervals.setStartDate(srs.getString("StartDate").replaceAll("\\.\\d+", "")); assignmentIntervals.setEndDate(srs.getString("EndDate").replaceAll("\\.\\d+", "")); if (srs.getString("Published") != null) { assignmentIntervals.setPublishedDate(srs.getString("Published").replaceAll("\\.\\d+", "")); } int courseId = srs.getInt("courseId"); AssignmentModel assignment = new AssignmentModel(); assignment.setAssignmentID(assignmentID); assignment.setCourseID(courseId); assignment.setTitle(srs.getString("Title")); assignment.setVideoIntervall(videoInterval); assignment.setAssignmentIntervall(assignmentIntervals); assignment.setScale(srs.getString("GradeScale")); String description = FilesystemInterface.getAssignmentDescription(assignment); assignment.setDescription(description); String recap = FilesystemInterface.getAssignmentRecap(assignment); assignment.setRecap(recap); return Optional.of(assignment); } /** * Removes an assignment from the database. * * @param assignment The assignment to remove * @return true if the assignment were removed, else false. */ public boolean removeAssignment(AssignmentModel assignment) throws IOException { int rowAffected = databaseConnection.update("DELETE FROM Assignment WHERE AssignmentId = ?", assignment.getAssignmentID()); FilesystemInterface.deleteAssignmentFiles(assignment); return rowAffected > 0; } }
package loci.formats.in; import java.io.IOException; import ome.scifio.apng.APNGChecker; import ome.scifio.apng.APNGMetadata; import ome.scifio.apng.APNGParser; import ome.scifio.io.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.gui.SCIFIOBIFormatReader; @Deprecated public class APNGReader extends SCIFIOBIFormatReader<APNGMetadata> { // -- Constants -- // -- Fields -- // -- Constructor -- /** Constructs a new APNGReader. */ public APNGReader() { super("Animated PNG", "png"); checker = new APNGChecker(); parser = new APNGParser(); reader = new ome.scifio.apng.APNGReader(); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ @Deprecated public boolean isThisType(RandomAccessInputStream stream) throws IOException { return checker.isFormat(stream); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ @Deprecated public byte[][] get8BitLookupTable() throws IOException, FormatException { try { return reader.getCoreMetadata().get8BitLookupTable(getSeries()); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } } /* @see IFormatReader#openBytes(int) */ @Override @Deprecated public byte[] openBytes(int no) throws FormatException, IOException { try { return reader.openBytes(getSeries(), no); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } } /* @see IFormatReader#openBytes(int, byte[]) */ @Override @Deprecated public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { try { return reader.openBytes(this.getSeries(), no, buf); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } } /* @see IFormatReader#openBytes(int, int, int, int, int) */ @Override @Deprecated public byte[] openBytes(int no, int x, int y, int w, int h) throws FormatException, IOException { try { return reader.openBytes(this.getSeries(), no, x, y, w, h); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } } /* @see loci.formats.IFormatReader#openPlane(int, int, int, int, int int) */ @Deprecated public Object openPlane(int no, int x, int y, int w, int h) throws FormatException, IOException { try { return reader.openPlane(this.getSeries(), no, x, y, w, h); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { parser.close(fileOnly); reader.close(fileOnly); } // -- Internal FormatReader methods -- /* @see loci.formats.FormatReader#initFile(String) */ @Deprecated protected void initFile(String id) throws FormatException, IOException { super.initFile(id); APNGMetadata meta = null; try { meta = parser.parse(id); } catch (ome.scifio.FormatException e) { throw new FormatException(e.getCause()); } reader.setSource(id); reader.setMetadata(meta); } }
package ui.components.pickers; import backend.resource.TurboIssue; import backend.resource.TurboLabel; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.logging.log4j.Logger; import ui.UI; import util.HTLog; /** * Serves as a presenter that synchronizes changes in labels with dialog view */ public class LabelPickerDialog extends Dialog<List<String>> { private static final int ELEMENT_MAX_WIDTH = 400; private static final Insets GROUPLESS_PAD = new Insets(5, 0, 0, 0); private static final Insets GROUP_PAD = new Insets(0, 0, 10, 10); private static final Logger logger = HTLog.get(LabelPickerDialog.class); private final List<TurboLabel> allLabels; private final TurboIssue issue; private LabelPickerState state; @FXML private VBox mainLayout; @FXML private Label title; @FXML private FlowPane assignedLabels; @FXML private TextField queryField; @FXML private VBox feedbackLabels; LabelPickerDialog(TurboIssue issue, List<TurboLabel> allLabels, Stage stage) { this.allLabels = allLabels; this.issue = issue; initUI(stage, issue); Platform.runLater(queryField::requestFocus); } // Initialisation of UI @FXML public void initialize() { queryField.textProperty().addListener( (observable, oldText, newText) -> handleUserInput(queryField.getText())); } private void initUI(Stage stage, TurboIssue issue) { initialiseDialog(stage, issue); setDialogPaneContent(issue); title.setTooltip(createTitleTooltip(issue)); createButtons(); state = new LabelPickerState(TurboLabel.getMatchedLabels(allLabels, issue.getLabels()), allLabels, ""); populatePanes(state); } private void initialiseDialog(Stage stage, TurboIssue issue) { initOwner(stage); initModality(Modality.APPLICATION_MODAL); setTitle("Edit Labels for " + (issue.isPullRequest() ? "PR #" : "Issue #") + issue.getId() + " in " + issue.getRepoId()); // Ensures height and width of dialog has been initialized before positioning Platform.runLater(() -> positionDialog(stage)); } private void setDialogPaneContent(TurboIssue issue) { createMainLayout(); setTitleLabel(issue); getDialogPane().setContent(mainLayout); } // Population of UI elements /** * Populates respective panes with labels that matches current user input * @param state */ private final void populatePanes(LabelPickerState state) { // Population of UI elements populateAssignedLabels(state.getInitialLabels(), state.getRemovedLabels(), state.getAddedLabels(), state.getCurrentSuggestion()); populateFeedbackLabels(state.getAssignedLabels(), state.getMatchedLabels(), state.getCurrentSuggestion()); // Ensures dialog pane resize according to content getDialogPane().getScene().getWindow().sizeToScene(); } private final void populateAssignedLabels(List<TurboLabel> initialLabels, List<TurboLabel> removedLabels, List<TurboLabel> addedLabels, Optional<TurboLabel> suggestion) { assignedLabels.getChildren().clear(); populateInitialLabels(initialLabels, removedLabels, suggestion); populateToBeAddedLabels(addedLabels, suggestion); } private final void populateInitialLabels(List<TurboLabel> initialLabels, List<TurboLabel> removedLabels, Optional<TurboLabel> suggestion) { initialLabels.stream() .forEach(label -> assignedLabels.getChildren() .add(processInitialLabel(label, removedLabels, suggestion))); } private final Node processInitialLabel(TurboLabel initialLabel, List<TurboLabel> removedLabels, Optional<TurboLabel> suggestion) { TurboLabel repoInitialLabel = TurboLabel.getFirstMatchingTurboLabel(allLabels, initialLabel.getFullName()); if (!removedLabels.contains(initialLabel)) { if (suggestion.isPresent() && initialLabel.equals(suggestion.get())) { return getPickerLabelNode( new PickerLabel(repoInitialLabel, true).faded(true).removed(true)); } return getPickerLabelNode(new PickerLabel(repoInitialLabel, true)); } if (suggestion.isPresent() && initialLabel.equals(suggestion.get())) { return getPickerLabelNode(new PickerLabel(repoInitialLabel, true).faded(true)); } return getPickerLabelNode(new PickerLabel(repoInitialLabel, true).removed(true)); } /** * @param label * @return Node from label after registering mouse handler */ private final Node getPickerLabelNode(PickerLabel label) { Node node = label.getNode(); node.setOnMouseClicked(e -> handleLabelClick(label.getFullName())); return node; } private final void populateToBeAddedLabels(List<TurboLabel> addedLabels, Optional<TurboLabel> suggestion) { if (!addedLabels.isEmpty() || hasNewSuggestion(addedLabels, suggestion)) { assignedLabels.getChildren().add(new Label("|")); } populateAddedLabels(addedLabels, suggestion); populateSuggestedLabel(addedLabels, suggestion); } private final void populateAddedLabels(List<TurboLabel> addedLabels, Optional<TurboLabel> suggestion) { addedLabels.stream() .forEach(label -> { assignedLabels.getChildren().add(processAddedLabel(label, suggestion)); }); } private final Node processAddedLabel(TurboLabel addedLabel, Optional<TurboLabel> suggestion) { if (!suggestion.isPresent() || !addedLabel.equals(suggestion.get())) { return getPickerLabelNode( new PickerLabel(TurboLabel.getFirstMatchingTurboLabel(allLabels, addedLabel.getFullName()), true)); } return getPickerLabelNode( new PickerLabel(TurboLabel.getFirstMatchingTurboLabel(allLabels, addedLabel.getFullName()), true) .faded(true).removed(true)); } private final void populateSuggestedLabel(List<TurboLabel> addedLabels, Optional<TurboLabel> suggestion) { if (hasNewSuggestion(addedLabels, suggestion)) { assignedLabels.getChildren().add(processSuggestedLabel(suggestion.get())); } } private final boolean hasNewSuggestion(List<TurboLabel> addedLabels, Optional<TurboLabel> suggestion) { return suggestion.isPresent() && !(TurboLabel.getMatchedLabels(allLabels, issue.getLabels())).contains(suggestion.get()) && !addedLabels.contains(suggestion.get()); } private final Node processSuggestedLabel(TurboLabel suggestedLabel) { return getPickerLabelNode( new PickerLabel(TurboLabel.getFirstMatchingTurboLabel(allLabels, suggestedLabel.getFullName()), true) .faded(true)); } private final void populateFeedbackLabels(List<TurboLabel> assignedLabels, List<TurboLabel> matchedLabels, Optional<TurboLabel> suggestion) { feedbackLabels.getChildren().clear(); populateGroupLabels(assignedLabels, matchedLabels, suggestion); populateGrouplessLabels(assignedLabels, matchedLabels, suggestion); } private final void populateGroupLabels(List<TurboLabel> finalLabels, List<TurboLabel> matchedLabels, Optional<TurboLabel> suggestion) { Map<String, FlowPane> groupContent = getGroupContent(finalLabels, matchedLabels, suggestion); groupContent.entrySet().forEach(entry -> { feedbackLabels.getChildren().addAll( createGroupTitle(entry.getKey()), entry.getValue()); }); } private final Map<String, FlowPane> getGroupContent(List<TurboLabel> finalLabels, List<TurboLabel> matchedLabels, Optional<TurboLabel> suggestion) { Map<String, FlowPane> groupContent = new HashMap<>(); allLabels.stream().sorted() .filter(label -> label.isInGroup()) .forEach(label -> { String group = label.getGroupName(); if (!groupContent.containsKey(group)) { groupContent.put(group, createGroupPane(GROUP_PAD)); } groupContent.get(group).getChildren().add(processMatchedLabel( label, matchedLabels, finalLabels, suggestion)); }); return groupContent; } private final void populateGrouplessLabels(List<TurboLabel> finalLabels, List<TurboLabel> matchedLabels, Optional<TurboLabel> suggestion) { FlowPane groupless = createGroupPane(GROUPLESS_PAD); allLabels.stream() .filter(label -> !label.isInGroup()) .forEach(label -> groupless.getChildren().add(processMatchedLabel( label, matchedLabels, finalLabels, suggestion))); feedbackLabels.getChildren().add(groupless); } private final Node processMatchedLabel(TurboLabel repoLabel, List<TurboLabel> matchedLabels, List<TurboLabel> assignedLabels, Optional<TurboLabel> suggestion) { return getPickerLabelNode( new PickerLabel(TurboLabel.getFirstMatchingTurboLabel(allLabels, repoLabel.getFullName()), false) .faded(!matchedLabels.contains(repoLabel)) .highlighted(suggestion.isPresent() && suggestion.get().equals(repoLabel)) .selected(assignedLabels.contains(repoLabel))); } /** * Positions dialog based on width and height of stage to avoid dialog appearing off-screen on certain computers * if default position is used * @param stage */ private final void positionDialog(Stage stage) { setX(stage.getX() + stage.getWidth() / 2); setY(stage.getY() + stage.getHeight() / 2 - getHeight() / 2); } private void createMainLayout() { FXMLLoader loader = new FXMLLoader(UI.class.getResource("fxml/LabelPickerView.fxml")); loader.setController(this); try { mainLayout = (VBox) loader.load(); } catch (IOException e) { logger.error("Failure to load FXML. " + e.getMessage()); close(); } } private void createButtons() { ButtonType confirmButtonType = new ButtonType("Confirm", ButtonBar.ButtonData.OK_DONE); getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL); // defines what happens when user confirms/presses enter setResultConverter(dialogButton -> { if (dialogButton == confirmButtonType) { // Ensures the last keyword in the query is toggled after confirmation if (!queryField.isDisabled()) queryField.appendText(" "); return TurboLabel.getLabelNames(state.getAssignedLabels()); } return null; }); } private Tooltip createTitleTooltip(TurboIssue issue) { Tooltip titleTooltip = new Tooltip( (issue.isPullRequest() ? "PR #" : "Issue #") + issue.getId() + ": " + issue.getTitle()); titleTooltip.setWrapText(true); titleTooltip.setMaxWidth(500); return titleTooltip; } private void setTitleLabel(TurboIssue issue) { title.setText((issue.isPullRequest() ? "PR #" : "Issue #") + issue.getId() + ": " + issue.getTitle()); } private Label createGroupTitle(String name) { Label groupName = new Label(name); groupName.setPadding(new Insets(0, 5, 5, 0)); groupName.setMaxWidth(ELEMENT_MAX_WIDTH - 10); groupName.setStyle("-fx-font-size: 110%; -fx-font-weight: bold; "); return groupName; } private FlowPane createGroupPane(Insets padding) { FlowPane group = new FlowPane(); group.setHgap(5); group.setVgap(5); group.setPadding(padding); return group; } // Event handling /** * Updates state of the label picker based on the entire query */ private final void handleUserInput(String query) { state = new LabelPickerState( TurboLabel.getMatchedLabels(allLabels, issue.getLabels()), allLabels, query.toLowerCase()); populatePanes(state); } private void handleLabelClick(String labelName) { queryField.setDisable(true); TurboLabel.getMatchedLabels(allLabels, labelName) .stream().findFirst().ifPresent(state::updateAssignedLabels); populatePanes(state); } }
package yanagishima.provider; import yanagishima.config.YanagishimaConfig; import javax.inject.Inject; import javax.inject.Provider; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionProvider implements Provider<Connection> { private final YanagishimaConfig config; @Inject public ConnectionProvider(YanagishimaConfig config) { this.config = config; } @Override public Connection get() { try { return DriverManager.getConnection(config.getConnectionUrl(), config.getConnectionUsername(), config.getConnectionPassword()); } catch (SQLException e) { throw new RuntimeException(e); } } }
package org.umlg.sqlg; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.umlg.sqlg.test.*; import org.umlg.sqlg.test.aggregate.TestAggregate; import org.umlg.sqlg.test.aggregate.TestGroupCount; import org.umlg.sqlg.test.aggregate.TestMax; import org.umlg.sqlg.test.batch.*; import org.umlg.sqlg.test.branchstep.TestSqlgBranchStep; import org.umlg.sqlg.test.complex.TestComplex; import org.umlg.sqlg.test.complex.TestGithub; import org.umlg.sqlg.test.datasource.TestCustomDataSource; import org.umlg.sqlg.test.datasource.TestDataSource; import org.umlg.sqlg.test.datasource.TestJNDIInitialization; import org.umlg.sqlg.test.edgehas.TestEdgeHas; import org.umlg.sqlg.test.edges.*; import org.umlg.sqlg.test.event.TestTinkerPopEvent; import org.umlg.sqlg.test.filter.and.TestAndStep; import org.umlg.sqlg.test.filter.and.barrier.TestAndStepBarrier; import org.umlg.sqlg.test.filter.connectivestep.TestAndandOrStep; import org.umlg.sqlg.test.filter.not.barrier.TestNotStepBarrier; import org.umlg.sqlg.test.filter.or.TestOrStep; import org.umlg.sqlg.test.filter.or.TestOrStepAfterVertexStepBarrier; import org.umlg.sqlg.test.filter.or.barrier.TestOrStepBarrier; import org.umlg.sqlg.test.graph.MidTraversalGraphTest; import org.umlg.sqlg.test.graph.TestEmptyGraph; import org.umlg.sqlg.test.graph.TestGraphStepWithIds; import org.umlg.sqlg.test.gremlincompile.*; import org.umlg.sqlg.test.index.TestIndex; import org.umlg.sqlg.test.index.TestIndexOnPartition; import org.umlg.sqlg.test.index.TestIndexTopologyTraversal; import org.umlg.sqlg.test.io.TestIo; import org.umlg.sqlg.test.io.TestIoEdge; import org.umlg.sqlg.test.json.TestJson; import org.umlg.sqlg.test.json.TestJsonUpdate; import org.umlg.sqlg.test.labels.TestHasLabelAndId; import org.umlg.sqlg.test.labels.TestLabelLength; import org.umlg.sqlg.test.labels.TestLabelsSchema; import org.umlg.sqlg.test.labels.TestMultipleLabels; import org.umlg.sqlg.test.localdate.TestLocalDate; import org.umlg.sqlg.test.localdate.TestLocalDateArray; import org.umlg.sqlg.test.localvertexstep.*; import org.umlg.sqlg.test.match.TestMatch; import org.umlg.sqlg.test.memory.TestMemoryUsage; import org.umlg.sqlg.test.mod.*; import org.umlg.sqlg.test.process.dropstep.*; import org.umlg.sqlg.test.properties.TestEscapedValues; import org.umlg.sqlg.test.properties.TestPropertyValues; import org.umlg.sqlg.test.remove.TestRemoveEdge; import org.umlg.sqlg.test.repeatstep.TestUnoptimizedRepeatStep; import org.umlg.sqlg.test.roles.TestReadOnlyRole; import org.umlg.sqlg.test.rollback.TestRollback; import org.umlg.sqlg.test.sack.TestSack; import org.umlg.sqlg.test.sample.TestSample; import org.umlg.sqlg.test.schema.*; import org.umlg.sqlg.test.topology.*; import org.umlg.sqlg.test.travers.TestTraversals; import org.umlg.sqlg.test.tree.TestColumnNamePropertyNameMapScope; import org.umlg.sqlg.test.usersuppliedpk.topology.TestMultipleIDQuery; import org.umlg.sqlg.test.usersuppliedpk.topology.TestSimpleJoinGremlin; import org.umlg.sqlg.test.usersuppliedpk.topology.TestSimpleVertexEdgeGremlin; import org.umlg.sqlg.test.usersuppliedpk.topology.TestUserSuppliedPKTopology; import org.umlg.sqlg.test.vertex.*; import org.umlg.sqlg.test.vertexout.TestVertexOutWithHas; import org.umlg.sqlg.test.where.TestTraversalFilterStepBarrier; @RunWith(Suite.class) @Suite.SuiteClasses({ TestAddVertexViaMap.class, TestAllEdges.class, TestAllVertices.class, TestArrayProperties.class, TestCountVerticesAndEdges.class, TestDeletedVertex.class, TestEdgeCreation.class, TestEdgeToDifferentLabeledVertexes.class, TestGetById.class, TestHas.class, TestHasLabelAndId.class, TestLoadArrayProperties.class, TestLoadElementProperties.class, TestLoadSchema.class, TestPool.class, TestRemoveElement.class, TestSetProperty.class, TestVertexCreation.class, TestVertexEdgeSameName.class, TestVertexNavToEdges.class, // are these tests gone? //TestByteArray.class, //TestQuery.class, TestSchema.class, TestIndex.class, TestVertexOutWithHas.class, TestEdgeHas.class, TestBatch.class, TestBatchNormalUpdate.class, TestMultiThreadedBatch.class, TestMultiThread.class, TestMultipleThreadMultipleJvm.class, TestRemoveEdge.class, TestEdgeSchemaCreation.class, TestRollback.class, TestNewVertex.class, TestEdgeCache.class, TestVertexCache.class, TestTinkerpopBug.class, TestLoadSchemaViaNotify.class, TestCreateEdgeBetweenVertices.class, TestRemovedVertex.class, TestCaptureSchemaTableEdges.class, TestGremlinCompileWithHas.class, TestGremlinCompileE.class, TestEmptyGraph.class, TestOutE.class, TestForeignKeysAreOptional.class, TestGremlinCompileWithAs.class, TestGremlinCompileWithInOutV.class, TestGremlinCompileV.class, TestGremlinCompileGraphStep.class, TestGremlinCompileGraphV.class, TestGremlinCompileWhere.class, TestGremlinCompileTextPredicate.class, TestGremlinCompileFullTextPredicate.class, TestGremlinCompileChoose.class, TestGremlinCompileVertexStep.class, TestGremlinCompileWhereLocalDate.class, TestGremlinCompileArrayContains.class, TestGremlinCompileArrayOverlaps.class, TestColumnNameTranslation.class, TestGraphStepOrderBy.class, TestVertexStepOrderBy.class, TestPathStep.class, TestLocalDate.class, TestLocalDateArray.class, TestBatchStreamVertex.class, TestBatchStreamEdge.class, TestJson.class, TestSchemaManagerGetTablesFor.class, TestBatchServerSideEdgeCreation.class, TestBatchedStreaming.class, TestBulkWithin.class, TestBulkWithout.class, TestRemoveProperty.class, TestSchemaManagerGetTablesFor.class, TestAggregate.class, TestTreeStep.class, TestRepeatStepGraphOut.class, TestRepeatStepGraphIn.class, TestRepeatStepVertexOut.class, TestRepeatStepGraphBoth.class, TestRepeatStepWithLabels.class, TestGraphStepWithIds.class, TestOtherVertex.class, TestGremlinMod.class, TestTopologyUpgrade.class, TestTopologyMultipleGraphs.class, TestTraversals.class, TestGremlinOptional.class, TestAlias.class, TestGithub.class, TestLocalVertexStepOptional.class, TestLocalVertexStepRepeatStep.class, TestLocalEdgeVertexStep.class, TestLocalEdgeOtherVertexStep.class, TestBatchNormalDateTime.class, TestBatchEdgeDateTime.class, TestBatchJson.class, TestMemoryUsage.class, TestBatchStreamTemporaryVertex.class, TestBatchNormalPrimitiveArrays.class, TestBatchNormalPrimitive.class, TestBatchNormalUpdatePrimitiveArrays.class, TestJsonUpdate.class, TestBatchNormalUpdateDateTime.class, TestOptionalWithOrder.class, TestMultipleLabels.class, TestColumnNamePropertyNameMapScope.class, TestJNDIInitialization.class, TestSchemaTableTreeAndHasContainer.class, TestEscapedValues.class, TestRepeatStepOnEdges.class, TestLoadingAdjacent.class, TestLabelsSchema.class, MidTraversalGraphTest.class, //TODO fails, issue // TestEdgeFromDifferentSchema.class TestBatchModeMultipleGraphs.class, TestDetachedEdge.class, TestSchemaEagerCreation.class, TestIndexTopologyTraversal.class, TestNotifyJson.class, TestGlobalUniqueIndex.class, TestBatchGlobalUniqueIndexes.class, TestVertexEdges.class, TestSqlgSchema.class, TestValidateTopology.class, TestBatchNormalUpdateDateTimeArrays.class, TestTopologyChangeListener.class, TestRangeLimit.class, TestReplacedStepEmitComparator.class, TestLocalStepCompile.class, TestLocalVertexStepLimit.class, TestLocalVertexStepOptionalWithOrder.class, TestOptionalWithRange.class, TestRepeatWithOrderAndRange.class, TestMatch.class, TestSqlgBranchStep.class, TestLocalVertexStepWithOrder.class, TestMax.class, TestGroupCount.class, TestSack.class, TestSample.class, TestTopologyChangeListener.class, TestTopologyDelete.class, TestTopologyDeleteSpecific.class, TestTinkerPopEvent.class, TestIo.class, TestComplex.class, TestTopologyDeleteSpecific.class, TestDeadLock.class, TestLabelLength.class, TestAddTemporaryVertex.class, TestIoEdge.class, TestBatchTemporaryVertex.class, TestUnoptimizedRepeatStep.class, TestTraversalFilterStepBarrier.class, TestOrStepBarrier.class, TestAndStepBarrier.class, TestNotStepBarrier.class, TestOrStep.class, TestAndStep.class, TestAndandOrStep.class, TestOrStepAfterVertexStepBarrier.class, TestDropStep.class, TestDropStepBarrier.class, TestDropStepTruncate.class, TestTopologyGraph.class, TestUnoptimizedRepeatStep.class, TestPropertyReference.class, TestPartitioning.class, TestPartitionMultipleGraphs.class, TestSubSubPartition.class, TestIndexOnPartition.class, TestUserSuppliedPKTopology.class, TestSimpleJoinGremlin.class, TestSimpleVertexEdgeGremlin.class, TestMultipleIDQuery.class, // TestSharding.class, // TestShardingGremlin.class, TestRecordId.class, TestPropertyValues.class, TestReadOnlyRole.class, TestVarChar.class, TestTopologySchemaDeleteMultipleGraphs.class, TestTraversalAddV.class, TestDataSource.class, TestCustomDataSource.class, TestPartitionedDrop.class, TestDropStepPartition.class, TestBatchUpdatePartitioning.class }) public class AllTest { }
package org.pentaho.di.ui.core.gui; import java.util.Collection; import java.util.Hashtable; import java.util.Map; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleStepLoaderException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.job.JobEntryLoader; import org.pentaho.di.job.JobEntryType; import org.pentaho.di.job.JobPlugin; import org.pentaho.di.laf.BasePropertyHandler; import org.pentaho.di.trans.StepLoader; import org.pentaho.di.trans.StepPlugin; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.util.ImageUtil; /** * This is a singleton class that contains allocated Fonts, Colors, etc. All * colors etc. are allocated once and released once at the end of the program. * * @author Matt * @since 27/10/2005 * */ public class GUIResource { private static LogWriter log = LogWriter.getInstance(); private static GUIResource guiResource; private Display display; // 33 resources /* * * Colors * * */ private ManagedColor colorBackground; private ManagedColor colorGraph; private ManagedColor colorTab; private ManagedColor colorRed; private ManagedColor colorGreen; private ManagedColor colorBlue; private ManagedColor colorOrange; private ManagedColor colorYellow; private ManagedColor colorMagenta; private ManagedColor colorBlack; private ManagedColor colorGray; private ManagedColor colorDarkGray; private ManagedColor colorLightGray; private ManagedColor colorDemoGray; private ManagedColor colorWhite; private ManagedColor colorDirectory; private ManagedColor colorPentaho; private ManagedColor colorLightPentaho; /* * * Fonts * * */ private ManagedFont fontGraph; private ManagedFont fontNote; private ManagedFont fontFixed; private ManagedFont fontLarge; private ManagedFont fontTiny; /* * * Images * * */ private Map<String, Image> imagesSteps; private Map<String, Image> imagesStepsSmall; private Map<String, Image> imagesJobentries; private Map<String, Image> imagesJobentriesSmall; private Image imageHop; private Image imageConnection; private Image imageKettleLogo; private Image imageLogoSmall; private Image imageBanner; private Image imageBol; private Image imageArrow; private Image imageCredits; private Image imageStart; private Image imageDummy; private Image imageStartSmall; private Image imageDummySmall; private Image imageSpoon; private Image imageJob; private Image imagePentaho; private Image imageVariable; private Image imageTransGraph; private Image imageJobGraph; private Image imageEditOptionButton; private Image imageResetOptionButton; private ManagedFont fontBold; /** * GUIResource also contains the clipboard as it has to be allocated only * once! I don't want to put it in a separate singleton just for this one * member. */ private static Clipboard clipboard; private GUIResource(Display display) { this.display = display; getResources(false); display.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event event) { dispose(false); } }); clipboard = null; } public static final GUIResource getInstance() { if (guiResource != null) return guiResource; guiResource = new GUIResource(PropsUI.getDisplay()); return guiResource; } public void reload() { dispose(true); getResources(true); } private void getResources(boolean reload) { PropsUI props = PropsUI.getInstance(); colorBackground = new ManagedColor(display, props.getBackgroundRGB()); colorGraph = new ManagedColor(display, props.getGraphColorRGB()); colorTab = new ManagedColor(display, props.getTabColorRGB()); colorRed = new ManagedColor(display, 255, 0, 0); colorGreen = new ManagedColor(display, 0, 255, 0); colorBlue = new ManagedColor(display, 0, 0, 255); colorYellow = new ManagedColor(display, 255, 255, 0); colorMagenta = new ManagedColor(display, 255, 0, 255); colorOrange = new ManagedColor(display, 255, 165, 0); colorWhite = new ManagedColor(display, 255, 255, 255); colorDemoGray = new ManagedColor(display, 240, 240, 240); colorLightGray = new ManagedColor(display, 225, 225, 225); colorGray = new ManagedColor(display, 150, 150, 150); colorDarkGray = new ManagedColor(display, 100, 100, 100); colorBlack = new ManagedColor(display, 0, 0, 0); colorDirectory = new ManagedColor(display, 0, 0, 255); // colorPentaho = new ManagedColor(display, 239, 128, 51 ); // Orange colorPentaho = new ManagedColor(display, 188, 198, 82); colorLightPentaho = new ManagedColor(display, 238, 248, 152); // Load all images from files... if (!reload) { loadFonts(); loadCommonImages(); loadStepImages(); loadJobEntryImages(); } } private void dispose(boolean reload) { // Colors colorBackground.dispose(); colorGraph.dispose(); colorTab.dispose(); colorRed.dispose(); colorGreen.dispose(); colorBlue.dispose(); colorGray.dispose(); colorYellow.dispose(); colorMagenta.dispose(); colorOrange.dispose(); colorWhite.dispose(); colorDemoGray.dispose(); colorLightGray.dispose(); colorDarkGray.dispose(); colorBlack.dispose(); colorDirectory.dispose(); colorPentaho.dispose(); colorLightPentaho.dispose(); if (!reload) // display shutdown, clean up our mess { // Fonts fontGraph.dispose(); fontNote.dispose(); fontFixed.dispose(); fontLarge.dispose(); fontTiny.dispose(); fontBold.dispose(); // Common images imageHop.dispose(); imageConnection.dispose(); imageLogoSmall.dispose(); imageKettleLogo.dispose(); imageBanner.dispose(); imageBol.dispose(); imageArrow.dispose(); imageCredits.dispose(); imageStart.dispose(); imageDummy.dispose(); imageStartSmall.dispose(); imageDummySmall.dispose(); imageSpoon.dispose(); imageJob.dispose(); imagePentaho.dispose(); imageVariable.dispose(); imageTransGraph.dispose(); imageJobGraph.dispose(); disposeImage(imageEditOptionButton); disposeImage(imageResetOptionButton); // big images disposeImages(imagesSteps.values()); // Small images disposeImages(imagesStepsSmall.values()); } } private void disposeImages(Collection<Image> c) { for (Image image : c) { disposeImage(image); } } private void disposeImage(Image image) { if (image != null && !image.isDisposed()) image.dispose(); } /** * Load all step images from files. * */ private void loadStepImages() { imagesSteps = new Hashtable<String, Image>(); imagesStepsSmall = new Hashtable<String, Image>(); // // STEP IMAGES TO LOAD StepLoader steploader = StepLoader.getInstance(); StepPlugin steps[] = steploader.getStepsWithType(StepPlugin.TYPE_ALL); for (int i = 0; i < steps.length; i++) { Image image = null; Image small_image = null; if (steps[i].isNative()) { String filename = steps[i].getIconFilename(); try { //InputStream stream = getClass().getResourceAsStream(filename); image = ImageUtil.getImage(display, filename); // new Image(display, stream); } catch (Exception e) { log.logError("Kettle", "Unable to find required step image file or image format not supported (e.g. interlaced) [" + filename + " : " + e.toString()); image = new Image(display, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); GC gc = new GC(image); gc.drawRectangle(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(ConstUI.ICON_SIZE, 0, 0, ConstUI.ICON_SIZE); gc.dispose(); } } else { String filename = steps[i].getIconFilename(); try { image = new Image(display, filename); } catch (Exception e) { log.logError("Kettle", "Unable to find required step image file [" + filename + " : " + e.toString()); image = new Image(display, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); GC gc = new GC(image); gc.drawRectangle(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(ConstUI.ICON_SIZE, 0, 0, ConstUI.ICON_SIZE); gc.dispose(); } } // Calculate the smaller version of the image @ 16x16... // Perhaps we should make this configurable? if (image != null) { int xsize = image.getBounds().width; int ysize = image.getBounds().height; small_image = new Image(display, 16, 16); GC gc = new GC(small_image); gc.drawImage(image, 0, 0, xsize, ysize, 0, 0, 16, 16); gc.dispose(); } imagesSteps.put(steps[i].getID()[0], image); imagesStepsSmall.put(steps[i].getID()[0], small_image); } } private void loadFonts() { PropsUI props = PropsUI.getInstance(); fontGraph = new ManagedFont(display, props.getGraphFont()); fontNote = new ManagedFont(display, props.getNoteFont()); fontFixed = new ManagedFont(display, props.getFixedFont()); // Create a large version of the graph font FontData largeFontData = new FontData(props.getGraphFont().getName(), props.getGraphFont().getHeight() * 3, props.getGraphFont().getStyle()); fontLarge = new ManagedFont(display, largeFontData); // Create a tiny version of the graph font FontData tinyFontData = new FontData(props.getGraphFont().getName(), props.getGraphFont().getHeight() -2, props.getGraphFont().getStyle()); fontTiny = new ManagedFont(display, tinyFontData); // Create a bold version of the default font to display shared objects // in the trees int extraHeigth=0; if (Const.isOSX()) extraHeigth=3; FontData boldFontData = new FontData( props.getDefaultFont().getName(), props.getDefaultFont().getHeight()+extraHeigth, props.getDefaultFont().getStyle() | SWT.BOLD ); fontBold = new ManagedFont(display, boldFontData); } private void loadCommonImages() { imageHop = ImageUtil.getImageAsResource(display,BasePropertyHandler.getProperty("HOP_image")); // "ui/images/HOP.png" imageConnection = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("CNC_image")); // , "ui/images/CNC.png" imageKettleLogo = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Logo_lrg_image")); // , "ui/images/logo_kettle_lrg.png" imageBanner = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Banner_bg_image")); // , "ui/images/bg_banner.png" imageBol = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("BOL_image")); // , "ui/images/BOL.png" imageCredits = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Credits_image")); // , "ui/images/credits.png" imageStart = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("STR_image")); // , "ui/images/STR.png" imageDummy = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("DUM_image")); // , "ui/images/DUM.png" imageSpoon = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("spoon_image")); // , "ui/images/spoon32.png" imageJob = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Chef_image")); // , "ui/images/chef.png" imagePentaho = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("CorpLogo_image")); // , "ui/images/PentahoLogo.png" imageVariable = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Variable_image")); // , "ui/images/variable.png" imageEditOptionButton = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("EditOption_image")); // , "ui/images/edit_option.png" imageResetOptionButton = ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("ResetOption_image")); // , "ui/images/reset_option.png" imageStartSmall = new Image(display, 16, 16); GC gc = new GC(imageStartSmall); gc.drawImage(imageStart, 0, 0, 32, 32, 0, 0, 16, 16); gc.dispose(); imageDummySmall = new Image(display, 16, 16); gc = new GC(imageDummySmall); gc.drawImage(imageDummy, 0, 0, 32, 32, 0, 0, 16, 16); gc.dispose(); // Makes transparent images "on the fly" imageTransGraph = ImageUtil.makeImageTransparent(display, ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("SpoonIcon_image")), new RGB(255, 255, 255)); // , "ui/images/spoongraph.png" imageJobGraph = ImageUtil.makeImageTransparent(display, ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("ChefIcon_image")), // , "ui/images/chefgraph.png" new RGB(255, 255, 255)); imageLogoSmall = ImageUtil.makeImageTransparent(display, ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Logo_sml_image")), new RGB(255, 255, 255)); // , "ui/images/kettle_logo_small.png" imageArrow = ImageUtil.makeImageTransparent(display, ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("ArrowIcon_image")), // , "ui/images/arrow.png" new RGB(255, 255, 255)); imageBanner = ImageUtil.makeImageTransparent(display, ImageUtil.getImageAsResource(display, BasePropertyHandler.getProperty("Banner_bg_image")), // , "ui/images/bg_banner.png" new RGB(255, 255, 255)); } /** * Load all step images from files. * */ private void loadJobEntryImages() { imagesJobentries = new Hashtable<String, Image>(); imagesJobentriesSmall = new Hashtable<String, Image>(); // // JOB ENTRY IMAGES TO LOAD JobEntryLoader jobEntryLoader = JobEntryLoader.getInstance(); if (!jobEntryLoader.isInitialized()) return; // Running in Spoon I guess... JobPlugin plugins[] = jobEntryLoader.getJobEntriesWithType(JobPlugin.TYPE_ALL); for (int i = 0; i < plugins.length; i++) { try { if (jobEntryLoader.getJobEntryClass(plugins[i]).getJobEntryType() == JobEntryType.SPECIAL) continue; } catch (KettleStepLoaderException e) { log.logError("Kettle", "Unable to create job entry from plugin [" + plugins[i] + "]", e); continue; } Image image = null; Image small_image = null; if (plugins[i].isNative()) { String filename = plugins[i].getIconFilename(); try { image = ImageUtil.getImage(display, filename); } catch (Exception e) { log.logError("Kettle", "Unable to find required job entry image file [" + filename + "] : " + e.toString()); image = new Image(display, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); GC gc = new GC(image); gc.drawRectangle(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(ConstUI.ICON_SIZE, 0, 0, ConstUI.ICON_SIZE); gc.dispose(); } } else { String filename = plugins[i].getIconFilename(); try { image = new Image(display, filename); } catch (Exception e) { log.logError("Kettle", "Unable to find required job entry image file [" + filename + "] : " + e.toString()); image = new Image(display, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); GC gc = new GC(image); gc.drawRectangle(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(0, 0, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE); gc.drawLine(ConstUI.ICON_SIZE, 0, 0, ConstUI.ICON_SIZE); gc.dispose(); } } // Calculate the smaller version of the image @ 16x16... // Perhaps we should make this configurable? if (image != null) { int xsize = image.getBounds().width; int ysize = image.getBounds().height; small_image = new Image(display, 16, 16); GC gc = new GC(small_image); gc.drawImage(image, 0, 0, xsize, ysize, 0, 0, 16, 16); gc.dispose(); } imagesJobentries.put(plugins[i].getID(), image); imagesJobentriesSmall.put(plugins[i].getID(), small_image); } } /** * @return Returns the colorBackground. */ public Color getColorBackground() { return colorBackground.getColor(); } /** * @return Returns the colorBlack. */ public Color getColorBlack() { return colorBlack.getColor(); } /** * @return Returns the colorBlue. */ public Color getColorBlue() { return colorBlue.getColor(); } /** * @return Returns the colorDarkGray. */ public Color getColorDarkGray() { return colorDarkGray.getColor(); } /** * @return Returns the colorDemoGray. */ public Color getColorDemoGray() { return colorDemoGray.getColor(); } /** * @return Returns the colorDirectory. */ public Color getColorDirectory() { return colorDirectory.getColor(); } /** * @return Returns the colorGraph. */ public Color getColorGraph() { return colorGraph.getColor(); } /** * @return Returns the colorGray. */ public Color getColorGray() { return colorGray.getColor(); } /** * @return Returns the colorGreen. */ public Color getColorGreen() { return colorGreen.getColor(); } /** * @return Returns the colorLightGray. */ public Color getColorLightGray() { return colorLightGray.getColor(); } /** * @return Returns the colorMagenta. */ public Color getColorMagenta() { return colorMagenta.getColor(); } /** * @return Returns the colorOrange. */ public Color getColorOrange() { return colorOrange.getColor(); } /** * @return Returns the colorRed. */ public Color getColorRed() { return colorRed.getColor(); } /** * @return Returns the colorTab. */ public Color getColorTab() { return colorTab.getColor(); } /** * @return Returns the colorWhite. */ public Color getColorWhite() { return colorWhite.getColor(); } /** * @return Returns the colorYellow. */ public Color getColorYellow() { return colorYellow.getColor(); } /** * @return Returns the display. */ public Display getDisplay() { return display; } /** * @return Returns the fontFixed. */ public Font getFontFixed() { return fontFixed.getFont(); } /** * @return Returns the fontGraph. */ public Font getFontGraph() { return fontGraph.getFont(); } /** * @return Returns the fontNote. */ public Font getFontNote() { return fontNote.getFont(); } /** * @return Returns the imageBol. */ public Image getImageBol() { return imageBol; } /** * @return Returns the imageConnection. */ public Image getImageConnection() { return imageConnection; } /** * @return Returns the imageCredits. */ public Image getImageCredits() { return imageCredits; } /** * @return Returns the imageDummy. */ public Image getImageDummy() { return imageDummy; } /** * @return Returns the imageHop. */ public Image getImageHop() { return imageHop; } /** * @return Returns the imageSpoon. */ public Image getImageSpoon() { return imageSpoon; } /** * @return Returns the image Pentaho. */ public Image getImagePentaho() { return imagePentaho; } /** * @return Returns the imagesSteps. */ public Map<String, Image> getImagesSteps() { return imagesSteps; } /** * @return Returns the imagesStepsSmall. */ public Map<String, Image> getImagesStepsSmall() { return imagesStepsSmall; } /** * @return Returns the imageStart. */ public Image getImageStart() { return imageStart; } /** * @return Returns the imagesJobentries. */ public Map<String, Image> getImagesJobentries() { return imagesJobentries; } /** * @param imagesJobentries * The imagesJobentries to set. */ public void setImagesJobentries(Hashtable<String, Image> imagesJobentries) { this.imagesJobentries = imagesJobentries; } /** * @return Returns the imagesJobentriesSmall. */ public Map<String, Image> getImagesJobentriesSmall() { return imagesJobentriesSmall; } /** * @param imagesJobentriesSmall * The imagesJobentriesSmall to set. */ public void setImagesJobentriesSmall(Hashtable<String, Image> imagesJobentriesSmall) { this.imagesJobentriesSmall = imagesJobentriesSmall; } /** * @return Returns the imageChef. */ public Image getImageChef() { return imageJob; } /** * @param imageChef * The imageChef to set. */ public void setImageChef(Image imageChef) { this.imageJob = imageChef; } /** * @return the fontLarge */ public Font getFontLarge() { return fontLarge.getFont(); } /** * @return the tiny font */ public Font getFontTiny() { return fontTiny.getFont(); } /** * @return Returns the clipboard. */ public Clipboard getNewClipboard() { if (clipboard != null) { clipboard.dispose(); clipboard = null; } clipboard = new Clipboard(display); return clipboard; } public void toClipboard(String cliptext) { if (cliptext == null) return; getNewClipboard(); TextTransfer tran = TextTransfer.getInstance(); clipboard.setContents(new String[] { cliptext }, new Transfer[] { tran }); } public String fromClipboard() { getNewClipboard(); TextTransfer tran = TextTransfer.getInstance(); return (String) clipboard.getContents(tran); } public Font getFontBold() { return fontBold.getFont(); } /** * @return the imageVariable */ public Image getImageVariable() { return imageVariable; } public Image getImageTransGraph() { return imageTransGraph; } public Image getImageJobGraph() { return imageJobGraph; } public Image getEditOptionButton() { return imageEditOptionButton; } public Image getResetOptionButton() { return imageResetOptionButton; } /** * @return the imageArrow */ public Image getImageArrow() { return imageArrow; } /** * @param imageArrow * the imageArrow to set */ public void setImageArrow(Image imageArrow) { this.imageArrow = imageArrow; } /** * @return the imageDummySmall */ public Image getImageDummySmall() { return imageDummySmall; } /** * @param imageDummySmall * the imageDummySmall to set */ public void setImageDummySmall(Image imageDummySmall) { this.imageDummySmall = imageDummySmall; } /** * @return the imageStartSmall */ public Image getImageStartSmall() { return imageStartSmall; } /** * @param imageStartSmall * the imageStartSmall to set */ public void setImageStartSmall(Image imageStartSmall) { this.imageStartSmall = imageStartSmall; } /** * @return the imageBanner */ public Image getImageBanner() { return imageBanner; } /** * @param imageBanner * the imageBanner to set */ public void setImageBanner(Image imageBanner) { this.imageBanner = imageBanner; } /** * @return the imageKettleLogo */ public Image getImageKettleLogo() { return imageKettleLogo; } /** * @param imageKettleLogo * the imageKettleLogo to set */ public void setImageKettleLogo(Image imageKettleLogo) { this.imageKettleLogo = imageKettleLogo; } /** * @return the colorPentaho */ public Color getColorPentaho() { return colorPentaho.getColor(); } /** * @return the imageLogoSmall */ public Image getImageLogoSmall() { return imageLogoSmall; } /** * @param imageLogoSmall * the imageLogoSmall to set */ public void setImageLogoSmall(Image imageLogoSmall) { this.imageLogoSmall = imageLogoSmall; } /** * @return the colorLightPentaho */ public Color getColorLightPentaho() { return colorLightPentaho.getColor(); } public void drawPentahoGradient(Display display, GC gc, Rectangle rect, boolean vertical) { if (!vertical) { gc.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.setBackground(GUIResource.getInstance().getColorPentaho()); gc.fillGradientRectangle(rect.x, rect.y, 2 * rect.width / 3, rect.height, vertical); gc.setForeground(GUIResource.getInstance().getColorPentaho()); gc.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillGradientRectangle(rect.x + 2 * rect.width / 3, rect.y, rect.width / 3 + 1, rect.height, vertical); } else { gc.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.setBackground(GUIResource.getInstance().getColorPentaho()); gc.fillGradientRectangle(rect.x, rect.y, rect.width, 2 * rect.height / 3, vertical); gc.setForeground(GUIResource.getInstance().getColorPentaho()); gc.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillGradientRectangle(rect.x, rect.y + 2 * rect.height / 3, rect.width, rect.height / 3 + 1, vertical); } } /** * Generic popup with a toggle option * * @param dialogTitle * @param image * @param message * @param dialogImageType * @param buttonLabels * @param defaultIndex * @param toggleMessage * @param toggleState * @return */ public Object[] messageDialogWithToggle(Shell shell, String dialogTitle, Image image, String message, int dialogImageType, String buttonLabels[], int defaultIndex, String toggleMessage, boolean toggleState) { int imageType = 0; switch (dialogImageType) { case Const.WARNING: imageType = MessageDialog.WARNING; break; } MessageDialogWithToggle md = new MessageDialogWithToggle(shell, dialogTitle, image, message, imageType, buttonLabels, defaultIndex, toggleMessage, toggleState); int idx = md.open(); return new Object[] { Integer.valueOf(idx), Boolean.valueOf(md.getToggleState()) }; } public static Point calculateControlPosition(Control control) { // Calculate the exact location... Rectangle r = control.getBounds(); Point p = control.getParent().toDisplay(r.x, r.y); return p; /* Point location = control.getLocation(); Composite parent = control.getParent(); while (parent!=null) { Composite newParent = parent.getParent(); if (newParent!=null) { location.x+=parent.getLocation().x; location.y+=parent.getLocation().y; } else { if (parent instanceof Shell) { // Top level shell. Shell shell = (Shell)parent; Rectangle bounds = shell.getBounds(); Rectangle clientArea = shell.getClientArea(); location.x += bounds.width-clientArea.width; location.y += bounds.height-clientArea.height; } } parent = newParent; } return location; */ } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; import me.dreamteam.tardis.EnemyEntity; import me.dreamteam.tardis.Background; import me.dreamteam.tardis.Utils; import me.dreamteam.tardis.UtilsHTML; /** Main Class */ public class Game extends Canvas { private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; private boolean gameStart = false; long lastLoopTime; private Entity Background; private Entity Background2; private Entity ship; private int shipS = 0; private ArrayList entities = new ArrayList(); private ArrayList enemies = new ArrayList(); private ArrayList backgroundImages = new ArrayList(); private ArrayList removeList = new ArrayList(); private double moveSpeed = 180; private boolean leftPressed = false; private boolean rightPressed = false; private boolean logicRequiredThisLoop = false; private boolean advanceLevel = false; private int level = 1; long lastFrame; long finalTime = 0; private String timeDisplay = ""; private String livesDisplay = ""; public int gameTime = 0; public int gameLives = 3; int timeMil; long lastTime; int SpriteLoc; int SpriteLoc2; int SpriteLoc3; int tWait = 0; int CurSprite = 1; double curY = 0; int debugHits = 0; ImageIcon blankIcon = new ImageIcon(); Random rSpriteLoc = new Random(); public Game() { JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version); JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); setBounds(0,0,500,650); panel.add(this); setIgnoreRepaint(true); container.setResizable(false); container.pack(); // Window setup Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); container.setBackground(Color.black); container.setVisible(true); //What to do when user choose to close container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Utils.quitGame(); } }); ImageIcon icon = new ImageIcon(Utils.iconURL); container.setIconImage(icon.getImage()); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); titleScreen(); } public void updateLogic() { logicRequiredThisLoop = true; } /** * Create our ship */ private void initEntities() { if (shipS == 0) { ship = new ShipEntity(this,"sprites/ship.png",220,568); entities.add(ship); } if (shipS == 1) { ship = new ShipEntity(this,"sprites/ship2.png",220,568); entities.add(ship); } if (shipS == 2) { ship = new ShipEntity(this,"sprites/ship3.png",220,568); entities.add(ship); } } private void updateEnt(){ moveSpeed = 180+(tWait*0.7); SpriteLoc = rSpriteLoc.nextInt(200); SpriteLoc2 = 200+rSpriteLoc.nextInt(250); if(SpriteLoc2 < SpriteLoc+56){ if(SpriteLoc2 > SpriteLoc-56){ SpriteLoc2 = SpriteLoc-56; if (SpriteLoc2 > 450) SpriteLoc2 = SpriteLoc-56; } } if(tWait != gameTime){ int FinalLoc; if(gameTime >= tWait+2 && advanceLevel == false){ tWait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if (advanceLevel == true){ if(gameTime>= tWait && level ==2){ tWait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } }else if(gameTime>= tWait && level >2){ tWait = gameTime; for(int i = 0; i<2; i++){ if(i==0){ FinalLoc = SpriteLoc; }else{ FinalLoc = SpriteLoc2; } Entity Enemies = new EnemyEntity(this,"sprites/enemies/0"+CurSprite+".png",FinalLoc,-50, (tWait+(100*0.45)-30)); entities.add(Enemies); CurSprite += 1; if (CurSprite>5) CurSprite=1; } } } } } private void startGame() { entities.clear(); Background = new ShipEntity(this,"sprites/background.png", 0, 0); backgroundImages.add(Background); Background2 = new ShipEntity(this,"sprites/background.png", 0, 650); backgroundImages.add(Background2); initEntities(); // reset key presses leftPressed = false; rightPressed = false; //reset time timeMil = 0; //reset lives gameLives = 3; level = 1; gameStart = true; tWait = 0; gameTime = 0; finalTime = 0; lastLoopTime = System.currentTimeMillis(); debugHits = 0; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); System.out.println("============================================="); System.out.println("Beginning session @" + dateFormat.format(date)); System.out.println("============================================="); } public void characterSelect() { ImageIcon ship1 = new ImageIcon(Utils.ship1URL); ImageIcon ship2 = new ImageIcon(Utils.ship2URL); ImageIcon ship3 = new ImageIcon(Utils.ship3URL); Utils.systemLF(); Object[] coptions = {UtilsHTML.bpcsStart + ship1 + UtilsHTML.bpcsMiddle + Utils.ship1Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship2 + UtilsHTML.bpcsMiddle + Utils.ship2Name + UtilsHTML.bpcsEnd, UtilsHTML.bpcsStart + ship3 + UtilsHTML.bpcsMiddle + Utils.ship3Name + UtilsHTML.bpcsEnd}; int characterS = JOptionPane.showOptionDialog(null, UtilsHTML.csDialog, Utils.csDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, blankIcon, coptions, coptions[0]); if (characterS != 2 && characterS != 1 && characterS != 0) { titleScreen(); } if (characterS == 2) { shipS = 2; startGame(); } if (characterS == 1) { shipS = 1; startGame(); } if (characterS == 0) { shipS = 0; startGame(); } } public void titleScreen() { ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); Object[] options = {Utils.bPlay, Utils.bQuit}; int startG = JOptionPane.showOptionDialog(null, Utils.txtTS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (startG != 0 && startG != 1) { Utils.quitGame(); } if (startG == 1) { System.exit(0); } if (startG == 0) { characterSelect(); } } public void gameOver() { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("GAME OVER DISPLAYED AFTER " + gameTime + " SECONDS"); System.out.println("HITS:" + debugHits + "/3"); System.out.println("LEVEL: " + level); ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); Object[] options = {Utils.bPlayAgain, Utils.bQuit}; int goG = JOptionPane.showOptionDialog(null, Utils.txtSurvive + gameTime + Utils.txtSeconds, Utils.goDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (goG != 0 && goG != 1) { Utils.quitGame(); } if (goG == 1) { System.exit(0); } if (goG == 0) { characterSelect(); } } public void pauseGame() { ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); gameStart = false; long LoopTempTime = System.currentTimeMillis(); Object[] options = {Utils.bReturn, Utils.bRestart, Utils.bQuit}; int pauseG = JOptionPane.showOptionDialog(null, Utils.txtPS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); double[] entCurYLoc = new double[entities.size()]; for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entCurYLoc[i] = entity.getVerticalMovement(); entity.setVerticalMovement(0); } if (pauseG != 1 && pauseG != 2) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.setVerticalMovement(entCurYLoc[i]); } finalTime = System.currentTimeMillis() - LoopTempTime; gameStart = true; } if (pauseG == 2) { System.exit(0); } if (pauseG == 1) { gameTime = 0; characterSelect(); } } public void gameLoop() { lastLoopTime = System.currentTimeMillis(); long bgLoop = System.currentTimeMillis(); while (isRunning) { if(gameStart == true){ long delta = (System.currentTimeMillis()-finalTime) - lastLoopTime; finalTime = 0; lastLoopTime = System.currentTimeMillis(); lastTime = getTime(); updateTime(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); for (int i=0;i<backgroundImages.size();i++) { Entity entity = (Entity) backgroundImages.get(i); entity.move(delta); } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } long bgLoopCheck = System.currentTimeMillis(); for(int i=1; i<3; i++){ if(i == 2){ Background2.setVerticalMovement(-10); }else{ Background.setVerticalMovement(-10); } if((bgLoopCheck -bgLoop)> 63000){ Background = new ShipEntity(this,"sprites/Background.png",0,650); backgroundImages.add(Background); bgLoop =System.currentTimeMillis(); } } entities.removeAll(removeList); removeList.clear(); if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<backgroundImages.size();i++) { Entity entity = (Entity) backgroundImages.get(i); entity.draw(g); } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } if(gameTime >90){ advanceLevel = true; if(gameTime > 200){ level = 3; }else{ level = 2; } } /* * Game Text */ //Level g.setColor(Color.red); g.setFont(new Font("Century Gothic", Font.BOLD, Utils.levelFS)); g.drawString(Utils.txtLevel + level,(500-g.getFontMetrics().stringWidth(Utils.txtLevel + level))/2,18); // Timer g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.timeFS)); g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(Utils.txtTime,(70-g.getFontMetrics().stringWidth(Utils.txtTime))/2,18); if (timeMil > 99){ gameTime = timeMil/100; } String convtime = String.valueOf(gameTime); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.timeIFS)); g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18); //Lives g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, Utils.livesFS)); g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18); g.drawString(Utils.txtLives,(875-g.getFontMetrics().stringWidth(Utils.txtLives))/2,18); String convlives = String.valueOf(gameLives); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, Utils.livesIFS)); g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18); // Clear Graphics g.dispose(); strategy.show(); updateEnt(); ship.setHorizontalMovement(0); // Ship movement if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } //testing for collision of player and enemy for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); debugHits++; gameLives if (gameLives <= 0){ gameOver(); } } } } try { Thread.sleep(10); } catch (Exception e) {} }else{ try { Thread.sleep(10); } catch (Exception e) {} } } } /** * Update the game time */ public void updateTime() { if (getTime() - lastTime > 1000) { timeMil = 0; //reset the timer counter lastTime += 1000; //add one second } timeMil++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } public int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } public void removeEntity(Entity entity) { removeList.add(entity); } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) { rightPressed = true; } if (e.getKeyChar() == 27 || e.getKeyCode() == KeyEvent.VK_PAUSE || e.getKeyCode() == KeyEvent.VK_P) { pauseGame(); } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) { rightPressed = false; } } } public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; /** Main Class */ public class Game extends Canvas { /** * Begin the game parameters that will allow us to define certain elements. */ private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; // Is the game running or not? private String gameName = "Codename TARDIS "; private String build = "Alpha "; private String version = "0.2b"; private Entity ship; private ArrayList entities = new ArrayList(); private double moveSpeed = 180; private boolean leftPressed = false; private boolean rightPressed = false; private boolean logicRequiredThisLoop = false; long lastFrame; private String timeDisplay = ""; private String livesDisplay = ""; public int gameTime = 0; public int gameLives = 3; int fps; long lastFPS; // To grab the FPS, for debugging purposes. 60 FPS is the best FPS! Timer newtimer = new Timer(); public Game() { // create a frame to contain our game JFrame container = new JFrame(gameName + "- " + build + version); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,500,650); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); //Don't move this variable as it will add extra padding if moved below pack container.setResizable(false); container.pack(); // Make sure the window shows up smack bang in the centre Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); // Then set the container as visible container.setBackground(Color.black); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(null, "Closing " + gameName + version); // Debug to ensure that game exits correctly System.exit(0); } }); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); } public void updateLogic() { logicRequiredThisLoop = true; } public void quitGame() { JOptionPane.showMessageDialog(null, "Closing " + gameName + version); // Debug to ensure that game exits correctly System.exit(0); } /** * initialise entities */ private void initEntities() { // create the player ship and place it roughly in the center of the screen ship = new ShipEntity(this,"sprites/ship.png",220,568); entities.add(ship); Entity Enemy = new EnemyEntity(this,"sprites/alien1.png",150,50); entities.add(Enemy); } /** * Garbage collection and looping */ private void startGame() { entities.clear(); initEntities(); // reset key presses leftPressed = false; rightPressed = false; } /** * Calculate the FPS and set it in the title bar */ public void updateFPS() { if (getTime() - lastFPS > 1000) { fps = 0; //reset the FPS counter lastFPS += 1000; //add one second } fps++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } /** * GAME LOOP and Main below */ public int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); while (isRunning) { long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); lastFPS = getTime(); updateFPS(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); int fontSize = 18; g.setColor(Color.red); g.setFont(new Font("Century Gothic", Font.PLAIN, fontSize)); g.drawString("WORK IN PROGRESS",(500-g.getFontMetrics().stringWidth("WORK IN PROGRESS"))/2,25); // Timer g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, fontSize)); g.drawString(timeDisplay,(70-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString("Time:",(70-g.getFontMetrics().stringWidth("Time:"))/2,18); String convtime = String.valueOf(fps); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, fontSize)); g.drawString(timeDisplay,(175-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convtime,(175-g.getFontMetrics().stringWidth(convtime))/2,18); //Lives g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.BOLD, fontSize)); g.drawString(livesDisplay,(875-g.getFontMetrics().stringWidth(livesDisplay))/2,18); g.drawString("Lives:",(875-g.getFontMetrics().stringWidth("Lives:"))/2,18); String convlives = String.valueOf(gameLives); g.setColor(Color.white); g.setFont(new Font("Lucida Console", Font.ITALIC, fontSize)); g.drawString(timeDisplay,(965-g.getFontMetrics().stringWidth(timeDisplay))/2,18); g.drawString(convlives,(965-g.getFontMetrics().stringWidth(convlives))/2,18); // Adds the ship into game. for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // Clear Graphics g.dispose(); strategy.show(); ship.setHorizontalMovement(0); // Ship movement if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } try { Thread.sleep(10); } catch (Exception e) {} } } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } if (e.getKeyChar() == 27) { quitGame(); } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } } } /** * Game Start */ public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package me.dreamteam.tardis; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.lwjgl.Sys; import me.dreamteam.tardis.Entity; import me.dreamteam.tardis.ShipEntity; /** Main Class */ public class Game extends Canvas { /** * Begin the game parameters that will allow us to define certain elements. */ private BufferStrategy strategy; // This provides hardware acceleration private boolean isRunning = true; // Is the game running or not? private String gameName = "Codename TARDIS "; private String build = "Alpha "; private String version = "0.1.7b"; // Version set up so that we can see where we are at private Entity ship; private ArrayList entities = new ArrayList(); //game player private double moveSpeed = 300; private boolean leftPressed = false; private boolean rightPressed = false; private boolean logicRequiredThisLoop = false; int fps; long lastFPS; // To grab the FPS, for debugging purposes. 60 FPS is the best FPS! public Game() { // create a frame to contain our game JFrame container = new JFrame(gameName + "- " + build + version + " | FPS: " + lastFPS); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500,650)); panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,500,650); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); //Don't move this variable as it will add extra padding if moved below pack container.setResizable(false); container.pack(); // Make sure the window shows up smack bang in the centre Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; container.setLocation(x, y); // Then set the container as visible container.setBackground(Color.black); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { JOptionPane.showMessageDialog(null, "Closing " + gameName + version); // Debug to ensure that game exits correctly System.exit(0); } }); // Init keys addKeyListener(new KeyInputHandler()); // create the buffering strategy for graphics createBufferStrategy(2); strategy = getBufferStrategy(); requestFocus(); initEntities(); } public void updateLogic() { logicRequiredThisLoop = true; } /** * initialise entities */ private void initEntities() { // create the player ship and place it roughly in the center of the screen ship = new ShipEntity(this,"sprites/ship.png",220,568); System.out.println("Loading ship..."); //debug entities.add(ship); } /** * Garbage collection and looping */ private void startGame() { entities.clear(); initEntities(); // reset key presses leftPressed = false; rightPressed = false; } /** * Calculate the FPS and set it in the title bar */ public void updateFPS() { if (getTime() - lastFPS > 1000) { fps = 0; //reset the FPS counter lastFPS += 1000; //add one second } fps++; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } /** * GAME LOOP and Main below */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); while (isRunning) { long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); lastFPS = getTime(); // Colour in background Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,500,650); // Adds the ship into game. for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // Draw the entities and other items g.dispose(); strategy.show(); if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); } try { Thread.sleep(10); } catch (Exception e) {} } } private class KeyInputHandler extends KeyAdapter { private int pressCount = 1; public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } } public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } } public void keyTyped(KeyEvent e) { startGame(); pressCount = 0; pressCount++; } } /** * Game Start */ public static void main(String argv[]) { Game g =new Game(); // Start the main game loop g.gameLoop(); } }
package org.intermine.objectstore.query; import org.apache.log4j.Logger; import java.lang.ref.SoftReference; import java.util.List; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.NoSuchElementException; import java.util.Iterator; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.CacheMap; /** * Results representation as a List of ResultRows * Extending AbstractList requires implementation of get(int) and size() * In addition subList(int, int) overrides AbstractList implementation for efficiency * * @author Mark Woodbridge * @author Richard Smith * @author Matthew Wakeling */ public class Results extends AbstractList { private static final Logger LOG = Logger.getLogger(Results.class); protected Query query; protected ObjectStore os; protected int sequence; protected boolean optimise = true; protected boolean explain = true; protected int minSize = 0; // TODO: update this to use ObjectStore.getMaxRows(). protected int maxSize = Integer.MAX_VALUE; // -1 stands for "not estimated yet" protected int estimatedSize = -1; protected int originalMaxSize = maxSize; protected int batchSize = 1000; protected boolean initialised = false; // Some prefetch stuff. protected int lastGet = -1; protected int sequential = 0; private static final int PREFETCH_SEQUENTIAL_THRESHOLD = 6; // Basically, this keeps a tally of how many times in a row accesses have been sequential. // If sequential gets above a PREFETCH_SEQUENTIAL_THRESHOLD, then we prefetch the batch after // the one we are currently using. protected SoftReference thisBatchHolder; protected SoftReference nextBatchHolder; protected int lastGetAtGetInfoBatch = -1; protected ResultsInfo info; // A map of batch number against a List of ResultsRows protected Map batches = Collections.synchronizedMap(new CacheMap("Results batches")); /** * No argument constructor for testing purposes * */ protected Results() { } /** * Constructor for a Results object * * @param query the Query that produces this Results * @param os the ObjectStore that can be used to get results rows from * @param sequence a number representing the state of the ObjectStore, which should be quoted * back to the ObjectStore when requests are made */ public Results(Query query, ObjectStore os, int sequence) { if (query == null) { throw new NullPointerException("query must not be null"); } if (os == null) { throw new NullPointerException("os must not be null"); } this.query = query; this.os = os; this.sequence = sequence; } /** * Sets this Results object to bypass the optimiser. */ public void setNoOptimise() { optimise = false; } /** * Sets this Results object to bypass the explain check in ObjectStore.execute(). */ public void setNoExplain() { explain = false; } /** * Get the Query that produced this Results object * * @return the Query that produced this Results object */ public Query getQuery() { return query; } /** * Returns the ObjectStore that this Results object will use * * @return an ObjectStore */ public ObjectStore getObjectStore() { return os; } public List range(int start, int end) throws ObjectStoreException { if (start > end + 1) { throw new IllegalArgumentException("start=" + start + " > (end + 1)=" + (end + 1)); } // If we know the size of the results (ie. have had a last partial batch), check that // the end is within range if (end >= maxSize) { throw new IndexOutOfBoundsException("(end + 1)=" + (end + 1) + " > size=" + maxSize); } int startBatch = getBatchNoForRow(start); int endBatch = getBatchNoForRow(end); List ret = new ArrayList(); for (int i = startBatch; i <= endBatch; i++) { ret.addAll(getRowsFromBatch(i, start, end)); } if (start - 1 == lastGet) { sequential += end - start + 1; //LOG.debug("This access sequential = " + sequential // + " Result " + query.hashCode() // + " access " + start + " - " + end); } else { sequential = 0; //LOG.debug("This access not sequential Result " // + query.hashCode() + " access " + start + " - " + end); } if ((os != null) && os.isMultiConnection() && (sequential > PREFETCH_SEQUENTIAL_THRESHOLD) && (getBatchNoForRow(maxSize) > endBatch) && !batches.containsKey(new Integer(endBatch + 1))) { PrefetchManager.addRequest(this, endBatch + 1); } synchronized (this) { if (sequential > PREFETCH_SEQUENTIAL_THRESHOLD) { if (startBatch == getBatchNoForRow(end + 1) - 1) { thisBatchHolder = nextBatchHolder; nextBatchHolder = null; } if (thisBatchHolder != null) { thisBatchHolder.get(); } if (nextBatchHolder != null) { nextBatchHolder.get(); } } else { thisBatchHolder = null; nextBatchHolder = null; } } lastGet = end; /* // Do the loop in reverse, so that we get IndexOutOfBoundsException first thing if we are // out of range for (int i = endBatch; i >= startBatch; i--) { // Only one thread does this test at a time to save on calls to ObjectStore synchronized (batches) { if (!batches.containsKey(new Integer(i))) { fetchBatchFromObjectStore(i); } } } */ return ret; } /** * Gets a range of rows from within a batch * * @param batchNo the batch number * @param start the row to start from (based on total rows) * @param end the row to end at (based on total rows) - returned List includes this row * @throws ObjectStoreException if an error occurs in the underlying ObjectStore * @throws IndexOutOfBoundsException if the batch is off the end of the results * @return the rows in the range */ protected List getRowsFromBatch(int batchNo, int start, int end) throws ObjectStoreException { List batchList = getBatch(batchNo); int startRowInBatch = batchNo * batchSize; int endRowInBatch = startRowInBatch + batchSize - 1; start = Math.max(start, startRowInBatch); end = Math.min(end, endRowInBatch); return batchList.subList(start - startRowInBatch, end - startRowInBatch + 1); } /** * Gets a batch by whatever means - maybe batches, maybe the ObjectStore. * * @param batchNo the batch number to get (zero-indexed) * @return a List which is the batch * @throws ObjectStoreException if an error occurs in the underlying ObjectStore * @throws IndexOutOfBoundsException if the batch is off the end of the results */ protected List getBatch(int batchNo) throws ObjectStoreException { List retval = (List) batches.get(new Integer(batchNo)); if (retval == null) { retval = PrefetchManager.doRequest(this, batchNo); } return retval; } /** * Gets a batch from the ObjectStore * * @param batchNo the batch number to get (zero-indexed) * @return a List which is the batch * @throws ObjectStoreException if an error occurs in the underlying ObjectStore */ protected List fetchBatchFromObjectStore(int batchNo) throws ObjectStoreException { int start = batchNo * batchSize; int limit = batchSize; //int end = start + batchSize - 1; initialised = true; // We now have 3 possibilities: // a) This is a full batch // b) This is a partial batch, in which case we have reached the end of the results // and can set size. // c) An error has occurred - ie. we have gone beyond the end of the results List rows = null; try { rows = os.execute(query, start, limit, optimise, explain, sequence); synchronized (this) { // Now deal with a partial batch, so we can update the maximum size if (rows.size() != batchSize) { int size = start + rows.size(); maxSize = (maxSize > size ? size : maxSize); } // Now deal with non-empty batch, so we can update the minimum size if (!rows.isEmpty()) { int size = start + rows.size(); minSize = (minSize > size ? minSize : size); } Integer key = new Integer(batchNo); // Set holders, so our data doesn't go away too quickly if (sequential > PREFETCH_SEQUENTIAL_THRESHOLD) { if (batchNo == getBatchNoForRow(lastGet + 1)) { thisBatchHolder = new SoftReference(rows); } else if (batchNo == getBatchNoForRow(lastGet + 1) + 1) { nextBatchHolder = new SoftReference(rows); } } batches.put(key, rows); } } catch (IndexOutOfBoundsException e) { synchronized (this) { if (rows == null) { maxSize = (maxSize > start ? start : maxSize); } } throw e; } return rows; } /** * @see AbstractList#get * @param index of the ResultsRow required * @return the relevant ResultsRow as an Object */ public Object get(int index) { List resultList = null; try { resultList = range(index, index); } catch (ObjectStoreException e) { //LOG.debug("get - " + e); throw new RuntimeException("ObjectStore error has occured (in get)", e); } return resultList.get(0); } /** * @see List#subList * @param start the index to start from (inclusive) * @param end the index to end at (exclusive) * @return the sub-list */ public List subList(int start, int end) { List ret = null; try { ret = range(start, end - 1); } catch (ObjectStoreException e) { //LOG.debug("subList - " + e); throw new RuntimeException("ObjectStore error has occured (in subList)", e); } return ret; } /** * Gets the number of results rows in this Results object * * @see AbstractList#size * @return the number of rows in this Results object */ public int size() { //LOG.debug("size - starting Result " // + query.hashCode() + " size " + minSize + " - " + maxSize); if ((minSize == 0) && (maxSize == Integer.MAX_VALUE)) { // Fetch the first batch, as it is reasonably likely that it will cover it. try { get(0); } catch (IndexOutOfBoundsException e) { // Ignore - that means there are NO rows in this results object. } return size(); } else if (minSize * 2 + batchSize < maxSize) { // Do a count, because it will probably be a little faster. try { maxSize = os.count(query, sequence); } catch (ObjectStoreException e) { throw new RuntimeException("ObjectStore error has occured (in size)", e); } minSize = maxSize; //LOG.debug("size - returning Result " // + query.hashCode() + " size " + maxSize); } else { int iterations = 0; while (minSize < maxSize) { try { int toGt = (maxSize == originalMaxSize ? minSize * 2 : (minSize + maxSize) / 2); //LOG.debug("size - getting " + toGt // + " Result " // + query.hashCode() + " size " + minSize + " - " + maxSize); get(toGt); } catch (IndexOutOfBoundsException e) { // Ignore - this will happen if the end of a batch lies on the // end of the results //LOG.debug("size - Exception caught Result " // + query.hashCode() + " size " + minSize + " - " + maxSize } iterations++; } //LOG.debug("size - returning after " + (iterations > 9 ? "" : " ") + iterations // + " iterations Result " // + query.hashCode() + " size " + maxSize); } return maxSize; } /** * Gets the best current estimate of the characteristics of the query. * * @throws ObjectStoreException if an error occurs in the underlying ObjectStore * @return a ResultsInfo object */ public ResultsInfo getInfo() throws ObjectStoreException { if ((info == null) || ((lastGet % batchSize) != lastGetAtGetInfoBatch)) { info = os.estimate(query); lastGetAtGetInfoBatch = lastGet % batchSize; } return new ResultsInfo(info, minSize, maxSize); } /** * Sets the number of rows requested from the ObjectStore whenever an execute call is made * * @param size the number of rows */ public void setBatchSize(int size) { if (initialised) { throw new IllegalStateException("Cannot set batchSize if rows have been retrieved"); } batchSize = size; } /** * Gets the batch for a particular row * * @param row the row to get the batch for * @return the batch number */ protected int getBatchNoForRow(int row) { return (int) (row / batchSize); } /** * @see AbstractList#iterator */ public Iterator iterator() { return new Iter(); } /** * Returns an iterator over the List, starting fromthe given position. * This method is mainly useful for testing. * * @param from the index of the first object to be fetched * @return an Interator */ public Iterator iteratorFrom(int from) { Iter iter = new Iter(); iter.cursor = from; return iter; } private class Iter implements Iterator { /** * Index of element to be returned by subsequent call to next. */ int cursor = 0; Object nextObject = null; public boolean hasNext() { //LOG.debug("iterator.hasNext Result " // + query.hashCode() + " access " + cursor); if (cursor < minSize) { return true; } if (nextObject != null) { return true; } try { nextObject = get(cursor); return true; } catch (IndexOutOfBoundsException e) { // Ignore - it means that we should return false; } return false; } public Object next() { //LOG.debug("iterator.next Result " // + query.hashCode() + " access " + cursor); Object retval = null; if (nextObject != null) { retval = nextObject; nextObject = null; } else { try { retval = get(cursor); } catch (IndexOutOfBoundsException e) { throw (new NoSuchElementException()); } } cursor++; return retval; } public void remove() { throw (new UnsupportedOperationException()); } } }
package protka.main; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import protka.FastaItem; import protka.io.ProteinStatsArffWriter; import protka.io.FastaReader; import protka.stat.ProteinAminoAcidStats; public class CreateArffFromFragmentStats { private static final String[] requiredProps = { "inputFastaFile", "proteinStatsArffFile" }; private void createOutDirsAndFile(String outFilePath) throws IOException { String outFileDir = outFilePath.substring(0, outFilePath.lastIndexOf(File.separator)); File targetFile = new File(outFileDir); targetFile.mkdirs(); os = new FileOutputStream(outFilePath); } public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: CreateArffFromFragmentStats prop.properties"); return; } PropertyHandler propHandler = new PropertyHandler(requiredProps); Properties properties; FileInputStream is; FileOutputStream os; try { properties = propHandler.readPropertiesFile(args[0]); if (propHandler.checkProps(properties)) { createOutDirsAndFile(properties.getProperty("outputDatFile")); is = new FileInputStream( properties.getProperty("inputFastaFile")); os = new FileOutputStream( properties.getProperty("proteinStatsArffFile")); FastaReader fastaReader = new FastaReader(is); ProteinAminoAcidStats fastaStats = new ProteinAminoAcidStats(); ProteinStatsArffWriter arffWriter = new ProteinStatsArffWriter(os); arffWriter.writeHeader(); int counter = 0; FastaItem fastaItem = fastaReader.getNextFastaItem(); while(fastaItem != null){ arffWriter.writeData(fastaStats.computeCsvStatsString(fastaItem)); fastaItem = fastaReader.getNextFastaItem(); ++counter; if (counter % 2 == 0) { System.out.println("Read and wrote " + counter + " fasta items."); } } arffWriter.closeOS(); } else { System.out.println("Missing property! Aborting."); System.exit(2); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package org.jhaws.common.lang; import java.nio.charset.StandardCharsets; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.text.StringEscapeUtils; // [^abc], which is anything but abc, // or negative lookahead: a(?!b), which is a not followed by b // or negative lookbehind: (?<!a)b, which is b not preceeded by a public interface StringUtils { public static final String UTF8 = StandardCharsets.UTF_8.toString(); public static final String REGULAR_STRING = "\\<([{^-=$!|]})?*+.>"; public static final char[] REGULAR_ARRAY = REGULAR_STRING.toCharArray(); public static final List<Character> REGULAR_LIST = Collections.unmodifiableList(CollectionUtils8.stream(REGULAR_STRING).collect(Collectors.toList())); public static final char[] whitespace_chars = ( "\u0009" // CHARACTER TABULATION + "\n" // LINE FEED (LF) + "\u000B" // LINE TABULATION + "\u000C" // FORM FEED (FF) + "\r" // CARRIAGE RETURN (CR) + "\u0020" // SPACE + "\u0085" // NEXT LINE (NEL) + "\u00A0" // NO-BREAK SPACE + "\u1680" // OGHAM SPACE MARK + "\u180E" // MONGOLIAN VOWEL SEPARATOR + "\u2000" // EN QUAD + "\u2001" // EM QUAD + "\u2002" // EN SPACE + "\u2003" // EM SPACE + "\u2004" // THREE-PER-EM SPACE + "\u2005" // FOUR-PER-EM SPACE + "\u2006" // SIX-PER-EM SPACE + "\u2007" // FIGURE SPACE + "\u2008" // PUNCTUATION SPACE + "\u2009" // THIN SPACE + "\u200A" // HAIR SPACE + "\u2028" // LINE SEPARATOR + "\u2029" // PARAGRAPH SEPARATOR + "\u202F" // NARROW NO-BREAK SPACE + "\u205F" // MEDIUM MATHEMATICAL SPACE + "\u3000" // IDEOGRAPHIC SPACE ).toCharArray(); public static boolean isWhiteSpace(char c) { for (char ws : whitespace_chars) { if (ws == c) { return true; } } return false; } public static String removeUnnecessaryWhiteSpaces(String s) { StringBuilder sb = new StringBuilder(); boolean wasWhiteSpace = false; // was previous character(s) whitespaces boolean start = true; // to remove whitespaces at front for (char c : s.toCharArray()) { if (isWhiteSpace(c)) { if (start || wasWhiteSpace) { continue; } wasWhiteSpace = true; } else { if (wasWhiteSpace) { sb.append(" "); // replace all previous whitespaces by a // single space } sb.append(c); // append non-whitespace character wasWhiteSpace = false; start = false; } } return sb.toString(); } public static String abc(String string) { if (org.apache.commons.lang3.StringUtils.isBlank(string)) { return null; } StringBuilder sb = new StringBuilder(); for (char c : Normalizer.normalize(string, Normalizer.Form.NFKD).toCharArray()) { if (('A' <= c) && (c <= 'Z')) { sb.append(c); } else { if (('a' <= c) && (c <= 'z')) { sb.append(c); } else { sb.append(' '); } } } return sb.toString(); } public static String abcSpace(String string) { if (org.apache.commons.lang3.StringUtils.isBlank(string)) { return null; } StringBuilder sb = new StringBuilder(); for (char c : Normalizer.normalize(string, Normalizer.Form.NFKD).toCharArray()) { if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == ' ') { sb.append(c); } } return sb.toString(); } public static String splitCamelCase(String s) { return s == null ? null : s.replaceAll(String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), " "); } public static String sortable(String string) { return sortable(string, null); } public static String sortable(String string, Collection<Character> keep) { if (org.apache.commons.lang3.StringUtils.isBlank(string)) { return null; } StringBuilder sb = new StringBuilder(); for (char c : Normalizer.normalize(string, Normalizer.Form.NFKD).toUpperCase().toCharArray()) { if (('A' <= c) && (c <= 'Z')) { sb.append(c); } else if (('0' <= c) && (c <= '9')) { sb.append(c); } else if (keep != null && keep.contains(c)) { sb.append(c); } } return sb.toString(); } public static String regularize(String s) { return s == null ? null : s.chars().mapToObj(i -> (char) i).map(StringUtils::regularize).collect(Collectors.joining()); } public static String regularize(char c) { return REGULAR_LIST.contains(c) ? "\\" + c : String.valueOf(c); } public static String escape(String s) { s = s.replaceAll("\\\\", "\\\\\\\\"); s = s.replaceAll("\"", "\\\\\""); return s; } public static String regularUntil(String s) { return "(.*?)\\b" + s + ".*"; } public static boolean isNotBlank(String s) { return org.apache.commons.lang3.StringUtils.isNotBlank(s); } public static boolean isBlank(String s) { return org.apache.commons.lang3.StringUtils.isBlank(s); } public static boolean isNotEmpty(String s) { return org.apache.commons.lang3.StringUtils.isNotEmpty(s); } /** a not followed by b */ public static String regexNotLookAhead(String a, String notB) { return groupRegex(a) + "(" + "?!" + notB + ")"; } /** b not preceeded by a */ public static String regexNotLookBehind(String notA, String b) { return "(" + "?<!" + notA + ")" + groupRegex(b); } public static String regexNot(String notA) { return "!" + notA; } public static String regexMultipleOr(String... x) { String r = x[0]; for (int i = 1; i < x.length; i++) { r = regexOr(r, x[i]); } return r; } static String regexOr(String x, String y) { return "(" + groupRegex(x) + "|" + groupRegex(y) + ")"; } public static String regexMultipleAnd(String... x) { String r = x[0]; for (int i = 1; i < x.length; i++) { r = regexAnd(r, x[i]); } return r; } static String regexAnd(String x, String y) { return "((" + "?=" + x + ")" + groupRegex(y) + ")"; } static String groupRegex(String x) { return x.startsWith("(") && x.endsWith(")") ? x : "(" + x + ")"; } public static String cleanSpaces(String s) { return s.replaceAll("^ +| +$|( )+", "$1"); } public static String repeat(char c, int len) { char[] cc = new char[len]; for (int i = 0; i < cc.length; i++) { cc[i] = c; } return new String(cc); } public static String replaceLeading(String string, char replaced, char replacedBy) { Pattern p = Pattern.compile(replaced + "++"); Matcher matcher = p.matcher(string); if (matcher.find()) { string = matcher.replaceFirst(matcher.group(0).replace(replaced, replacedBy)); } return string; } public static String replaceLeading(String string, String replaced, String replacedBy) { Pattern p = Pattern.compile("(" + replaced + ")++"); Matcher matcher = p.matcher(string); if (matcher.find()) { string = matcher.replaceFirst(matcher.group(0).replace(replaced, replacedBy)); } return string; } public static int count(String string, String findStr) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = string.indexOf(findStr, lastIndex); if (lastIndex != -1) { count++; lastIndex += findStr.length(); } } return count; } public static String ucLeading(String string) { if (string == null || string.length() == 0) return string; if (string.length() == 1) return String.valueOf(Character.toUpperCase(string.charAt(0))); return Character.toUpperCase(string.charAt(0)) + string.substring(1); } public static List<String> splitKeepDelimiter(String delimiter, String input) { return Arrays.asList(input.split( "(?i)" // case insensitive + "((?<=" + delimiter + ")|(?=" + delimiter + "))" )); } public static List<String> splitHtmlTagKeepDelimiter(String tag, String input) { return splitHtmlTagKeepDelimiter(tag, 100, input); } public static List<String> splitHtmlTagKeepDelimiter(String tag, int max, String input) { // max: could not use "+?" because of "Look-behind group does not have // obvious maximum length near index NR" String tagRegex = "(<" + tag + ">(.{0," + max + "})</" + tag + ">)"; return splitKeepDelimiter(tagRegex, input); } public static String replaceLast(String text, String regex, String replacement) { return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement); } public static final Pattern HTML_CODE = Pattern.compile("\\& public static String unescapeHtml(String markup) { StringValue html = new StringValue(markup); html.operate(StringEscapeUtils::unescapeHtml4); Matcher m = HTML_CODE.matcher(markup); Map<String, String> map = new LinkedHashMap<>(); while (m.find()) { map.put(m.group(), String.valueOf((char) Integer.parseInt(m.group(1)))); } map.entrySet().forEach(e -> html.operate(t -> t.replace(e.getKey(), e.getValue()))); return html.get(); } public static final Normalizer.Form CompatibilityDecomposition = Normalizer.Form.NFKD; public static final Normalizer.Form CanonicalDecomposition = Normalizer.Form.NFD; public static char[] compatibilityDecomposition(char c) { return Normalizer.normalize(String.valueOf(c), CompatibilityDecomposition).toCharArray(); } public static char[] canonicalDecomposition(char c) { return Normalizer.normalize(String.valueOf(c), CanonicalDecomposition).toCharArray(); } public static String normalize(String s) { if ((s == null) || "".equals(s.trim())) { return null; } StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { for (char nc : canonicalDecomposition(c)) { sb.append(nc); } } return sb.toString(); } public static String compatible(String s) { if ((s == null) || "".equals(s.trim())) { return null; } StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { for (char nc : compatibilityDecomposition(c)) { sb.append(nc); } } return sb.toString(); } public static String decodeUnicode(String string) { return Pattern.compile("U\\+[0-9A-F]{4}").matcher(string).replaceAll(mr -> Character.toString(Integer.parseInt(mr.group().substring(2), 16))); } public static Optional<String> optional(String s) { return Optional.ofNullable(s).filter(Predicate.not(String::isEmpty)); } public static List<String> plainCharacters(String s) { List<String> queryTermCharacters = new ArrayList<>(); for (char queryTermCharacter : s.toCharArray()) { String cc = Normalizer.normalize("" + queryTermCharacter, Normalizer.Form.NFKD).toLowerCase(); queryTermCharacters.add("" + cc.charAt(0)); } return queryTermCharacters; } public static final Pattern PATTERN_SEARCHPARTS = Pattern.compile("([^\"]\\S*|\".+?\")\\s*"); public static List<String> termen(String s) { Matcher m = PATTERN_SEARCHPARTS.matcher(s); List<String> list = new ArrayList<String>(); while (m.find()) { list.add(m.group(1).replace("\"", "").toLowerCase()); } return list; } public static List<List<String>> termenPlainCharacters(String s) { return termen(s).stream().map(StringUtils::plainCharacters).collect(Collectors.toList()); } public static String highlight(String query, String string, String prefix, String suffix) { return highlight(termenPlainCharacters(query), string, Optional.ofNullable(prefix), Optional.ofNullable(suffix)); } // TODO optimalistatie public static String highlight(List<List<String>> queryTermenCharacters, String string, Optional<String> prefixO, Optional<String> suffixO) { boolean debug = false; if (debug) System.out.println("string=" + queryTermenCharacters); if (debug) System.out.println("string=" + string); int strLen = string.length(); List<String> plainStringCharacters = new ArrayList<>(); List<String> originalStringCharacters = new ArrayList<>(); for (char character : string.toCharArray()) { String cc = Normalizer.normalize(String.valueOf(character), Normalizer.Form.NFKD).toLowerCase(); plainStringCharacters.add("" + cc.charAt(0)); originalStringCharacters.add("" + character); } List<Integer> queryMatchIndices = new ArrayList<>(); for (int i = 0; i < plainStringCharacters.size(); i++) { String stringCharacter = plainStringCharacters.get(i); if (debug) System.out.println(i + ":" + stringCharacter); final int fi = i; queryTermenCharacters.forEach(queryTermCharacters -> { if (stringCharacter.equals(queryTermCharacters.get(0))) { if (debug) System.out.println(" " + fi + "::0:" + queryTermCharacters.get(0)); List<Integer> termMatchIndices = new ArrayList<>(); boolean b = plainStringCharacters.size() >= (fi + queryTermCharacters.size()); if (debug) System.out.println("plainStringCharacters.size() >= (i + queryTermCharacters.size()) = " + plainStringCharacters.size() + ">=" + (fi + queryTermCharacters.size()) + " = " + b); if (b && stringCharacter.equals(queryTermCharacters.get(0))) { termMatchIndices.add(fi); for (int j = 1; termMatchIndices != null && j < queryTermCharacters.size(); j++) { if (debug) System.out.println(" " + (fi + j) + "::" + j + ":" + queryTermCharacters.get(j)); if (plainStringCharacters.get(fi + j).equals(queryTermCharacters.get(j))) { termMatchIndices.add(fi + j); } else { termMatchIndices = null; } } if (termMatchIndices != null && termMatchIndices.size() == queryTermCharacters.size()) { termMatchIndices.stream().filter(x -> !queryMatchIndices.contains(x)).forEach(queryMatchIndices::add); } } } }); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < strLen; i++) { String stringCharacter = originalStringCharacters.get(i); if (queryMatchIndices.contains(i)) { if (prefixO.isPresent()) { sb.append(prefixO.get()); } sb.append(stringCharacter); if (suffixO.isPresent()) { sb.append(suffixO.get()); } } else { sb.append(stringCharacter); } } String marked = sb.toString(); if (prefixO.isPresent() && suffixO.isPresent()) { marked = marked.replace(suffixO.get() + prefixO.get(), ""); } return marked; } }
package jsettlers.ai.highlevel; import static jsettlers.common.buildings.EBuildingType.BAKER; import static jsettlers.common.buildings.EBuildingType.BARRACK; import static jsettlers.common.buildings.EBuildingType.BIG_LIVINGHOUSE; import static jsettlers.common.buildings.EBuildingType.COALMINE; import static jsettlers.common.buildings.EBuildingType.FARM; import static jsettlers.common.buildings.EBuildingType.FORESTER; import static jsettlers.common.buildings.EBuildingType.GOLDMELT; import static jsettlers.common.buildings.EBuildingType.GOLDMINE; import static jsettlers.common.buildings.EBuildingType.IRONMELT; import static jsettlers.common.buildings.EBuildingType.IRONMINE; import static jsettlers.common.buildings.EBuildingType.LUMBERJACK; import static jsettlers.common.buildings.EBuildingType.MEDIUM_LIVINGHOUSE; import static jsettlers.common.buildings.EBuildingType.MILL; import static jsettlers.common.buildings.EBuildingType.PIG_FARM; import static jsettlers.common.buildings.EBuildingType.SAWMILL; import static jsettlers.common.buildings.EBuildingType.SLAUGHTERHOUSE; import static jsettlers.common.buildings.EBuildingType.SMALL_LIVINGHOUSE; import static jsettlers.common.buildings.EBuildingType.STONECUTTER; import static jsettlers.common.buildings.EBuildingType.TEMPLE; import static jsettlers.common.buildings.EBuildingType.TOOLSMITH; import static jsettlers.common.buildings.EBuildingType.TOWER; import static jsettlers.common.buildings.EBuildingType.WATERWORKS; import static jsettlers.common.buildings.EBuildingType.WEAPONSMITH; import static jsettlers.common.buildings.EBuildingType.WINEGROWER; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jsettlers.ai.construction.BestConstructionPositionFinderFactory; import jsettlers.ai.construction.BuildingCount; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.movable.EMovableType; import jsettlers.common.position.ShortPoint2D; import jsettlers.input.tasks.ConstructBuildingTask; import jsettlers.input.tasks.EGuiAction; import jsettlers.logic.map.grid.MainGrid; import jsettlers.network.client.interfaces.ITaskScheduler; public class RomanWhatToDoAi implements IWhatToDoAi { private final MainGrid mainGrid; private final byte playerId; private final ITaskScheduler taskScheduler; private final AiStatistics aiStatistics; private final List<BuildingCount> buildMaterialEconomy; private final List<BuildingCount> foodEconomy; private final List<BuildingCount> weaponsEconomy; private final List<BuildingCount> toolsEconomy; private final List<BuildingCount> manaEconomy; private final List<BuildingCount> goldEconomy; private final List<List<BuildingCount>> economiesOrder; BestConstructionPositionFinderFactory bestConstructionPositionFinderFactory; public RomanWhatToDoAi(byte playerId, AiStatistics aiStatistics, MainGrid mainGrid, ITaskScheduler taskScheduler) { this.playerId = playerId; this.mainGrid = mainGrid; this.taskScheduler = taskScheduler; this.aiStatistics = aiStatistics; bestConstructionPositionFinderFactory = new BestConstructionPositionFinderFactory(); buildMaterialEconomy = new ArrayList<BuildingCount>(); foodEconomy = new ArrayList<BuildingCount>(); weaponsEconomy = new ArrayList<BuildingCount>(); toolsEconomy = new ArrayList<BuildingCount>(); manaEconomy = new ArrayList<BuildingCount>(); goldEconomy = new ArrayList<BuildingCount>(); economiesOrder = new ArrayList<List<BuildingCount>>(); initializeEconomies(); } private void initializeEconomies() { buildMaterialEconomy.add(new BuildingCount(LUMBERJACK, 3)); buildMaterialEconomy.add(new BuildingCount(SAWMILL, 1)); buildMaterialEconomy.add(new BuildingCount(FORESTER, 1.5f)); buildMaterialEconomy.add(new BuildingCount(STONECUTTER, 1.7f)); foodEconomy.add(new BuildingCount(FARM, 3)); foodEconomy.add(new BuildingCount(PIG_FARM, 1.4f)); foodEconomy.add(new BuildingCount(WATERWORKS, 1.5f)); foodEconomy.add(new BuildingCount(MILL, 0.7f)); foodEconomy.add(new BuildingCount(BAKER, 2)); foodEconomy.add(new BuildingCount(SLAUGHTERHOUSE, 0.7f)); weaponsEconomy.add(new BuildingCount(COALMINE, 1)); weaponsEconomy.add(new BuildingCount(IRONMINE, 0.5f)); weaponsEconomy.add(new BuildingCount(IRONMELT, 1)); weaponsEconomy.add(new BuildingCount(WEAPONSMITH, 1)); weaponsEconomy.add(new BuildingCount(BARRACK, 0.4f)); toolsEconomy.add(new BuildingCount(COALMINE, 1)); toolsEconomy.add(new BuildingCount(IRONMINE, 0.5f)); toolsEconomy.add(new BuildingCount(IRONMELT, 1)); toolsEconomy.add(new BuildingCount(TOOLSMITH, 1)); manaEconomy.add(new BuildingCount(WINEGROWER, 1)); manaEconomy.add(new BuildingCount(TEMPLE, 1)); goldEconomy.add(new BuildingCount(COALMINE, 0.5f)); goldEconomy.add(new BuildingCount(GOLDMINE, 0.5f)); goldEconomy.add(new BuildingCount(GOLDMELT, 1)); economiesOrder.add(buildMaterialEconomy); economiesOrder.add(buildMaterialEconomy); economiesOrder.add(buildMaterialEconomy); economiesOrder.add(manaEconomy); economiesOrder.add(foodEconomy); economiesOrder.add(toolsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(goldEconomy); economiesOrder.add(foodEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(goldEconomy); economiesOrder.add(foodEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(foodEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(foodEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); economiesOrder.add(weaponsEconomy); } @Override public void applyRules() { int numberOfNotFinishedBuildings = aiStatistics.getNumberOfNotFinishedBuildingsForPlayer(playerId); Map<EBuildingType, Integer> numberOf = new HashMap<EBuildingType, Integer>(); numberOf.put(SMALL_LIVINGHOUSE, aiStatistics.getNumberOfBuildingTypeForPlayer(SMALL_LIVINGHOUSE, playerId)); numberOf.put(MEDIUM_LIVINGHOUSE, aiStatistics.getNumberOfBuildingTypeForPlayer(MEDIUM_LIVINGHOUSE, playerId)); numberOf.put(BIG_LIVINGHOUSE, aiStatistics.getNumberOfBuildingTypeForPlayer(BIG_LIVINGHOUSE, playerId)); numberOf.put(COALMINE, aiStatistics.getNumberOfBuildingTypeForPlayer(COALMINE, playerId)); numberOf.put(IRONMINE, aiStatistics.getNumberOfBuildingTypeForPlayer(IRONMINE, playerId)); numberOf.put(IRONMELT, aiStatistics.getNumberOfBuildingTypeForPlayer(IRONMELT, playerId)); numberOf.put(TOOLSMITH, aiStatistics.getNumberOfBuildingTypeForPlayer(TOOLSMITH, playerId)); int numberOfNotOccupiedTowers = aiStatistics.getNumberOfNotOccupiedTowers(playerId); int numberOfBearers = aiStatistics.getMovablePositionsByTypeForPlayer(EMovableType.BEARER, playerId).size(); int numberOfTotalBuildings = aiStatistics.getNumberOfTotalBuildingsForPlayer(playerId); if (numberOfNotFinishedBuildings <= 4) { int futureNumberOfBearers = numberOfBearers + aiStatistics.getTotalNumberOfBuildingTypeForPlayer(SMALL_LIVINGHOUSE, playerId) * 10 - aiStatistics.getNumberOfBuildingTypeForPlayer(SMALL_LIVINGHOUSE, playerId) * 10 + aiStatistics.getTotalNumberOfBuildingTypeForPlayer(MEDIUM_LIVINGHOUSE, playerId) * 30 - aiStatistics.getNumberOfBuildingTypeForPlayer(MEDIUM_LIVINGHOUSE, playerId) * 30 + aiStatistics.getTotalNumberOfBuildingTypeForPlayer(BIG_LIVINGHOUSE, playerId) * 100 - aiStatistics.getNumberOfBuildingTypeForPlayer(BIG_LIVINGHOUSE, playerId) * 100; if (futureNumberOfBearers < 10 || numberOfTotalBuildings > 1.5 * futureNumberOfBearers) { if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(STONECUTTER, playerId) < 4 || aiStatistics.getTotalNumberOfBuildingTypeForPlayer(SAWMILL, playerId) < 3) { construct(SMALL_LIVINGHOUSE); return; } else { construct(MEDIUM_LIVINGHOUSE); return; } } if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(STONECUTTER, playerId) >= 1 && numberOfNotOccupiedTowers == 0) { construct(TOWER); return; } boolean toolsEconomyNeedsToBeChecked = true; Map<EBuildingType, Float> currentBuildingPlan = new HashMap<EBuildingType, Float>(); for (List<BuildingCount> currentEconomy : economiesOrder) { for (BuildingCount currentBuildingCount : currentEconomy) { if (!currentBuildingPlan.containsKey(currentBuildingCount.buildingType)) { currentBuildingPlan.put(currentBuildingCount.buildingType, 0f); } float newCount = currentBuildingPlan.get(currentBuildingCount.buildingType) + currentBuildingCount.count; currentBuildingPlan.put(currentBuildingCount.buildingType, currentBuildingPlan.get(currentBuildingCount.buildingType) + currentBuildingCount.count); if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(currentBuildingCount.buildingType, playerId) < Math.max(1, Math.floor(newCount))) { if (toolsEconomyNeedsToBeChecked && !aiStatistics.toolIsAvailableForBuildingTypeAndPlayer(currentBuildingCount.buildingType, playerId)) { if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(COALMINE, playerId) < 1 && construct(COALMINE)) { return; } if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(IRONMINE, playerId) < 1 && construct(IRONMINE)) { return; } if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(IRONMELT, playerId) < 1 && construct(IRONMELT)) { return; } if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(TOOLSMITH, playerId) < 1 && construct(TOOLSMITH)) { return; } toolsEconomyNeedsToBeChecked = false; } boolean constructWasSuccessful = construct(currentBuildingCount.buildingType); if (constructWasSuccessful) { return; } } } } } } private boolean construct(EBuildingType type) { ShortPoint2D position = bestConstructionPositionFinderFactory .getBestConstructionPositionFinderFor(type) .findBestConstructionPosition(aiStatistics, mainGrid.getConstructionMarksGrid(), playerId); if (position != null) { taskScheduler.scheduleTask(new ConstructBuildingTask(EGuiAction.BUILD, playerId, position, type)); if (type == TOWER) { aiStatistics.sendAnySoldierToPosition(position, playerId); } return true; } return false; } }