lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
mit
2ccd5b111b50ed9eba8fcae0f053e66d3d4b2736
0
ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform,ljshj/actor-platform
package im.actor.runtime; import im.actor.runtime.power.WakeLock; public class LifecycleRuntimeProvider implements LifecycleRuntime { @Override public void killApp() { throw new RuntimeException("Dumb"); } @Override public WakeLock makeWakeLock() { throw new RuntimeException("Dumb"); } }
actor-sdk/sdk-core/runtime/runtime-shared/src/template/java/im/actor/runtime/LifecycleRuntimeProvider.java
package im.actor.runtime; public class LifecycleRuntimeProvider implements LifecycleRuntime { @Override public void killApp() { throw new RuntimeException("Dumb"); } }
fix(runtime): Fixing compilation error
actor-sdk/sdk-core/runtime/runtime-shared/src/template/java/im/actor/runtime/LifecycleRuntimeProvider.java
fix(runtime): Fixing compilation error
Java
mit
363d423b43e5bb17cc268c5c66019a4c4e6448a5
0
MNascimentoS/CineTudo
package cinetudoproject.model.domain; /** * Created by diogo on 20/08/16. */ public class Assento { private String fila; private int numero; private int ocupado; public Assento(String fila, int numero) { this.fila = fila; this.numero = numero; this.ocupado = 0; } public Assento() { } public String getFila() { return fila; } public void setFila(String fila) { this.fila = fila; } public int getNumero() { return numero; } public void setNumero(int numero) { if(numero > 0) this.numero = numero; } public int getOcupado() { return ocupado; } public void setOcupado(int ocupado) { this.ocupado = ocupado; } }
src/cinetudoproject/model/domain/Assento.java
package cinetudoproject.model.domain; /** * Created by diogo on 20/08/16. */ public class Assento { private char fila; private int numero; private boolean ocupado; public Assento(char fila, int numero) { this.fila = fila; this.numero = numero; this.ocupado = false; } public char getFila() { return fila; } public void setFila(char fila) { if(fila >= 'a' && fila <= 'z') this.fila = fila; } public int getNumero() { return numero; } public void setNumero(int numero) { if(numero > 0) this.numero = numero; } public boolean isOcupado() { return ocupado; } public void setOcupado(boolean ocupado) { this.ocupado = ocupado; } }
adicionado logica da classe assento
src/cinetudoproject/model/domain/Assento.java
adicionado logica da classe assento
Java
mit
1b3e400f93c5459bd1fcf558521d01569e09c957
0
vivekyadav01/fluent-jdbc
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codejargon.fluentjdbc.internal.query.namedparameter; import java.util.*; import org.codejargon.fluentjdbc.api.FluentJdbcException; import org.codejargon.fluentjdbc.internal.support.Preconditions; /** * Helper methods for named parameter parsing. * * <p>Only intended for internal use within Spring's JDBC framework. * * @author Thomas Risberg * @author Juergen Hoeller * @since 2.0 * * Class has been slightly simplified for FluentJdbc (dropped declaredParams, paramSource, introduced FluentJdbc-specific namedParams) */ abstract class NamedParameterUtils { /** * Set of characters that qualify as parameter separators, * indicating that a parameter name in a SQL String has ended. */ private static final char[] PARAMETER_SEPARATORS = new char[] {'"', '\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\', '<', '>', '^'}; /** * Set of characters that qualify as comment or quotes starting characters. */ private static final String[] START_SKIP = new String[] {"'", "\"", "--", "/*"}; /** * Set of characters that at are the corresponding comment or quotes ending characters. */ private static final String[] STOP_SKIP = new String[] {"'", "\"", "\n", "*/"}; //------------------------------------------------------------------------- // Core methods used by NamedParameterJdbcTemplate and SqlQuery/SqlUpdate //------------------------------------------------------------------------- /** * Parse the SQL statement and locate any placeholders or named parameters. * Named parameters are substituted for a JDBC placeholder. * @param sql the SQL statement * @return the parsed statement, represented as ParsedSql instance */ static ParsedSql parseSqlStatement(final String sql) { Preconditions.checkNotNull(sql, "SQL must not be null"); Set<String> namedParameters = new HashSet<>(); String sqlToUse = sql; List<ParameterHolder> parameterList = new ArrayList<>(); char[] statement = sql.toCharArray(); int namedParameterCount = 0; int unnamedParameterCount = 0; int totalParameterCount = 0; int escapes = 0; int i = 0; while (i < statement.length) { int skipToPosition; while (i < statement.length) { skipToPosition = skipCommentsAndQuotes(statement, i); if (i == skipToPosition) { break; } else { i = skipToPosition; } } if (i >= statement.length) { break; } char c = statement[i]; if (c == ':' || c == '&') { int j = i + 1; if (j < statement.length && statement[j] == ':' && c == ':') { // Postgres-style "::" casting operator - to be skipped. i = i + 2; continue; } if (j < statement.length && c == ':' && statement[j] == '{') { // :{x} style parameter while (j < statement.length && !('}' == statement[j])) { j++; if (':' == statement[j] || '{' == statement[j]) { throw new FluentJdbcException("Parameter name contains invalid character '" + statement[j] + "' at position " + i + " in statement: " + sql); } } if (j >= statement.length) { throw new FluentJdbcException( "Non-terminated named parameter declaration at position " + i + " in statement: " + sql); } if (j - i > 3) { String parameter = sql.substring(i + 2, j); namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter); } j++; } else { while (j < statement.length && !isParameterSeparator(statement[j])) { j++; } if (j - i > 1) { String parameter = sql.substring(i + 1, j); namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter); } } i = j - 1; } else { if (c == '\\') { int j = i + 1; if (j < statement.length && statement[j] == ':') { // this is an escaped : and should be skipped sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1); escapes++; i = i + 2; continue; } } if (c == '?') { unnamedParameterCount++; totalParameterCount++; } } i++; } ParsedSql parsedSql = new ParsedSql(sqlToUse); for (ParameterHolder ph : parameterList) { parsedSql.addNamedParameter(ph.getParameterName(), ph.getStartIndex(), ph.getEndIndex()); } parsedSql.setNamedParameterCount(namedParameterCount); parsedSql.setUnnamedParameterCount(unnamedParameterCount); parsedSql.setTotalParameterCount(totalParameterCount); return parsedSql; } private static int addNamedParameter( List<ParameterHolder> parameterList, int totalParameterCount, int escapes, int i, int j, String parameter) { parameterList.add(new ParameterHolder(parameter, i - escapes, j - escapes)); totalParameterCount++; return totalParameterCount; } private static int addNewNamedParameter(Set<String> namedParameters, int namedParameterCount, String parameter) { if (!namedParameters.contains(parameter)) { namedParameters.add(parameter); namedParameterCount++; } return namedParameterCount; } /** * Skip over comments and quoted names present in an SQL statement * @param statement character array containing SQL statement * @param position current position of statement * @return next position to process after any comments or quotes are skipped */ private static int skipCommentsAndQuotes(char[] statement, int position) { for (int i = 0; i < START_SKIP.length; i++) { if (statement[position] == START_SKIP[i].charAt(0)) { boolean match = true; for (int j = 1; j < START_SKIP[i].length(); j++) { if (!(statement[position + j] == START_SKIP[i].charAt(j))) { match = false; break; } } if (match) { int offset = START_SKIP[i].length(); for (int m = position + offset; m < statement.length; m++) { if (statement[m] == STOP_SKIP[i].charAt(0)) { boolean endMatch = true; int endPos = m; for (int n = 1; n < STOP_SKIP[i].length(); n++) { if (m + n >= statement.length) { // last comment not closed properly return statement.length; } if (!(statement[m + n] == STOP_SKIP[i].charAt(n))) { endMatch = false; break; } endPos = m + n; } if (endMatch) { // found character sequence ending comment or quote return endPos + 1; } } } // character sequence ending comment or quote not found return statement.length; } } } return position; } /** * Parse the SQL statement and locate any placeholders or named parameters. Named * parameters are substituted for a JDBC placeholder, and any select list is expanded * to the required number of placeholders. Select lists may contain an array of * objects, and in that case the placeholders will be grouped and enclosed with * parentheses. This allows for the use of "expression lists" in the SQL statement * like: * {@code select id, name, state from table where (name, age) in (('John', 35), ('Ann', 50))} * <p>The parameter values passed in are used to determine the number of placeholders to * be used for a select list. Select lists should be limited to 100 or fewer elements. * A larger number of elements is not guaranteed to be supported by the database and * is strictly vendor-dependent. * @param parsedSql the parsed representation of the SQL statement * @return the SQL statement with substituted parameters * @see #parseSqlStatement */ static String substituteNamedParameters(ParsedSql parsedSql) { String originalSql = parsedSql.getOriginalSql(); StringBuilder actualSql = new StringBuilder(); List<String> paramNames = parsedSql.getParameterNames(); int lastIndex = 0; for (int i = 0; i < paramNames.size(); i++) { int[] indexes = parsedSql.getParameterIndexes(i); int startIndex = indexes[0]; int endIndex = indexes[1]; actualSql.append(originalSql, lastIndex, startIndex); actualSql.append("?"); lastIndex = endIndex; } actualSql.append(originalSql, lastIndex, originalSql.length()); return actualSql.toString(); } /** * Convert a Map of named parameter values to a corresponding array. * @param parsedSql the parsed SQL statement * (may be {@code null}). If specified, the parameter metadata will * be built into the value array in the form of SqlParameterValue objects. * @return the array of values */ static Object[] buildValueArray(ParsedSql parsedSql, Map<String, Object> namedParams) { Object[] paramArray = new Object[parsedSql.getTotalParameterCount()]; if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) { throw new FluentJdbcException( "Not allowed to mix named and traditional ? placeholders. You have " + parsedSql.getNamedParameterCount() + " named parameter(s) and " + parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " + parsedSql.getOriginalSql()); } List<String> paramNames = parsedSql.getParameterNames(); for (int i = 0; i < paramNames.size(); i++) { String paramName = paramNames.get(i); if(!namedParams.containsKey(paramName)) { throw new FluentJdbcException(String.format("Named parameter not set: %s", paramName)); } Object value = namedParams.get(paramName); paramArray[i] = value; } return paramArray; } /** * Determine whether a parameter name ends at the current position, * that is, whether the given character qualifies as a separator. */ private static boolean isParameterSeparator(char c) { if (Character.isWhitespace(c)) { return true; } for (char separator : PARAMETER_SEPARATORS) { if (c == separator) { return true; } } return false; } private static class ParameterHolder { private final String parameterName; private final int startIndex; private final int endIndex; public ParameterHolder(String parameterName, int startIndex, int endIndex) { this.parameterName = parameterName; this.startIndex = startIndex; this.endIndex = endIndex; } public String getParameterName() { return this.parameterName; } public int getStartIndex() { return this.startIndex; } public int getEndIndex() { return this.endIndex; } } }
fluent-jdbc/src/main/java/org/codejargon/fluentjdbc/internal/query/namedparameter/NamedParameterUtils.java
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codejargon.fluentjdbc.internal.query.namedparameter; import java.util.*; import org.codejargon.fluentjdbc.api.FluentJdbcException; import org.codejargon.fluentjdbc.internal.support.Preconditions; /** * Helper methods for named parameter parsing. * * <p>Only intended for internal use within Spring's JDBC framework. * * @author Thomas Risberg * @author Juergen Hoeller * @since 2.0 * * Class has been slightly simplified for FluentJdbc (dropped declaredParams, paramSource, introduced FluentJdbc-specific namedParams) */ abstract class NamedParameterUtils { /** * Set of characters that qualify as parameter separators, * indicating that a parameter name in a SQL String has ended. */ private static final char[] PARAMETER_SEPARATORS = new char[] {'"', '\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\', '<', '>', '^'}; /** * Set of characters that qualify as comment or quotes starting characters. */ private static final String[] START_SKIP = new String[] {"'", "\"", "--", "/*"}; /** * Set of characters that at are the corresponding comment or quotes ending characters. */ private static final String[] STOP_SKIP = new String[] {"'", "\"", "\n", "*/"}; //------------------------------------------------------------------------- // Core methods used by NamedParameterJdbcTemplate and SqlQuery/SqlUpdate //------------------------------------------------------------------------- /** * Parse the SQL statement and locate any placeholders or named parameters. * Named parameters are substituted for a JDBC placeholder. * @param sql the SQL statement * @return the parsed statement, represented as ParsedSql instance */ static ParsedSql parseSqlStatement(final String sql) { Preconditions.checkNotNull(sql, "SQL must not be null"); Set<String> namedParameters = new HashSet<String>(); String sqlToUse = sql; List<ParameterHolder> parameterList = new ArrayList<ParameterHolder>(); char[] statement = sql.toCharArray(); int namedParameterCount = 0; int unnamedParameterCount = 0; int totalParameterCount = 0; int escapes = 0; int i = 0; while (i < statement.length) { int skipToPosition = i; while (i < statement.length) { skipToPosition = skipCommentsAndQuotes(statement, i); if (i == skipToPosition) { break; } else { i = skipToPosition; } } if (i >= statement.length) { break; } char c = statement[i]; if (c == ':' || c == '&') { int j = i + 1; if (j < statement.length && statement[j] == ':' && c == ':') { // Postgres-style "::" casting operator - to be skipped. i = i + 2; continue; } String parameter = null; if (j < statement.length && c == ':' && statement[j] == '{') { // :{x} style parameter while (j < statement.length && !('}' == statement[j])) { j++; if (':' == statement[j] || '{' == statement[j]) { throw new FluentJdbcException("Parameter name contains invalid character '" + statement[j] + "' at position " + i + " in statement: " + sql); } } if (j >= statement.length) { throw new FluentJdbcException( "Non-terminated named parameter declaration at position " + i + " in statement: " + sql); } if (j - i > 3) { parameter = sql.substring(i + 2, j); namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter); } j++; } else { while (j < statement.length && !isParameterSeparator(statement[j])) { j++; } if (j - i > 1) { parameter = sql.substring(i + 1, j); namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter); totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter); } } i = j - 1; } else { if (c == '\\') { int j = i + 1; if (j < statement.length && statement[j] == ':') { // this is an escaped : and should be skipped sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1); escapes++; i = i + 2; continue; } } if (c == '?') { unnamedParameterCount++; totalParameterCount++; } } i++; } ParsedSql parsedSql = new ParsedSql(sqlToUse); for (ParameterHolder ph : parameterList) { parsedSql.addNamedParameter(ph.getParameterName(), ph.getStartIndex(), ph.getEndIndex()); } parsedSql.setNamedParameterCount(namedParameterCount); parsedSql.setUnnamedParameterCount(unnamedParameterCount); parsedSql.setTotalParameterCount(totalParameterCount); return parsedSql; } private static int addNamedParameter( List<ParameterHolder> parameterList, int totalParameterCount, int escapes, int i, int j, String parameter) { parameterList.add(new ParameterHolder(parameter, i - escapes, j - escapes)); totalParameterCount++; return totalParameterCount; } private static int addNewNamedParameter(Set<String> namedParameters, int namedParameterCount, String parameter) { if (!namedParameters.contains(parameter)) { namedParameters.add(parameter); namedParameterCount++; } return namedParameterCount; } /** * Skip over comments and quoted names present in an SQL statement * @param statement character array containing SQL statement * @param position current position of statement * @return next position to process after any comments or quotes are skipped */ private static int skipCommentsAndQuotes(char[] statement, int position) { for (int i = 0; i < START_SKIP.length; i++) { if (statement[position] == START_SKIP[i].charAt(0)) { boolean match = true; for (int j = 1; j < START_SKIP[i].length(); j++) { if (!(statement[position + j] == START_SKIP[i].charAt(j))) { match = false; break; } } if (match) { int offset = START_SKIP[i].length(); for (int m = position + offset; m < statement.length; m++) { if (statement[m] == STOP_SKIP[i].charAt(0)) { boolean endMatch = true; int endPos = m; for (int n = 1; n < STOP_SKIP[i].length(); n++) { if (m + n >= statement.length) { // last comment not closed properly return statement.length; } if (!(statement[m + n] == STOP_SKIP[i].charAt(n))) { endMatch = false; break; } endPos = m + n; } if (endMatch) { // found character sequence ending comment or quote return endPos + 1; } } } // character sequence ending comment or quote not found return statement.length; } } } return position; } /** * Parse the SQL statement and locate any placeholders or named parameters. Named * parameters are substituted for a JDBC placeholder, and any select list is expanded * to the required number of placeholders. Select lists may contain an array of * objects, and in that case the placeholders will be grouped and enclosed with * parentheses. This allows for the use of "expression lists" in the SQL statement * like: * {@code select id, name, state from table where (name, age) in (('John', 35), ('Ann', 50))} * <p>The parameter values passed in are used to determine the number of placeholders to * be used for a select list. Select lists should be limited to 100 or fewer elements. * A larger number of elements is not guaranteed to be supported by the database and * is strictly vendor-dependent. * @param parsedSql the parsed representation of the SQL statement * @return the SQL statement with substituted parameters * @see #parseSqlStatement */ static String substituteNamedParameters(ParsedSql parsedSql) { String originalSql = parsedSql.getOriginalSql(); StringBuilder actualSql = new StringBuilder(); List<String> paramNames = parsedSql.getParameterNames(); int lastIndex = 0; for (int i = 0; i < paramNames.size(); i++) { int[] indexes = parsedSql.getParameterIndexes(i); int startIndex = indexes[0]; int endIndex = indexes[1]; actualSql.append(originalSql, lastIndex, startIndex); actualSql.append("?"); lastIndex = endIndex; } actualSql.append(originalSql, lastIndex, originalSql.length()); return actualSql.toString(); } /** * Convert a Map of named parameter values to a corresponding array. * @param parsedSql the parsed SQL statement * (may be {@code null}). If specified, the parameter metadata will * be built into the value array in the form of SqlParameterValue objects. * @return the array of values */ static Object[] buildValueArray(ParsedSql parsedSql, Map<String, Object> namedParams) { Object[] paramArray = new Object[parsedSql.getTotalParameterCount()]; if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) { throw new FluentJdbcException( "Not allowed to mix named and traditional ? placeholders. You have " + parsedSql.getNamedParameterCount() + " named parameter(s) and " + parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " + parsedSql.getOriginalSql()); } List<String> paramNames = parsedSql.getParameterNames(); for (int i = 0; i < paramNames.size(); i++) { String paramName = paramNames.get(i); if(!namedParams.containsKey(paramName)) { throw new FluentJdbcException(String.format("Named parameter not set: %s", paramName)); } Object value = namedParams.get(paramName); paramArray[i] = value; } return paramArray; } /** * Determine whether a parameter name ends at the current position, * that is, whether the given character qualifies as a separator. */ private static boolean isParameterSeparator(char c) { if (Character.isWhitespace(c)) { return true; } for (char separator : PARAMETER_SEPARATORS) { if (c == separator) { return true; } } return false; } private static class ParameterHolder { private final String parameterName; private final int startIndex; private final int endIndex; public ParameterHolder(String parameterName, int startIndex, int endIndex) { this.parameterName = parameterName; this.startIndex = startIndex; this.endIndex = endIndex; } public String getParameterName() { return this.parameterName; } public int getStartIndex() { return this.startIndex; } public int getEndIndex() { return this.endIndex; } } }
getting rid of minor warnings
fluent-jdbc/src/main/java/org/codejargon/fluentjdbc/internal/query/namedparameter/NamedParameterUtils.java
getting rid of minor warnings
Java
mit
ecf1a7cad797eb07e72f5894125e8cc8458da515
0
gubatron/frostwire-jlibtorrent,aldenml/frostwire-jlibtorrent,aldenml/frostwire-jlibtorrent,aldenml/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent,gubatron/frostwire-jlibtorrent,gubatron/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent,frostwire/frostwire-jlibtorrent
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.alerts.*; import com.frostwire.jlibtorrent.plugins.Plugin; import com.frostwire.jlibtorrent.plugins.SwigPlugin; import com.frostwire.jlibtorrent.swig.*; import com.frostwire.jlibtorrent.swig.session_handle.options_t; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * The session holds all state that spans multiple torrents. Among other * things it runs the network loop and manages all torrents. Once it's * created, the session object will spawn the main thread that will do all * the work. The main thread will be idle as long it doesn't have any * torrents to participate in. * <p/> * This class belongs to a middle logical layer of abstraction. It's a wrapper * of the underlying swig session object (from libtorrent), but it does not * expose all the raw features, not expose a very high level interface * like {@link com.frostwire.jlibtorrent.DHT DHT} or * {@link com.frostwire.jlibtorrent.Downloader Downloader}. * * @author gubatron * @author aldenml */ public final class Session extends SessionHandle { private static final Logger LOG = Logger.getLogger(Session.class); private static final long REQUEST_STATS_RESOLUTION_MILLIS = 1000; private static final long ALERTS_LOOP_WAIT_MILLIS = 500; private final session s; private final JavaStat stat; private final SessionStats stats; private long lastStatsRequestTime; private long lastStatSecondTick; private final SparseArray<ArrayList<AlertListener>> listeners; private final SparseArray<AlertListener[]> listenerSnapshots; private boolean running; private final LinkedList<SwigPlugin> plugins; /** * The flag alert_mask is always set to all_categories. * * @param settings * @param logging */ public Session(SettingsPack settings, boolean logging) { super(createSession(settings, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : defaultRouters()) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } @Deprecated public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { super(createSessionDeprecated(print, prange, iface, routers, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<AlertListener>>(); this.listenerSnapshots = new SparseArray<AlertListener[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : routers) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers) { this(print, prange, iface, routers, false); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface) { this(print, prange, iface, defaultRouters()); } public Session(Fingerprint print) { this(print, new Pair<Integer, Integer>(0, 0), "0.0.0.0"); } public Session(Pair<Integer, Integer> prange, String iface) { this(new Fingerprint(), prange, iface); } public Session() { this(new SettingsPack(), false); } public session getSwig() { return s; } public void addListener(AlertListener listener) { modifyListeners(true, listener); } public void removeListener(AlertListener listener) { modifyListeners(false, listener); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param ti * @param saveDir * @param priorities * @param resumeFile * @return */ public TorrentHandle addTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { return addTorrentSupport(ti, saveDir, priorities, resumeFile, false); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile * @return */ public TorrentHandle addTorrent(File torrent, File saveDir, File resumeFile) { return addTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @return */ public TorrentHandle addTorrent(File torrent, File saveDir) { return addTorrent(torrent, saveDir, null); } /** * In order to add torrents more efficiently, consider using this which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * * @param ti * @param saveDir * @param priorities * @param resumeFile */ public void asyncAddTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { addTorrentSupport(ti, saveDir, priorities, resumeFile, true); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile */ public void asyncAddTorrent(File torrent, File saveDir, File resumeFile) { asyncAddTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir */ public void asyncAddTorrent(File torrent, File saveDir) { asyncAddTorrent(torrent, saveDir, null); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * <p/> * The optional second argument options can be used to delete all the files downloaded * by this torrent. To do so, pass in the value session::delete_files. The removal of * the torrent is asyncronous, there is no guarantee that adding the same torrent immediately * after it was removed will not throw a libtorrent_exception exception. Once the torrent * is deleted, a torrent_deleted_alert is posted. * * @param th */ public void removeTorrent(TorrentHandle th, Options options) { s.remove_torrent(th.getSwig(), options.getSwig()); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * * @param th */ public void removeTorrent(TorrentHandle th) { if (th.isValid()) { s.remove_torrent(th.getSwig()); } } /** * Applies the settings specified by the settings_pack ``sp``. This is an * asynchronous operation that will return immediately and actually apply * the settings to the main thread of libtorrent some time later. * * @param sp */ public void applySettings(SettingsPack sp) { s.apply_settings(sp.getSwig()); } /** * In case you want to destruct the session asynchrounously, you can * request a session destruction proxy. If you don't do this, the * destructor of the session object will block while the trackers are * contacted. If you keep one ``session_proxy`` to the session when * destructing it, the destructor will not block, but start to close down * the session, the destructor of the proxy will then synchronize the * threads. So, the destruction of the session is performed from the * ``session`` destructor call until the ``session_proxy`` destructor * call. The ``session_proxy`` does not have any operations on it (since * the session is being closed down, no operations are allowed on it). * The only valid operation is calling the destructor:: * * @return */ public SessionProxy abort() { running = false; return new SessionProxy(s.abort()); } /** * Pausing the session has the same effect as pausing every torrent in * it, except that torrents will not be resumed by the auto-manage * mechanism. */ public void pause() { s.pause(); } /** * Resuming will restore the torrents to their previous paused * state. i.e. the session pause state is separate from the torrent pause * state. A torrent is inactive if it is paused or if the session is * paused. */ public void resume() { s.resume(); } public boolean isPaused() { return s.is_paused(); } /** * returns the port we ended up listening on. Since you * just pass a port-range to the constructor and to ``listen_on()``, to * know which port it ended up using, you have to ask the session using * this function. * * @return */ public int getListenPort() { return s.listen_port(); } public int getSslListenPort() { return s.ssl_listen_port(); } /** * will tell you whether or not the session has * successfully opened a listening port. If it hasn't, this function will * return false, and then you can use ``listen_on()`` to make another * attempt. * * @return */ public boolean isListening() { return s.is_listening(); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @return */ public byte[] saveState() { entry e = new entry(); s.save_state(e); return Vectors.char_vector2bytes(e.bencode()); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @param data */ public void loadState(byte[] data) { char_vector buffer = Vectors.bytes2char_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { s.load_state(n); } else { LOG.error("failed to decode torrent: " + ec.message()); } } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. This flag is on by default. See add_torrent_params. * the ``flags`` argument is the same as for torrent_handle::status(). * see torrent_handle::status_flags_t. * * @param flags */ public void postTorrentUpdates(TorrentHandle.StatusFlags flags) { s.post_torrent_updates(flags.getSwig()); } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. */ public void postTorrentUpdates() { s.post_torrent_updates(); } /** * This function will post a {@link com.frostwire.jlibtorrent.alerts.SessionStatsAlert} object, containing a * snapshot of the performance counters from the internals of libtorrent. * To interpret these counters, query the session via * session_stats_metrics(). */ public void postSessionStats() { s.post_session_stats(); } /** * This will cause a dht_stats_alert to be posted. */ public void postDHTStats() { s.post_dht_stats(); } /** * Looks for a torrent with the given info-hash. In * case there is such a torrent in the session, a torrent_handle to that * torrent is returned. * <p/> * In case the torrent cannot be found, a null is returned. * * @param infoHash * @return */ public TorrentHandle findTorrent(Sha1Hash infoHash) { torrent_handle th = s.find_torrent(infoHash.getSwig()); return th != null && th.is_valid() ? new TorrentHandle(th) : null; } /** * Returns a list of torrent handles to all the * torrents currently in the session. * * @return */ public List<TorrentHandle> getTorrents() { torrent_handle_vector v = s.get_torrents(); long size = v.size(); List<TorrentHandle> l = new ArrayList<TorrentHandle>((int) size); for (int i = 0; i < size; i++) { l.add(new TorrentHandle(v.get(i))); } return l; } // starts/stops UPnP, NATPMP or LSD port mappers they are stopped by // default These functions are not available in case // ``TORRENT_DISABLE_DHT`` is defined. ``start_dht`` starts the dht node // and makes the trackerless service available to torrents. The startup // state is optional and can contain nodes and the node id from the // previous session. The dht node state is a bencoded dictionary with the // following entries: // // nodes // A list of strings, where each string is a node endpoint encoded in // binary. If the string is 6 bytes long, it is an IPv4 address of 4 // bytes, encoded in network byte order (big endian), followed by a 2 // byte port number (also network byte order). If the string is 18 // bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes // port number (also network byte order). // // node-id // The node id written as a readable string as a hexadecimal number. // // ``dht_state`` will return the current state of the dht node, this can // be used to start up the node again, passing this entry to // ``start_dht``. It is a good idea to save this to disk when the session // is closed, and read it up again when starting. // // If the port the DHT is supposed to listen on is already in use, and // exception is thrown, ``asio::error``. // // ``stop_dht`` stops the dht node. // // ``add_dht_node`` adds a node to the routing table. This can be used if // your client has its own source of bootstrapping nodes. // // ``set_dht_settings`` sets some parameters availavle to the dht node. // See dht_settings for more information. // // ``is_dht_running()`` returns true if the DHT support has been started // and false // otherwise. void setDHTSettings(DHTSettings settings) { s.set_dht_settings(settings.getSwig()); } public boolean isDHTRunning() { return s.is_dht_running(); } /** * takes a host name and port pair. That endpoint will be * pinged, and if a valid DHT reply is received, the node will be added to * the routing table. * * @param node */ public void addDHTNode(Pair<String, Integer> node) { s.add_dht_node(node.to_string_int_pair()); } /** * adds the given endpoint to a list of DHT router nodes. * If a search is ever made while the routing table is empty, those nodes will * be used as backups. Nodes in the router node list will also never be added * to the regular routing table, which effectively means they are only used * for bootstrapping, to keep the load off them. * <p/> * An example routing node that you could typically add is * ``router.bittorrent.com``. * * @param node */ public void addDHTRouter(Pair<String, Integer> node) { s.add_dht_router(node.to_string_int_pair()); } /** * Query the DHT for an immutable item at the target hash. * the result is posted as a {@link DhtImmutableItemAlert}. * * @param target */ public void dhtGetItem(Sha1Hash target) { s.dht_get_item(target.getSwig()); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key */ public void dhtGetItem(byte[] key) { s.dht_get_item(Vectors.bytes2char_vector(key)); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key * @param salt */ public void dhtGetItem(byte[] key, String salt) { s.dht_get_item(Vectors.bytes2char_vector(key), salt); } /** * Store the given bencoded data as an immutable item in the DHT. * the returned hash is the key that is to be used to look the item * up agan. It's just the sha-1 hash of the bencoded form of the * structure. * * @param entry * @return */ public Sha1Hash dhtPutItem(Entry entry) { return new Sha1Hash(s.dht_put_item(entry.getSwig())); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig()); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, String salt) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig(), salt); } public void dhtGetPeers(Sha1Hash infoHash) { s.dht_get_peers(infoHash.getSwig()); } public void dhtAnnounce(Sha1Hash infoHash, int port, int flags) { s.dht_announce(infoHash.getSwig(), port, flags); } public void dhtAnnounce(Sha1Hash infoHash) { s.dht_announce(infoHash.getSwig()); } public void dhtDirectRequest(UdpEndpoint endp, Entry entry) { s.dht_direct_request(endp.getSwig(), entry.getSwig()); } public void addExtension(Plugin p) { SwigPlugin sp = new SwigPlugin(p); s.add_swig_extension(sp); plugins.add(sp); } /** * add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP, * whichever is enabled. The return value is a handle referring to the * port mapping that was just created. Pass it to delete_port_mapping() * to remove it. * * @param t * @param externalPort * @param localPort * @return */ public int addPortMapping(ProtocolType t, int externalPort, int localPort) { return s.add_port_mapping(t.getSwig(), externalPort, localPort); } public void deletePortMapping(int handle) { s.delete_port_mapping(handle); } public SessionStats getStats() { return stats; } @Deprecated public SessionSettings getSettings() { return new SessionSettings(s.get_settings()); } @Deprecated public ProxySettings getProxy() { return new ProxySettings(new settings_pack()); } @Deprecated public void setProxy(ProxySettings s) { this.s.apply_settings(s.getSwig()); } @Deprecated public void setSettings(SessionSettings s) { this.applySettings(s.toPack()); } @Deprecated public SessionStatus getStatus() { return new SessionStatus(stats); } // You add torrents through the add_torrent() function where you give an // object with all the parameters. The add_torrent() overloads will block // until the torrent has been added (or failed to be added) and returns // an error code and a torrent_handle. In order to add torrents more // efficiently, consider using async_add_torrent() which returns // immediately, without waiting for the torrent to add. Notification of // the torrent being added is sent as add_torrent_alert. // // The overload that does not take an error_code throws an exception on // error and is not available when building without exception support. // The torrent_handle returned by add_torrent() can be used to retrieve // information about the torrent's progress, its peers etc. It is also // used to abort a torrent. // // If the torrent you are trying to add already exists in the session (is // either queued for checking, being checked or downloading) // ``add_torrent()`` will throw libtorrent_exception which derives from // ``std::exception`` unless duplicate_is_error is set to false. In that // case, add_torrent() will return the handle to the existing torrent. // // all torrent_handles must be destructed before the session is destructed! public TorrentHandle addTorrent(AddTorrentParams params) { return new TorrentHandle(s.add_torrent(params.getSwig())); } public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { return new TorrentHandle(s.add_torrent(params.getSwig(), ec.getSwig())); } public void asyncAddTorrent(AddTorrentParams params) { s.async_add_torrent(params.getSwig()); } @Override protected void finalize() throws Throwable { this.running = false; super.finalize(); } void fireAlert(Alert<?> a) { int type = a.getSwig() != null ? a.getSwig().type() : a.getType().getSwig(); fireAlert(a, type); fireAlert(a, -1); } private void fireAlert(Alert<?> a, int type) { AlertListener[] listeners = listenerSnapshots.get(type); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { try { AlertListener l = listeners[i]; if (l != null) { l.alert(a); } } catch (Throwable e) { LOG.warn("Error calling alert listener", e); } } } } private TorrentHandle addTorrentSupport(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile, boolean async) { String savePath = null; if (saveDir != null) { savePath = saveDir.getAbsolutePath(); } else if (resumeFile == null) { throw new IllegalArgumentException("Both saveDir and resumeFile can't be null at the same time"); } add_torrent_params p = add_torrent_params.create_instance(); p.set_ti(ti.getSwig()); if (savePath != null) { p.setSave_path(savePath); } if (priorities != null) { p.setFile_priorities(Vectors.priorities2unsigned_char_vector(priorities)); } p.setStorage_mode(storage_mode_t.storage_mode_sparse); long flags = p.getFlags(); flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue(); if (resumeFile != null) { try { byte[] data = Files.bytes(resumeFile); p.setResume_data(Vectors.bytes2char_vector(data)); flags |= add_torrent_params.flags_t.flag_use_resume_save_path.swigValue(); } catch (Throwable e) { LOG.warn("Unable to set resume data", e); } } p.setFlags(flags); if (async) { s.async_add_torrent(p); return null; } else { torrent_handle th = s.add_torrent(p); return new TorrentHandle(th); } } private void alertsLoop() { Runnable r = new Runnable() { @Override public void run() { alert_ptr_vector vector = new alert_ptr_vector(); high_resolution_clock.duration max_wait = libtorrent.to_milliseconds(ALERTS_LOOP_WAIT_MILLIS); while (running) { alert ptr = s.wait_for_alert(max_wait); if (ptr != null) { s.pop_alerts(vector); long size = vector.size(); for (int i = 0; i < size; i++) { alert swigAlert = vector.get(i); int type = swigAlert.type(); Alert<?> alert = null; if (type == AlertType.SESSION_STATS.getSwig()) { alert = Alerts.cast(swigAlert); updateSessionStat((SessionStatsAlert) alert); } if (listeners.indexOfKey(type) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, type); } if (type != AlertType.SESSION_STATS.getSwig() && listeners.indexOfKey(-1) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, -1); } } vector.clear(); } long now = System.currentTimeMillis(); if ((now - lastStatsRequestTime) >= REQUEST_STATS_RESOLUTION_MILLIS) { lastStatsRequestTime = now; postSessionStats(); } } } }; Thread t = new Thread(r, "Session-alertsLoop"); t.setDaemon(true); t.start(); } private void modifyListeners(boolean adding, AlertListener listener) { if (listener != null) { int[] types = listener.types(); //all alert-type including listener if (types == null) { modifyListeners(adding, -1, listener); } else { for (int i = 0; i < types.length; i++) { if (types[i] == -1) { throw new IllegalArgumentException("Type can't be the key of all (-1)"); } modifyListeners(adding, types[i], listener); } } } } private void modifyListeners(boolean adding, int type, AlertListener listener) { ArrayList<AlertListener> l = listeners.get(type); if (l == null) { l = new ArrayList<AlertListener>(); listeners.append(type, l); } if (adding) { l.add(listener); } else { l.remove(listener); } listenerSnapshots.append(type, l.toArray(new AlertListener[0])); } private static List<Pair<String, Integer>> defaultRouters() { List<Pair<String, Integer>> list = new LinkedList<Pair<String, Integer>>(); list.add(new Pair<String, Integer>("router.bittorrent.com", 6881)); list.add(new Pair<String, Integer>("dht.transmissionbt.com", 6881)); return list; } private void updateSessionStat(SessionStatsAlert alert) { long now = System.currentTimeMillis(); long tickIntervalMs = now - lastStatSecondTick; lastStatSecondTick = now; long received = alert.value(counters.stats_counter_t.recv_bytes.swigValue()); long payload = alert.value(counters.stats_counter_t.recv_payload_bytes.swigValue()); long protocol = received - payload; long ip = alert.value(counters.stats_counter_t.recv_ip_overhead_bytes.swigValue()); payload -= stat.downloadPayload(); protocol -= stat.downloadProtocol(); ip -= stat.downloadIPProtocol(); stat.received(payload, protocol, ip); long sent = alert.value(counters.stats_counter_t.sent_bytes.swigValue()); payload = alert.value(counters.stats_counter_t.sent_payload_bytes.swigValue()); protocol = sent - payload; ip = alert.value(counters.stats_counter_t.sent_ip_overhead_bytes.swigValue()); payload -= stat.uploadPayload(); protocol -= stat.uploadProtocol(); ip -= stat.uploadIPProtocol(); stat.sent(payload, protocol, ip); stat.secondTick(tickIntervalMs); } private static session createSession(SettingsPack settings, boolean logging) { settings_pack sp = settings.getSwig(); int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } // we always override alert_mask since we use it for our internal operations sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); return new session(sp); } private static session createSessionDeprecated(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } settings_pack sp = new settings_pack(); sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); sp.set_int(settings_pack.int_types.max_retry_port_bind.swigValue(), prange.second - prange.first); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), print.toString()); String if_string = String.format("%s:%d", iface, prange.first); sp.set_str(settings_pack.string_types.listen_interfaces.swigValue(), if_string); return new session(sp); } /** * Flags to be passed in to remove_torrent(). */ public enum Options { /** * Delete the files belonging to the torrent from disk. */ DELETE_FILES(options_t.delete_files.swigValue()), /** * */ UNKNOWN(-1); Options(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * protocols used by add_port_mapping(). */ public enum ProtocolType { UDP(session.protocol_type.udp), TCP(session.protocol_type.tcp); ProtocolType(session.protocol_type swigObj) { this.swigObj = swigObj; } private final session.protocol_type swigObj; public session.protocol_type getSwig() { return swigObj; } } }
src/main/java/com/frostwire/jlibtorrent/Session.java
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.alerts.*; import com.frostwire.jlibtorrent.plugins.Plugin; import com.frostwire.jlibtorrent.plugins.SwigPlugin; import com.frostwire.jlibtorrent.swig.*; import com.frostwire.jlibtorrent.swig.session_handle.options_t; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * The session holds all state that spans multiple torrents. Among other * things it runs the network loop and manages all torrents. Once it's * created, the session object will spawn the main thread that will do all * the work. The main thread will be idle as long it doesn't have any * torrents to participate in. * <p/> * This class belongs to a middle logical layer of abstraction. It's a wrapper * of the underlying swig session object (from libtorrent), but it does not * expose all the raw features, not expose a very high level interface * like {@link com.frostwire.jlibtorrent.DHT DHT} or * {@link com.frostwire.jlibtorrent.Downloader Downloader}. * * @author gubatron * @author aldenml */ public final class Session extends SessionHandle { private static final Logger LOG = Logger.getLogger(Session.class); private static final long REQUEST_STATS_RESOLUTION_MILLIS = 1000; private static final long ALERTS_LOOP_WAIT_MILLIS = 500; private final session s; private final JavaStat stat; private final SessionStats stats; private long lastStatsRequestTime; private long lastStatSecondTick; private final SparseArray<ArrayList<WeakReference<AlertListener>>> listeners; private final SparseArray<WeakReference<AlertListener>[]> listenerSnapshots; private boolean running; private final LinkedList<SwigPlugin> plugins; /** * The flag alert_mask is always set to all_categories. * * @param settings * @param logging */ public Session(SettingsPack settings, boolean logging) { super(createSession(settings, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<WeakReference<AlertListener>>>(); this.listenerSnapshots = new SparseArray<WeakReference<AlertListener>[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : defaultRouters()) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } @Deprecated public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { super(createSessionDeprecated(print, prange, iface, routers, logging)); this.s = (session) super.s; this.stat = new JavaStat(); this.stats = new SessionStats(stat); this.listeners = new SparseArray<ArrayList<WeakReference<AlertListener>>>(); this.listenerSnapshots = new SparseArray<WeakReference<AlertListener>[]>(); this.running = true; alertsLoop(); for (Pair<String, Integer> router : routers) { s.add_dht_router(router.to_string_int_pair()); } this.plugins = new LinkedList<SwigPlugin>(); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers) { this(print, prange, iface, routers, false); } public Session(Fingerprint print, Pair<Integer, Integer> prange, String iface) { this(print, prange, iface, defaultRouters()); } public Session(Fingerprint print) { this(print, new Pair<Integer, Integer>(0, 0), "0.0.0.0"); } public Session(Pair<Integer, Integer> prange, String iface) { this(new Fingerprint(), prange, iface); } public Session() { this(new SettingsPack(), false); } public session getSwig() { return s; } public void addListener(AlertListener listener) { modifyListeners(true, listener); } public void removeListener(AlertListener listener) { modifyListeners(false, listener); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param ti * @param saveDir * @param priorities * @param resumeFile * @return */ public TorrentHandle addTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { return addTorrentSupport(ti, saveDir, priorities, resumeFile, false); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile * @return */ public TorrentHandle addTorrent(File torrent, File saveDir, File resumeFile) { return addTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @return */ public TorrentHandle addTorrent(File torrent, File saveDir) { return addTorrent(torrent, saveDir, null); } /** * In order to add torrents more efficiently, consider using this which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * * @param ti * @param saveDir * @param priorities * @param resumeFile */ public void asyncAddTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) { addTorrentSupport(ti, saveDir, priorities, resumeFile, true); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir * @param resumeFile */ public void asyncAddTorrent(File torrent, File saveDir, File resumeFile) { asyncAddTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile); } /** * You add torrents through the add_torrent() function where you give an * object with all the parameters. The add_torrent() overloads will block * until the torrent has been added (or failed to be added) and returns * an error code and a torrent_handle. In order to add torrents more * efficiently, consider using async_add_torrent() which returns * immediately, without waiting for the torrent to add. Notification of * the torrent being added is sent as add_torrent_alert. * <p/> * The overload that does not take an error_code throws an exception on * error and is not available when building without exception support. * The torrent_handle returned by add_torrent() can be used to retrieve * information about the torrent's progress, its peers etc. It is also * used to abort a torrent. * <p/> * If the torrent you are trying to add already exists in the session (is * either queued for checking, being checked or downloading) * ``add_torrent()`` will throw libtorrent_exception which derives from * ``std::exception`` unless duplicate_is_error is set to false. In that * case, add_torrent() will return the handle to the existing torrent. * <p/> * all torrent_handles must be destructed before the session is destructed! * * @param torrent * @param saveDir */ public void asyncAddTorrent(File torrent, File saveDir) { asyncAddTorrent(torrent, saveDir, null); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * <p/> * The optional second argument options can be used to delete all the files downloaded * by this torrent. To do so, pass in the value session::delete_files. The removal of * the torrent is asyncronous, there is no guarantee that adding the same torrent immediately * after it was removed will not throw a libtorrent_exception exception. Once the torrent * is deleted, a torrent_deleted_alert is posted. * * @param th */ public void removeTorrent(TorrentHandle th, Options options) { s.remove_torrent(th.getSwig(), options.getSwig()); } /** * This method will close all peer connections associated with the torrent and tell the * tracker that we've stopped participating in the swarm. This operation cannot fail. * When it completes, you will receive a torrent_removed_alert. * * @param th */ public void removeTorrent(TorrentHandle th) { if (th.isValid()) { s.remove_torrent(th.getSwig()); } } /** * Applies the settings specified by the settings_pack ``sp``. This is an * asynchronous operation that will return immediately and actually apply * the settings to the main thread of libtorrent some time later. * * @param sp */ public void applySettings(SettingsPack sp) { s.apply_settings(sp.getSwig()); } /** * In case you want to destruct the session asynchrounously, you can * request a session destruction proxy. If you don't do this, the * destructor of the session object will block while the trackers are * contacted. If you keep one ``session_proxy`` to the session when * destructing it, the destructor will not block, but start to close down * the session, the destructor of the proxy will then synchronize the * threads. So, the destruction of the session is performed from the * ``session`` destructor call until the ``session_proxy`` destructor * call. The ``session_proxy`` does not have any operations on it (since * the session is being closed down, no operations are allowed on it). * The only valid operation is calling the destructor:: * * @return */ public SessionProxy abort() { running = false; return new SessionProxy(s.abort()); } /** * Pausing the session has the same effect as pausing every torrent in * it, except that torrents will not be resumed by the auto-manage * mechanism. */ public void pause() { s.pause(); } /** * Resuming will restore the torrents to their previous paused * state. i.e. the session pause state is separate from the torrent pause * state. A torrent is inactive if it is paused or if the session is * paused. */ public void resume() { s.resume(); } public boolean isPaused() { return s.is_paused(); } /** * returns the port we ended up listening on. Since you * just pass a port-range to the constructor and to ``listen_on()``, to * know which port it ended up using, you have to ask the session using * this function. * * @return */ public int getListenPort() { return s.listen_port(); } public int getSslListenPort() { return s.ssl_listen_port(); } /** * will tell you whether or not the session has * successfully opened a listening port. If it hasn't, this function will * return false, and then you can use ``listen_on()`` to make another * attempt. * * @return */ public boolean isListening() { return s.is_listening(); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @return */ public byte[] saveState() { entry e = new entry(); s.save_state(e); return Vectors.char_vector2bytes(e.bencode()); } /** * Loads and saves all session settings, including dht_settings, * encryption settings and proxy settings. ``save_state`` writes all keys * to the ``entry`` that's passed in, which needs to either not be * initialized, or initialized as a dictionary. * <p/> * ``load_state`` expects a lazy_entry which can be built from a bencoded * buffer with lazy_bdecode(). * <p/> * The ``flags`` arguments passed in to ``save_state`` can be used to * filter which parts of the session state to save. By default, all state * is saved (except for the individual torrents). see save_state_flags_t * * @param data */ public void loadState(byte[] data) { char_vector buffer = Vectors.bytes2char_vector(data); bdecode_node n = new bdecode_node(); error_code ec = new error_code(); int ret = bdecode_node.bdecode(buffer, n, ec); if (ret == 0) { s.load_state(n); } else { LOG.error("failed to decode torrent: " + ec.message()); } } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. This flag is on by default. See add_torrent_params. * the ``flags`` argument is the same as for torrent_handle::status(). * see torrent_handle::status_flags_t. * * @param flags */ public void postTorrentUpdates(TorrentHandle.StatusFlags flags) { s.post_torrent_updates(flags.getSwig()); } /** * This functions instructs the session to post the state_update_alert, * containing the status of all torrents whose state changed since the * last time this function was called. * <p/> * Only torrents who has the state subscription flag set will be * included. */ public void postTorrentUpdates() { s.post_torrent_updates(); } /** * This function will post a {@link com.frostwire.jlibtorrent.alerts.SessionStatsAlert} object, containing a * snapshot of the performance counters from the internals of libtorrent. * To interpret these counters, query the session via * session_stats_metrics(). */ public void postSessionStats() { s.post_session_stats(); } /** * This will cause a dht_stats_alert to be posted. */ public void postDHTStats() { s.post_dht_stats(); } /** * Looks for a torrent with the given info-hash. In * case there is such a torrent in the session, a torrent_handle to that * torrent is returned. * <p/> * In case the torrent cannot be found, a null is returned. * * @param infoHash * @return */ public TorrentHandle findTorrent(Sha1Hash infoHash) { torrent_handle th = s.find_torrent(infoHash.getSwig()); return th != null && th.is_valid() ? new TorrentHandle(th) : null; } /** * Returns a list of torrent handles to all the * torrents currently in the session. * * @return */ public List<TorrentHandle> getTorrents() { torrent_handle_vector v = s.get_torrents(); long size = v.size(); List<TorrentHandle> l = new ArrayList<TorrentHandle>((int) size); for (int i = 0; i < size; i++) { l.add(new TorrentHandle(v.get(i))); } return l; } // starts/stops UPnP, NATPMP or LSD port mappers they are stopped by // default These functions are not available in case // ``TORRENT_DISABLE_DHT`` is defined. ``start_dht`` starts the dht node // and makes the trackerless service available to torrents. The startup // state is optional and can contain nodes and the node id from the // previous session. The dht node state is a bencoded dictionary with the // following entries: // // nodes // A list of strings, where each string is a node endpoint encoded in // binary. If the string is 6 bytes long, it is an IPv4 address of 4 // bytes, encoded in network byte order (big endian), followed by a 2 // byte port number (also network byte order). If the string is 18 // bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes // port number (also network byte order). // // node-id // The node id written as a readable string as a hexadecimal number. // // ``dht_state`` will return the current state of the dht node, this can // be used to start up the node again, passing this entry to // ``start_dht``. It is a good idea to save this to disk when the session // is closed, and read it up again when starting. // // If the port the DHT is supposed to listen on is already in use, and // exception is thrown, ``asio::error``. // // ``stop_dht`` stops the dht node. // // ``add_dht_node`` adds a node to the routing table. This can be used if // your client has its own source of bootstrapping nodes. // // ``set_dht_settings`` sets some parameters availavle to the dht node. // See dht_settings for more information. // // ``is_dht_running()`` returns true if the DHT support has been started // and false // otherwise. void setDHTSettings(DHTSettings settings) { s.set_dht_settings(settings.getSwig()); } public boolean isDHTRunning() { return s.is_dht_running(); } /** * takes a host name and port pair. That endpoint will be * pinged, and if a valid DHT reply is received, the node will be added to * the routing table. * * @param node */ public void addDHTNode(Pair<String, Integer> node) { s.add_dht_node(node.to_string_int_pair()); } /** * adds the given endpoint to a list of DHT router nodes. * If a search is ever made while the routing table is empty, those nodes will * be used as backups. Nodes in the router node list will also never be added * to the regular routing table, which effectively means they are only used * for bootstrapping, to keep the load off them. * <p/> * An example routing node that you could typically add is * ``router.bittorrent.com``. * * @param node */ public void addDHTRouter(Pair<String, Integer> node) { s.add_dht_router(node.to_string_int_pair()); } /** * Query the DHT for an immutable item at the target hash. * the result is posted as a {@link DhtImmutableItemAlert}. * * @param target */ public void dhtGetItem(Sha1Hash target) { s.dht_get_item(target.getSwig()); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key */ public void dhtGetItem(byte[] key) { s.dht_get_item(Vectors.bytes2char_vector(key)); } /** * Query the DHT for a mutable item under the public key ``key``. * this is an ed25519 key. ``salt`` is optional and may be left * as an empty string if no salt is to be used. * if the item is found in the DHT, a dht_mutable_item_alert is * posted. * * @param key * @param salt */ public void dhtGetItem(byte[] key, String salt) { s.dht_get_item(Vectors.bytes2char_vector(key), salt); } /** * Store the given bencoded data as an immutable item in the DHT. * the returned hash is the key that is to be used to look the item * up agan. It's just the sha-1 hash of the bencoded form of the * structure. * * @param entry * @return */ public Sha1Hash dhtPutItem(Entry entry) { return new Sha1Hash(s.dht_put_item(entry.getSwig())); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig()); } // store an immutable item. The ``key`` is the public key the blob is // to be stored under. The optional ``salt`` argument is a string that // is to be mixed in with the key when determining where in the DHT // the value is to be stored. The callback function is called from within // the libtorrent network thread once we've found where to store the blob, // possibly with the current value stored under the key. // The values passed to the callback functions are: // // entry& value // the current value stored under the key (may be empty). Also expected // to be set to the value to be stored by the function. // // boost::array<char,64>& signature // the signature authenticating the current value. This may be zeroes // if there is currently no value stored. The functon is expected to // fill in this buffer with the signature of the new value to store. // To generate the signature, you may want to use the // ``sign_mutable_item`` function. // // boost::uint64_t& seq // current sequence number. May be zero if there is no current value. // The function is expected to set this to the new sequence number of // the value that is to be stored. Sequence numbers must be monotonically // increasing. Attempting to overwrite a value with a lower or equal // sequence number will fail, even if the signature is correct. // // std::string const& salt // this is the salt that was used for this put call. // // Since the callback function ``cb`` is called from within libtorrent, // it is critical to not perform any blocking operations. Ideally not // even locking a mutex. Pass any data required for this function along // with the function object's context and make the function entirely // self-contained. The only reason data blobs' values are computed // via a function instead of just passing in the new value is to avoid // race conditions. If you want to *update* the value in the DHT, you // must first retrieve it, then modify it, then write it back. The way // the DHT works, it is natural to always do a lookup before storing and // calling the callback in between is convenient. public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, String salt) { s.dht_put_item(Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey), entry.getSwig(), salt); } public void dhtGetPeers(Sha1Hash infoHash) { s.dht_get_peers(infoHash.getSwig()); } public void dhtAnnounce(Sha1Hash infoHash, int port, int flags) { s.dht_announce(infoHash.getSwig(), port, flags); } public void dhtAnnounce(Sha1Hash infoHash) { s.dht_announce(infoHash.getSwig()); } public void dhtDirectRequest(UdpEndpoint endp, Entry entry) { s.dht_direct_request(endp.getSwig(), entry.getSwig()); } public void addExtension(Plugin p) { SwigPlugin sp = new SwigPlugin(p); s.add_swig_extension(sp); plugins.add(sp); } /** * add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP, * whichever is enabled. The return value is a handle referring to the * port mapping that was just created. Pass it to delete_port_mapping() * to remove it. * * @param t * @param externalPort * @param localPort * @return */ public int addPortMapping(ProtocolType t, int externalPort, int localPort) { return s.add_port_mapping(t.getSwig(), externalPort, localPort); } public void deletePortMapping(int handle) { s.delete_port_mapping(handle); } public SessionStats getStats() { return stats; } @Deprecated public SessionSettings getSettings() { return new SessionSettings(s.get_settings()); } @Deprecated public ProxySettings getProxy() { return new ProxySettings(new settings_pack()); } @Deprecated public void setProxy(ProxySettings s) { this.s.apply_settings(s.getSwig()); } @Deprecated public void setSettings(SessionSettings s) { this.applySettings(s.toPack()); } @Deprecated public SessionStatus getStatus() { return new SessionStatus(stats); } // You add torrents through the add_torrent() function where you give an // object with all the parameters. The add_torrent() overloads will block // until the torrent has been added (or failed to be added) and returns // an error code and a torrent_handle. In order to add torrents more // efficiently, consider using async_add_torrent() which returns // immediately, without waiting for the torrent to add. Notification of // the torrent being added is sent as add_torrent_alert. // // The overload that does not take an error_code throws an exception on // error and is not available when building without exception support. // The torrent_handle returned by add_torrent() can be used to retrieve // information about the torrent's progress, its peers etc. It is also // used to abort a torrent. // // If the torrent you are trying to add already exists in the session (is // either queued for checking, being checked or downloading) // ``add_torrent()`` will throw libtorrent_exception which derives from // ``std::exception`` unless duplicate_is_error is set to false. In that // case, add_torrent() will return the handle to the existing torrent. // // all torrent_handles must be destructed before the session is destructed! public TorrentHandle addTorrent(AddTorrentParams params) { return new TorrentHandle(s.add_torrent(params.getSwig())); } public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) { return new TorrentHandle(s.add_torrent(params.getSwig(), ec.getSwig())); } public void asyncAddTorrent(AddTorrentParams params) { s.async_add_torrent(params.getSwig()); } @Override protected void finalize() throws Throwable { this.running = false; super.finalize(); } void fireAlert(Alert<?> a) { int type = a.getSwig() != null ? a.getSwig().type() : a.getType().getSwig(); fireAlert(a, type); fireAlert(a, -1); } private void fireAlert(Alert<?> a, int type) { WeakReference<AlertListener>[] listeners = listenerSnapshots.get(type); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { try { AlertListener l = listeners[i].get(); if (l != null) { l.alert(a); } } catch (Throwable e) { LOG.warn("Error calling alert listener", e); } } } } private TorrentHandle addTorrentSupport(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile, boolean async) { String savePath = null; if (saveDir != null) { savePath = saveDir.getAbsolutePath(); } else if (resumeFile == null) { throw new IllegalArgumentException("Both saveDir and resumeFile can't be null at the same time"); } add_torrent_params p = add_torrent_params.create_instance(); p.set_ti(ti.getSwig()); if (savePath != null) { p.setSave_path(savePath); } if (priorities != null) { p.setFile_priorities(Vectors.priorities2unsigned_char_vector(priorities)); } p.setStorage_mode(storage_mode_t.storage_mode_sparse); long flags = p.getFlags(); flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue(); if (resumeFile != null) { try { byte[] data = Files.bytes(resumeFile); p.setResume_data(Vectors.bytes2char_vector(data)); flags |= add_torrent_params.flags_t.flag_use_resume_save_path.swigValue(); } catch (Throwable e) { LOG.warn("Unable to set resume data", e); } } p.setFlags(flags); if (async) { s.async_add_torrent(p); return null; } else { torrent_handle th = s.add_torrent(p); return new TorrentHandle(th); } } private void alertsLoop() { Runnable r = new Runnable() { @Override public void run() { alert_ptr_vector vector = new alert_ptr_vector(); high_resolution_clock.duration max_wait = libtorrent.to_milliseconds(ALERTS_LOOP_WAIT_MILLIS); while (running) { alert ptr = s.wait_for_alert(max_wait); if (ptr != null) { s.pop_alerts(vector); long size = vector.size(); for (int i = 0; i < size; i++) { alert swigAlert = vector.get(i); int type = swigAlert.type(); Alert<?> alert = null; if (type == AlertType.SESSION_STATS.getSwig()) { alert = Alerts.cast(swigAlert); updateSessionStat((SessionStatsAlert) alert); } if (listeners.indexOfKey(type) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, type); } if (type != AlertType.SESSION_STATS.getSwig() && listeners.indexOfKey(-1) >= 0) { if (alert == null) { alert = Alerts.cast(swigAlert); } fireAlert(alert, -1); } } vector.clear(); } long now = System.currentTimeMillis(); if ((now - lastStatsRequestTime) >= REQUEST_STATS_RESOLUTION_MILLIS) { lastStatsRequestTime = now; postSessionStats(); } } } }; Thread t = new Thread(r, "Session-alertsLoop"); t.setDaemon(true); t.start(); } private void modifyListeners(boolean adding, AlertListener listener) { if (listener != null) { int[] types = listener.types(); //all alert-type including listener if (types == null) { modifyListeners(adding, -1, listener); } else { for (int i = 0; i < types.length; i++) { if (types[i] == -1) { throw new IllegalArgumentException("Type can't be the key of all (-1)"); } modifyListeners(adding, types[i], listener); } } } } @SuppressWarnings("unchecked") private void modifyListeners(boolean adding, int type, AlertListener listener) { ArrayList<WeakReference<AlertListener>> l = listeners.get(type); if (l == null) { l = new ArrayList<WeakReference<AlertListener>>(); listeners.append(type, l); } if (adding) { l.add(new WeakReference<AlertListener>(listener)); } else { Iterator<WeakReference<AlertListener>> iterator = l.iterator(); while (iterator.hasNext()) { WeakReference<AlertListener> ref = iterator.next(); if (ref.get() == listener) { iterator.remove(); } } } listenerSnapshots.append(type, l.toArray(new WeakReference[0])); } private static List<Pair<String, Integer>> defaultRouters() { List<Pair<String, Integer>> list = new LinkedList<Pair<String, Integer>>(); list.add(new Pair<String, Integer>("router.bittorrent.com", 6881)); list.add(new Pair<String, Integer>("dht.transmissionbt.com", 6881)); return list; } private void updateSessionStat(SessionStatsAlert alert) { long now = System.currentTimeMillis(); long tickIntervalMs = now - lastStatSecondTick; lastStatSecondTick = now; long received = alert.value(counters.stats_counter_t.recv_bytes.swigValue()); long payload = alert.value(counters.stats_counter_t.recv_payload_bytes.swigValue()); long protocol = received - payload; long ip = alert.value(counters.stats_counter_t.recv_ip_overhead_bytes.swigValue()); payload -= stat.downloadPayload(); protocol -= stat.downloadProtocol(); ip -= stat.downloadIPProtocol(); stat.received(payload, protocol, ip); long sent = alert.value(counters.stats_counter_t.sent_bytes.swigValue()); payload = alert.value(counters.stats_counter_t.sent_payload_bytes.swigValue()); protocol = sent - payload; ip = alert.value(counters.stats_counter_t.sent_ip_overhead_bytes.swigValue()); payload -= stat.uploadPayload(); protocol -= stat.uploadProtocol(); ip -= stat.uploadIPProtocol(); stat.sent(payload, protocol, ip); stat.secondTick(tickIntervalMs); } private static session createSession(SettingsPack settings, boolean logging) { settings_pack sp = settings.getSwig(); int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } // we always override alert_mask since we use it for our internal operations sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); return new session(sp); } private static session createSessionDeprecated(Fingerprint print, Pair<Integer, Integer> prange, String iface, List<Pair<String, Integer>> routers, boolean logging) { int alert_mask = alert.category_t.all_categories.swigValue(); if (!logging) { int log_mask = alert.category_t.session_log_notification.swigValue() | alert.category_t.torrent_log_notification.swigValue() | alert.category_t.peer_log_notification.swigValue() | alert.category_t.dht_log_notification.swigValue() | alert.category_t.port_mapping_log_notification.swigValue(); alert_mask = alert_mask & ~log_mask; } settings_pack sp = new settings_pack(); sp.set_int(settings_pack.int_types.alert_mask.swigValue(), alert_mask); sp.set_int(settings_pack.int_types.max_retry_port_bind.swigValue(), prange.second - prange.first); sp.set_str(settings_pack.string_types.peer_fingerprint.swigValue(), print.toString()); String if_string = String.format("%s:%d", iface, prange.first); sp.set_str(settings_pack.string_types.listen_interfaces.swigValue(), if_string); return new session(sp); } /** * Flags to be passed in to remove_torrent(). */ public enum Options { /** * Delete the files belonging to the torrent from disk. */ DELETE_FILES(options_t.delete_files.swigValue()), /** * */ UNKNOWN(-1); Options(int swigValue) { this.swigValue = swigValue; } private final int swigValue; public int getSwig() { return swigValue; } } /** * protocols used by add_port_mapping(). */ public enum ProtocolType { UDP(session.protocol_type.udp), TCP(session.protocol_type.tcp); ProtocolType(session.protocol_type swigObj) { this.swigObj = swigObj; } private final session.protocol_type swigObj; public session.protocol_type getSwig() { return swigObj; } } }
Reverting the weak reference change. Kind of bad idea at this moment.
src/main/java/com/frostwire/jlibtorrent/Session.java
Reverting the weak reference change. Kind of bad idea at this moment.
Java
mit
7fb08ec14ed24005b4eb68b31a2b724f494fb14c
0
bitcoin-solutions/multibit-hd,oscarguindzberg/multibit-hd,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,akonring/multibit-hd-modified,oscarguindzberg/multibit-hd
package org.multibit.hd.ui.views.wizards.receive_bitcoin; import com.google.bitcoin.uri.BitcoinURI; import com.google.common.base.Optional; import net.miginfocom.swing.MigLayout; import org.multibit.hd.ui.events.view.ViewEvents; import org.multibit.hd.ui.i18n.MessageKey; import org.multibit.hd.ui.views.components.*; import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressModel; import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressView; import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeModel; import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeView; import org.multibit.hd.ui.views.components.enter_amount.EnterAmountModel; import org.multibit.hd.ui.views.components.enter_amount.EnterAmountView; import org.multibit.hd.ui.views.wizards.AbstractWizard; import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView; import org.multibit.hd.ui.views.wizards.WizardButton; import javax.swing.*; import java.awt.event.ActionEvent; import java.math.BigInteger; /** * <p>View to provide the following to UI:</p> * <ul> * <li>Receive bitcoin: Enter amount</li> * </ul> * * @since 0.0.1 *   */ public class ReceiveBitcoinEnterAmountPanelView extends AbstractWizardPanelView<ReceiveBitcoinWizardModel, ReceiveBitcoinEnterAmountPanelModel> { // Panel specific components private ModelAndView<EnterAmountModel, EnterAmountView> enterAmountMaV; private ModelAndView<DisplayBitcoinAddressModel, DisplayBitcoinAddressView> displayBitcoinAddressMaV; private ModelAndView<DisplayQRCodeModel, DisplayQRCodeView> displayQRCodeMaV; private JTextField label; private JButton showQRCode; /** * @param wizard The wizard managing the states */ public ReceiveBitcoinEnterAmountPanelView(AbstractWizard<ReceiveBitcoinWizardModel> wizard, String panelName) { super(wizard.getWizardModel(), panelName, MessageKey.RECEIVE_BITCOIN_TITLE); PanelDecorator.addFinish(this, wizard); } @Override public void newPanelModel() { enterAmountMaV = Components.newEnterAmountMaV(getPanelName()); // TODO Link this to the recipient address service displayBitcoinAddressMaV = Components.newDisplayBitcoinAddressMaV("1AhN6rPdrMuKBGFDKR1k9A8SCLYaNgXhty"); // Create the QR code display displayQRCodeMaV = Components.newDisplayQRCodeMaV(); label = TextBoxes.newEnterLabel(); showQRCode = Buttons.newQRCodeButton(getShowQRCodePopoverAction()); // Configure the panel model setPanelModel(new ReceiveBitcoinEnterAmountPanelModel( getPanelName(), enterAmountMaV.getModel(), displayBitcoinAddressMaV.getModel() )); getWizardModel().setEnterAmountModel(enterAmountMaV.getModel()); getWizardModel().setTransactionLabel(label.getText()); } @Override public JPanel newWizardViewPanel() { JPanel panel = Panels.newPanel(new MigLayout( "fillx,insets 0", // Layout constraints "[][][]", // Column constraints "[]10[]" // Row constraints )); panel.add(enterAmountMaV.getView().newComponentPanel(), "span 3,wrap"); panel.add(Labels.newRecipient()); panel.add(displayBitcoinAddressMaV.getView().newComponentPanel(), "growx,push"); panel.add(showQRCode, "wrap"); panel.add(Labels.newTransactionLabel()); panel.add(label, "span 2,wrap"); return panel; } @Override public void fireInitialStateViewEvents() { // Finish button is always enabled ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, true); } @Override public void updateFromComponentModels(Optional componentModel) { // No need to update since we expose the component models // No view events to fire } /** * @return A new action for showing the QR code popover */ private Action getShowQRCodePopoverAction() { // Show or hide the QR code return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ReceiveBitcoinEnterAmountPanelModel model = getPanelModel().get(); String bitcoinAddress = model.getDisplayBitcoinAddressModel().getValue(); BigInteger satoshis = model.getEnterAmountModel().getSatoshis(); // Form a Bitcoin URI from the contents String bitcoinUri = BitcoinURI.convertToBitcoinURI( bitcoinAddress, satoshis, label.getText(), null ); displayQRCodeMaV.getModel().setValue(bitcoinUri); // Show the QR code as a popover Panels.showLightBoxPopover(displayQRCodeMaV.getView().newComponentPanel()); } }; } }
mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/receive_bitcoin/ReceiveBitcoinEnterAmountPanelView.java
package org.multibit.hd.ui.views.wizards.receive_bitcoin; import com.google.bitcoin.uri.BitcoinURI; import com.google.common.base.Optional; import net.miginfocom.swing.MigLayout; import org.multibit.hd.ui.i18n.MessageKey; import org.multibit.hd.ui.events.view.ViewEvents; import org.multibit.hd.ui.views.components.*; import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressModel; import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressView; import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeModel; import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeView; import org.multibit.hd.ui.views.components.enter_amount.EnterAmountModel; import org.multibit.hd.ui.views.components.enter_amount.EnterAmountView; import org.multibit.hd.ui.views.wizards.AbstractWizard; import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView; import org.multibit.hd.ui.views.wizards.WizardButton; import javax.swing.*; import java.awt.event.ActionEvent; import java.math.BigDecimal; import java.math.BigInteger; /** * <p>View to provide the following to UI:</p> * <ul> * <li>Receive bitcoin: Enter amount</li> * </ul> * * @since 0.0.1 *   */ public class ReceiveBitcoinEnterAmountPanelView extends AbstractWizardPanelView<ReceiveBitcoinWizardModel, ReceiveBitcoinEnterAmountPanelModel> { // Panel specific components private ModelAndView<EnterAmountModel, EnterAmountView> enterAmountMaV; private ModelAndView<DisplayBitcoinAddressModel, DisplayBitcoinAddressView> displayBitcoinAddressMaV; private ModelAndView<DisplayQRCodeModel, DisplayQRCodeView> displayQRCodeMaV; private JTextField label; private JButton showQRCode; /** * @param wizard The wizard managing the states */ public ReceiveBitcoinEnterAmountPanelView(AbstractWizard<ReceiveBitcoinWizardModel> wizard, String panelName) { super(wizard.getWizardModel(), panelName, MessageKey.RECEIVE_BITCOIN_TITLE); PanelDecorator.addCancelFinish(this, wizard); } @Override public void newPanelModel() { enterAmountMaV = Components.newEnterAmountMaV(getPanelName()); // TODO Link this to the recipient address service displayBitcoinAddressMaV = Components.newDisplayBitcoinAddressMaV("1AhN6rPdrMuKBGFDKR1k9A8SCLYaNgXhty"); // Create the QR code display displayQRCodeMaV = Components.newDisplayQRCodeMaV(); label = TextBoxes.newEnterLabel(); showQRCode = Buttons.newQRCodeButton(getShowQRCodePopoverAction()); // Configure the panel model setPanelModel(new ReceiveBitcoinEnterAmountPanelModel( getPanelName(), enterAmountMaV.getModel(), displayBitcoinAddressMaV.getModel() )); getWizardModel().setEnterAmountModel(enterAmountMaV.getModel()); getWizardModel().setTransactionLabel(label.getText()); } @Override public JPanel newWizardViewPanel() { JPanel panel = Panels.newPanel(new MigLayout( "fillx,insets 0", // Layout constraints "[][][]", // Column constraints "[]10[]" // Row constraints )); panel.add(enterAmountMaV.getView().newComponentPanel(), "span 3,wrap"); panel.add(Labels.newRecipient()); panel.add(displayBitcoinAddressMaV.getView().newComponentPanel(), "growx,push"); panel.add(showQRCode, "wrap"); panel.add(Labels.newTransactionLabel()); panel.add(label, "span 2,wrap"); return panel; } @Override public void fireInitialStateViewEvents() { // Disable the finish button ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, false); } @Override public void updateFromComponentModels(Optional componentModel) { // No need to update since we expose the component models // Determine any events ViewEvents.fireWizardButtonEnabledEvent( getPanelName(), WizardButton.NEXT, isNextEnabled() ); } /** * @return True if the "next" button should be enabled */ private boolean isNextEnabled() { return !getWizardModel().getSatoshis().equals(BigDecimal.ZERO); } /** * @return A new action for showing the QR code popover */ private Action getShowQRCodePopoverAction() { // Show or hide the QR code return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ReceiveBitcoinEnterAmountPanelModel model = getPanelModel().get(); String bitcoinAddress = model.getDisplayBitcoinAddressModel().getValue(); BigInteger satoshis = model.getEnterAmountModel().getSatoshis(); // Form a Bitcoin URI from the contents String bitcoinUri = BitcoinURI.convertToBitcoinURI( bitcoinAddress, satoshis, label.getText(), null ); displayQRCodeMaV.getModel().setValue(bitcoinUri); // Show the QR code as a popover Panels.showLightBoxPopover(displayQRCodeMaV.getView().newComponentPanel()); } }; } }
Set Finish to be permanently enabled on Receive panel Removed Cancel from Receive panel (useless)
mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/receive_bitcoin/ReceiveBitcoinEnterAmountPanelView.java
Set Finish to be permanently enabled on Receive panel Removed Cancel from Receive panel (useless)
Java
mit
ea0ead5adbfc37eb12806dfc83ceb4f944fb36e7
0
uq-eresearch/aorra,uq-eresearch/aorra,uq-eresearch/aorra,uq-eresearch/aorra
package charts.builder.spreadsheet; import static charts.ChartType.LOADS; import static charts.ChartType.LOADS_DIN; import static charts.ChartType.LOADS_PSII; import static charts.ChartType.LOADS_TN; import static charts.ChartType.LOADS_TSS; import static com.google.common.collect.Lists.newLinkedList; import static java.lang.String.format; import java.awt.Dimension; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.supercsv.io.CsvListWriter; import org.supercsv.prefs.CsvPreference; import charts.AbstractChart; import charts.Chart; import charts.ChartDescription; import charts.ChartType; import charts.Drawable; import charts.Region; import charts.builder.DataSource.MissingDataException; import charts.graphics.Loads; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; public class LoadsBuilder extends AbstractBuilder { private static final String PERIOD = "period"; private static final String TOTAL = "Total"; private static enum Indicator { TSS("Total suspended solids", true), TP("Total phosphorus", true), PP("Particulate phosphorus", true), DIP(false), DOP(false), TN("Total nitrogen", true), PN("Particulate nitrogen", true), DIN("Dissolved Inorganic nitrogen", true), DON(false), PSII("PSII pesticides", true); private String label; private boolean include; private Indicator(boolean include) { this.include = include; } private Indicator(String label, boolean include) { this(include); this.label = label; } public boolean include() { return include; } public String getLabel() { return label!=null?label:name(); } } private static final ImmutableMap<Region, Integer> ROWS = new ImmutableMap.Builder<Region, Integer>() .put(Region.CAPE_YORK, 5) .put(Region.WET_TROPICS, 6) .put(Region.BURDEKIN, 7) .put(Region.MACKAY_WHITSUNDAY, 8) .put(Region.FITZROY, 9) .put(Region.BURNETT_MARY, 10) .put(Region.GBR, 12) .build(); private static final ImmutableMap<ChartType, Indicator> INDICATORS = new ImmutableMap.Builder<ChartType, Indicator>() .put(LOADS_DIN, Indicator.DIN) .put(LOADS_TN, Indicator.TN) .put(LOADS_PSII, Indicator.PSII) .put(LOADS_TSS, Indicator.TSS) .build(); public LoadsBuilder() { super(Lists.newArrayList(LOADS, LOADS_DIN, LOADS_TN, LOADS_PSII, LOADS_TSS)); } @Override public boolean canHandle(SpreadsheetDataSource datasource) { return sheet(datasource) != -1; } private int sheet(SpreadsheetDataSource ds) { for(int i=0;i<ds.sheets();i++) { try { String name = ds.getSheetname(i); if(name != null) { if(StringUtils.equalsIgnoreCase("Region", ds.select(name, "C3").asString()) && StringUtils.equalsIgnoreCase("Total Change (%)", ds.select(name, "C12").asString())) { return i; } } } catch(Exception e) {} } return -1; } @Override protected Map<String, List<String>> getParameters(SpreadsheetDataSource datasource, ChartType type) { return new ImmutableMap.Builder<String, List<String>>() .put(PERIOD, Lists.newArrayList(TOTAL)) .build(); } private List<String> getPeriods(SpreadsheetDataSource ds) { try { List<String> periods = Lists.newArrayList(); int row = 2; for(int col = 3;true;col++) { String s = ds.select(row, col).asString(); if(StringUtils.isBlank(s) || periods.contains(s)) { return periods; } else { periods.add(s); } } } catch(MissingDataException e) { throw new RuntimeException(e); } } @Override public Chart build(final SpreadsheetDataSource datasource, final ChartType type, final Region region, Dimension queryDimensions, final Map<String, String> parameters) { int sheet = sheet(datasource); if(sheet == -1) { return null; } else { datasource.setDefaultSheet(sheet); } if(type == LOADS) { return buildLoads(datasource, type, region, queryDimensions, parameters); } else if(region == Region.GBR) { return buildLoadRegions(datasource, type, region, queryDimensions, parameters); } else { return null; } } public Chart buildLoadRegions(final SpreadsheetDataSource datasource, final ChartType type, final Region region, final Dimension queryDimensions, final Map<String, ?> parameters ) { final String period = (String)parameters.get(PERIOD); if(StringUtils.isBlank(period)) { return null; } final Indicator indicator = INDICATORS.get(type); if(indicator == null) { throw new RuntimeException(String.format("chart type %s not implemented", type.name())); } return new AbstractChart(queryDimensions) { @Override public ChartDescription getDescription() { return new ChartDescription(type, region, parameters); } @Override public Drawable getChart() { return Loads.createChart(getTitle(datasource, indicator, period), "Region", getRegionsDataset(datasource, indicator, period), new Dimension(750, 500)); } @Override public String getCSV() throws UnsupportedFormatException { final StringWriter sw = new StringWriter(); try { final CategoryDataset dataset = getRegionsDataset(datasource, indicator, period); final CsvListWriter csv = new CsvListWriter(sw, CsvPreference.STANDARD_PREFERENCE); @SuppressWarnings("unchecked") List<String> columnKeys = dataset.getColumnKeys(); @SuppressWarnings("unchecked") List<String> rowKeys = dataset.getRowKeys(); final List<String> heading = ImmutableList.<String>builder() .add(format("%s %s %s load reductions", region, indicator, period)) .addAll(rowKeys) .build(); csv.write(heading); for (String col : columnKeys) { List<String> line = newLinkedList(); line.add(col); for (String row : rowKeys) { line.add(format("%.1f", dataset.getValue(row, col).doubleValue())); } csv.write(line); } csv.close(); } catch (IOException e) { // How on earth would you get an IOException with a StringWriter? throw new RuntimeException(e); } return sw.toString(); } @Override public String getCommentary() throws UnsupportedFormatException { throw new UnsupportedFormatException(); }}; } private Chart buildLoads(final SpreadsheetDataSource datasource, final ChartType type, final Region region, Dimension queryDimensions, final Map<String, ?> parameters) { final String period = (String)parameters.get(PERIOD); if(StringUtils.isBlank(period)) { return null; } return new AbstractChart(queryDimensions) { @Override public ChartDescription getDescription() { return new ChartDescription(type, region, parameters); } @Override public Drawable getChart() { return Loads.createChart(getTitle(datasource, region, period), "Pollutants", getDataset(datasource, region, period), new Dimension(750, 500)); } @Override public String getCSV() throws UnsupportedFormatException { final StringWriter sw = new StringWriter(); try { final CategoryDataset dataset = getDataset(datasource, region, period); final CsvListWriter csv = new CsvListWriter(sw, CsvPreference.STANDARD_PREFERENCE); @SuppressWarnings("unchecked") List<String> columnKeys = dataset.getColumnKeys(); @SuppressWarnings("unchecked") List<String> rowKeys = dataset.getRowKeys(); final List<String> heading = ImmutableList.<String>builder() .add(format("%s %s load reductions", region, period)) .addAll(rowKeys) .build(); csv.write(heading); for (String col : columnKeys) { List<String> line = newLinkedList(); line.add(col); for (String row : rowKeys) { line.add(format("%.1f", dataset.getValue(row, col).doubleValue())); } csv.write(line); } csv.close(); } catch (IOException e) { // How on earth would you get an IOException with a StringWriter? throw new RuntimeException(e); } return sw.toString(); } @Override public String getCommentary() throws UnsupportedFormatException { throw new UnsupportedFormatException(); }}; } private CategoryDataset getRegionsDataset(SpreadsheetDataSource ds, Indicator indicator, String period) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(Region region : Region.values()) { Integer row = ROWS.get(region); if(row == null) { throw new RuntimeException(String.format("region %s not configured", region.getName())); } try { double val = selectAsDouble(ds, region, indicator, period); dataset.addValue(val, indicator.getLabel(), region.getProperName()); } catch(Exception e) { throw new RuntimeException("region "+region.getName(), e); } } return dataset; } private CategoryDataset getDataset(SpreadsheetDataSource ds, Region region, String period) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Integer row = ROWS.get(region); if(row == null) { throw new RuntimeException("unknown region "+region); } row--; try { for(Indicator indicator : Indicator.values()) { if(indicator.include()) { dataset.addValue(selectAsDouble(ds, region, indicator, period), region.getProperName() , indicator.getLabel()); } } return dataset; } catch(MissingDataException e) { throw new RuntimeException(e); } } private Double selectAsDouble(SpreadsheetDataSource ds, Region region, Indicator indicator, String period) throws MissingDataException { List<String> periods = getPeriods(ds); int row = ROWS.get(region) - 1; int col = indicator.ordinal() * periods.size() + periods.indexOf(period) + 3; return ds.select(row, col).asDouble(); } private String getTitle(SpreadsheetDataSource ds, Indicator indicator, String period) { return getTitle(ds, indicator.getLabel() + " load reductions from\n", period); } private String getTitle(SpreadsheetDataSource ds, Region region, String period) { String title = region.getProperName() + " total load reductions from\n"; return getTitle(ds, title, period); } private String getTitle(SpreadsheetDataSource ds, String prefix, String period) { String title = prefix; List<String> periods = getPeriods(ds); if(StringUtils.equalsIgnoreCase(period, TOTAL)) { title += formatPeriods(periods, -1, periods.size()-2); } else { int start = periods.indexOf(period); title += formatPeriods(periods, start-1, start); } return title; } private String formatPeriods(List<String> periods, int start, int end) { if(start == -1) { return " the baseline (2008-2009) to " + formatPeriod(periods.get(end)); } else { return formatPeriod(periods.get(start)) + " to " + formatPeriod(periods.get(end)); } } private String formatPeriod(String period) { try { String p = StringUtils.substringBetween(period, "(", ")"); String[] sa = StringUtils.split(p, "/"); if(sa[0].length() == 2 && sa[1].length() == 2) { return "20"+sa[0]+"-"+"20"+sa[1]; } return period; } catch(Exception e) { return period; } } }
app/charts/builder/spreadsheet/LoadsBuilder.java
package charts.builder.spreadsheet; import static charts.ChartType.LOADS; import static charts.ChartType.LOADS_DIN; import static charts.ChartType.LOADS_PSII; import static charts.ChartType.LOADS_TN; import static charts.ChartType.LOADS_TSS; import static com.google.common.collect.Lists.newLinkedList; import static java.lang.String.format; import java.awt.Dimension; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.supercsv.io.CsvListWriter; import org.supercsv.prefs.CsvPreference; import charts.AbstractChart; import charts.Chart; import charts.ChartDescription; import charts.ChartType; import charts.Drawable; import charts.Region; import charts.builder.DataSource.MissingDataException; import charts.graphics.Loads; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; public class LoadsBuilder extends AbstractBuilder { private static final String PERIOD = "period"; private static final String TOTAL = "Total"; private static enum Indicator { TSS("Total suspended solids", true), TP("Total phosphorus", true), PP("Particulate phosphorus", true), DIP(false), DOP(false), TN("Total nitrogen", true), PN("Particulate nitrogen", true), DIN("Dissolved Inorganic nitrogen", true), DON(false), PSII("PSII pesticides", true); private String label; private boolean include; private Indicator(boolean include) { this.include = include; } private Indicator(String label, boolean include) { this(include); this.label = label; } public boolean include() { return include; } public String getLabel() { return label!=null?label:name(); } } private static final ImmutableMap<Region, Integer> ROWS = new ImmutableMap.Builder<Region, Integer>() .put(Region.CAPE_YORK, 5) .put(Region.WET_TROPICS, 6) .put(Region.BURDEKIN, 7) .put(Region.MACKAY_WHITSUNDAY, 8) .put(Region.FITZROY, 9) .put(Region.BURNETT_MARY, 10) .put(Region.GBR, 12) .build(); private static final ImmutableMap<ChartType, Indicator> INDICATORS = new ImmutableMap.Builder<ChartType, Indicator>() .put(LOADS_DIN, Indicator.DIN) .put(LOADS_TN, Indicator.TN) .put(LOADS_PSII, Indicator.PSII) .put(LOADS_TSS, Indicator.TSS) .build(); public LoadsBuilder() { super(Lists.newArrayList(LOADS, LOADS_DIN, LOADS_TN, LOADS_PSII, LOADS_TSS)); } @Override public boolean canHandle(SpreadsheetDataSource datasource) { return sheet(datasource) != -1; } private int sheet(SpreadsheetDataSource ds) { for(int i=0;i<ds.sheets();i++) { try { String name = ds.getSheetname(i); if(name != null) { if(StringUtils.equalsIgnoreCase("Region", ds.select(name, "C3").asString()) && StringUtils.equalsIgnoreCase("Total Change (%)", ds.select(name, "C12").asString())) { return i; } } } catch(Exception e) {} } return -1; } @Override protected Map<String, List<String>> getParameters(SpreadsheetDataSource datasource, ChartType type) { return new ImmutableMap.Builder<String, List<String>>() .put(PERIOD, Lists.newArrayList(TOTAL)) .build(); } private List<String> getPeriods(SpreadsheetDataSource ds) { try { List<String> periods = Lists.newArrayList(); int row = 2; for(int col = 3;true;col++) { String s = ds.select(row, col).asString(); if(StringUtils.isBlank(s) || periods.contains(s)) { return periods; } else { periods.add(s); } } } catch(MissingDataException e) { throw new RuntimeException(e); } } @Override public Chart build(final SpreadsheetDataSource datasource, final ChartType type, final Region region, Dimension queryDimensions, final Map<String, String> parameters) { int sheet = sheet(datasource); if(sheet == -1) { return null; } else { datasource.setDefaultSheet(sheet); } if(type == LOADS) { return buildLoads(datasource, type, region, queryDimensions, parameters); } else if(region == Region.GBR) { return buildLoadRegions(datasource, type, region, queryDimensions, parameters); } else { return null; } } public Chart buildLoadRegions(final SpreadsheetDataSource datasource, final ChartType type, final Region region, final Dimension queryDimensions, final Map<String, ?> parameters ) { final String period = (String)parameters.get(PERIOD); if(StringUtils.isBlank(period)) { return null; } final Indicator indicator = INDICATORS.get(type); if(indicator == null) { throw new RuntimeException(String.format("chart type %s not implemented", type.name())); } return new AbstractChart(queryDimensions) { @Override public ChartDescription getDescription() { return new ChartDescription(type, region, parameters); } @Override public Drawable getChart() { return Loads.createChart(getTitle(datasource, indicator, period), "Region", getRegionsDataset(datasource, indicator, period), new Dimension(750, 500)); } @Override public String getCSV() throws UnsupportedFormatException { final StringWriter sw = new StringWriter(); try { final CategoryDataset dataset = getRegionsDataset(datasource, indicator, period); final CsvListWriter csv = new CsvListWriter(sw, CsvPreference.STANDARD_PREFERENCE); @SuppressWarnings("unchecked") List<String> columnKeys = dataset.getColumnKeys(); @SuppressWarnings("unchecked") List<String> rowKeys = dataset.getRowKeys(); final List<String> heading = ImmutableList.<String>builder() .add(format("%s %s %s load reductions", region, indicator, period)) .addAll(rowKeys) .build(); csv.write(heading); for (String col : columnKeys) { List<String> line = newLinkedList(); line.add(col); for (String row : rowKeys) { line.add(format("%.1f", dataset.getValue(row, col).doubleValue())); } csv.write(line); } csv.close(); } catch (IOException e) { // How on earth would you get an IOException with a StringWriter? throw new RuntimeException(e); } return sw.toString(); } @Override public String getCommentary() throws UnsupportedFormatException { throw new UnsupportedFormatException(); }}; } private Chart buildLoads(final SpreadsheetDataSource datasource, final ChartType type, final Region region, Dimension queryDimensions, final Map<String, ?> parameters) { final String period = (String)parameters.get(PERIOD); if(StringUtils.isBlank(period)) { return null; } final CategoryDataset dataset = getDataset(datasource, region, period); return new AbstractChart(queryDimensions) { @Override public ChartDescription getDescription() { return new ChartDescription(type, region, parameters); } @Override public Drawable getChart() { return Loads.createChart(getTitle(datasource, region, period), "Pollutants", dataset, new Dimension(750, 500)); } @Override public String getCSV() throws UnsupportedFormatException { throw new UnsupportedFormatException(); } @Override public String getCommentary() throws UnsupportedFormatException { throw new UnsupportedFormatException(); }}; } private CategoryDataset getRegionsDataset(SpreadsheetDataSource ds, Indicator indicator, String period) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(Region region : Region.values()) { Integer row = ROWS.get(region); if(row == null) { throw new RuntimeException(String.format("region %s not configured", region.getName())); } try { double val = selectAsDouble(ds, region, indicator, period); dataset.addValue(val, indicator.getLabel(), region.getProperName()); } catch(Exception e) { throw new RuntimeException("region "+region.getName(), e); } } return dataset; } private CategoryDataset getDataset(SpreadsheetDataSource ds, Region region, String period) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Integer row = ROWS.get(region); if(row == null) { throw new RuntimeException("unknown region "+region); } row--; try { for(Indicator indicator : Indicator.values()) { if(indicator.include()) { dataset.addValue(selectAsDouble(ds, region, indicator, period), region.getProperName() , indicator.getLabel()); } } return dataset; } catch(MissingDataException e) { throw new RuntimeException(e); } } private Double selectAsDouble(SpreadsheetDataSource ds, Region region, Indicator indicator, String period) throws MissingDataException { List<String> periods = getPeriods(ds); int row = ROWS.get(region) - 1; int col = indicator.ordinal() * periods.size() + periods.indexOf(period) + 3; return ds.select(row, col).asDouble(); } private String getTitle(SpreadsheetDataSource ds, Indicator indicator, String period) { return getTitle(ds, indicator.getLabel() + " load reductions from\n", period); } private String getTitle(SpreadsheetDataSource ds, Region region, String period) { String title = region.getProperName() + " total load reductions from\n"; return getTitle(ds, title, period); } private String getTitle(SpreadsheetDataSource ds, String prefix, String period) { String title = prefix; List<String> periods = getPeriods(ds); if(StringUtils.equalsIgnoreCase(period, TOTAL)) { title += formatPeriods(periods, -1, periods.size()-2); } else { int start = periods.indexOf(period); title += formatPeriods(periods, start-1, start); } return title; } private String formatPeriods(List<String> periods, int start, int end) { if(start == -1) { return " the baseline (2008-2009) to " + formatPeriod(periods.get(end)); } else { return formatPeriod(periods.get(start)) + " to " + formatPeriod(periods.get(end)); } } private String formatPeriod(String period) { try { String p = StringUtils.substringBetween(period, "(", ")"); String[] sa = StringUtils.split(p, "/"); if(sa[0].length() == 2 && sa[1].length() == 2) { return "20"+sa[0]+"-"+"20"+sa[1]; } return period; } catch(Exception e) { return period; } } }
Adding CSV output for loads.
app/charts/builder/spreadsheet/LoadsBuilder.java
Adding CSV output for loads.
Java
epl-1.0
467b613c5cba11126b4f0194d832c96fb797abd8
0
tobiasbaum/reviewtool
package de.setsoftware.reviewtool.model.changestructure; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Display; import de.setsoftware.reviewtool.base.Logger; import de.setsoftware.reviewtool.base.Pair; import de.setsoftware.reviewtool.base.ReviewtoolException; import de.setsoftware.reviewtool.base.WeakListeners; import de.setsoftware.reviewtool.model.Constants; import de.setsoftware.reviewtool.model.api.IBinaryChange; import de.setsoftware.reviewtool.model.api.IChange; import de.setsoftware.reviewtool.model.api.IChangeData; import de.setsoftware.reviewtool.model.api.IChangeSource; import de.setsoftware.reviewtool.model.api.IChangeSourceUi; import de.setsoftware.reviewtool.model.api.IChangeVisitor; import de.setsoftware.reviewtool.model.api.ICommit; import de.setsoftware.reviewtool.model.api.IFileHistoryNode; import de.setsoftware.reviewtool.model.api.IFragment; import de.setsoftware.reviewtool.model.api.IFragmentTracer; import de.setsoftware.reviewtool.model.api.IRevisionedFile; import de.setsoftware.reviewtool.model.api.ITextualChange; import de.setsoftware.reviewtool.ordering.efficientalgorithm.TourCalculatorControl; import de.setsoftware.reviewtool.telemetry.Telemetry; /** * Manages the current state regarding the changes/tours under review. */ public class ToursInReview { /** * Interface for observers of instances of {@link ToursInReview}. */ public static interface IToursInReviewChangeListener { /** * Is called when the available tours change (e.g. due to a merge or split). */ public abstract void toursChanged(); /** * Is called when the active tour changes. Will not be called when the active tour * changes together with the tours as a whole. Both arguments can be null, meaning that * there is no respective tour. */ public abstract void activeTourChanged(Tour oldActive, Tour newActive); } /** * Interface for user interaction during the creation of {@link ToursInReview}. */ public static interface ICreateToursUi { /** * Lets the user choose one of the given tour structures. * The given list contains pairs with a description of the merge algorithm and the resulting tours. * There always is at least one choice. * When the user cancels, null is returned. */ public abstract List<? extends Tour> selectInitialTours( List<? extends Pair<String, List<? extends Tour>>> choices); /** * Lets the user choose which subset of commits to review, which filters * to apply and which of the commits to merge into a tour. * When the user cancels, null is returned. * * @param changes All commits belonging to the review. * @param strategyResults Pairs with a description of the filter strategy and the resulting filter candidates * @param reviewRounds The review rounds conducted so far (to show them to the user). */ public abstract UserSelectedReductions selectIrrelevant( List<? extends ICommit> changes, List<Pair<String, Set<? extends IChange>>> strategyResults, List<ReviewRoundInfo> reviewRounds); } /** * Transfer object for the results of the user interaction to select * subset of commits, filters, ... */ public static final class UserSelectedReductions { private final List<? extends ICommit> commitSubset; private final List<? extends Pair<String, Set<? extends IChange>>> toMakeIrrelevant; public UserSelectedReductions( List<? extends ICommit> chosenCommitSubset, List<Pair<String, Set<? extends IChange>>> chosenFilterSubset) { this.commitSubset = chosenCommitSubset; this.toMakeIrrelevant = chosenFilterSubset; } } /** * Infos on a review round. */ public static final class ReviewRoundInfo implements Comparable<ReviewRoundInfo> { private final int number; private final Date date; private final String user; public ReviewRoundInfo(int number, Date date, String user) { this.number = number; this.date = date; this.user = user; } @Override public int compareTo(ReviewRoundInfo o) { return Integer.compare(this.number, o.number); } @Override public boolean equals(Object o) { if (!(o instanceof ReviewRoundInfo)) { return false; } return this.compareTo((ReviewRoundInfo) o) == 0; } @Override public int hashCode() { return this.number; } public Date getTime() { return this.date; } public String getReviewer() { return this.user; } public int getNumber() { return this.number; } } private final VirtualFileHistoryGraph historyGraph; private final List<Tour> topmostTours; private final IChangeData remoteChanges; private Map<File, IRevisionedFile> modifiedFiles; private int currentTourIndex; private final WeakListeners<IToursInReviewChangeListener> listeners = new WeakListeners<>(); private ToursInReview(final List<? extends Tour> topmostTours, final IChangeData remoteChanges) { this.historyGraph = new VirtualFileHistoryGraph(remoteChanges.getHistoryGraph()); this.topmostTours = new ArrayList<>(topmostTours); this.remoteChanges = remoteChanges; this.modifiedFiles = remoteChanges.getLocalPathMap(); this.currentTourIndex = 0; } private ToursInReview(final List<? extends Tour> topmostTours) { this.historyGraph = new VirtualFileHistoryGraph(); this.topmostTours = new ArrayList<>(topmostTours); this.remoteChanges = null; this.modifiedFiles = new LinkedHashMap<>(); this.currentTourIndex = 0; } /** * Creates a new object with the given tours (mainly for tests). */ public static ToursInReview create(List<Tour> tours) { return new ToursInReview(tours); } /** * Loads the tours for the given ticket and creates a corresponding {@link ToursInReview} * object with initial settings. When there is user interaction and the user cancels, * null is returned. */ public static ToursInReview create( IChangeSource src, final IChangeSourceUi changeSourceUi, List<? extends IIrrelevanceDetermination> irrelevanceDeterminationStrategies, List<? extends ITourRestructuring> tourRestructuringStrategies, IStopOrdering orderingAlgorithm, ICreateToursUi createUi, String ticketKey, List<ReviewRoundInfo> reviewRounds) { changeSourceUi.subTask("Determining relevant changes..."); final IChangeData changes = src.getRepositoryChanges(ticketKey, changeSourceUi); changeSourceUi.subTask("Filtering changes..."); final List<? extends ICommit> filteredChanges = filterChanges(irrelevanceDeterminationStrategies, changes.getMatchedCommits(), createUi, changeSourceUi, reviewRounds); if (filteredChanges == null) { return null; } changeSourceUi.subTask("Creating tours from changes..."); final List<Tour> tours = toTours( filteredChanges, new FragmentTracer(changes.getHistoryGraph()), changeSourceUi); final List<? extends Tour> userSelection = determinePossibleRestructurings(tourRestructuringStrategies, tours, createUi, changeSourceUi); if (userSelection == null) { return null; } changeSourceUi.subTask("Ordering stops..."); final List<? extends Tour> toursToShow = groupAndSort( userSelection, orderingAlgorithm, new TourCalculatorControl() { private static final long FAST_MODE_THRESHOLD = 20000; private final long startTime = System.currentTimeMillis(); @Override public synchronized boolean isCanceled() { return changeSourceUi.isCanceled(); } @Override public boolean isFastModeNeeded() { return System.currentTimeMillis() - this.startTime > FAST_MODE_THRESHOLD; } }); final ToursInReview result = new ToursInReview(toursToShow, changes); result.createLocalTour(null, changeSourceUi, null); return result; } private static List<? extends Tour> groupAndSort( List<? extends Tour> userSelection, IStopOrdering orderingAlgorithm, TourCalculatorControl isCanceled) { try { final List<Tour> ret = new ArrayList<>(); for (final Tour t : userSelection) { ret.add(new Tour(t.getDescription(), orderingAlgorithm.groupAndSort(t.getStops(), isCanceled))); } return ret; } catch (final InterruptedException e) { throw new OperationCanceledException(); } } /** * (Re)creates the local tour by (re)collecting local changes and combining them with the repository changes * in a {@link VirtualFileHistoryGraph}. * * @param progressMonitor The progress monitor to use. * @param markerFactory The marker factory to use. May be null if initially called while creating the tours. */ public void createLocalTour( final List<File> paths, final IProgressMonitor progressMonitor, final IStopMarkerFactory markerFactory) { progressMonitor.subTask("Collecting local changes..."); final IChangeData localChanges; try { if (paths == null) { localChanges = this.remoteChanges.getSource().getLocalChanges(this.remoteChanges, null, progressMonitor); } else { final List<File> allFilesToAnalyze = new ArrayList<>(this.modifiedFiles.keySet()); allFilesToAnalyze.addAll(paths); localChanges = this.remoteChanges.getSource().getLocalChanges(this.remoteChanges, allFilesToAnalyze, progressMonitor); } } catch (final ReviewtoolException e) { //if there is a problem while determining the local changes, ignore them Logger.warn("problem while determining local changes", e); return; } this.modifiedFiles = new LinkedHashMap<>(localChanges.getLocalPathMap()); if (this.historyGraph.size() > 1) { this.historyGraph.remove(1); } this.historyGraph.add(localChanges.getHistoryGraph()); this.updateMostRecentFragmentsWithLocalChanges(); this.notifyListenersAboutTourStructureChange(markerFactory); } private void updateMostRecentFragmentsWithLocalChanges() { final IFragmentTracer tracer = new FragmentTracer(this.historyGraph); for (final Tour tour : this.topmostTours) { for (final Stop stop : tour.getStops()) { stop.updateMostRecentData(tracer); } } } private static List<? extends ICommit> filterChanges( final List<? extends IIrrelevanceDetermination> irrelevanceDeterminationStrategies, final List<? extends ICommit> changes, final ICreateToursUi createUi, final IProgressMonitor progressMonitor, final List<ReviewRoundInfo> reviewRounds) { Telemetry.event("originalChanges") .param("count", countChanges(changes, false)) .param("relevant", countChanges(changes, true)) .log(); final List<Pair<String, Set<? extends IChange>>> strategyResults = new ArrayList<>(); for (final IIrrelevanceDetermination strategy : irrelevanceDeterminationStrategies) { try { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } final Set<? extends IChange> irrelevantChanges = determineIrrelevantChanges(changes, strategy); Telemetry.event("relevanceFilterResult") .param("description", strategy.getDescription()) .param("size", irrelevantChanges.size()) .log(); if (areAllIrrelevant(irrelevantChanges)) { //skip strategies that won't result in further changes to irrelevant continue; } strategyResults.add(Pair.<String, Set<? extends IChange>>create( strategy.getDescription(), irrelevantChanges)); } catch (final Exception e) { //skip instable strategies Logger.error("exception in filtering", e); } } final UserSelectedReductions selected = createUi.selectIrrelevant(changes, strategyResults, reviewRounds); if (selected == null) { return null; } final Set<IChange> toMakeIrrelevant = new HashSet<>(); final Set<String> selectedDescriptions = new LinkedHashSet<>(); for (final Pair<String, Set<? extends IChange>> set : selected.toMakeIrrelevant) { toMakeIrrelevant.addAll(set.getSecond()); selectedDescriptions.add(set.getFirst()); } Telemetry.event("selectedRelevanceFilter") .param("descriptions", selectedDescriptions) .log(); final Set<String> selectedCommits = new LinkedHashSet<>(); for (final ICommit commit : selected.commitSubset) { selectedCommits.add(commit.getRevision().toString()); } Telemetry.event("selectedCommitSubset") .param("commits", selectedCommits) .log(); final List<ICommit> ret = new ArrayList<>(); for (final ICommit c : selected.commitSubset) { ret.add(c.makeChangesIrrelevant(toMakeIrrelevant)); } return ret; } private static int countChanges(List<? extends ICommit> changes, boolean onlyRelevant) { int ret = 0; for (final ICommit commit : changes) { for (final IChange change : commit.getChanges()) { if (!(onlyRelevant && change.isIrrelevantForReview())) { ret++; } } } return ret; } private static Set<? extends IChange> determineIrrelevantChanges( List<? extends ICommit> changes, IIrrelevanceDetermination strategy) { final Set<IChange> ret = new HashSet<>(); for (final ICommit commit : changes) { for (final IChange change : commit.getChanges()) { if (strategy.isIrrelevant(change)) { ret.add(change); } } } return ret; } private static boolean areAllIrrelevant(Set<? extends IChange> changes) { for (final IChange change : changes) { if (!change.isIrrelevantForReview()) { return false; } } return true; } private static List<? extends Tour> determinePossibleRestructurings( final List<? extends ITourRestructuring> tourRestructuringStrategies, final List<Tour> originalTours, final ICreateToursUi createUi, final IProgressMonitor progressMonitor) { final List<Pair<String, List<? extends Tour>>> possibleRestructurings = new ArrayList<>(); possibleRestructurings.add(Pair.<String, List<? extends Tour>>create("one tour per commit", originalTours)); Telemetry.event("originalTourStructure") .params(Tour.determineSize(originalTours)) .log(); for (final ITourRestructuring restructuringStrategy : tourRestructuringStrategies) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } try { final List<? extends Tour> restructuredTour = restructuringStrategy.restructure(new ArrayList<>(originalTours)); Telemetry.event("possibleTourStructure") .param("strategy", restructuringStrategy.getClass()) .params(Tour.determineSize(restructuredTour)) .log(); if (restructuredTour != null) { possibleRestructurings.add(Pair.<String, List<? extends Tour>>create( restructuringStrategy.getDescription(), restructuredTour)); } } catch (final Exception e) { //skip instable restructurings Logger.error("exception in restructuring", e); } } return createUi.selectInitialTours(possibleRestructurings); } private static List<Tour> toTours(final List<? extends ICommit> changes, final IFragmentTracer tracer, final IProgressMonitor progressMonitor) { final List<Tour> ret = new ArrayList<>(); for (final ICommit c : changes) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } assert c.isVisible(); ret.add(new Tour( c.getMessage(), toSliceFragments(c.getChanges(), tracer))); } return ret; } private static List<Stop> toSliceFragments(List<? extends IChange> changes, IFragmentTracer tracer) { final List<Stop> ret = new ArrayList<>(); for (final IChange c : changes) { ret.addAll(toSliceFragment(c, tracer)); } return ret; } private static List<Stop> toSliceFragment(IChange c, final IFragmentTracer tracer) { final List<Stop> ret = new ArrayList<>(); c.accept(new IChangeVisitor() { @Override public void handle(ITextualChange visitee) { final List<? extends IFragment> mostRecentFragments = tracer.traceFragment(visitee.getToFragment()); for (final IFragment fragment : mostRecentFragments) { ret.add(new Stop(visitee, fragment)); } } @Override public void handle(IBinaryChange visitee) { for (final IRevisionedFile fileInRevision : tracer.traceFile(visitee.getFrom())) { ret.add(new Stop(visitee, fileInRevision)); } } }); return ret; } /** * Creates markers for the tour stops. */ public void createMarkers(final IStopMarkerFactory markerFactory, final IProgressMonitor progressMonitor) { final Map<IResource, PositionLookupTable> lookupTables = new HashMap<>(); for (int i = 0; i < this.topmostTours.size(); i++) { final Tour s = this.topmostTours.get(i); for (final Stop f : s.getStops()) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } this.createMarkerFor(markerFactory, lookupTables, f, i == this.currentTourIndex); } } } private IMarker createMarkerFor( IStopMarkerFactory markerFactory, final Map<IResource, PositionLookupTable> lookupTables, final Stop f, final boolean tourActive) { try { final IResource resource = f.getMostRecentFile().determineResource(); if (resource == null) { return null; } if (f.isDetailedFragmentKnown()) { if (!lookupTables.containsKey(resource)) { lookupTables.put(resource, PositionLookupTable.create((IFile) resource)); } final IFragment pos = f.getMostRecentFragment(); final IMarker marker = markerFactory.createStopMarker(resource, tourActive); marker.setAttribute(IMarker.LINE_NUMBER, pos.getFrom().getLine()); marker.setAttribute(IMarker.CHAR_START, lookupTables.get(resource).getCharsSinceFileStart(pos.getFrom())); marker.setAttribute(IMarker.CHAR_END, lookupTables.get(resource).getCharsSinceFileStart(pos.getTo())); return marker; } else { return markerFactory.createStopMarker(resource, tourActive); } } catch (final CoreException | IOException e) { throw new ReviewtoolException(e); } } /** * Creates a marker for the given fragment. * If multiple markers have to be created, use the method that caches lookup tables instead. * If a marker could not be created (for example because the resource is not available in Eclipse), null * is returned. */ public IMarker createMarkerFor( IStopMarkerFactory markerFactory, final Stop f) { return this.createMarkerFor(markerFactory, new HashMap<IResource, PositionLookupTable>(), f, true); } /** * Returns a {@link IFileHistoryNode} for passed file. * @param file The file whose change history to retrieve. * @return The {@link IFileHistoryNode} describing changes for passed {@link FileInRevision} or null if not found. */ public IFileHistoryNode getFileHistoryNode(final IRevisionedFile file) { return this.historyGraph.getNodeFor(file); } public List<Tour> getTopmostTours() { return this.topmostTours; } /** * Sets the given tour as the active tour, if it is not already active. * Recreates markers accordingly. */ public void ensureTourActive(Tour t, IStopMarkerFactory markerFactory) throws CoreException { this.ensureTourActive(t, markerFactory, true); } /** * Sets the given tour as the active tour, if it is not already active. * Recreates markers accordingly. */ public void ensureTourActive(Tour t, final IStopMarkerFactory markerFactory, boolean notify) throws CoreException { final int index = this.topmostTours.indexOf(t); if (index != this.currentTourIndex) { final Tour oldActive = this.getActiveTour(); this.currentTourIndex = index; new WorkspaceJob("Review marker update") { @Override public IStatus runInWorkspace(IProgressMonitor progressMonitor) throws CoreException { ToursInReview.this.clearMarkers(); ToursInReview.this.createMarkers(markerFactory, progressMonitor); return Status.OK_STATUS; } }.schedule(); if (notify) { for (final IToursInReviewChangeListener l : this.listeners) { l.activeTourChanged(oldActive, this.getActiveTour()); } } Telemetry.event("tourActivated") .param("tourIndex", index) .log(); } } /** * Clears all current tour stop markers. */ public void clearMarkers() throws CoreException { ResourcesPlugin.getWorkspace().getRoot().deleteMarkers( Constants.STOPMARKER_ID, true, IResource.DEPTH_INFINITE); ResourcesPlugin.getWorkspace().getRoot().deleteMarkers( Constants.INACTIVESTOPMARKER_ID, true, IResource.DEPTH_INFINITE); } /** * Returns the currently active tour or null if there is none (which should only * occur when there are no tours). */ public Tour getActiveTour() { return this.currentTourIndex >= this.topmostTours.size() || this.currentTourIndex < 0 ? null : this.topmostTours.get(this.currentTourIndex); } private void notifyListenersAboutTourStructureChange(final IStopMarkerFactory markerFactory) { // markerFactors is null only if called from ToursInReview.create(), and in this case ensureTourActive() // is called later on which recreates the markers if (markerFactory != null) { new WorkspaceJob("Stop marker update") { @Override public IStatus runInWorkspace(IProgressMonitor progressMonitor) throws CoreException { ToursInReview.this.clearMarkers(); ToursInReview.this.createMarkers(markerFactory, progressMonitor); return Status.OK_STATUS; } }.schedule(); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { for (final IToursInReviewChangeListener l : ToursInReview.this.listeners) { l.toursChanged(); } } }); } public void registerListener(IToursInReviewChangeListener listener) { this.listeners.add(listener); } /** * Returns all stops (from all tours) that refer to the given file. */ public List<Stop> getStopsFor(File absolutePath) { final List<Stop> ret = new ArrayList<>(); for (final Tour t : this.topmostTours) { for (final Stop s : t.getStops()) { if (absolutePath.equals(s.getAbsoluteFile())) { ret.add(s); } } } return ret; } /** * Returns the (first) tour that contains the given stop. * If none exists, -1 is returned. */ public int findTourIndexWithStop(Stop currentStop) { for (int i = 0; i < this.topmostTours.size(); i++) { for (final Stop s : this.topmostTours.get(i).getStops()) { if (s == currentStop) { return i; } } } return 0; } /** * Determines a stop that is as close as possible to the given line in the given resource. * The closeness measure is tweaked to (hopefully) capture the users intention as good as possible * for cases where he did not click directly on a stop. */ public Pair<Tour, Stop> findNearestStop(IPath absoluteResourcePath, int line) { if (this.topmostTours.isEmpty()) { return null; } Tour bestTour = null; Stop bestStop = null; int bestDist = Integer.MAX_VALUE; for (final Tour t : this.topmostTours) { for (final Stop stop : t.getStops()) { final int candidateDist = this.calculateDistance(stop, absoluteResourcePath, line); if (candidateDist < bestDist) { bestTour = t; bestStop = stop; bestDist = candidateDist; } } } return Pair.create(bestTour, bestStop); } private int calculateDistance(Stop stop, IPath resource, int line) { if (!stop.getMostRecentFile().toLocalPath().equals(resource)) { return Integer.MAX_VALUE; } final IFragment fragment = stop.getMostRecentFragment(); if (fragment == null) { return Integer.MAX_VALUE - 1; } if (line < fragment.getFrom().getLine()) { //there is a bias that lets lines between stops belong more closely to the stop above than below // to a certain degree return (fragment.getFrom().getLine() - line) * 4; } else if (line > fragment.getTo().getLine()) { return line - fragment.getTo().getLine(); } else { return 0; } } /** * Determines the direct parent tour of the given element. * Returns null when none is found. */ public Tour getParentFor(TourElement element) { for (final Tour t : this.topmostTours) { final Tour parent = t.findParentFor(element); if (parent != null) { return parent; } } return null; } /** * Determines the topmost parent tour of the given element. * Returns null when none is found. */ public Tour getTopmostTourWith(TourElement element) { for (final Tour t : this.topmostTours) { final Tour parent = t.findParentFor(element); if (parent != null) { return t; } } return null; } }
de.setsoftware.reviewtool.core/src/de/setsoftware/reviewtool/model/changestructure/ToursInReview.java
package de.setsoftware.reviewtool.model.changestructure; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Display; import de.setsoftware.reviewtool.base.Logger; import de.setsoftware.reviewtool.base.Pair; import de.setsoftware.reviewtool.base.ReviewtoolException; import de.setsoftware.reviewtool.base.WeakListeners; import de.setsoftware.reviewtool.model.Constants; import de.setsoftware.reviewtool.model.api.IBinaryChange; import de.setsoftware.reviewtool.model.api.IChange; import de.setsoftware.reviewtool.model.api.IChangeData; import de.setsoftware.reviewtool.model.api.IChangeSource; import de.setsoftware.reviewtool.model.api.IChangeSourceUi; import de.setsoftware.reviewtool.model.api.IChangeVisitor; import de.setsoftware.reviewtool.model.api.ICommit; import de.setsoftware.reviewtool.model.api.IFileHistoryNode; import de.setsoftware.reviewtool.model.api.IFragment; import de.setsoftware.reviewtool.model.api.IFragmentTracer; import de.setsoftware.reviewtool.model.api.IRevisionedFile; import de.setsoftware.reviewtool.model.api.ITextualChange; import de.setsoftware.reviewtool.ordering.efficientalgorithm.TourCalculatorControl; import de.setsoftware.reviewtool.telemetry.Telemetry; /** * Manages the current state regarding the changes/tours under review. */ public class ToursInReview { /** * Interface for observers of instances of {@link ToursInReview}. */ public static interface IToursInReviewChangeListener { /** * Is called when the available tours change (e.g. due to a merge or split). */ public abstract void toursChanged(); /** * Is called when the active tour changes. Will not be called when the active tour * changes together with the tours as a whole. Both arguments can be null, meaning that * there is no respective tour. */ public abstract void activeTourChanged(Tour oldActive, Tour newActive); } /** * Interface for user interaction during the creation of {@link ToursInReview}. */ public static interface ICreateToursUi { /** * Lets the user choose one of the given tour structures. * The given list contains pairs with a description of the merge algorithm and the resulting tours. * There always is at least one choice. * When the user cancels, null is returned. */ public abstract List<? extends Tour> selectInitialTours( List<? extends Pair<String, List<? extends Tour>>> choices); /** * Lets the user choose which subset of commits to review, which filters * to apply and which of the commits to merge into a tour. * When the user cancels, null is returned. * * @param changes All commits belonging to the review. * @param strategyResults Pairs with a description of the filter strategy and the resulting filter candidates * @param reviewRounds The review rounds conducted so far (to show them to the user). */ public abstract UserSelectedReductions selectIrrelevant( List<? extends ICommit> changes, List<Pair<String, Set<? extends IChange>>> strategyResults, List<ReviewRoundInfo> reviewRounds); } /** * Transfer object for the results of the user interaction to select * subset of commits, filters, ... */ public static final class UserSelectedReductions { private final List<? extends ICommit> commitSubset; private final List<? extends Pair<String, Set<? extends IChange>>> toMakeIrrelevant; public UserSelectedReductions( List<? extends ICommit> chosenCommitSubset, List<Pair<String, Set<? extends IChange>>> chosenFilterSubset) { this.commitSubset = chosenCommitSubset; this.toMakeIrrelevant = chosenFilterSubset; } } /** * Infos on a review round. */ public static final class ReviewRoundInfo implements Comparable<ReviewRoundInfo> { private final int number; private final Date date; private final String user; public ReviewRoundInfo(int number, Date date, String user) { this.number = number; this.date = date; this.user = user; } @Override public int compareTo(ReviewRoundInfo o) { return Integer.compare(this.number, o.number); } @Override public boolean equals(Object o) { if (!(o instanceof ReviewRoundInfo)) { return false; } return this.compareTo((ReviewRoundInfo) o) == 0; } @Override public int hashCode() { return this.number; } public Date getTime() { return this.date; } public String getReviewer() { return this.user; } public int getNumber() { return this.number; } } private final VirtualFileHistoryGraph historyGraph; private final List<Tour> topmostTours; private final IChangeData remoteChanges; private Map<File, IRevisionedFile> modifiedFiles; private int currentTourIndex; private final WeakListeners<IToursInReviewChangeListener> listeners = new WeakListeners<>(); private ToursInReview(final List<? extends Tour> topmostTours, final IChangeData remoteChanges) { this.historyGraph = new VirtualFileHistoryGraph(remoteChanges.getHistoryGraph()); this.topmostTours = new ArrayList<>(topmostTours); this.remoteChanges = remoteChanges; this.modifiedFiles = remoteChanges.getLocalPathMap(); this.currentTourIndex = 0; } private ToursInReview(final List<? extends Tour> topmostTours) { this.historyGraph = new VirtualFileHistoryGraph(); this.topmostTours = new ArrayList<>(topmostTours); this.remoteChanges = null; this.modifiedFiles = new LinkedHashMap<>(); this.currentTourIndex = 0; } /** * Creates a new object with the given tours (mainly for tests). */ public static ToursInReview create(List<Tour> tours) { return new ToursInReview(tours); } /** * Loads the tours for the given ticket and creates a corresponding {@link ToursInReview} * object with initial settings. When there is user interaction and the user cancels, * null is returned. */ public static ToursInReview create( IChangeSource src, final IChangeSourceUi changeSourceUi, List<? extends IIrrelevanceDetermination> irrelevanceDeterminationStrategies, List<? extends ITourRestructuring> tourRestructuringStrategies, IStopOrdering orderingAlgorithm, ICreateToursUi createUi, String ticketKey, List<ReviewRoundInfo> reviewRounds) { changeSourceUi.subTask("Determining relevant changes..."); final IChangeData changes = src.getRepositoryChanges(ticketKey, changeSourceUi); changeSourceUi.subTask("Filtering changes..."); final List<? extends ICommit> filteredChanges = filterChanges(irrelevanceDeterminationStrategies, changes.getMatchedCommits(), createUi, changeSourceUi, reviewRounds); if (filteredChanges == null) { return null; } changeSourceUi.subTask("Creating tours from changes..."); final List<Tour> tours = toTours( filteredChanges, new FragmentTracer(changes.getHistoryGraph()), changeSourceUi); final List<? extends Tour> userSelection = determinePossibleRestructurings(tourRestructuringStrategies, tours, createUi, changeSourceUi); if (userSelection == null) { return null; } changeSourceUi.subTask("Ordering stops..."); final List<? extends Tour> toursToShow = groupAndSort( userSelection, orderingAlgorithm, new TourCalculatorControl() { private static final long FAST_MODE_THRESHOLD = 20000; private final long startTime = System.currentTimeMillis(); @Override public synchronized boolean isCanceled() { return changeSourceUi.isCanceled(); } @Override public boolean isFastModeNeeded() { return System.currentTimeMillis() - this.startTime > FAST_MODE_THRESHOLD; } }); final ToursInReview result = new ToursInReview(toursToShow, changes); result.createLocalTour(null, changeSourceUi, null); return result; } private static List<? extends Tour> groupAndSort( List<? extends Tour> userSelection, IStopOrdering orderingAlgorithm, TourCalculatorControl isCanceled) { try { final List<Tour> ret = new ArrayList<>(); for (final Tour t : userSelection) { ret.add(new Tour(t.getDescription(), orderingAlgorithm.groupAndSort(t.getStops(), isCanceled))); } return ret; } catch (final InterruptedException e) { throw new OperationCanceledException(); } } /** * (Re)creates the local tour by (re)collecting local changes and combining them with the repository changes * in a {@link VirtualFileHistoryGraph}. * * @param progressMonitor The progress monitor to use. * @param markerFactory The marker factory to use. May be null if initially called while creating the tours. */ public void createLocalTour( final List<File> paths, final IProgressMonitor progressMonitor, final IStopMarkerFactory markerFactory) { progressMonitor.subTask("Collecting local changes..."); final IChangeData localChanges; try { if (paths == null) { localChanges = this.remoteChanges.getSource().getLocalChanges(this.remoteChanges, null, progressMonitor); } else { final List<File> allFilesToAnalyze = new ArrayList<>(this.modifiedFiles.keySet()); allFilesToAnalyze.addAll(paths); localChanges = this.remoteChanges.getSource().getLocalChanges(this.remoteChanges, allFilesToAnalyze, progressMonitor); } } catch (final ReviewtoolException e) { //if there is a problem while determining the local changes, ignore them Logger.warn("problem while determining local changes", e); return; } this.modifiedFiles = new LinkedHashMap<>(localChanges.getLocalPathMap()); if (this.historyGraph.size() > 1) { this.historyGraph.remove(1); } this.historyGraph.add(localChanges.getHistoryGraph()); this.updateMostRecentFragmentsWithLocalChanges(); this.notifyListenersAboutTourStructureChange(markerFactory); } private void updateMostRecentFragmentsWithLocalChanges() { final IFragmentTracer tracer = new FragmentTracer(this.historyGraph); for (final Tour tour : this.topmostTours) { for (final Stop stop : tour.getStops()) { stop.updateMostRecentData(tracer); } } } private static List<? extends ICommit> filterChanges( final List<? extends IIrrelevanceDetermination> irrelevanceDeterminationStrategies, final List<? extends ICommit> changes, final ICreateToursUi createUi, final IProgressMonitor progressMonitor, final List<ReviewRoundInfo> reviewRounds) { Telemetry.event("originalChanges") .param("count", countChanges(changes, false)) .param("relevant", countChanges(changes, true)) .log(); final List<Pair<String, Set<? extends IChange>>> strategyResults = new ArrayList<>(); for (final IIrrelevanceDetermination strategy : irrelevanceDeterminationStrategies) { try { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } final Set<? extends IChange> irrelevantChanges = determineIrrelevantChanges(changes, strategy); Telemetry.event("relevanceFilterResult") .param("description", strategy.getDescription()) .param("size", irrelevantChanges.size()) .log(); if (areAllIrrelevant(irrelevantChanges)) { //skip strategies that won't result in further changes to irrelevant continue; } strategyResults.add(Pair.<String, Set<? extends IChange>>create( strategy.getDescription(), irrelevantChanges)); } catch (final Exception e) { //skip instable strategies Logger.error("exception in filtering", e); } } final UserSelectedReductions selected = createUi.selectIrrelevant(changes, strategyResults, reviewRounds); if (selected == null) { return null; } final Set<IChange> toMakeIrrelevant = new HashSet<>(); final Set<String> selectedDescriptions = new LinkedHashSet<>(); for (final Pair<String, Set<? extends IChange>> set : selected.toMakeIrrelevant) { toMakeIrrelevant.addAll(set.getSecond()); selectedDescriptions.add(set.getFirst()); } Telemetry.event("selectedRelevanceFilter") .param("descriptions", selectedDescriptions) .log(); final Set<String> selectedCommits = new LinkedHashSet<>(); for (final ICommit commit : selected.commitSubset) { selectedCommits.add(commit.getRevision().toString()); } Telemetry.event("selectedCommitSubset") .param("commits", selectedCommits) .log(); final List<ICommit> ret = new ArrayList<>(); for (final ICommit c : selected.commitSubset) { ret.add(c.makeChangesIrrelevant(toMakeIrrelevant)); } return ret; } private static int countChanges(List<? extends ICommit> changes, boolean onlyRelevant) { int ret = 0; for (final ICommit commit : changes) { for (final IChange change : commit.getChanges()) { if (!(onlyRelevant && change.isIrrelevantForReview())) { ret++; } } } return ret; } private static Set<? extends IChange> determineIrrelevantChanges( List<? extends ICommit> changes, IIrrelevanceDetermination strategy) { final Set<IChange> ret = new HashSet<>(); for (final ICommit commit : changes) { for (final IChange change : commit.getChanges()) { if (strategy.isIrrelevant(change)) { ret.add(change); } } } return ret; } private static boolean areAllIrrelevant(Set<? extends IChange> changes) { for (final IChange change : changes) { if (!change.isIrrelevantForReview()) { return false; } } return true; } private static List<? extends Tour> determinePossibleRestructurings( final List<? extends ITourRestructuring> tourRestructuringStrategies, final List<Tour> originalTours, final ICreateToursUi createUi, final IProgressMonitor progressMonitor) { final List<Pair<String, List<? extends Tour>>> possibleRestructurings = new ArrayList<>(); possibleRestructurings.add(Pair.<String, List<? extends Tour>>create("one tour per commit", originalTours)); Telemetry.event("originalTourStructure") .params(Tour.determineSize(originalTours)) .log(); for (final ITourRestructuring restructuringStrategy : tourRestructuringStrategies) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } try { final List<? extends Tour> restructuredTour = restructuringStrategy.restructure(new ArrayList<>(originalTours)); Telemetry.event("possibleTourStructure") .param("strategy", restructuringStrategy.getClass()) .params(Tour.determineSize(restructuredTour)) .log(); if (restructuredTour != null) { possibleRestructurings.add(Pair.<String, List<? extends Tour>>create( restructuringStrategy.getDescription(), restructuredTour)); } } catch (final Exception e) { //skip instable restructurings Logger.error("exception in restructuring", e); } } return createUi.selectInitialTours(possibleRestructurings); } private static List<Tour> toTours(final List<? extends ICommit> changes, final IFragmentTracer tracer, final IProgressMonitor progressMonitor) { final List<Tour> ret = new ArrayList<>(); for (final ICommit c : changes) { if (progressMonitor.isCanceled()) { throw new OperationCanceledException(); } assert c.isVisible(); ret.add(new Tour( c.getMessage(), toSliceFragments(c.getChanges(), tracer))); } return ret; } private static List<Stop> toSliceFragments(List<? extends IChange> changes, IFragmentTracer tracer) { final List<Stop> ret = new ArrayList<>(); for (final IChange c : changes) { ret.addAll(toSliceFragment(c, tracer)); } return ret; } private static List<Stop> toSliceFragment(IChange c, final IFragmentTracer tracer) { final List<Stop> ret = new ArrayList<>(); c.accept(new IChangeVisitor() { @Override public void handle(ITextualChange visitee) { final List<? extends IFragment> mostRecentFragments = tracer.traceFragment(visitee.getToFragment()); for (final IFragment fragment : mostRecentFragments) { ret.add(new Stop(visitee, fragment)); } } @Override public void handle(IBinaryChange visitee) { for (final IRevisionedFile fileInRevision : tracer.traceFile(visitee.getFrom())) { ret.add(new Stop(visitee, fileInRevision)); } } }); return ret; } /** * Creates markers for the tour stops. */ public void createMarkers(final IStopMarkerFactory markerFactory, final IProgressMonitor progressMonitor) { final Map<IResource, PositionLookupTable> lookupTables = new HashMap<>(); for (int i = 0; i < this.topmostTours.size(); i++) { final Tour s = this.topmostTours.get(i); for (final Stop f : s.getStops()) { if (progressMonitor != null && progressMonitor.isCanceled()) { throw new OperationCanceledException(); } this.createMarkerFor(markerFactory, lookupTables, f, i == this.currentTourIndex); } } } private IMarker createMarkerFor( IStopMarkerFactory markerFactory, final Map<IResource, PositionLookupTable> lookupTables, final Stop f, final boolean tourActive) { try { final IResource resource = f.getMostRecentFile().determineResource(); if (resource == null) { return null; } if (f.isDetailedFragmentKnown()) { if (!lookupTables.containsKey(resource)) { lookupTables.put(resource, PositionLookupTable.create((IFile) resource)); } final IFragment pos = f.getMostRecentFragment(); final IMarker marker = markerFactory.createStopMarker(resource, tourActive); marker.setAttribute(IMarker.LINE_NUMBER, pos.getFrom().getLine()); marker.setAttribute(IMarker.CHAR_START, lookupTables.get(resource).getCharsSinceFileStart(pos.getFrom())); marker.setAttribute(IMarker.CHAR_END, lookupTables.get(resource).getCharsSinceFileStart(pos.getTo())); return marker; } else { return markerFactory.createStopMarker(resource, tourActive); } } catch (final CoreException | IOException e) { throw new ReviewtoolException(e); } } /** * Creates a marker for the given fragment. * If multiple markers have to be created, use the method that caches lookup tables instead. * If a marker could not be created (for example because the resource is not available in Eclipse), null * is returned. */ public IMarker createMarkerFor( IStopMarkerFactory markerFactory, final Stop f) { return this.createMarkerFor(markerFactory, new HashMap<IResource, PositionLookupTable>(), f, true); } /** * Returns a {@link IFileHistoryNode} for passed file. * @param file The file whose change history to retrieve. * @return The {@link IFileHistoryNode} describing changes for passed {@link FileInRevision} or null if not found. */ public IFileHistoryNode getFileHistoryNode(final IRevisionedFile file) { return this.historyGraph.getNodeFor(file); } public List<Tour> getTopmostTours() { return this.topmostTours; } /** * Sets the given tour as the active tour, if it is not already active. * Recreates markers accordingly. */ public void ensureTourActive(Tour t, IStopMarkerFactory markerFactory) throws CoreException { this.ensureTourActive(t, markerFactory, true); } /** * Sets the given tour as the active tour, if it is not already active. * Recreates markers accordingly. */ public void ensureTourActive(Tour t, IStopMarkerFactory markerFactory, boolean notify) throws CoreException { final int index = this.topmostTours.indexOf(t); if (index != this.currentTourIndex) { this.clearMarkers(); final Tour oldActive = this.getActiveTour(); this.currentTourIndex = index; this.createMarkers(markerFactory, null); if (notify) { for (final IToursInReviewChangeListener l : this.listeners) { l.activeTourChanged(oldActive, this.getActiveTour()); } } Telemetry.event("tourActivated") .param("tourIndex", index) .log(); } } /** * Clears all current tour stop markers. */ public void clearMarkers() throws CoreException { ResourcesPlugin.getWorkspace().getRoot().deleteMarkers( Constants.STOPMARKER_ID, true, IResource.DEPTH_INFINITE); ResourcesPlugin.getWorkspace().getRoot().deleteMarkers( Constants.INACTIVESTOPMARKER_ID, true, IResource.DEPTH_INFINITE); } /** * Returns the currently active tour or null if there is none (which should only * occur when there are no tours). */ public Tour getActiveTour() { return this.currentTourIndex >= this.topmostTours.size() || this.currentTourIndex < 0 ? null : this.topmostTours.get(this.currentTourIndex); } private void notifyListenersAboutTourStructureChange(final IStopMarkerFactory markerFactory) { // markerFactors is null only if called from ToursInReview.create(), and in this case ensureTourActive() // is called later on which recreates the markers if (markerFactory != null) { new WorkspaceJob("Stop marker update") { @Override public IStatus runInWorkspace(IProgressMonitor progressMonitor) throws CoreException { ToursInReview.this.clearMarkers(); ToursInReview.this.createMarkers(markerFactory, progressMonitor); return Status.OK_STATUS; } }.schedule(); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { for (final IToursInReviewChangeListener l : ToursInReview.this.listeners) { l.toursChanged(); } } }); } public void registerListener(IToursInReviewChangeListener listener) { this.listeners.add(listener); } /** * Returns all stops (from all tours) that refer to the given file. */ public List<Stop> getStopsFor(File absolutePath) { final List<Stop> ret = new ArrayList<>(); for (final Tour t : this.topmostTours) { for (final Stop s : t.getStops()) { if (absolutePath.equals(s.getAbsoluteFile())) { ret.add(s); } } } return ret; } /** * Returns the (first) tour that contains the given stop. * If none exists, -1 is returned. */ public int findTourIndexWithStop(Stop currentStop) { for (int i = 0; i < this.topmostTours.size(); i++) { for (final Stop s : this.topmostTours.get(i).getStops()) { if (s == currentStop) { return i; } } } return 0; } /** * Determines a stop that is as close as possible to the given line in the given resource. * The closeness measure is tweaked to (hopefully) capture the users intention as good as possible * for cases where he did not click directly on a stop. */ public Pair<Tour, Stop> findNearestStop(IPath absoluteResourcePath, int line) { if (this.topmostTours.isEmpty()) { return null; } Tour bestTour = null; Stop bestStop = null; int bestDist = Integer.MAX_VALUE; for (final Tour t : this.topmostTours) { for (final Stop stop : t.getStops()) { final int candidateDist = this.calculateDistance(stop, absoluteResourcePath, line); if (candidateDist < bestDist) { bestTour = t; bestStop = stop; bestDist = candidateDist; } } } return Pair.create(bestTour, bestStop); } private int calculateDistance(Stop stop, IPath resource, int line) { if (!stop.getMostRecentFile().toLocalPath().equals(resource)) { return Integer.MAX_VALUE; } final IFragment fragment = stop.getMostRecentFragment(); if (fragment == null) { return Integer.MAX_VALUE - 1; } if (line < fragment.getFrom().getLine()) { //there is a bias that lets lines between stops belong more closely to the stop above than below // to a certain degree return (fragment.getFrom().getLine() - line) * 4; } else if (line > fragment.getTo().getLine()) { return line - fragment.getTo().getLine(); } else { return 0; } } /** * Determines the direct parent tour of the given element. * Returns null when none is found. */ public Tour getParentFor(TourElement element) { for (final Tour t : this.topmostTours) { final Tour parent = t.findParentFor(element); if (parent != null) { return parent; } } return null; } /** * Determines the topmost parent tour of the given element. * Returns null when none is found. */ public Tour getTopmostTourWith(TourElement element) { for (final Tour t : this.topmostTours) { final Tour parent = t.findParentFor(element); if (parent != null) { return t; } } return null; } }
changed creation of markers to WorkspaceJob to avoid performance problems due to a lot of events
de.setsoftware.reviewtool.core/src/de/setsoftware/reviewtool/model/changestructure/ToursInReview.java
changed creation of markers to WorkspaceJob to avoid performance problems due to a lot of events
Java
agpl-3.0
a58e0a308b15eb1a519841c4b9b8471411f71f13
0
MarkehMe/FactionsPlus
package markehme.factionsplus; import markehme.factionsplus.config.Config; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; public class FactionsPlusTemplates { public static String Go(String templateOption, String args[]) { String workingstring = "Invalid Template File for " + templateOption; if(templateOption == "announcement_message") { workingstring = Config.templates.getString("announcement_message"); } if(templateOption == "warp_created") { workingstring = Config.templates.getString("warp_created"); } if(templateOption == "notify_warp_created") { workingstring = Config.templates.getString("notify_warp_created"); } if(templateOption == "jailed_message") { workingstring = Config.templates.getString("jailed_message"); } workingstring = colorFormat(workingstring); if(args.length == 2) { workingstring = workingstring.replace("$1", args[1]); workingstring = workingstring.replace("!1", args[1]); return(workingstring); } if(args.length == 3) { workingstring = workingstring.replace("!1", args[1]); workingstring = workingstring.replace("!2", args[2]); return(workingstring); } if(args.length == 4) { workingstring = workingstring.replaceAll("!1", args[1]); workingstring = workingstring.replaceAll("!2", args[2]); workingstring = workingstring.replaceAll("!3", args[3]); return(workingstring); } if(args.length == 5) { workingstring = workingstring.replace("!1", args[1]); workingstring = workingstring.replace("!2", args[2]); workingstring = workingstring.replace("!3", args[3]); workingstring = workingstring.replace("!4", args[4]); return(workingstring); } return workingstring; } public static String colorFormat(String a) { String b = a.replaceAll("<green>", ChatColor.GREEN + ""); b = b.replaceAll("<red>", ChatColor.RED + ""); b = b.replaceAll("<white>", ChatColor.WHITE + ""); b = b.replaceAll("<purple>", ChatColor.DARK_PURPLE + ""); b = b.replaceAll("<aqua>", ChatColor.AQUA + ""); b = b.replaceAll("<black>", ChatColor.BLACK + ""); b = b.replaceAll("<blue>", ChatColor.BLUE + ""); b = b.replaceAll("<yellow>", ChatColor.YELLOW + ""); b = b.replaceAll("<gray>", ChatColor.GRAY + ""); b = b.replaceAll("<grey>", ChatColor.GRAY + ""); return b; } @SuppressWarnings("boxing") public static void createTemplatesFile() { try { if(Config.templatesFile.exists()) { Config.templatesFile.delete(); } Config.templatesFile.createNewFile(); Config.templates = YamlConfiguration.loadConfiguration(Config.templatesFile); // For announcements Config.templates.set("announcement_message", "<red>!1 <white>announced: !2"); // For warps Config.templates.set("warp_created", "<green>Warp <white>!1 <green>set for your Faction!"); Config.templates.set("notify_warp_created", "!1 created a warp in your faction called !2"); // For jail Config.templates.set("jailed_message", "<red>You have been Jailed! If you are unhappy with this faction, you can leave the Faction."); // Default value don't change Config.templates.set("doNotChangeMe", 3); Config.templates.save(Config.templatesFile); } catch (Exception e) { e.printStackTrace(); FactionsPlusPlugin.info("ERROR: Couldn't create templates file."); return; } } }
src/markehme/factionsplus/FactionsPlusTemplates.java
package markehme.factionsplus; import markehme.factionsplus.config.Config; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; public class FactionsPlusTemplates { public static String Go(String templateOption, String args[]) { String workingstring = "Invalid Template File for " + templateOption; if(templateOption == "announcement_message") { workingstring = Config.templates.getString("announcement_message"); } if(templateOption == "warp_created") { workingstring = Config.templates.getString("warp_created"); } if(templateOption == "notify_warp_created") { workingstring = Config.templates.getString("notify_warp_created"); } if(templateOption == "jailed_message") { workingstring = Config.templates.getString("jailed_message"); } workingstring = colorFormat(workingstring); if(args.length == 2) { workingstring = workingstring.replace("$1", args[1]); return(workingstring); } if(args.length == 3) { workingstring = workingstring.replace("!1", args[1]); workingstring = workingstring.replace("!2", args[2]); return(workingstring); } if(args.length == 4) { workingstring = workingstring.replaceAll("!1", args[1]); workingstring = workingstring.replaceAll("!2", args[2]); workingstring = workingstring.replaceAll("!3", args[3]); return(workingstring); } if(args.length == 5) { workingstring = workingstring.replace("!1", args[1]); workingstring = workingstring.replace("!2", args[2]); workingstring = workingstring.replace("!3", args[3]); workingstring = workingstring.replace("!4", args[4]); return(workingstring); } return workingstring; } public static String colorFormat(String a) { String b = a.replaceAll("<green>", ChatColor.GREEN + ""); b = b.replaceAll("<red>", ChatColor.RED + ""); b = b.replaceAll("<white>", ChatColor.WHITE + ""); b = b.replaceAll("<purple>", ChatColor.DARK_PURPLE + ""); b = b.replaceAll("<aqua>", ChatColor.AQUA + ""); b = b.replaceAll("<black>", ChatColor.BLACK + ""); b = b.replaceAll("<blue>", ChatColor.BLUE + ""); b = b.replaceAll("<yellow>", ChatColor.YELLOW + ""); b = b.replaceAll("<gray>", ChatColor.GRAY + ""); b = b.replaceAll("<grey>", ChatColor.GRAY + ""); return b; } @SuppressWarnings("boxing") public static void createTemplatesFile() { try { if(Config.templatesFile.exists()) { Config.templatesFile.delete(); } Config.templatesFile.createNewFile(); Config.templates = YamlConfiguration.loadConfiguration(Config.templatesFile); // For announcements Config.templates.set("announcement_message", "<red>!1 <white>announced: !2"); // For warps Config.templates.set("warp_created", "<green>Warp <white>!1 <green>set for your Faction!"); Config.templates.set("notify_warp_created", "!1 created a warp in your faction called !2"); // For jail Config.templates.set("jailed_message", "<red>You have been Jailed! If you are unhappy with this faction, you can leave the Faction."); // Default value don't change Config.templates.set("doNotChangeMe", 3); Config.templates.save(Config.templatesFile); } catch (Exception e) { e.printStackTrace(); FactionsPlusPlugin.info("ERROR: Couldn't create templates file."); return; } } }
Potential bug here?
src/markehme/factionsplus/FactionsPlusTemplates.java
Potential bug here?
Java
agpl-3.0
42bb43f2273ead4b6b5cc34c47c72f5cdc249b6e
0
Concursive/concourseconnect-community,Concursive/concourseconnect-community,Concursive/concourseconnect-community
/* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.wiki.portlets.main; import com.concursive.commons.web.mvc.beans.GenericBean; import com.concursive.connect.web.modules.login.dao.User; import com.concursive.connect.web.modules.profile.dao.Project; import com.concursive.connect.web.modules.profile.utils.ProjectUtils; import com.concursive.connect.web.modules.wiki.dao.Wiki; import com.concursive.connect.web.modules.wiki.dao.WikiComment; import com.concursive.connect.web.modules.wiki.dao.WikiList; import com.concursive.connect.web.portal.IPortletAction; import com.concursive.connect.web.portal.PortalUtils; import static com.concursive.connect.web.portal.PortalUtils.*; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import java.sql.Connection; /** * Action for saving a wiki comment * * @author matt rajkowski * @created November 3, 2008 */ public class SaveWikiCommentsAction implements IPortletAction { public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); if (!ProjectUtils.hasAccess(project.getId(), user, "project-wiki-view")) { throw new PortletException("Unauthorized to view in this project"); } // Determine the record to show String subject = PortalUtils.getPageView(request); // Parameters String comment = request.getParameter("comment"); // Find the record to record comments against Connection db = getConnection(request); Wiki wiki = WikiList.queryBySubject(db, subject, project.getId()); if (wiki.getId() > -1) { WikiComment wikiComment = new WikiComment(); wikiComment.setComment(comment); wikiComment.setWikiId(wiki.getId()); wikiComment.setEnteredBy(user.getId()); wikiComment.setModifiedBy(user.getId()); boolean inserted = wikiComment.insert(db); if (!inserted) { return wikiComment; } } // This call will close panels and perform redirects return (PortalUtils.performRefresh(request, response, "/show/wiki/" + wiki.getSubjectLink())); } }
concourseconnect/trunk/src/main/java/com/concursive/connect/web/modules/wiki/portlets/main/SaveWikiCommentsAction.java
/* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.wiki.portlets.main; import com.concursive.commons.web.mvc.beans.GenericBean; import com.concursive.connect.web.modules.login.dao.User; import com.concursive.connect.web.modules.profile.dao.Project; import com.concursive.connect.web.modules.profile.utils.ProjectUtils; import com.concursive.connect.web.modules.wiki.dao.Wiki; import com.concursive.connect.web.modules.wiki.dao.WikiComment; import com.concursive.connect.web.modules.wiki.dao.WikiList; import com.concursive.connect.web.portal.IPortletAction; import com.concursive.connect.web.portal.PortalUtils; import static com.concursive.connect.web.portal.PortalUtils.*; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import java.sql.Connection; /** * Action for saving a wiki comment * * @author matt rajkowski * @created November 3, 2008 */ public class SaveWikiCommentsAction implements IPortletAction { public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); if (!ProjectUtils.hasAccess(project.getId(), user, "project-wiki-view")) { throw new PortletException("Unauthorized to view in this project"); } // Parameters String subject = request.getParameter("subject"); String comment = request.getParameter("comment"); // Find the record to record comments against Connection db = getConnection(request); Wiki wiki = WikiList.queryBySubject(db, subject, project.getId()); if (wiki.getId() > -1) { WikiComment wikiComment = new WikiComment(); wikiComment.setComment(comment); wikiComment.setWikiId(wiki.getId()); wikiComment.setEnteredBy(user.getId()); wikiComment.setModifiedBy(user.getId()); boolean inserted = wikiComment.insert(db); if (!inserted) { return wikiComment; } } // This call will close panels and perform redirects return (PortalUtils.performRefresh(request, response, "/show/wiki/" + wiki.getSubjectLink())); } }
FIX: Commenting on a specific page was broke and defaulted to the wiki's home page
concourseconnect/trunk/src/main/java/com/concursive/connect/web/modules/wiki/portlets/main/SaveWikiCommentsAction.java
FIX: Commenting on a specific page was broke and defaulted to the wiki's home page
Java
agpl-3.0
ffd87f332adebc0a16f5010da9a8ff1bd0e400ef
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
dd870330-2e61-11e5-9284-b827eb9e62be
hello.java
dd81a138-2e61-11e5-9284-b827eb9e62be
dd870330-2e61-11e5-9284-b827eb9e62be
hello.java
dd870330-2e61-11e5-9284-b827eb9e62be
Java
lgpl-2.1
3d67f687fe591bb9af11dc38656c5e69ba605aa1
0
victos/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core,serrapos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,victos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,victos/opencms-core,ggiudetti/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,alkacon/opencms-core,MenZil/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,victos/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/defaults/Attic/A_CmsContentDefinition.java,v $ * Date : $Date: 2001/10/19 15:02:17 $ * Version: $Revision: 1.7 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.defaults; import com.opencms.template.*; import com.opencms.file.*; import java.util.*; import java.lang.reflect.*; import com.opencms.core.*; import com.opencms.core.exceptions.*; /** * Abstract class for the content definition * Creation date: (27.10.00 10:04:42) * author: Michael Knoll * version 1.0 */ public abstract class A_CmsContentDefinition implements I_CmsContent, I_CmsConstants { /** * The owner of this resource. */ private int m_user; /** * The group of this resource. */ private String m_group; /** * The access flags of this resource. */ private int m_accessFlags; /** * applies the filter method * @returns an Vector containing the method */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod) throws Exception { return applyFilter(cms, filterMethod, null); } /** * applies the filter through the method object and the user parameters * @returns a vector with the filtered content */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod, String userParameter) throws Exception { Method method = filterMethod.getFilterMethod(); Object[] defaultParams = filterMethod.getDefaultParameter(); Vector allParameters = new Vector(); Object[] allParametersArray; Class[] paramTypes = method.getParameterTypes(); if( (paramTypes.length > 0) && (paramTypes[0] == CmsObject.class) ) { allParameters.addElement(cms); } for(int i = 0; i < defaultParams.length; i++) { allParameters.addElement(defaultParams[i]); } if (filterMethod.hasUserParameter()) { allParameters.addElement(userParameter); } allParametersArray = new Object[allParameters.size()]; allParameters.copyInto(allParametersArray); return (Vector) method.invoke(null, allParametersArray); } public void check(boolean finalcheck) throws CmsPlausibilizationException { // do nothing here, just an empty method for compatibility reasons. } /** * abstract delete method * for delete instance of content definition * must be overwritten in your content definition */ public abstract void delete(CmsObject cms) throws Exception; /** * Gets the getXXX methods * You have to override this method in your content definition. * @returns a Vector with the filed methods. */ public static Vector getFieldMethods(CmsObject cms) { return new Vector(); } /** * Gets the headlines of the table * You have to override this method in your content definition. * @returns a Vector with the colum names. */ public static Vector getFieldNames(CmsObject cms) { return new Vector(); } /** * Gets the filter methods. * You have to override this method in your content definition. * @returns a Vector of FilterMethod objects containing the methods, names and default parameters */ public static Vector getFilterMethods(CmsObject cms) { return new Vector(); } /** * Gets the lockstates * You have to override this method in your content definition, if you have overwritten * the isLockable method with true. * @returns a int with the lockstate */ public int getLockstate() { return -1; } /** * gets the unique Id of a content definition instance * @returns a string with the Id */ public abstract String getUniqueId(CmsObject cms) ; /** * Gets the url of the field entry * You have to override this method in your content definition, * if you wish to link urls to the field entries * @returns a String with the url */ public String getUrl() { return null; } /** * if the content definition objects should be lockable * this method has to be overwritten with value true * @returns a boolean */ public static boolean isLockable() { return false; } /** *Sets the lockstates * You have to override this method in your content definition, * if you have overwritten the isLockable method with true. * @sets the lockstate for the actual entry */ public void setLockstate(int lockstate) { } /** * abstract write method * must be overwritten in content definition */ public abstract void write(CmsObject cms) throws Exception; /** * returns true if the CD is readable for the current user * @retruns true */ public boolean isReadable() { return true; } /** * returns true if the CD is writeable for the current user * @retruns true */ public boolean isWriteable() { return true; } /** * set the owner of the CD * @param id of the owner */ public void setOwner(int userId) { m_user = userId; } /** * get the owner of the CD * @returns id of the owner (int) */ public int getOwner() { return m_user; } /** * set the group of the CD * @param the group ID */ public void setGroup(String group) { m_group = group; } /** * get the group of the CD * @returns the group ID */ public String getGroup() { return m_group; } /** * set the accessFlag for the CD * @param the accessFlag */ public void setAccessFlags(int accessFlags) { m_accessFlags = accessFlags; } /** * get the accessFlag for the CD * @returns the accessFlag */ public int getAccessFlags() { return m_accessFlags; } /** * has the current user the right to read the CD * @returns a boolean */ protected boolean hasReadAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); if ( !accessOther(C_ACCESS_PUBLIC_READ) && !accessOwner(cms, currentUser, C_ACCESS_OWNER_READ) && !accessGroup(cms, currentUser, C_ACCESS_GROUP_READ)) { return false; } return true; } /** * has the current user the right to write the CD * @returns a boolean */ protected boolean hasWriteAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); // check, if the resource is locked by the current user if( isLockable() && (getLockstate() != currentUser.getId()) ) { // resource is not locked by the current user, no writing allowed return(false); } // check the rights for the current resource if( ! ( accessOther(C_ACCESS_PUBLIC_WRITE) || accessOwner(cms, currentUser, C_ACCESS_OWNER_WRITE) || accessGroup(cms, currentUser, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } return true; } /** * Checks, if the owner may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOwner(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // The Admin has always access if( cms.isAdmin() ) { return(true); } // is the resource owned by this user? if(getOwner() == currentUser.getId()) { if( (getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the group may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessGroup(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // is the user in the group for the resource? if(cms.userInGroup(currentUser.getName(), getGroup() )) { if( (getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOther( int flags ) throws CmsException { if ((getAccessFlags() & flags) == flags) { return true; } else { return false; } } /** * if the content definition objects should be displayed * in an extended list with projectflags and state * this method must be overwritten with value true * @returns a boolean */ public static boolean isExtendedList() { return false; } }
src/com/opencms/defaults/A_CmsContentDefinition.java
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/defaults/Attic/A_CmsContentDefinition.java,v $ * Date : $Date: 2001/07/31 15:50:13 $ * Version: $Revision: 1.6 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.defaults; import com.opencms.template.*; import com.opencms.file.*; import java.util.*; import java.lang.reflect.*; import com.opencms.core.*; import com.opencms.core.exceptions.*; /** * Abstract class for the content definition * Creation date: (27.10.00 10:04:42) * author: Michael Knoll * version 1.0 */ public abstract class A_CmsContentDefinition implements I_CmsContent, I_CmsConstants { /** * The owner of this resource. */ private int m_user; /** * The group of this resource. */ private String m_group; /** * The access flags of this resource. */ private int m_accessFlags; /** * applies the filter method * @returns an Vector containing the method */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod) throws Exception { return applyFilter(cms, filterMethod, null); } /** * applies the filter through the method object and the user parameters * @returns a vector with the filtered content */ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod, String userParameter) throws Exception { Method method = filterMethod.getFilterMethod(); Object[] defaultParams = filterMethod.getDefaultParameter(); Vector allParameters = new Vector(); Object[] allParametersArray; Class[] paramTypes = method.getParameterTypes(); if( (paramTypes.length > 0) && (paramTypes[0] == CmsObject.class) ) { allParameters.addElement(cms); } for(int i = 0; i < defaultParams.length; i++) { allParameters.addElement(defaultParams[i]); } if (filterMethod.hasUserParameter()) { allParameters.addElement(userParameter); } allParametersArray = new Object[allParameters.size()]; allParameters.copyInto(allParametersArray); return (Vector) method.invoke(null, allParametersArray); } public void check(boolean finalcheck) throws CmsPlausibilizationException { // do nothing here, just an empty method for compatibility reasons. } /** * abstract delete method * for delete instance of content definition * must be overwritten in your content definition */ public abstract void delete(CmsObject cms) throws Exception; /** * Gets the getXXX methods * You have to override this method in your content definition. * @returns a Vector with the filed methods. */ public static Vector getFieldMethods(CmsObject cms) { return new Vector(); } /** * Gets the headlines of the table * You have to override this method in your content definition. * @returns a Vector with the colum names. */ public static Vector getFieldNames(CmsObject cms) { return new Vector(); } /** * Gets the filter methods. * You have to override this method in your content definition. * @returns a Vector of FilterMethod objects containing the methods, names and default parameters */ public static Vector getFilterMethods(CmsObject cms) { return new Vector(); } /** * Gets the lockstates * You have to override this method in your content definition, if you have overwritten * the isLockable method with true. * @returns a int with the lockstate */ public int getLockstate() { return -1; } /** * gets the unique Id of a content definition instance * @returns a string with the Id */ public abstract String getUniqueId(CmsObject cms) ; /** * Gets the url of the field entry * You have to override this method in your content definition, * if you wish to link urls to the field entries * @returns a String with the url */ public String getUrl() { return null; } /** * if the content definition objects should be lockable * this method has to be overwritten with value true * @returns a boolean */ public static boolean isLockable() { return false; } /** *Sets the lockstates * You have to override this method in your content definition, * if you have overwritten the isLockable method with true. * @sets the lockstate for the actual entry */ public void setLockstate(int lockstate) { } /** * abstract write method * must be overwritten in content definition */ public abstract void write(CmsObject cms) throws Exception; /** * returns true if the CD is readable for the current user * @retruns true */ public boolean isReadable() { return true; } /** * returns true if the CD is writeable for the current user * @retruns true */ public boolean isWriteable() { return true; } /** * set the owner of the CD * @param id of the owner */ public void setOwner(int userId) { m_user = userId; } /** * get the owner of the CD * @returns id of the owner (int) */ public int getOwner() { return m_user; } /** * set the group of the CD * @param the group ID */ public void setGroup(String group) { m_group = group; } /** * get the group of the CD * @returns the group ID */ public String getGroup() { return m_group; } /** * set the accessFlag for the CD * @param the accessFlag */ public void setAccessFlags(int accessFlags) { m_accessFlags = accessFlags; } /** * get the accessFlag for the CD * @returns the accessFlag */ public int getAccessFlags() { return m_accessFlags; } /** * has the current user the right to read the CD * @returns a boolean */ protected boolean hasReadAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); if ( !accessOther(C_ACCESS_PUBLIC_READ) && !accessOwner(cms, currentUser, C_ACCESS_OWNER_READ) && !accessGroup(cms, currentUser, C_ACCESS_GROUP_READ)) { return false; } return true; } /** * has the current user the right to write the CD * @returns a boolean */ protected boolean hasWriteAccess(CmsObject cms) throws CmsException { CmsUser currentUser = cms.getRequestContext().currentUser(); // check, if the resource is locked by the current user if( isLockable() && (getLockstate() != currentUser.getId()) ) { // resource is not locked by the current user, no writing allowed return(false); } // check the rights for the current resource if( ! ( accessOther(C_ACCESS_PUBLIC_WRITE) || accessOwner(cms, currentUser, C_ACCESS_OWNER_WRITE) || accessGroup(cms, currentUser, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } return true; } /** * Checks, if the owner may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOwner(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // The Admin has always access if( cms.isAdmin() ) { return(true); } // is the resource owned by this user? if(getOwner() == currentUser.getId()) { if( (getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the group may access this resource. * * @param cms the cmsObject * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessGroup(CmsObject cms, CmsUser currentUser, int flags) throws CmsException { // is the user in the group for the resource? if(cms.userInGroup(currentUser.getName(), getGroup() )) { if( (getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param flags The flags to check. * * @return wether the user has access, or not. */ private boolean accessOther( int flags ) throws CmsException { if ((getAccessFlags() & flags) == flags) { return true; } else { return false; } } }
New method isExtendedList returns true if the content definition should use the new list with projectflag and state.
src/com/opencms/defaults/A_CmsContentDefinition.java
New method isExtendedList returns true if the content definition should use the new list with projectflag and state.
Java
lgpl-2.1
afb5307e0281960ea1dd105dd1d086e48c945cff
0
deadcyclo/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features
/* * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id$ */ package org.nuxeo.ecm.platform.pictures.tiles.service.test; import static org.junit.Assert.assertNotNull; import java.io.File; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.impl.blob.FileBlob; import org.nuxeo.ecm.core.storage.sql.SQLRepositoryTestCase; import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTiles; import org.nuxeo.ecm.platform.pictures.tiles.api.adapter.PictureTilesAdapter; public class TestAdapters extends SQLRepositoryTestCase { @Before public void setUp() throws Exception { super.setUp(); deployBundle("org.nuxeo.ecm.platform.types.api"); deployBundle("org.nuxeo.ecm.platform.commandline.executor"); deployBundle("org.nuxeo.ecm.platform.picture.api"); deployBundle("org.nuxeo.ecm.platform.picture.core"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-framework.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-contrib.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-adapter-contrib.xml"); openSession(); } @After public void tearDown() throws Exception { closeSession(); super.tearDown(); } @Test public void testAdapter() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel doc = session.createDocumentModel(root.getPathAsString(), "file", "File"); doc.setProperty("dublincore", "title", "MyDoc"); doc.setProperty("dublincore", "coverage", "MyDocCoverage"); doc.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); doc.setProperty("file", "content", image); doc.setProperty("file", "filename", "test.jpg"); doc = session.createDocument(doc); session.save(); assertTilingIsWorkingFor(doc); } protected void assertTilingIsWorkingFor(DocumentModel doc) throws Exception { PictureTilesAdapter tilesAdapter = doc.getAdapter(PictureTilesAdapter.class); assertNotNull(tilesAdapter); PictureTiles tiles = tilesAdapter.getTiles(255, 255, 15); assertNotNull(tiles); PictureTiles tiles2 = tilesAdapter.getTiles(255, 255, 20); assertNotNull(tiles2); } @Test public void testAdapterOnPicture() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } @Test public void testAdapterOnPictureWithOriginalJpegView() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "OriginalJpeg"); map.put("description", "OriginalJpeg Size"); map.put("filename", "test.jpg"); map.put("tag", "originalJpeg"); map.put("width", 3872); map.put("height", 2592); image.setFilename("OriginalJpeg" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } protected List<Map<String, Object>> getDefaultViewsList(Blob image) { List<Map<String, Object>> viewsList = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "Medium"); map.put("description", "Medium Size"); map.put("filename", "test.jpg"); map.put("tag", "medium"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Medium" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Original"); map.put("description", "Original Size"); map.put("filename", "test.jpg"); map.put("tag", "original"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Original" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Thumbnail"); map.put("description", "Thumbnail Size"); map.put("filename", "test.jpg"); map.put("tag", "thumbnail"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Thumbnail" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); return viewsList; } }
nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/test/java/org/nuxeo/ecm/platform/pictures/tiles/service/test/TestAdapters.java
/* * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id$ */ package org.nuxeo.ecm.platform.pictures.tiles.service.test; import static org.junit.Assert.assertNotNull; import java.io.File; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.impl.blob.FileBlob; import org.nuxeo.ecm.core.storage.sql.SQLRepositoryTestCase; import org.nuxeo.ecm.platform.pictures.tiles.api.PictureTiles; import org.nuxeo.ecm.platform.pictures.tiles.api.adapter.PictureTilesAdapter; // NXP-13240: failing randomly => disabled waiting for investigation @Ignore public class TestAdapters extends SQLRepositoryTestCase { @Before public void setUp() throws Exception { super.setUp(); deployBundle("org.nuxeo.ecm.platform.types.api"); deployBundle("org.nuxeo.ecm.platform.commandline.executor"); deployBundle("org.nuxeo.ecm.platform.picture.api"); deployBundle("org.nuxeo.ecm.platform.picture.core"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-framework.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-contrib.xml"); deployContrib("org.nuxeo.ecm.platform.pictures.tiles", "OSGI-INF/pictures-tiles-adapter-contrib.xml"); openSession(); } @After public void tearDown() throws Exception { closeSession(); super.tearDown(); } @Test public void testAdapter() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel doc = session.createDocumentModel(root.getPathAsString(), "file", "File"); doc.setProperty("dublincore", "title", "MyDoc"); doc.setProperty("dublincore", "coverage", "MyDocCoverage"); doc.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); doc.setProperty("file", "content", image); doc.setProperty("file", "filename", "test.jpg"); doc = session.createDocument(doc); session.save(); assertTilingIsWorkingFor(doc); } protected void assertTilingIsWorkingFor(DocumentModel doc) throws Exception { PictureTilesAdapter tilesAdapter = doc.getAdapter(PictureTilesAdapter.class); assertNotNull(tilesAdapter); PictureTiles tiles = tilesAdapter.getTiles(255, 255, 15); assertNotNull(tiles); PictureTiles tiles2 = tilesAdapter.getTiles(255, 255, 20); assertNotNull(tiles2); } @Test public void testAdapterOnPicture() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } @Test public void testAdapterOnPictureWithOriginalJpegView() throws Exception { DocumentModel root = session.getRootDocument(); DocumentModel picture = session.createDocumentModel( root.getPathAsString(), "picture1", "Picture"); picture.setProperty("dublincore", "description", "test picture"); picture.setProperty("dublincore", "modified", new GregorianCalendar()); File file = FileUtils.getResourceFileFromContext("test.jpg"); Blob image = new FileBlob(file); List<Map<String, Object>> viewsList = getDefaultViewsList(image); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "OriginalJpeg"); map.put("description", "OriginalJpeg Size"); map.put("filename", "test.jpg"); map.put("tag", "originalJpeg"); map.put("width", 3872); map.put("height", 2592); image.setFilename("OriginalJpeg" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); picture.getProperty("picture:views").setValue(viewsList); picture = session.createDocument(picture); session.save(); assertTilingIsWorkingFor(picture); } protected List<Map<String, Object>> getDefaultViewsList(Blob image) { List<Map<String, Object>> viewsList = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "Medium"); map.put("description", "Medium Size"); map.put("filename", "test.jpg"); map.put("tag", "medium"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Medium" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Original"); map.put("description", "Original Size"); map.put("filename", "test.jpg"); map.put("tag", "original"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Original" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); map = new HashMap<String, Object>(); map.put("title", "Thumbnail"); map.put("description", "Thumbnail Size"); map.put("filename", "test.jpg"); map.put("tag", "thumbnail"); map.put("width", 3872); map.put("height", 2592); image.setFilename("Thumbnail" + "_" + "test.jpg"); map.put("content", image); viewsList.add(map); return viewsList; } }
NXP-13240: re-enable tiling test failing randomly
nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/test/java/org/nuxeo/ecm/platform/pictures/tiles/service/test/TestAdapters.java
NXP-13240: re-enable tiling test failing randomly
Java
unlicense
07c2ca801cb059b6e5f2856fe4caf149ebbbc244
0
Kramermp/FoodMood
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package moodprofile.controller; import foodprofile.view.FoodUI; import java.sql.Connection; import moodprofile.model.Mood; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.GregorianCalendar; import moodprofile.model.MoodList; import moodprofile.view.MoodListUI; import moodprofile.view.MoodUI; import userprofile.model.User; /** * * @author Michael Kramer */ public class MoodController { private MoodList moodList; private Connection theConnection; private Statement theStatement; public MoodController(User currentUser){ } /** * This sets the MoodList for the current user * @param moodList the moodList to set */ public void setMoodList(MoodList moodList) { this.moodList = moodList; } /** * Adds a Mood to the current user's FoodList * @param mood the mood to add */ public void addMood(Mood mood){ moodList.addMoodProfile(mood); } /** * This updates a mood, using the id stored within the mood class. Also updates linkages * @param mood the mood to update */ public void updateMood(Mood mood){ } /** * This deletes the mood from the current user's MoodList * @param moodID the mood to delete */ public void deleteMood(int moodID){ } /** * Deletes a mood from the current user's MoodList and the linkages of all foods it was linked to * @param mood the mood to delete */ public void deleteMood(Mood mood){ moodList.removeMoodProfile(mood); } /** * Links foods and moods based on the time the food was consumed * @param moodID the ID of the mood * @param time time the mood was entered */ public void addLinkedFoodsToMood(int moodID, GregorianCalendar time){ } public void readMoods(){ System.out.println("Reading moods"); try{ Class.forName("org.sqlite.JDBC"); theConnection = DriverManager.getConnection("jdbc:sqlite:foodmood.db"); theStatement = theConnection.createStatement(); ResultSet set = theStatement.executeQuery("SELECT * FROM mood"); ArrayList<Mood> moods = new ArrayList(); while(set.next()){ int id = set.getInt("id"); String name = set.getString("name"); int score = set.getInt("score"); Mood mood = new Mood(); mood.setId(id); mood.setName(name); mood.setMoodScore(score); moods.add(mood); } moodList = new MoodList(moods); theStatement.close(); theConnection.close(); }catch(Exception e){ e.printStackTrace(); System.exit(0); } } public void goListView(){ MoodListUI moodListUI = new MoodListUI(this); moodListUI.setVisible(true); } public void addMood(String name, GregorianCalendar time){ if(moodList==null){ moodList = new MoodList(); } moodList.add(name, time); } public MoodList getMoodList(){ if(moodList == null){ moodList = new MoodList(); } return moodList; } public void newMood(){ MoodUI moodUI = new MoodUI(this); moodUI.setVisible(true); } public void viewMood(Mood mood){ MoodUI moodUI = new MoodUI(this, mood); moodUI.setVisible(true); } }
src/moodprofile/controller/MoodController.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package moodprofile.controller; import java.sql.Connection; import moodprofile.model.Mood; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.GregorianCalendar; import moodprofile.model.MoodList; import userprofile.model.User; /** * * @author Michael Kramer */ public class MoodController { private MoodList moodList; private Connection theConnection; private Statement theStatement; public MoodController(User currentUser){ } /** * This sets the MoodList for the current user * @param moodList the moodList to set */ public void setMoodList(MoodList moodList) { this.moodList = moodList; } /** * Adds a Mood to the current user's FoodList * @param mood the mood to add */ public void addMood(Mood mood){ moodList.addMoodProfile(mood); } /** * This updates a mood, using the id stored within the mood class. Also updates linkages * @param mood the mood to update */ public void updateMood(Mood mood){ } /** * This deletes the mood from the current user's MoodList * @param moodID the mood to delete */ public void deleteMood(int moodID){ } /** * Deletes a mood from the current user's MoodList and the linkages of all foods it was linked to * @param mood the mood to delete */ public void deleteMood(Mood mood){ moodList.removeMoodProfile(mood); } /** * Links foods and moods based on the time the food was consumed * @param moodID the ID of the mood * @param time time the mood was entered */ public void addLinkedFoodsToMood(int moodID, GregorianCalendar time){ } public void readMoods(){ System.out.println("Reading moods"); try{ Class.forName("org.sqlite.JDBC"); theConnection = DriverManager.getConnection("jdbc:sqlite:foodmood.db"); theStatement = theConnection.createStatement(); ResultSet set = theStatement.executeQuery("SELECT * FROM mood"); ArrayList<Mood> moods = new ArrayList(); while(set.next()){ int id = set.getInt("id"); String name = set.getString("name"); int score = set.getInt("score"); Mood mood = new Mood(); mood.setId(id); mood.setName(name); mood.setMoodScore(score); moods.add(mood); } moodList = new MoodList(moods); theStatement.close(); theConnection.close(); }catch(Exception e){ e.printStackTrace(); System.exit(0); } } }
Exception catching
src/moodprofile/controller/MoodController.java
Exception catching
Java
apache-2.0
6b78f2471342547e6b406da581deb65f6cef73aa
0
PhenoImageShare/PhenoImageShare,PhenoImageShare/PhenoImageShare,PhenoImageShare/PhenoImageShare,PhenoImageShare/PhenoImageShare,PhenoImageShare/PhenoImageShare
package uk.ac.ebi.phis.service; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.json.JSONArray; import org.json.JSONObject; import org.neo4j.cypher.ParameterNotFoundException; import org.springframework.stereotype.Service; import uk.ac.ebi.phis.solrj.dto.ImageDTO; import uk.ac.ebi.phis.solrj.dto.RoiDTO; import uk.ac.ebi.phis.utils.web.JSONRestUtil; @Service public class ImageService { private HttpSolrServer solr; private static final Logger log = Logger.getLogger(ImageService.class); public ImageService(String solrUrl) { solr = new HttpSolrServer(solrUrl); } public String getAutosuggest(String term, String mutantGene, String expressedGeneOrAllele, String phenotype, Integer rows){ SolrQuery solrQuery = new SolrQuery(); ArrayList<String> suggestions = new ArrayList<>(); Integer suggestionNumber = 10; Integer solrRows = 100; if (term != null){ if (term.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.TERM_AUTOSUGGEST + ":" + term); solrQuery.setFields(ImageDTO.TERM_AUTOSUGGEST); solrQuery.addHighlightField(ImageDTO.TERM_AUTOSUGGEST); solrQuery.set("f.term_autosuggest_analysed.hl.preserveMulti", true); } else if (mutantGene != null){ if (mutantGene.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.GENE_SYMBOL + ":" + mutantGene); solrQuery.setFields(ImageDTO.GENE_SYMBOL); solrQuery.addHighlightField(ImageDTO.GENE_SYMBOL); solrQuery.set("f." + ImageDTO.GENE_SYMBOL + ".hl.preserveMulti", true); } else if (expressedGeneOrAllele != null){ if (expressedGeneOrAllele.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":" + expressedGeneOrAllele); solrQuery.setFields(ImageDTO.EXPRESSED_GF_SYMBOL_BAG); solrQuery.addHighlightField(ImageDTO.EXPRESSED_GF_SYMBOL_BAG); solrQuery.set("f." + ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ".hl.preserveMulti", true); } else if (phenotype != null){ if (phenotype.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.PHENOTYPE_LABEL_BAG + ":" + phenotype); solrQuery.setFields(ImageDTO.PHENOTYPE_LABEL_BAG); solrQuery.addHighlightField(ImageDTO.PHENOTYPE_LABEL_BAG); solrQuery.set("f." + ImageDTO.PHENOTYPE_LABEL_BAG + ".hl.preserveMulti", true); } solrQuery.setHighlight(true); solrQuery.setHighlightRequireFieldMatch(true); if (rows != null){ solrRows = rows*10; suggestionNumber = rows; } solrQuery.setRows(solrRows); System.out.println("Solr URL : " + solr.getBaseURL() + "/select?" + solrQuery); log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery); // Parse results to filter out un-highlighted entries and duplicates try { int i = 1; while ((suggestions.size() < suggestionNumber && solr.query(solrQuery).getResults().getNumFound() > i*solrRows) || i == 1){ Map<String, Map<String, List<String>>> highlights = solr.query(solrQuery).getHighlighting(); OUTERMOST: for (Map<String, List<String>> suggests : highlights.values()){ for (List<String> suggestLists : suggests.values()){ for(String highlighted : suggestLists){ if (highlighted.contains("<b>") && !suggestions.contains(highlighted)){ suggestions.add(highlighted); if (suggestions.size() == suggestionNumber){ break OUTERMOST; } } } } } solrQuery.setStart(i++*solrRows); } } catch (SolrServerException e) { e.printStackTrace(); } // Return in JSON format JSONObject returnObj = new JSONObject(); returnObj.put("response", new JSONObject().put("suggestions", new JSONArray(suggestions))); return returnObj.toString().replaceAll("<\\\\", "<"); } public String getImage(String term, String phenotype, String geneParameterToBeDeleted, String mutantGene, String anatomy, String expressedGene, String sex, String taxon, String image_type, String sample_type, String stage, String visualisationMethod, String samplePreparation, String imagingMethod, Integer rows, Integer start) throws SolrServerException{ SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); if ( geneParameterToBeDeleted != null){ mutantGene = geneParameterToBeDeleted; } if (term != null){ solrQuery.setQuery(ImageDTO.GENERIC_SEARCH + ":" + term); if (term.contains(" ")){ String[] splittedQuery = term.split(" "); String query = ImageDTO.GENERIC_SEARCH + ":" + org.apache.commons.lang3.StringUtils.join(splittedQuery, "^1 " + ImageDTO.GENERIC_SEARCH + ":"); solrQuery.set("defType", "edismax"); solrQuery.set("qf", ImageDTO.GENERIC_SEARCH); solrQuery.set("bq", ImageDTO.GENERIC_SEARCH + ":\"" + term + "\"^10 " + query); }else{ solrQuery.addFilterQuery(ImageDTO.GENERIC_SEARCH + ":"+ term); } /* solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_COMPUTED_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_COMPUTED_TERM_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_FREETEXT + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_ID + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_TERM + ":\""+ term + "\" OR " + ImageDTO.GENE_ID + ":\""+ term + "\" OR " + ImageDTO.GENE_SYMBOL + ":\""+ term + "\" OR " + ImageDTO.EXPRESSED_GF_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_FREETEXT_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_LABEL_BAG + ":\""+ term + "\" OR " + ImageDTO.IMAGE_GENERATED_BY + ":\""+ term + "\" OR " + ImageDTO.IMAGING_METHOD_ID + ":\""+ term + "\" OR " + ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\""+ term + "\" OR " + ImageDTO.VISUALISATION_METHOD_ID + ":\""+ term + "\" OR " + ImageDTO.VISUALISATION_METHOD_LABEL + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_GENERATED_BY + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_PREPARATION_ID + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_PREPARATION_LABEL + ":\""+ term + "\" OR " + ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ term + "\""); */ } if (phenotype != null){ solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ phenotype + "\" OR " + ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ phenotype + "\" OR " + ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ phenotype + "\""); } if (mutantGene != null){ solrQuery.addFilterQuery(ImageDTO.GENE_ID + ":\""+ mutantGene + "\" OR " + ImageDTO.GENE_SYMBOL + ":\""+ mutantGene + "\""); } if (anatomy != null){ solrQuery.addFilterQuery(ImageDTO.ANATOMY_ID + ":\""+ anatomy + "\" OR " + ImageDTO.ANATOMY_TERM + ":\""+ anatomy + "\" OR " + ImageDTO.ANATOMY_FREETEXT + ":\""+ anatomy + "\"" ); } if (expressedGene != null){ solrQuery.addFilterQuery(ImageDTO.EXPRESSED_GF_ID_BAG + ":\"" + expressedGene + "\""); } if (taxon != null){ solrQuery.addFilterQuery(ImageDTO.TAXON + ":\"" + taxon + "\" OR " + ImageDTO.NCBI_TAXON_ID + ":\"" + taxon + "\""); } if (image_type != null){ solrQuery.addFilterQuery(ImageDTO.IMAGE_TYPE + ":\"" + image_type + "\""); } if (sample_type != null){ solrQuery.addFilterQuery(ImageDTO.SAMPLE_TYPE + ":\"" + sample_type + "\""); } if (stage != null){ solrQuery.addFilterQuery(ImageDTO.STAGE + ":\"" + stage + "\" OR " + ImageDTO.STAGE_ID + ":\"" + stage + "\""); } if (visualisationMethod != null){ solrQuery.addFilterQuery(ImageDTO.VISUALISATION_METHOD_ID + ":\"" + visualisationMethod + "\" OR " + ImageDTO.VISUALISATION_METHOD_LABEL + ":\"" + visualisationMethod + "\""); } if (samplePreparation != null){ solrQuery.addFilterQuery(ImageDTO.SAMPLE_PREPARATION_ID + ":\"" + samplePreparation + "\" OR " + ImageDTO.SAMPLE_PREPARATION_LABEL + ":\"" + samplePreparation + "\""); } if (samplePreparation != null){ solrQuery.addFilterQuery(ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\"" + imagingMethod + "\" OR " + ImageDTO.IMAGING_METHOD_ID + ":\"" + imagingMethod + "\""); } if (sex != null){ solrQuery.addFilterQuery(ImageDTO.SEX + ":\"" + sex + "\""); } if (rows != null){ solrQuery.setRows(rows); } else solrQuery.setRows(100); if (start != null){ solrQuery.set("start", start); } solrQuery.set("wt", "json"); solrQuery.setFacet(true); solrQuery.addFacetField(ImageDTO.STAGE); solrQuery.addFacetField(ImageDTO.IMAGING_METHOD_LABEL); solrQuery.addFacetField(ImageDTO.TAXON); solrQuery.addFacetField(ImageDTO.SAMPLE_TYPE); solrQuery.setFacetMinCount(1); // add pivot facets to get the number of image types per solrQuery.set("facet.pivot", ImageDTO.SAMPLE_TYPE + "," + ImageDTO.IMAGE_TYPE); System.out.println("\nSolr URL : " + solr.getBaseURL() + "/select?" + solrQuery); log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery); try { return JSONRestUtil.getResults(getQueryUrl(solrQuery)).toString(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return "Couldn't get anything back from solr."; } /** * * @param roiToReplace must exist * @param roiToAdd must have teh same id as roiToReplace */ public void updateImageFromRoi(RoiDTO roiToReplace, RoiDTO roiToAdd){ if (imageIdExists(roiToAdd.getAssociatedImage()) && imageIdExists(roiToReplace.getAssociatedImage())){ deleteRoiRefferences(roiToReplace); addToImageFromRoi(roiToAdd); } } public boolean imageIdExists(String id){ return getImageById(id) != null; } /** * Delete all refferences to this roi (roi id, annotations from annotations bags) * @param roi */ public void deleteRoiRefferences(RoiDTO roi){ ImageDTO img = getImageById(roi.getAssociatedImage()); System.out.println("Roi list before " + img.getAssociatedRoi().size() + " " + img.getAssociatedRoi()); List<String> list = img.getAssociatedRoi(); list.remove(roi.getId()); img.setAssociatedRoi(list); if (roi.getAbnormalityAnatomyId() != null){ img.setAbnormalAnatomyIdBag(removeOnce(img.getAbnormalAnatomyIdBag(), roi.getAbnormalityAnatomyId())); } if (roi.getAbnormalityAnatomyFreetext() != null){ img.setAbnormalAnatomyFreetextBag(removeOnce(img.getAbnormalAnatomyFreetextBag(), roi.getAbnormalityAnatomyFreetext())); } if (roi.getPhenotypeId() != null){ img.setPhenotypeIdBag(removeOnce(img.getPhenotypeIdBag(), roi.getPhenotypeId())); } if (roi.getPhenotypeFreetext() != null){ img.setPhenotypeFreetextBag(removeOnce(img.getPhenotypeFreetextBag(), roi.getPhenotypeFreetext())); } if (roi.getObservations() != null){ img.setObservationBag(removeOnce(img.getObservationBag(), roi.getObservations())); } if (roi.getDepictedAnatomyId() != null){ img.setDepictedAnatomyIdBag(removeOnce(img.getDepictedAnatomyIdBag(), roi.getDepictedAnatomyId())); } if (roi.getDepictedAnatomyFreetext() != null){ img.setDepictedAnatomyFreetextBag(removeOnce(img.getDepictedAnatomyFreetextBag(), roi.getDepictedAnatomyFreetext())); } if (roi.getExpressedAnatomyFreetext() != null){ img.setExpressionInFreetextBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyFreetext())); } if (roi.getExpressedAnatomyId() != null){ img.setExpressionInIdBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyId())); } img.setGenericSearch(new ArrayList<String>()); List<ImageDTO> update = new ArrayList<>(); update.add(img); addBeans(update); } public ArrayList<String> removeOnce(ArrayList<String> from, List<String> whatToDelete){ ArrayList<String> res = from; if ( res != null){ for(String toRemove : whatToDelete){ from.remove(toRemove); } } return from; } /** * To be used for atomic updates when a user adds a new annotation * @param roi * @throws Exception */ public void addToImageFromRoi(RoiDTO roi) throws ParameterNotFoundException{ ImageDTO img = getImageById(roi.getAssociatedImage()); if (img.getAssociatedRoi() == null){ throw new ParameterNotFoundException("Image id does not exist"); }else if(!img.getAssociatedRoi().contains(roi.getId())){ img.addAssociatedRoi(roi.getId()); if (roi.getAbnormalityAnatomyId() != null){ System.out.println("Adding " + roi.getAbnormalityAnatomyId().get(0)); img.addAbnormalAnatomyIdBag(roi.getAbnormalityAnatomyId().get(0)); } if (roi.getAbnormalityAnatomyFreetext() != null){ img.addAbnormalAnatomyFreetextBag(roi.getAbnormalityAnatomyFreetext().get(0)); } if (roi.getPhenotypeId() != null){ img.addPhenotypeIdBag((ArrayList<String>) roi.getPhenotypeId()); } if (roi.getPhenotypeFreetext() != null){ img.addPhenotypeFreetextBag((ArrayList<String>) roi.getPhenotypeFreetext()); } if (roi.getObservations() != null){ img.addObservationBag((ArrayList<String>) roi.getObservations()); } if (roi.getDepictedAnatomyId() != null){ img.addDepictedAnatomyIdBag(roi.getDepictedAnatomyId()); } if (roi.getDepictedAnatomyFreetext() != null){ img.addDepictedAnatomyFreetextBag(roi.getDepictedAnatomyFreetext()); } if (roi.getExpressedAnatomyFreetext() != null){ System.out.println("Expression added \n\n\n\n"); img.addExpressionInFreetextBag(roi.getExpressedAnatomyFreetext()); } if (roi.getExpressedAnatomyId() != null){ img.addExpressionInIdBag(roi.getExpressedAnatomyId()); } img.setGenericSearch(new ArrayList<String>()); List<ImageDTO> update = new ArrayList<>(); update.add(img); addBeans(update); } } public ImageDTO getImageById(String imageId){ ImageDTO img = null; SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery(ImageDTO.ID + ":" + imageId); try { List<ImageDTO> images = solr.query(solrQuery).getBeans(ImageDTO.class); img = images.get(0); } catch (SolrServerException e) { e.printStackTrace(); } return img; } public String getSolrUrl () { return solr.getBaseURL(); } public void addBeans(List<ImageDTO> imageDocs){ try { solr.addBeans(imageDocs); solr.commit(); } catch (SolrServerException | IOException e) { e.printStackTrace(); } } /** * Removes all documents from the core * @throws IOException * @throws SolrServerException */ public void clear() throws SolrServerException, IOException{ solr.deleteByQuery("*:*"); } public String getQueryUrl(SolrQuery q){ return solr.getBaseURL() + "/select?" + q.toString(); } }
PhIS/source/main/java/uk/ac/ebi/phis/service/ImageService.java
package uk.ac.ebi.phis.service; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.json.JSONArray; import org.json.JSONObject; import org.neo4j.cypher.ParameterNotFoundException; import org.springframework.stereotype.Service; import uk.ac.ebi.phis.solrj.dto.ImageDTO; import uk.ac.ebi.phis.solrj.dto.RoiDTO; import uk.ac.ebi.phis.utils.web.JSONRestUtil; @Service public class ImageService { private HttpSolrServer solr; private static final Logger log = Logger.getLogger(ImageService.class); public ImageService(String solrUrl) { solr = new HttpSolrServer(solrUrl); } public String getAutosuggest(String term, String mutantGene, String expressedGeneOrAllele, String phenotype, Integer rows){ SolrQuery solrQuery = new SolrQuery(); ArrayList<String> suggestions = new ArrayList<>(); Integer suggestionNumber = 10; Integer solrRows = 100; if (term != null){ if (term.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.TERM_AUTOSUGGEST + ":" + term); solrQuery.setFields(ImageDTO.TERM_AUTOSUGGEST); solrQuery.addHighlightField(ImageDTO.TERM_AUTOSUGGEST); solrQuery.set("f.term_autosuggest_analysed.hl.preserveMulti", true); } else if (mutantGene != null){ if (mutantGene.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.GENE_SYMBOL + ":" + mutantGene); solrQuery.setFields(ImageDTO.GENE_SYMBOL); solrQuery.addHighlightField(ImageDTO.GENE_SYMBOL); solrQuery.set("f." + ImageDTO.GENE_SYMBOL + ".hl.preserveMulti", true); } else if (expressedGeneOrAllele != null){ if (expressedGeneOrAllele.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":" + expressedGeneOrAllele); solrQuery.setFields(ImageDTO.EXPRESSED_GF_SYMBOL_BAG); solrQuery.addHighlightField(ImageDTO.EXPRESSED_GF_SYMBOL_BAG); solrQuery.set("f." + ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ".hl.preserveMulti", true); } else if (phenotype != null){ if (phenotype.length() < 1){ return ""; } solrQuery.setQuery(ImageDTO.PHENOTYPE_LABEL_BAG + ":" + phenotype); solrQuery.setFields(ImageDTO.PHENOTYPE_LABEL_BAG); solrQuery.addHighlightField(ImageDTO.PHENOTYPE_LABEL_BAG); solrQuery.set("f." + ImageDTO.PHENOTYPE_LABEL_BAG + ".hl.preserveMulti", true); } solrQuery.setHighlight(true); solrQuery.setHighlightRequireFieldMatch(true); solrQuery.set("hl.simple.pre", "<b>"); solrQuery.set("hl.simple.post", "</b>"); if (rows != null){ solrRows = rows*10; suggestionNumber = rows; } solrQuery.setRows(solrRows); System.out.println("Solr URL : " + solr.getBaseURL() + "/select?" + solrQuery); log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery); // Parse results to filter out un-highlighted entries and duplicates try { int i = 1; while ((suggestions.size() < suggestionNumber && solr.query(solrQuery).getResults().getNumFound() > i*solrRows) || i == 1){ Map<String, Map<String, List<String>>> highlights = solr.query(solrQuery).getHighlighting(); OUTERMOST: for (Map<String, List<String>> suggests : highlights.values()){ for (List<String> suggestLists : suggests.values()){ for(String highlighted : suggestLists){ if (highlighted.contains("<b>") && !suggestions.contains(highlighted)){ suggestions.add(highlighted); if (suggestions.size() == suggestionNumber){ break OUTERMOST; } } } } } solrQuery.setStart(i++*solrRows); } } catch (SolrServerException e) { e.printStackTrace(); } // Return in JSON format JSONObject returnObj = new JSONObject(); returnObj.put("response", new JSONObject().put("suggestions", new JSONArray(suggestions))); return returnObj.toString().replaceAll("<\\\\", "<"); } public String getImage(String term, String phenotype, String geneParameterToBeDeleted, String mutantGene, String anatomy, String expressedGene, String sex, String taxon, String image_type, String sample_type, String stage, String visualisationMethod, String samplePreparation, String imagingMethod, Integer rows, Integer start) throws SolrServerException{ SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery("*:*"); if ( geneParameterToBeDeleted != null){ mutantGene = geneParameterToBeDeleted; } if (term != null){ solrQuery.setQuery(ImageDTO.GENERIC_SEARCH + ":" + term); if (term.contains(" ")){ String[] splittedQuery = term.split(" "); String query = ImageDTO.GENERIC_SEARCH + ":" + org.apache.commons.lang3.StringUtils.join(splittedQuery, "^1 " + ImageDTO.GENERIC_SEARCH + ":"); solrQuery.set("defType", "edismax"); solrQuery.set("qf", ImageDTO.GENERIC_SEARCH); solrQuery.set("bq", ImageDTO.GENERIC_SEARCH + ":\"" + term + "\"^10 " + query); }else{ solrQuery.addFilterQuery(ImageDTO.GENERIC_SEARCH + ":"+ term); } /* solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_COMPUTED_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_COMPUTED_TERM_BAG + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_FREETEXT + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_ID + ":\""+ term + "\" OR " + ImageDTO.ANATOMY_TERM + ":\""+ term + "\" OR " + ImageDTO.GENE_ID + ":\""+ term + "\" OR " + ImageDTO.GENE_SYMBOL + ":\""+ term + "\" OR " + ImageDTO.EXPRESSED_GF_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSED_GF_SYMBOL_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_FREETEXT_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_ID_BAG + ":\""+ term + "\" OR " + ImageDTO.EXPRESSION_IN_LABEL_BAG + ":\""+ term + "\" OR " + ImageDTO.IMAGE_GENERATED_BY + ":\""+ term + "\" OR " + ImageDTO.IMAGING_METHOD_ID + ":\""+ term + "\" OR " + ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\""+ term + "\" OR " + ImageDTO.VISUALISATION_METHOD_ID + ":\""+ term + "\" OR " + ImageDTO.VISUALISATION_METHOD_LABEL + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_GENERATED_BY + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_PREPARATION_ID + ":\""+ term + "\" OR " + ImageDTO.SAMPLE_PREPARATION_LABEL + ":\""+ term + "\" OR " + ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ term + "\""); */ } if (phenotype != null){ solrQuery.addFilterQuery(ImageDTO.PHENOTYPE_ID_BAG + ":\""+ phenotype + "\" OR " + ImageDTO.PHENOTYPE_FREETEXT_BAG + ":\""+ phenotype + "\" OR " + ImageDTO.PHENOTYPE_LABEL_BAG + ":\""+ phenotype + "\""); } if (mutantGene != null){ solrQuery.addFilterQuery(ImageDTO.GENE_ID + ":\""+ mutantGene + "\" OR " + ImageDTO.GENE_SYMBOL + ":\""+ mutantGene + "\""); } if (anatomy != null){ solrQuery.addFilterQuery(ImageDTO.ANATOMY_ID + ":\""+ anatomy + "\" OR " + ImageDTO.ANATOMY_TERM + ":\""+ anatomy + "\" OR " + ImageDTO.ANATOMY_FREETEXT + ":\""+ anatomy + "\"" ); } if (expressedGene != null){ solrQuery.addFilterQuery(ImageDTO.EXPRESSED_GF_ID_BAG + ":\"" + expressedGene + "\""); } if (taxon != null){ solrQuery.addFilterQuery(ImageDTO.TAXON + ":\"" + taxon + "\" OR " + ImageDTO.NCBI_TAXON_ID + ":\"" + taxon + "\""); } if (image_type != null){ solrQuery.addFilterQuery(ImageDTO.IMAGE_TYPE + ":\"" + image_type + "\""); } if (sample_type != null){ solrQuery.addFilterQuery(ImageDTO.SAMPLE_TYPE + ":\"" + sample_type + "\""); } if (stage != null){ solrQuery.addFilterQuery(ImageDTO.STAGE + ":\"" + stage + "\" OR " + ImageDTO.STAGE_ID + ":\"" + stage + "\""); } if (visualisationMethod != null){ solrQuery.addFilterQuery(ImageDTO.VISUALISATION_METHOD_ID + ":\"" + visualisationMethod + "\" OR " + ImageDTO.VISUALISATION_METHOD_LABEL + ":\"" + visualisationMethod + "\""); } if (samplePreparation != null){ solrQuery.addFilterQuery(ImageDTO.SAMPLE_PREPARATION_ID + ":\"" + samplePreparation + "\" OR " + ImageDTO.SAMPLE_PREPARATION_LABEL + ":\"" + samplePreparation + "\""); } if (samplePreparation != null){ solrQuery.addFilterQuery(ImageDTO.IMAGING_METHOD_LABEL_ANALYSED + ":\"" + imagingMethod + "\" OR " + ImageDTO.IMAGING_METHOD_ID + ":\"" + imagingMethod + "\""); } if (sex != null){ solrQuery.addFilterQuery(ImageDTO.SEX + ":\"" + sex + "\""); } if (rows != null){ solrQuery.setRows(rows); } else solrQuery.setRows(100); if (start != null){ solrQuery.set("start", start); } solrQuery.set("wt", "json"); solrQuery.setFacet(true); solrQuery.addFacetField(ImageDTO.STAGE); solrQuery.addFacetField(ImageDTO.IMAGING_METHOD_LABEL); solrQuery.addFacetField(ImageDTO.TAXON); solrQuery.addFacetField(ImageDTO.SAMPLE_TYPE); solrQuery.setFacetMinCount(1); // add pivot facets to get the number of image types per solrQuery.set("facet.pivot", ImageDTO.SAMPLE_TYPE + "," + ImageDTO.IMAGE_TYPE); System.out.println("\nSolr URL : " + solr.getBaseURL() + "/select?" + solrQuery); log.info("Solr URL in getImages : " + solr.getBaseURL() + "/select?" + solrQuery); try { return JSONRestUtil.getResults(getQueryUrl(solrQuery)).toString(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return "Couldn't get anything back from solr."; } /** * * @param roiToReplace must exist * @param roiToAdd must have teh same id as roiToReplace */ public void updateImageFromRoi(RoiDTO roiToReplace, RoiDTO roiToAdd){ if (imageIdExists(roiToAdd.getAssociatedImage()) && imageIdExists(roiToReplace.getAssociatedImage())){ deleteRoiRefferences(roiToReplace); addToImageFromRoi(roiToAdd); } } public boolean imageIdExists(String id){ return getImageById(id) != null; } /** * Delete all refferences to this roi (roi id, annotations from annotations bags) * @param roi */ public void deleteRoiRefferences(RoiDTO roi){ ImageDTO img = getImageById(roi.getAssociatedImage()); System.out.println("Roi list before " + img.getAssociatedRoi().size() + " " + img.getAssociatedRoi()); List<String> list = img.getAssociatedRoi(); list.remove(roi.getId()); img.setAssociatedRoi(list); if (roi.getAbnormalityAnatomyId() != null){ img.setAbnormalAnatomyIdBag(removeOnce(img.getAbnormalAnatomyIdBag(), roi.getAbnormalityAnatomyId())); } if (roi.getAbnormalityAnatomyFreetext() != null){ img.setAbnormalAnatomyFreetextBag(removeOnce(img.getAbnormalAnatomyFreetextBag(), roi.getAbnormalityAnatomyFreetext())); } if (roi.getPhenotypeId() != null){ img.setPhenotypeIdBag(removeOnce(img.getPhenotypeIdBag(), roi.getPhenotypeId())); } if (roi.getPhenotypeFreetext() != null){ img.setPhenotypeFreetextBag(removeOnce(img.getPhenotypeFreetextBag(), roi.getPhenotypeFreetext())); } if (roi.getObservations() != null){ img.setObservationBag(removeOnce(img.getObservationBag(), roi.getObservations())); } if (roi.getDepictedAnatomyId() != null){ img.setDepictedAnatomyIdBag(removeOnce(img.getDepictedAnatomyIdBag(), roi.getDepictedAnatomyId())); } if (roi.getDepictedAnatomyFreetext() != null){ img.setDepictedAnatomyFreetextBag(removeOnce(img.getDepictedAnatomyFreetextBag(), roi.getDepictedAnatomyFreetext())); } if (roi.getExpressedAnatomyFreetext() != null){ img.setExpressionInFreetextBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyFreetext())); } if (roi.getExpressedAnatomyId() != null){ img.setExpressionInIdBag(removeOnce(img.getExpressionInFreetextBag(), roi.getExpressedAnatomyId())); } img.setGenericSearch(new ArrayList<String>()); List<ImageDTO> update = new ArrayList<>(); update.add(img); addBeans(update); } public ArrayList<String> removeOnce(ArrayList<String> from, List<String> whatToDelete){ ArrayList<String> res = from; if ( res != null){ for(String toRemove : whatToDelete){ from.remove(toRemove); } } return from; } /** * To be used for atomic updates when a user adds a new annotation * @param roi * @throws Exception */ public void addToImageFromRoi(RoiDTO roi) throws ParameterNotFoundException{ ImageDTO img = getImageById(roi.getAssociatedImage()); if (img.getAssociatedRoi() == null){ throw new ParameterNotFoundException("Image id does not exist"); }else if(!img.getAssociatedRoi().contains(roi.getId())){ img.addAssociatedRoi(roi.getId()); if (roi.getAbnormalityAnatomyId() != null){ System.out.println("Adding " + roi.getAbnormalityAnatomyId().get(0)); img.addAbnormalAnatomyIdBag(roi.getAbnormalityAnatomyId().get(0)); } if (roi.getAbnormalityAnatomyFreetext() != null){ img.addAbnormalAnatomyFreetextBag(roi.getAbnormalityAnatomyFreetext().get(0)); } if (roi.getPhenotypeId() != null){ img.addPhenotypeIdBag((ArrayList<String>) roi.getPhenotypeId()); } if (roi.getPhenotypeFreetext() != null){ img.addPhenotypeFreetextBag((ArrayList<String>) roi.getPhenotypeFreetext()); } if (roi.getObservations() != null){ img.addObservationBag((ArrayList<String>) roi.getObservations()); } if (roi.getDepictedAnatomyId() != null){ img.addDepictedAnatomyIdBag(roi.getDepictedAnatomyId()); } if (roi.getDepictedAnatomyFreetext() != null){ img.addDepictedAnatomyFreetextBag(roi.getDepictedAnatomyFreetext()); } if (roi.getExpressedAnatomyFreetext() != null){ System.out.println("Expression added \n\n\n\n"); img.addExpressionInFreetextBag(roi.getExpressedAnatomyFreetext()); } if (roi.getExpressedAnatomyId() != null){ img.addExpressionInIdBag(roi.getExpressedAnatomyId()); } img.setGenericSearch(new ArrayList<String>()); List<ImageDTO> update = new ArrayList<>(); update.add(img); addBeans(update); } } public ImageDTO getImageById(String imageId){ ImageDTO img = null; SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery(ImageDTO.ID + ":" + imageId); try { List<ImageDTO> images = solr.query(solrQuery).getBeans(ImageDTO.class); img = images.get(0); } catch (SolrServerException e) { e.printStackTrace(); } return img; } public String getSolrUrl () { return solr.getBaseURL(); } public void addBeans(List<ImageDTO> imageDocs){ try { solr.addBeans(imageDocs); solr.commit(); } catch (SolrServerException | IOException e) { e.printStackTrace(); } } /** * Removes all documents from the core * @throws IOException * @throws SolrServerException */ public void clear() throws SolrServerException, IOException{ solr.deleteByQuery("*:*"); } public String getQueryUrl(SolrQuery q){ return solr.getBaseURL() + "/select?" + q.toString(); } }
removed bold for autsuggest match highlight
PhIS/source/main/java/uk/ac/ebi/phis/service/ImageService.java
removed bold for autsuggest match highlight
Java
apache-2.0
b394760aff2af802d562920767b18b80bcbf0346
0
statsbiblioteket/ticket-system
package dk.statsbiblioteket.medieplatform.ticketsystem; import dk.statsbiblioteket.doms.webservices.configuration.ConfigCollection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by IntelliJ IDEA. * User: abr * Date: 3/25/11 * Time: 12:17 PM * To change this template use File | Settings | File Templates. */ @Path("/tickets/") public class TicketSystemService { private static TicketSystem tickets; private static final Object lock = new Object(); private static final String TICKET_TTL_PROP = "dk.statsbiblioteket.ticket-system.timeToLive"; private static final String TICKET_AUTH_SERVICE = "dk.statsbiblioteket.ticket-system.auth-checker"; private final Log log = LogFactory.getLog(TicketSystemService.class); public TicketSystemService() throws BackendException { log.trace("Created a new TicketSystem webservice object"); synchronized (lock){ if (tickets == null){ long ttl; try { String ttlString = ConfigCollection.getProperties() .getProperty(TICKET_TTL_PROP,""+30*1000); log.trace("Read '"+TICKET_TTL_PROP+"' property as '"+ttlString+"'"); ttl = Long.parseLong(ttlString); } catch (NumberFormatException e) { log.warn("Could not parse the '"+ TICKET_TTL_PROP +"' as a long, using default 30 sec timetolive",e); ttl = 30*1000; } String authService = ConfigCollection.getProperties().getProperty(TICKET_AUTH_SERVICE); Authorization authorization = new Authorization(authService); tickets = new TicketSystem(ttl, authorization); } } } /*Issuing of tickets*/ @GET @Path("issueTicket") @Produces({MediaType.APPLICATION_JSON}) public Map<String, String> issueTicketGet( @QueryParam("id") List<String> id, @QueryParam("type") String type, @QueryParam("userIdentifier") String userIdentifier, @Context UriInfo uriInfo ) throws MissingArgumentException { return issueTicketQueryParams(id, type, userIdentifier, uriInfo); } @POST @Path("issueTicket") @Produces({MediaType.APPLICATION_JSON}) public Map<String, String> issueTicketQueryParams( @QueryParam("id") List<String> resources, @QueryParam("type") String type, @QueryParam("userIdentifier") String userIdentifier, @Context UriInfo uriInfo ) throws MissingArgumentException { MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); queryParams.remove("id"); queryParams.remove("type"); queryParams.remove("userIdentifier"); if (resources == null){ throw new MissingArgumentException("id is missing"); } if (type == null){ throw new MissingArgumentException("type is missing"); } if (userIdentifier == null){ throw new MissingArgumentException("userIdentifier is missing"); } Map<String, List<String>> userAttributes = new HashMap<String, List<String>>(); for (String key : queryParams.keySet()) { List<String> values = queryParams.get(key); if (values != null && values.size() > 0) { userAttributes.put(key, values); } } HashMap<String, String> ticketMap = new HashMap<String, String>(); Ticket ticket = tickets.issueTicket(resources, type, userIdentifier, userAttributes); for (String resource : ticket.getResources()) { ticketMap.put(resource, ticket.getID()); } log.debug("Issued ticket: " + ticket); return ticketMap; } /*Resolving of tickets*/ @GET @Path("resolveTicket") @Produces({MediaType.APPLICATION_JSON}) public Ticket resolveTicket( @QueryParam("ID") String ID) throws TicketNotFoundException { log.trace("Entered resolveTicket with param ID='"+ID+"'"); Ticket ticket = tickets.getTicketFromID(ID); if (ticket == null){ throw new TicketNotFoundException("The ticket ID '"+ID+"' was not found in the system"); } log.trace("Found ticket='"+ticket.getID()+"'"); return ticket; } @GET @Path("resolveTicket/{ID}") @Produces({MediaType.APPLICATION_JSON}) public Ticket resolveTicketAlt( @PathParam("ID") String ID) throws TicketNotFoundException { return resolveTicket(ID); } }
ticket-system-service/src/main/java/dk/statsbiblioteket/medieplatform/ticketsystem/TicketSystemService.java
package dk.statsbiblioteket.medieplatform.ticketsystem; import dk.statsbiblioteket.doms.webservices.configuration.ConfigCollection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by IntelliJ IDEA. * User: abr * Date: 3/25/11 * Time: 12:17 PM * To change this template use File | Settings | File Templates. */ @Path("/tickets/") public class TicketSystemService { private static TicketSystem tickets; private static Authorization authorization; private static final Object lock = new Object(); private static final String TICKET_TTL_PROP = "dk.statsbiblioteket.ticket-system.timeToLive"; private static final String TICKET_AUTH_SERVICE = "dk.statsbiblioteket.ticket-system.auth-checker"; private final Log log = LogFactory.getLog(TicketSystemService.class); public TicketSystemService() throws BackendException { log.trace("Created a new TicketSystem webservice object"); synchronized (lock){ if (tickets == null){ long ttl; try { String ttlString = ConfigCollection.getProperties() .getProperty(TICKET_TTL_PROP,""+30*1000); log.trace("Read '"+TICKET_TTL_PROP+"' property as '"+ttlString+"'"); ttl = Long.parseLong(ttlString); } catch (NumberFormatException e) { log.warn("Could not parse the '"+ TICKET_TTL_PROP +"' as a long, using default 30 sec timetolive",e); ttl = 30*1000; } String authService = ConfigCollection.getProperties().getProperty(TICKET_AUTH_SERVICE); authorization = new Authorization(authService); tickets = new TicketSystem(ttl, authorization); } } } /*Issuing of tickets*/ @GET @Path("issueTicket") @Produces({MediaType.APPLICATION_JSON}) public Map<String, String> issueTicketGet( @QueryParam("id") List<String> id, @QueryParam("type") String type, @QueryParam("userIdentifier") String userIdentifier, @Context UriInfo uriInfo ) throws MissingArgumentException { return issueTicketQueryParams(id, type, userIdentifier, uriInfo); } @POST @Path("issueTicket") @Produces({MediaType.APPLICATION_JSON}) public Map<String, String> issueTicketQueryParams( @QueryParam("id") List<String> resources, @QueryParam("type") String type, @QueryParam("userIdentifier") String userIdentifier, @Context UriInfo uriInfo ) throws MissingArgumentException { MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); queryParams.remove("id"); queryParams.remove("type"); queryParams.remove("userIdentifier"); if (resources == null){ throw new MissingArgumentException("id is missing"); } if (type == null){ throw new MissingArgumentException("type is missing"); } if (userIdentifier == null){ throw new MissingArgumentException("userIdentifier is missing"); } Map<String, List<String>> userAttributes = new HashMap<String, List<String>>(); for (String key : queryParams.keySet()) { List<String> values = queryParams.get(key); if (values != null && values.size() > 0) { userAttributes.put(key, values); } } HashMap<String, String> ticketMap = new HashMap<String, String>(); Ticket ticket = tickets.issueTicket(resources, type, userIdentifier, userAttributes); for (String resource : ticket.getResources()) { ticketMap.put(resource, ticket.getID()); } log.debug("Issued ticket: " + ticket); return ticketMap; } /*Resolving of tickets*/ @GET @Path("resolveTicket") @Produces({MediaType.APPLICATION_JSON}) public Ticket resolveTicket( @QueryParam("ID") String ID) throws TicketNotFoundException { log.trace("Entered resolveTicket with param ID='"+ID+"'"); Ticket ticket = tickets.getTicketFromID(ID); if (ticket == null){ throw new TicketNotFoundException("The ticket ID '"+ID+"' was not found in the system"); } log.trace("Found ticket='"+ticket.getID()+"'"); return ticket; } @GET @Path("resolveTicket/{ID}") @Produces({MediaType.APPLICATION_JSON}) public Ticket resolveTicketAlt( @PathParam("ID") String ID) throws TicketNotFoundException { return resolveTicket(ID); } }
removed unneeded field
ticket-system-service/src/main/java/dk/statsbiblioteket/medieplatform/ticketsystem/TicketSystemService.java
removed unneeded field
Java
apache-2.0
d819b952d382d2fe2bb51afdd63ea2f947b4eb17
0
brandt/GridSphere,brandt/GridSphere
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.core.persistence.castor.descriptor.Description; import org.gridlab.gridsphere.layout.event.PortletComponentEvent; import org.gridlab.gridsphere.layout.event.PortletTabEvent; import org.gridlab.gridsphere.layout.event.impl.PortletTabEventImpl; import org.gridlab.gridsphere.portlet.PortletRequest; import org.gridlab.gridsphere.portlet.PortletResponse; import org.gridlab.gridsphere.portlet.PortletURI; import org.gridlab.gridsphere.portlet.impl.SportletProperties; import org.gridlab.gridsphere.portletcontainer.GridSphereEvent; import java.io.Serializable; import java.util.*; /** * A <code>PortletTab</code> represents the visual tab graphical interface and is contained * by a {@link PortletTabbedPane}. A tab contains a title and any additional * portlet component, such as another tabbed pane if a double level * tabbed pane is desired. */ public class PortletTab extends BasePortletComponent implements Serializable, Cloneable, Comparator { public static final int DEFAULT_USERTAB_ORDER = 20; private String title = "?"; private List titles = new ArrayList(); private transient boolean selected = false; private String url = null; private PortletComponent portletComponent = null; private int tabOrder = 50; //protected StringBuffer tab = new StringBuffer(); /** * Constructs an instance of PortletTab */ public PortletTab() { } /** * Constructs an instance of PortletTab with the supplied title and * portlet component. * * @param titles the titles of the portlet tab * @param portletComponent any portlet component to represent beneath the tab */ public PortletTab(List titles, PortletComponent portletComponent) { this.titles = titles; this.portletComponent = portletComponent; } public int getTabOrder() { return tabOrder; } public void setTabOrder(int tabOrder) { this.tabOrder = tabOrder; } public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } /** * Returns the portlet tab title * * @return the portlet tab title */ public List getTitles() { return titles; } /** * Sets the portlet tab title * * @param titles the portlet tab title */ public void setTitles(List titles) { this.titles = titles; } /** * Returns the portlet tab title * * @return the portlet tab title */ public String getTitle() { return title; } /** * Sets the portlet tab title * * @param title the portlet tab title */ public void setTitle(String title) { this.title = title; } public String getTitle(String lang) { if (lang == null) throw new IllegalArgumentException("lang is NULL"); Iterator it = titles.iterator(); String defTitle = title; while (it.hasNext()) { Description t = (Description) it.next(); if (t.getLang() == null) t.setLang(Locale.ENGLISH.getLanguage()); if (lang.equals(t.getLang())) return t.getText(); if (t.getLang().regionMatches(0, lang, 0, 2)) return t.getText(); if (t.getLang().equals(Locale.ENGLISH.getLanguage())) defTitle = t.getText(); } return defTitle; } public void setTitle(String lang, String title) { Iterator it = titles.iterator(); boolean found = false; if (lang == null) throw new IllegalArgumentException("lang is NULL"); if (title == null) throw new IllegalArgumentException("title is NULL"); while (it.hasNext()) { Description t = (Description) it.next(); if (lang.equalsIgnoreCase(t.getLang())) { found = true; t.setText(title); } } if (!found) { Description t = new Description(); t.setLang(lang); t.setText(title); titles.add(t); } } /** * Creates the portlet tab title links that are rendered by the * {@link PortletTabbedPane} * * @param event the gridsphere event */ public String createTabTitleLink(GridSphereEvent event) { if (url != null) return url; PortletResponse res = event.getPortletResponse(); PortletURI portletURI = res.createURI(); portletURI.addParameter(SportletProperties.COMPONENT_ID, componentIDStr); return portletURI.toString(); } /** * Sets the selected flag used in determining if this tab is selected and * should be rendered * * @param selected the selected flag is true if this tag is currently selected */ public void setSelected(boolean selected) { this.selected = selected; } /** * Returns the selected flag used in determining if this tab is selected and * hence rendered * * @return true if the tab is selected, false otherwise */ public boolean isSelected() { return selected; } /** * Sets the concrete portlet component contained by the portlet tab * * @param portletComponent a concrete portlet component instance */ public void setPortletComponent(PortletComponent portletComponent) { this.portletComponent = portletComponent; } /** * Returns the concrete portlet component contained by the portlet tab * * @return the concrete portlet component instance conatined by this tab */ public PortletComponent getPortletComponent() { return portletComponent; } public void removePortletComponent() { this.portletComponent = null; } /** * Initializes the portlet tab. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(PortletRequest req, List list) { list = super.init(req, list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setComponentID(list.size()); compId.setComponentLabel(label); compId.setClassName(this.getClass().getName()); list.add(compId); portletComponent.setTheme(theme); portletComponent.setRenderKit(renderKit); list = portletComponent.init(req, list); portletComponent.addComponentListener(this); portletComponent.setParentComponent(this); return list; } public void remove(PortletComponent pc, PortletRequest req) { portletComponent = null; parent.remove(this, req); } /** * Performs an action on this portlet tab component * * @param event a gridsphere event */ public void actionPerformed(GridSphereEvent event) { super.actionPerformed(event); PortletComponentEvent compEvt = event.getLastRenderEvent(); PortletTabEvent tabEvent = new PortletTabEventImpl(this, event.getPortletRequest(), PortletTabEvent.TabAction.TAB_SELECTED, COMPONENT_ID); List l = Collections.synchronizedList(listeners); synchronized (l) { Iterator it = l.iterator(); PortletComponent comp; while (it.hasNext()) { comp = (PortletComponent) it.next(); event.addNewRenderEvent(tabEvent); comp.actionPerformed(event); } } } /** * Renders the portlet tab component * * @param event a gridsphere event */ public void doRender(GridSphereEvent event) { super.doRender(event); List userRoles = event.getPortletRequest().getRoles(); StringBuffer tab = new StringBuffer(); if (roleString.equals("") || (userRoles.contains(roleString))) { portletComponent.doRender(event); tab.append(portletComponent.getBufferedOutput(event.getPortletRequest())); } event.getPortletRequest().setAttribute(SportletProperties.RENDER_OUTPUT + componentIDStr, tab); } public int compare(Object left, Object right) { int leftID = ((PortletTab) left).getTabOrder(); int rightID = ((PortletTab) right).getTabOrder(); int result; if (leftID < rightID) { result = -1; } else if (leftID > rightID) { result = 1; } else { result = 0; } return result; } public boolean equals(Object object) { if (object != null && (object.getClass().equals(this.getClass()))) { PortletTab portletTab = (PortletTab) object; return (tabOrder == portletTab.getTabOrder()); } return false; } public Object clone() throws CloneNotSupportedException { PortletTab t = (PortletTab) super.clone(); t.tabOrder = this.tabOrder; t.url = this.url; t.portletComponent = (this.portletComponent == null) ? null : (PortletComponent) this.portletComponent.clone(); t.selected = this.selected; List stitles = Collections.synchronizedList(titles); synchronized (stitles) { t.titles = new ArrayList(stitles.size()); for (int i = 0; i < stitles.size(); i++) { Description title = (Description) stitles.get(i); t.titles.add(title.clone()); } } return t; } }
src/org/gridlab/gridsphere/layout/PortletTab.java
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.core.persistence.castor.descriptor.Description; import org.gridlab.gridsphere.layout.event.PortletComponentEvent; import org.gridlab.gridsphere.layout.event.PortletTabEvent; import org.gridlab.gridsphere.layout.event.impl.PortletTabEventImpl; import org.gridlab.gridsphere.portlet.PortletRequest; import org.gridlab.gridsphere.portlet.PortletResponse; import org.gridlab.gridsphere.portlet.PortletRole; import org.gridlab.gridsphere.portlet.PortletURI; import org.gridlab.gridsphere.portlet.impl.SportletProperties; import org.gridlab.gridsphere.portletcontainer.GridSphereEvent; import java.io.IOException; import java.io.Serializable; import java.util.*; /** * A <code>PortletTab</code> represents the visual tab graphical interface and is contained * by a {@link PortletTabbedPane}. A tab contains a title and any additional * portlet component, such as another tabbed pane if a double level * tabbed pane is desired. */ public class PortletTab extends BasePortletComponent implements Serializable, Cloneable, Comparator { public static final int DEFAULT_USERTAB_ORDER = 20; private String title = "?"; private List titles = new ArrayList(); private transient boolean selected = false; private PortletComponent portletComponent = null; private int tabOrder = 50; //protected StringBuffer tab = new StringBuffer(); /** * Constructs an instance of PortletTab */ public PortletTab() { } /** * Constructs an instance of PortletTab with the supplied title and * portlet component. * * @param titles the titles of the portlet tab * @param portletComponent any portlet component to represent beneath the tab */ public PortletTab(List titles, PortletComponent portletComponent) { this.titles = titles; this.portletComponent = portletComponent; } public int getTabOrder() { return tabOrder; } public void setTabOrder(int tabOrder) { this.tabOrder = tabOrder; } /** * Returns the portlet tab title * * @return the portlet tab title */ public List getTitles() { return titles; } /** * Sets the portlet tab title * * @param titles the portlet tab title */ public void setTitles(List titles) { this.titles = titles; } /** * Returns the portlet tab title * * @return the portlet tab title */ public String getTitle() { return title; } /** * Sets the portlet tab title * * @param title the portlet tab title */ public void setTitle(String title) { this.title = title; } public String getTitle(String lang) { if (lang == null) throw new IllegalArgumentException("lang is NULL"); Iterator it = titles.iterator(); String defTitle = title; while (it.hasNext()) { Description t = (Description) it.next(); if (t.getLang() == null) t.setLang(Locale.ENGLISH.getLanguage()); if (lang.equals(t.getLang())) return t.getText(); if (t.getLang().regionMatches(0, lang, 0, 2)) return t.getText(); if (t.getLang().equals(Locale.ENGLISH.getLanguage())) defTitle = t.getText(); } return defTitle; } public void setTitle(String lang, String title) { Iterator it = titles.iterator(); boolean found = false; if (lang == null) throw new IllegalArgumentException("lang is NULL"); if (title == null) throw new IllegalArgumentException("title is NULL"); while (it.hasNext()) { Description t = (Description) it.next(); if (lang.equalsIgnoreCase(t.getLang())) { found = true; t.setText(title); } } if (!found) { Description t = new Description(); t.setLang(lang); t.setText(title); titles.add(t); } } /** * Creates the portlet tab title links that are rendered by the * {@link PortletTabbedPane} * * @param event the gridsphere event */ public String createTabTitleLink(GridSphereEvent event) { PortletResponse res = event.getPortletResponse(); PortletURI portletURI = res.createURI(); portletURI.addParameter(SportletProperties.COMPONENT_ID, componentIDStr); return portletURI.toString(); } /** * Sets the selected flag used in determining if this tab is selected and * should be rendered * * @param selected the selected flag is true if this tag is currently selected */ public void setSelected(boolean selected) { this.selected = selected; } /** * Returns the selected flag used in determining if this tab is selected and * hence rendered * * @return true if the tab is selected, false otherwise */ public boolean isSelected() { return selected; } /** * Sets the concrete portlet component contained by the portlet tab * * @param portletComponent a concrete portlet component instance */ public void setPortletComponent(PortletComponent portletComponent) { this.portletComponent = portletComponent; } /** * Returns the concrete portlet component contained by the portlet tab * * @return the concrete portlet component instance conatined by this tab */ public PortletComponent getPortletComponent() { return portletComponent; } public void removePortletComponent() { this.portletComponent = null; } /** * Initializes the portlet tab. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(PortletRequest req, List list) { list = super.init(req, list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setComponentID(list.size()); compId.setComponentLabel(label); compId.setClassName(this.getClass().getName()); list.add(compId); portletComponent.setTheme(theme); portletComponent.setRenderKit(renderKit); list = portletComponent.init(req, list); portletComponent.addComponentListener(this); portletComponent.setParentComponent(this); return list; } public void remove(PortletComponent pc, PortletRequest req) { portletComponent = null; parent.remove(this, req); } /** * Performs an action on this portlet tab component * * @param event a gridsphere event */ public void actionPerformed(GridSphereEvent event) { super.actionPerformed(event); PortletComponentEvent compEvt = event.getLastRenderEvent(); PortletTabEvent tabEvent = new PortletTabEventImpl(this, event.getPortletRequest(), PortletTabEvent.TabAction.TAB_SELECTED, COMPONENT_ID); List l = Collections.synchronizedList(listeners); synchronized (l) { Iterator it = l.iterator(); PortletComponent comp; while (it.hasNext()) { comp = (PortletComponent) it.next(); event.addNewRenderEvent(tabEvent); comp.actionPerformed(event); } } } /** * Renders the portlet tab component * * @param event a gridsphere event */ public void doRender(GridSphereEvent event) { super.doRender(event); List userRoles = event.getPortletRequest().getRoles(); StringBuffer tab = new StringBuffer(); if (roleString.equals("") || (userRoles.contains(roleString))) { portletComponent.doRender(event); tab.append(portletComponent.getBufferedOutput(event.getPortletRequest())); } event.getPortletRequest().setAttribute(SportletProperties.RENDER_OUTPUT + componentIDStr, tab); } public int compare(Object left, Object right) { int leftID = ((PortletTab) left).getTabOrder(); int rightID = ((PortletTab) right).getTabOrder(); int result; if (leftID < rightID) { result = -1; } else if (leftID > rightID) { result = 1; } else { result = 0; } return result; } public boolean equals(Object object) { if (object != null && (object.getClass().equals(this.getClass()))) { PortletTab portletTab = (PortletTab) object; return (tabOrder == portletTab.getTabOrder()); } return false; } public Object clone() throws CloneNotSupportedException { PortletTab t = (PortletTab) super.clone(); t.tabOrder = this.tabOrder; t.portletComponent = (this.portletComponent == null) ? null : (PortletComponent) this.portletComponent.clone(); t.selected = this.selected; List stitles = Collections.synchronizedList(titles); synchronized (stitles) { t.titles = new ArrayList(stitles.size()); for (int i = 0; i < stitles.size(); i++) { Description title = (Description) stitles.get(i); t.titles.add(title.clone()); } } return t; } }
GPF-185 add ability to provide external links in tabs. Added new attribute to portlet-tab 'url' to do this. AT the same time got rid of the javascript=enabled stuff git-svn-id: 616481d960d639df1c769687dde8737486ca2a9a@4540 9c99c85f-4d0c-0410-8460-a9a1c48a3a7f
src/org/gridlab/gridsphere/layout/PortletTab.java
GPF-185 add ability to provide external links in tabs. Added new attribute to portlet-tab 'url' to do this. AT the same time got rid of the javascript=enabled stuff
Java
apache-2.0
1ad4a07617d825c80bc7210575fb2e7d2d04f0a6
0
jjj117/airavata,gouravshenoy/airavata,apache/airavata,gouravshenoy/airavata,hasinitg/airavata,dogless/airavata,apache/airavata,gouravshenoy/airavata,hasinitg/airavata,apache/airavata,anujbhan/airavata,gouravshenoy/airavata,dogless/airavata,machristie/airavata,apache/airavata,machristie/airavata,gouravshenoy/airavata,anujbhan/airavata,glahiru/airavata,jjj117/airavata,apache/airavata,anujbhan/airavata,gouravshenoy/airavata,glahiru/airavata,hasinitg/airavata,apache/airavata,jjj117/airavata,apache/airavata,jjj117/airavata,glahiru/airavata,hasinitg/airavata,anujbhan/airavata,glahiru/airavata,machristie/airavata,anujbhan/airavata,hasinitg/airavata,dogless/airavata,machristie/airavata,dogless/airavata,machristie/airavata,hasinitg/airavata,dogless/airavata,jjj117/airavata,apache/airavata,anujbhan/airavata,glahiru/airavata,machristie/airavata,dogless/airavata,anujbhan/airavata,machristie/airavata,jjj117/airavata,gouravshenoy/airavata
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.common.registry.api.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import javax.jcr.Credentials; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.RepositoryFactory; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.observation.Event; import javax.jcr.observation.EventIterator; import javax.jcr.observation.EventListener; import org.apache.airavata.common.registry.api.Registry; import org.apache.airavata.common.registry.api.user.UserManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JCRRegistry extends Observable implements Registry{ private static final String XML_PROPERTY_NAME = "XML"; public static final String PUBLIC = "PUBLIC"; private Repository repository; private Credentials credentials; private UserManager userManager; private String username; private URI repositoryURI; private Class registryRepositoryFactory; private Map<String,String> connectionMap; private String password; private Session defaultSession=null; private boolean sessionKeepAlive=false; private EventListener workspaceChangeEventListener; private Thread sessionManager; private static final int SESSION_TIME_OUT = 60000; private static final int DEFINITE_SESSION_TIME_OUT = 300000; private static Logger log = LoggerFactory.getLogger(JCRRegistry.class); private Map<Node,Map<String,Node>> sessionNodes; private Map<Node,List<Node>> sessionNodeChildren; private Map<Session,Integer> currentSessionUseCount=new HashMap<Session, Integer>(); private boolean threadRun = true; public JCRRegistry(URI repositoryURI, String className, String user, String pass, Map<String, String> map) throws RepositoryException { try { /* * Load the configuration from properties file at this level and create the object */ connectionMap = map; registryRepositoryFactory = Class.forName(className); Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); setRepositoryURI(repositoryURI); repository = repositoryFactory.getRepository(connectionMap); setUsername(user); setPassword(pass); credentials = new SimpleCredentials(getUsername(), new String(pass).toCharArray()); definiteSessionTimeout(); workspaceChangeEventListener=new EventListener() { public void onEvent(EventIterator events) { for(;events.hasNext();){ Event event=events.nextEvent(); boolean isPropertyChange = (event.getType()&(Event.PROPERTY_CHANGED|Event.PROPERTY_ADDED|Event.PROPERTY_REMOVED))>0; try { String path = event.getPath(); synchronized (sessionSynchronousObject) { // System.out.println("something happened: " + event.getType() + " " + path); List<Node> nodesToRemove=new ArrayList<Node>(); Set<Node> nodeIterator = getSessionNodes().keySet(); for (Node node : nodeIterator) { if (node == null) { if (path.equals("/")) { nodesToRemove.add(node); } } else { if (node.getSession().isLive()) { if (isPropertyChange){ if (node.getPath().equals(path)) { nodesToRemove.add(node); } }else if (node.getPath().startsWith(path) || path.startsWith(node.getPath())) { nodesToRemove.add(node); } } } } for(Node node:nodesToRemove){ getSessionNodes().remove(node); } nodeIterator = getSessionNodeChildren().keySet(); nodesToRemove.clear(); for (Node node : nodeIterator) { if (node.getSession().isLive()) { if (isPropertyChange){ if (node.getPath().equals(path)) { nodesToRemove.add(node); } }else if (node.getPath().startsWith(path) || path.startsWith(node.getPath())) { nodesToRemove.add(node); } } } for(Node node:nodesToRemove){ getSessionNodeChildren().remove(node); } } triggerObservers(this); } catch (RepositoryException e) { e.printStackTrace(); } } } }; } catch (ClassNotFoundException e) { log.error("Error class path settting", e); } catch (RepositoryException e) { log.error("Error connecting Remote Registry instance", e); throw e; } catch (Exception e) { log.error("Error init", e); } } private void definiteSessionTimeout(){ Thread m=new Thread(new Runnable() { public void run() { while (threadRun){ int timeoutCount=0; int shortStep=10000; Session currentSession=defaultSession; while(timeoutCount<DEFINITE_SESSION_TIME_OUT){ try { Thread.sleep(shortStep); } catch (InterruptedException e) { //life sucks anyway, so who cares if this exception is thrown } timeoutCount=timeoutCount+shortStep; if (currentSession!=defaultSession){ //reset start from begining since its a new session currentSession=defaultSession; timeoutCount=0; } } reallyCloseSession(defaultSession); } } }); m.start(); } private void setupSessionManagement(){ stopSessionManager(); setSessionKeepAlive(true); sessionManager=new Thread(new Runnable() { public void run() { while (!isSessionInvalid() && isSessionKeepAlive()){ try { setSessionKeepAlive(false); Thread.sleep(SESSION_TIME_OUT); } catch (InterruptedException e) { //no issue } } reallyCloseSession(defaultSession); } }); sessionManager.start(); } private void stopSessionManager(){ if (sessionManager!=null) { sessionManager.interrupt(); } } protected boolean isSessionKeepAlive() { return sessionKeepAlive; } public JCRRegistry(Repository repo, Credentials credentials) { this.repository = repo; this.credentials = credentials; } protected Node getRootNode(Session session) throws RepositoryException { String ROOT_NODE_TEXT = "root"; if (!getSessionNodes().containsKey(null) || !getSessionNodes().get(null).get(ROOT_NODE_TEXT).getSession().isLive()){ getSessionNodes().put(null, new HashMap<String, Node>()); getSessionNodes().get(null).put(ROOT_NODE_TEXT, session.getRootNode()); } return getOrAddNode(null, ROOT_NODE_TEXT); } public Session getSession() throws RepositoryException { if (isSessionInvalid()){ reallyCloseSession(defaultSession); synchronized (sessionSynchronousObject) { // System.out.println("session created"); Session session = null; try { session = repository.login(credentials); if (session == null) { session = resetSession(session); } } catch (Exception e) { session = resetSession(session); } defaultSession=session; if (defaultSession!=null) { defaultSession .getWorkspace() .getObservationManager() .addEventListener( getWorkspaceChangeEventListener(), Event.NODE_ADDED | Event.NODE_REMOVED | Event.NODE_MOVED | Event.PROPERTY_CHANGED | Event.PROPERTY_ADDED | Event.PROPERTY_REMOVED, "/", true, null, null, false); currentSessionUseCount.put(session, 1); } } setupSessionManagement(); }else{ setSessionKeepAlive(true); synchronized (sessionSynchronousObject) { currentSessionUseCount.put(defaultSession, currentSessionUseCount.get(defaultSession)+1); } } return defaultSession; } protected Session resetSession(Session session){ try { Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); setRepositoryURI(repositoryURI); repository = repositoryFactory.getRepository(connectionMap); setUsername(username); credentials = new SimpleCredentials(getUsername(), getPassword().toCharArray()); session = repository.login(credentials); } catch (NoSuchMethodException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InstantiationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InvocationTargetException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (RepositoryException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return session; } protected Node getOrAddNode(Node node, String name) throws RepositoryException { Map<Node, Map<String, Node>> sessionNodes = getSessionNodes(); if (sessionNodes.containsKey(node)){ if (sessionNodes.get(node)!=null && sessionNodes.get(node).containsKey(name)){ if (sessionNodes.get(node).get(name).getSession().isLive()){ return sessionNodes.get(node).get(name); } } }else{ sessionNodes.put(node,new HashMap<String, Node>()); } Node node1 = null; try { // System.out.println("node extracted"); // if (node==null){ //root node // node1=getSession().getRootNode(); // }else{ node1 = node.getNode(name); // } sessionNodes.get(node).put(name, node1); } catch (PathNotFoundException pnfe) { node1 = node.addNode(name); } catch (RepositoryException e) { String msg = "failed to resolve the path of the given node "; log.debug(msg); throw new RepositoryException(msg, e); } return node1; } protected void closeSession(Session session) { if (session!=null) { if (currentSessionUseCount!=null) { currentSessionUseCount.put(session, currentSessionUseCount.get(session) - 1); } if (session != defaultSession) { reallyCloseSession(session); } } } protected void reallyCloseSession(Session session) { synchronized (sessionSynchronousObject) { if (session!=null && currentSessionUseCount.get(session)==0){ if (session != null && session.isLive()) { try { session.getWorkspace().getObservationManager().removeEventListener(getWorkspaceChangeEventListener()); } catch (UnsupportedRepositoryOperationException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } session.logout(); } sessionNodes=null; sessionNodeChildren=null; // sessionNodes=new HashMap<Node, Map<String,Node>>(); // sessionNodeChildren=new HashMap<Node, List<Node>>(); if (session!=defaultSession){ currentSessionUseCount.remove(session); } } } } private boolean isSessionInvalid(){ boolean isValid=false; synchronized (sessionSynchronousObject) { isValid=(defaultSession==null || !defaultSession.isLive()); } return isValid; } private Object sessionSynchronousObject=new Object(); public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public URI getRepositoryURI() { return repositoryURI; } protected void setRepositoryURI(URI repositoryURI) { this.repositoryURI = repositoryURI; } protected void triggerObservers(Object o) { setChanged(); notifyObservers(o); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return repository.getDescriptor(Repository.REP_NAME_DESC); } public Repository getRepository() { return repository; } public void setSessionKeepAlive(boolean sessionKeepAlive) { this.sessionKeepAlive = sessionKeepAlive; } private Map<Node,Map<String,Node>> getSessionNodes() { if (sessionNodes==null) { sessionNodes=new HashMap<Node, Map<String,Node>>(); } return sessionNodes; } protected List<Node> getChildNodes(Node node) throws RepositoryException{ if (getSessionNodeChildren().containsKey(node)){ if (getSessionNodeChildren().get(node).size()==0 || (getSessionNodeChildren().get(node).get(0).getSession().isLive())){ return getSessionNodeChildren().get(node); } } List<Node> children=new ArrayList<Node>(); NodeIterator nodes = node.getNodes(); for (;nodes.hasNext();) { children.add(nodes.nextNode()); } getSessionNodeChildren().put(node,children); return children; } public Map<Node,List<Node>> getSessionNodeChildren() { if (sessionNodeChildren==null) { sessionNodeChildren=new HashMap<Node, List<Node>>(); } return sessionNodeChildren; } public EventListener getWorkspaceChangeEventListener() { return workspaceChangeEventListener; } public void setWorkspaceChangeEventListener( EventListener workspaceChangeEventListener) { this.workspaceChangeEventListener = workspaceChangeEventListener; } private void setThreadRun(boolean threadRun) { this.threadRun = threadRun; } public void closeConnection(){ setThreadRun(false); } }
modules/commons/common-registry-api/src/main/java/org/apache/airavata/common/registry/api/impl/JCRRegistry.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.common.registry.api.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import javax.jcr.Credentials; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.RepositoryFactory; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.observation.Event; import javax.jcr.observation.EventIterator; import javax.jcr.observation.EventListener; import org.apache.airavata.common.registry.api.Registry; import org.apache.airavata.common.registry.api.user.UserManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JCRRegistry extends Observable implements Registry{ private static final String XML_PROPERTY_NAME = "XML"; public static final String PUBLIC = "PUBLIC"; private Repository repository; private Credentials credentials; private UserManager userManager; private String username; private URI repositoryURI; private Class registryRepositoryFactory; private Map<String,String> connectionMap; private String password; private Session defaultSession=null; private boolean sessionKeepAlive=false; private EventListener workspaceChangeEventListener; private Thread sessionManager; private static final int SESSION_TIME_OUT = 60000; private static final int DEFINITE_SESSION_TIME_OUT = 300000; private static Logger log = LoggerFactory.getLogger(JCRRegistry.class); private Map<Node,Map<String,Node>> sessionNodes; private Map<Node,List<Node>> sessionNodeChildren; private Map<Session,Integer> currentSessionUseCount=new HashMap<Session, Integer>(); private boolean threadRun = true; public JCRRegistry(URI repositoryURI, String className, String user, String pass, Map<String, String> map) throws RepositoryException { try { /* * Load the configuration from properties file at this level and create the object */ connectionMap = map; registryRepositoryFactory = Class.forName(className); Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); setRepositoryURI(repositoryURI); repository = repositoryFactory.getRepository(connectionMap); setUsername(user); setPassword(pass); credentials = new SimpleCredentials(getUsername(), new String(pass).toCharArray()); definiteSessionTimeout(); workspaceChangeEventListener=new EventListener() { public void onEvent(EventIterator events) { for(;events.hasNext();){ Event event=events.nextEvent(); boolean isPropertyChange = (event.getType()&(Event.PROPERTY_CHANGED|Event.PROPERTY_ADDED|Event.PROPERTY_REMOVED))>0; try { String path = event.getPath(); synchronized (sessionSynchronousObject) { // System.out.println("something happened: " + event.getType() + " " + path); List<Node> nodesToRemove=new ArrayList<Node>(); Set<Node> nodeIterator = getSessionNodes().keySet(); for (Node node : nodeIterator) { if (node == null) { if (path.equals("/")) { nodesToRemove.add(node); } } else { if (node.getSession().isLive()) { if (isPropertyChange){ if (node.getPath().equals(path)) { nodesToRemove.add(node); } }else if (node.getPath().startsWith(path) || path.startsWith(node.getPath())) { nodesToRemove.add(node); } } } } for(Node node:nodesToRemove){ getSessionNodes().remove(node); } nodeIterator = getSessionNodeChildren().keySet(); nodesToRemove.clear(); for (Node node : nodeIterator) { if (node.getSession().isLive()) { if (isPropertyChange){ if (node.getPath().equals(path)) { nodesToRemove.add(node); } }else if (node.getPath().startsWith(path) || path.startsWith(node.getPath())) { nodesToRemove.add(node); } } } for(Node node:nodesToRemove){ getSessionNodeChildren().remove(node); } } triggerObservers(this); } catch (RepositoryException e) { e.printStackTrace(); } } } }; } catch (ClassNotFoundException e) { log.error("Error class path settting", e); } catch (RepositoryException e) { log.error("Error connecting Remote Registry instance", e); throw e; } catch (Exception e) { log.error("Error init", e); } } private void definiteSessionTimeout(){ Thread m=new Thread(new Runnable() { public void run() { while (threadRun){ int timeoutCount=0; int shortStep=10000; Session currentSession=defaultSession; while(timeoutCount<DEFINITE_SESSION_TIME_OUT){ try { Thread.sleep(shortStep); } catch (InterruptedException e) { //life sucks anyway, so who cares if this exception is thrown } timeoutCount=timeoutCount+shortStep; if (currentSession!=defaultSession){ //reset start from begining since its a new session currentSession=defaultSession; timeoutCount=0; } } reallyCloseSession(defaultSession); } } }); m.start(); } private void setupSessionManagement(){ stopSessionManager(); setSessionKeepAlive(true); sessionManager=new Thread(new Runnable() { public void run() { while (!isSessionInvalid() && isSessionKeepAlive()){ try { setSessionKeepAlive(false); Thread.sleep(SESSION_TIME_OUT); } catch (InterruptedException e) { //no issue } } reallyCloseSession(defaultSession); } }); sessionManager.start(); } private void stopSessionManager(){ if (sessionManager!=null) { sessionManager.interrupt(); } } protected boolean isSessionKeepAlive() { return sessionKeepAlive; } public JCRRegistry(Repository repo, Credentials credentials) { this.repository = repo; this.credentials = credentials; } protected Node getRootNode(Session session) throws RepositoryException { String ROOT_NODE_TEXT = "root"; if (!getSessionNodes().containsKey(null)){ getSessionNodes().put(null, new HashMap<String, Node>()); getSessionNodes().get(null).put(ROOT_NODE_TEXT, session.getRootNode()); } return getOrAddNode(null, ROOT_NODE_TEXT); } public Session getSession() throws RepositoryException { if (isSessionInvalid()){ reallyCloseSession(defaultSession); synchronized (sessionSynchronousObject) { // System.out.println("session created"); Session session = null; try { session = repository.login(credentials); if (session == null) { session = resetSession(session); } } catch (Exception e) { session = resetSession(session); } defaultSession=session; if (defaultSession!=null) { defaultSession .getWorkspace() .getObservationManager() .addEventListener( getWorkspaceChangeEventListener(), Event.NODE_ADDED | Event.NODE_REMOVED | Event.NODE_MOVED | Event.PROPERTY_CHANGED | Event.PROPERTY_ADDED | Event.PROPERTY_REMOVED, "/", true, null, null, false); currentSessionUseCount.put(session, 1); } } setupSessionManagement(); }else{ setSessionKeepAlive(true); synchronized (sessionSynchronousObject) { currentSessionUseCount.put(defaultSession, currentSessionUseCount.get(defaultSession)+1); } } return defaultSession; } protected Session resetSession(Session session){ try { Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); setRepositoryURI(repositoryURI); repository = repositoryFactory.getRepository(connectionMap); setUsername(username); credentials = new SimpleCredentials(getUsername(), getPassword().toCharArray()); session = repository.login(credentials); } catch (NoSuchMethodException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InstantiationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InvocationTargetException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (RepositoryException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return session; } protected Node getOrAddNode(Node node, String name) throws RepositoryException { Map<Node, Map<String, Node>> sessionNodes = getSessionNodes(); if (sessionNodes.containsKey(node)){ if (sessionNodes.get(node)!=null && sessionNodes.get(node).containsKey(name)){ if (sessionNodes.get(node).get(name).getSession().isLive()){ return sessionNodes.get(node).get(name); } } }else{ sessionNodes.put(node,new HashMap<String, Node>()); } Node node1 = null; try { // System.out.println("node extracted"); node1 = node.getNode(name); sessionNodes.get(node).put(name, node1); } catch (PathNotFoundException pnfe) { node1 = node.addNode(name); } catch (RepositoryException e) { String msg = "failed to resolve the path of the given node "; log.debug(msg); throw new RepositoryException(msg, e); } return node1; } protected void closeSession(Session session) { if (session!=null) { if (currentSessionUseCount!=null) { currentSessionUseCount.put(session, currentSessionUseCount.get(session) - 1); } if (session != defaultSession) { reallyCloseSession(session); } } } protected void reallyCloseSession(Session session) { synchronized (sessionSynchronousObject) { if (session!=null && currentSessionUseCount.get(session)==0){ if (session != null && session.isLive()) { try { session.getWorkspace().getObservationManager().removeEventListener(getWorkspaceChangeEventListener()); } catch (UnsupportedRepositoryOperationException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } session.logout(); } sessionNodes=null; sessionNodeChildren=null; // sessionNodes=new HashMap<Node, Map<String,Node>>(); // sessionNodeChildren=new HashMap<Node, List<Node>>(); if (session!=defaultSession){ currentSessionUseCount.remove(session); } } } } private boolean isSessionInvalid(){ boolean isValid=false; synchronized (sessionSynchronousObject) { isValid=(defaultSession==null || !defaultSession.isLive()); } return isValid; } private Object sessionSynchronousObject=new Object(); public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public URI getRepositoryURI() { return repositoryURI; } protected void setRepositoryURI(URI repositoryURI) { this.repositoryURI = repositoryURI; } protected void triggerObservers(Object o) { setChanged(); notifyObservers(o); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return repository.getDescriptor(Repository.REP_NAME_DESC); } public Repository getRepository() { return repository; } public void setSessionKeepAlive(boolean sessionKeepAlive) { this.sessionKeepAlive = sessionKeepAlive; } private Map<Node,Map<String,Node>> getSessionNodes() { if (sessionNodes==null) { sessionNodes=new HashMap<Node, Map<String,Node>>(); } return sessionNodes; } protected List<Node> getChildNodes(Node node) throws RepositoryException{ if (getSessionNodeChildren().containsKey(node)){ if (getSessionNodeChildren().get(node).size()==0 || (getSessionNodeChildren().get(node).get(0).getSession().isLive())){ return getSessionNodeChildren().get(node); } } List<Node> children=new ArrayList<Node>(); NodeIterator nodes = node.getNodes(); for (;nodes.hasNext();) { children.add(nodes.nextNode()); } getSessionNodeChildren().put(node,children); return children; } public Map<Node,List<Node>> getSessionNodeChildren() { if (sessionNodeChildren==null) { sessionNodeChildren=new HashMap<Node, List<Node>>(); } return sessionNodeChildren; } public EventListener getWorkspaceChangeEventListener() { return workspaceChangeEventListener; } public void setWorkspaceChangeEventListener( EventListener workspaceChangeEventListener) { this.workspaceChangeEventListener = workspaceChangeEventListener; } private void setThreadRun(boolean threadRun) { this.threadRun = threadRun; } public void closeConnection(){ setThreadRun(false); } }
handling the case where the root node session has expired git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1304532 13f79535-47bb-0310-9956-ffa450edef68
modules/commons/common-registry-api/src/main/java/org/apache/airavata/common/registry/api/impl/JCRRegistry.java
handling the case where the root node session has expired
Java
apache-2.0
4969a1b1c46f199092ec5e78dee8f4db9ce5ff3c
0
InformaticsMatters/squonk,InformaticsMatters/squonk,InformaticsMatters/squonk,InformaticsMatters/squonk
package org.squonk.chemaxon.services; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.camel.model.rest.RestBindingMode; import org.squonk.camel.chemaxon.processor.clustering.SphereExclusionClusteringProcessor; import org.squonk.camel.chemaxon.processor.enumeration.ReactorProcessor; import org.squonk.camel.chemaxon.processor.screening.MoleculeScreenerProcessor; import org.squonk.camel.processor.DatasetToJsonProcessor; import org.squonk.camel.processor.JsonToDatasetProcessor; import org.squonk.camel.processor.MoleculeObjectRouteHttpProcessor; import org.squonk.chemaxon.molecule.ChemTermsEvaluator; import org.squonk.core.AccessMode; import org.squonk.core.ServiceDescriptor; import org.squonk.core.ServiceDescriptor.DataType; import org.squonk.execution.steps.StepDefinitionConstants; import org.squonk.mqueue.MessageQueueCredentials; import org.squonk.options.MoleculeTypeDescriptor; import org.squonk.options.OptionDescriptor; import org.squonk.types.MoleculeObject; import org.squonk.types.NumberRange; import org.squonk.types.TypeResolver; import org.squonk.util.CommonConstants; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_NAME; import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_PARAMS; /** * @author timbo */ public class ChemaxonRestRouteBuilder extends RouteBuilder { private static final Logger LOG = Logger.getLogger(ChemaxonRestRouteBuilder.class.getName()); private static final String ROUTE_STATS = "seda:post_stats"; private static final String HEADER = "header."; private static final String KEY_SIM_CUTTOFF = HEADER + MoleculeScreenerProcessor.HEADER_THRESHOLD; private static final String LABEL_SIM_CUTTOFF = "Similarity Cuttoff"; private static final String DESC_SIM_CUTTOFF = "Similarity score cuttoff between 0 and 1 (1 means identical)"; private static final String KEY_QMOL = HEADER + MoleculeScreenerProcessor.HEADER_QUERY_MOLECULE; private static final String LABEL_QMOL = "Query Structure"; private static final String DESC_QMOL = "Structure to use as the query"; // private static final String KEY_CT_EXPR = "ct_expr"; // private static final String LABEL_CT_EXPR = "ChemTerms Expression"; // private static final String DESC_CT_EXPR = "Expression using the Chemical Terms language"; private static final String KEY_MIN_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MIN_CLUSTER_COUNT; private static final String LABEL_MIN_CLUSTERS = "Min clusters"; private static final String DESC_MIN_CLUSTERS = "Minimum number of clusters to generate"; private static final String KEY_MAX_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MAX_CLUSTER_COUNT; private static final String LABEL_MAX_CLUSTERS = "Max clusters"; private static final String DESC_MAX_CLUSTERS = "Target maximum number of clusters to generate"; private static final TypeResolver resolver = new TypeResolver(); private final String mqueueUrl = new MessageQueueCredentials().generateUrl(MQUEUE_JOB_METRICS_EXCHANGE_NAME, MQUEUE_JOB_METRICS_EXCHANGE_PARAMS) + "&routingKey=tokens.chemaxon"; protected static final ServiceDescriptor[] SERVICE_DESCRIPTOR_CALCULATORS = new ServiceDescriptor[]{ createServiceDescriptor( "chemaxon.calculators.verify", "Verify structure (ChemAxon)", "Verify that the molecules are valid according to ChemAxon's Marvin", new String[]{"verify", "chemaxon"}, "icons/properties_add.png", new String[]{"/Chemistry/Toolkits/ChemAxon/Verify", "/Chemistry/Verify"}, "asyncHttp", "verify", 0f, new OptionDescriptor[] {OptionDescriptor.IS_FILTER, OptionDescriptor.FILTER_MODE}), createServiceDescriptor( "chemaxon.calculators.logp", "LogP (CXN)", "LogP using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-predictors/#logp_logd", new String[]{"logp", "partitioning", "molecularproperties", "chemaxon"}, "icons/properties_add.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Partioning"}, "asyncHttp", "logp", 0.001f, null), createServiceDescriptor( "chemaxon.calculators.atomcount", "Atom Count (CXN)", "Atom Count using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-calculations/#topology_analysis", new String[]{"atomcount", "topology", "molecularproperties", "chemaxon"}, "icons/properties_add.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Topological"}, "asyncHttp", "atomCount", 0f, null), createServiceDescriptor( "chemaxon.calculators.lipinski", "Lipinski (CXN)", "Lipinski rule of 5 filter using ChemAxon calculators", new String[]{"lipinski", "filter", "druglike", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "lipinski", 0.002f, createLipinskiOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.druglikefilter", "Drug-like Filter (CXN)", "Drug-like filter using ChemAxon calculators", new String[]{"druglike", "filter", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "drugLikeFilter", 0.0025f, createDrugLikeFilterOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.ghosefilter", "Ghose Filter (CXN)", "Ghose filter using ChemAxon calculators", new String[]{"ghose", "filter", "druglike", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/GhoseFilter"}, "asyncHttp", "ghosefilter", 0.0025f, createGhoseFilterOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.ruleofthreefilter", "Rule of 3 Filter (CXN)", "Astex Rule of 3 filter using ChemAxon calculators", new String[]{"ruleofthree", "ro3", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "leadlike", "molecularproperties", "filter", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "ruleOfThreeFilter", 0.0025f, createRuleOfThreeOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.reosfilter", "REOS (CXN)", "Rapid Elimination Of Swill (REOS) using ChemAxon calculators", new String[]{"reos", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "charge", "formalcharge", "leadlike", "molecularproperties", "filter", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "/Chemistry/Calculators/DrugLike"}, "asyncHttp", "reosFilter", 0.0025f, createReosFilterOptionDescriptors())//, // createServiceDescriptor( // "chemaxon.calculators.chemterms", // "CXN Chemical Terms", // "Property prediction using a user definable Chemical Terms expression. See http://docs.chemaxon.com/display/chemicalterms/Chemical+Terms+Home", // new String[]{"molecularproperties", "chemaxon"}, // new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/General"}, // "asyncHttp", // "chemTerms", // 0.01f, // new ServicePropertyDescriptor[]{ // new ServicePropertyDescriptor(ServicePropertyDescriptor.Type.STRING, KEY_CT_EXPR, LABEL_CT_EXPR, DESC_CT_EXPR) // }) }; static private OptionDescriptor[] createLipinskiOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 500f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createDrugLikeFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 400f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.RING_COUNT, "Ring count", "Ring count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(1, null))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rotatable bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createGhoseFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-0.4f, 5.6f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "MolWeight", "molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(160f, 480f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ATOM_COUNT, "Atom count", "Atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(20, 70))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLAR_REFRACTIVITY, "Refractivity", "Molar Refractivity").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(40f, 130f))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createRuleOfThreeOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 3.0f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 300f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createReosFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(200f, 500f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-5.0f, 5.0f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.FORMAL_CHARGE, "Formal charge", "Formal charge").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(-2, 2))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 8))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HEAVY_ATOM_COUNT, "Heavy atom count", "Heavy atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(15, 50))); return list.toArray(new OptionDescriptor[0]); } private static final ServiceDescriptor[] SERVICE_DESCRIPTOR_DESCRIPTORS = new ServiceDescriptor[]{ createServiceDescriptor( "chemaxon.screening.ecpf4", "ECFP4 Screen (CXN)", "Virtual screening using ChemAxon ECFP4 fingerprints. See http://www.chemaxon.com/products/screen/", new String[]{"virtualscreening", "screening", "ecfp", "ecfp4", "moleculardescriptors", "fingerprints", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"}, "asyncHttp", "screening/ecfp4", 0.001f, new OptionDescriptor[]{ new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false), new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL), new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f) }), createServiceDescriptor( "chemaxon.screening.pharmacophore", "Pharmacophore Screen (CXN)", "Virtual screening using ChemAxon 2D pharmacophore fingerprints. See http://www.chemaxon.com/products/screen/", new String[]{"virtualscreening", "screening", "parmacophore", "moleculardescriptors", "fingerprints", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"}, "asyncHttp", "screening/pharmacophore", 0.004f, new OptionDescriptor[]{ new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false), new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL), new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f) }), createServiceDescriptor( "chemaxon.clustering.sperex", "SpereEx Clustering (CXN)", "Sphere exclusion clustering using ChemAxon ECFP4 fingerprints. See http://www.chemaxon.com/products/jklustor/", new String[]{"clustering", "ecfp", "ecfp4", "chemaxon"}, "icons/clustering.png", new String[]{"/Vendors/ChemAxon/Clustering", "Chemistry/Clustering"}, "asyncHttp", "clustering/spherex/ecfp4", 0.002f, new OptionDescriptor[]{ new OptionDescriptor<>(Integer.class, KEY_MIN_CLUSTERS, LABEL_MIN_CLUSTERS, DESC_MIN_CLUSTERS).withDefaultValue(5), new OptionDescriptor<>(Integer.class, KEY_MAX_CLUSTERS, LABEL_MAX_CLUSTERS, DESC_MAX_CLUSTERS).withDefaultValue(10) }) }; static ServiceDescriptor createServiceDescriptor(String serviceDescriptorId, String name, String desc, String[] tags, String icon, String[] paths, String modeId, String endpoint, float cost, OptionDescriptor[] props) { return new ServiceDescriptor( serviceDescriptorId, name, desc, tags, null, paths, "Tim Dudgeon <[email protected]>", null, new String[]{"public"}, MoleculeObject.class, // inputClass MoleculeObject.class, // outputClass DataType.STREAM, // inputType DataType.STREAM, // outputType icon, new AccessMode[]{ new AccessMode( modeId, "Immediate execution", "Execute as an asynchronous REST web service", endpoint, true, // a relative URL null, null, cost, new ServiceDescriptor.LicenseToken[]{ServiceDescriptor.LicenseToken.CHEMAXON}, props, StepDefinitionConstants.MoleculeServiceThinExecutor.CLASSNAME) } ); } @Override public void configure() throws Exception { restConfiguration().component("servlet").host("0.0.0.0"); // send usage metrics to the message queue from(ROUTE_STATS) .marshal().json(JsonLibrary.Jackson) .to(mqueueUrl); /* These are the REST endpoints - exposed as public web services */ rest("ping") .get().description("Simple ping service to check things are running") .produces("text/plain") .route() .transform(constant("OK\n")).endRest(); rest("v1/calculators").description("Property calculation services using ChemAxon") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") // // service descriptor .get().description("ServiceDescriptors for ChemAxon calculators") .bindingMode(RestBindingMode.json) .produces("application/json") .route() .process((Exchange exch) -> { exch.getIn().setBody(SERVICE_DESCRIPTOR_CALCULATORS); }) .endRest() // .post("verify").description("Verify as Marvin molecules") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_STRUCTURE_VERIFY, resolver, ROUTE_STATS)) .endRest() // .post("logp").description("Calculate the logP for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LOGP, resolver, ROUTE_STATS)) .endRest() // .post("atomCount").description("Calculate the atom count for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_ATOM_COUNT, resolver, ROUTE_STATS)) .endRest() // .post("lipinski").description("Calculate the Lipinski properties for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LIPINSKI, resolver, ROUTE_STATS)) .endRest() // .post("drugLikeFilter").description("Apply a drug like filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_DRUG_LIKE_FILTER, resolver, ROUTE_STATS)) .endRest() // .post("ghoseFilter").description("Apply a Ghose filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_GHOSE_FILTER, resolver, ROUTE_STATS)) .endRest() // .post("ruleOfThreeFilter").description("Apply a Rule of 3 filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_RULE_OF_THREE, resolver, ROUTE_STATS)) .endRest() // .post("reosFilter").description("Apply a REOS filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_REOS, resolver, ROUTE_STATS)) .endRest() // .post("chemTerms").description("Calculate a chemical terms expression for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_CHEMTERMS, resolver, ROUTE_STATS)) .endRest(); rest("v1/descriptors").description("Screening and clustering services using ChemAxon") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") // // service descriptor .get().description("ServiceDescriptors for ChemAxon descriptors") .bindingMode(RestBindingMode.json) .produces("application/json") .route() .process((Exchange exch) -> { exch.getIn().setBody(SERVICE_DESCRIPTOR_DESCRIPTORS); }) .endRest() // .post("screening/ecfp4").description("Screen using ECFP4 fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_ECFP4, resolver, ROUTE_STATS)) .endRest() // .post("screening/pharmacophore").description("Screen using pharmacophore fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_PHARMACOPHORE, resolver, ROUTE_STATS)) .endRest() // .post("clustering/spherex/ecfp4").description("Sphere exclusion clustering using ECFP4 fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_CLUSTERING_SPHEREX_ECFP4, resolver, ROUTE_STATS)) .endRest(); rest("v1/reactor").description("Library enumeration using ChemAxon Reactor") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") .post("react").description("Simple enumeration") .route() .process(new JsonToDatasetProcessor(MoleculeObject.class)) .process(new ReactorProcessor("/chemaxon_reaction_library.zip", ROUTE_STATS)) .process(new DatasetToJsonProcessor(MoleculeObject.class)) .endRest(); } }
components/chem-services-chemaxon-basic/src/main/java/org/squonk/chemaxon/services/ChemaxonRestRouteBuilder.java
package org.squonk.chemaxon.services; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.camel.model.rest.RestBindingMode; import org.squonk.camel.chemaxon.processor.clustering.SphereExclusionClusteringProcessor; import org.squonk.camel.chemaxon.processor.enumeration.ReactorProcessor; import org.squonk.camel.chemaxon.processor.screening.MoleculeScreenerProcessor; import org.squonk.camel.processor.DatasetToJsonProcessor; import org.squonk.camel.processor.JsonToDatasetProcessor; import org.squonk.camel.processor.MoleculeObjectRouteHttpProcessor; import org.squonk.chemaxon.molecule.ChemTermsEvaluator; import org.squonk.core.AccessMode; import org.squonk.core.ServiceDescriptor; import org.squonk.core.ServiceDescriptor.DataType; import org.squonk.execution.steps.StepDefinitionConstants; import org.squonk.mqueue.MessageQueueCredentials; import org.squonk.options.MoleculeTypeDescriptor; import org.squonk.options.OptionDescriptor; import org.squonk.types.MoleculeObject; import org.squonk.types.NumberRange; import org.squonk.types.TypeResolver; import org.squonk.util.CommonConstants; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_NAME; import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_PARAMS; /** * @author timbo */ public class ChemaxonRestRouteBuilder extends RouteBuilder { private static final Logger LOG = Logger.getLogger(ChemaxonRestRouteBuilder.class.getName()); private static final String ROUTE_STATS = "seda:post_stats"; private static final String HEADER = "header."; private static final String KEY_SIM_CUTTOFF = HEADER + MoleculeScreenerProcessor.HEADER_THRESHOLD; private static final String LABEL_SIM_CUTTOFF = "Similarity Cuttoff"; private static final String DESC_SIM_CUTTOFF = "Similarity score cuttoff between 0 and 1 (1 means identical)"; private static final String KEY_QMOL = HEADER + MoleculeScreenerProcessor.HEADER_QUERY_MOLECULE; private static final String LABEL_QMOL = "Query Structure"; private static final String DESC_QMOL = "Structure to use as the query"; // private static final String KEY_CT_EXPR = "ct_expr"; // private static final String LABEL_CT_EXPR = "ChemTerms Expression"; // private static final String DESC_CT_EXPR = "Expression using the Chemical Terms language"; private static final String KEY_MIN_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MIN_CLUSTER_COUNT; private static final String LABEL_MIN_CLUSTERS = "Min clusters"; private static final String DESC_MIN_CLUSTERS = "Minimum number of clusters to generate"; private static final String KEY_MAX_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MAX_CLUSTER_COUNT; private static final String LABEL_MAX_CLUSTERS = "Max clusters"; private static final String DESC_MAX_CLUSTERS = "Target maximum number of clusters to generate"; private static final TypeResolver resolver = new TypeResolver(); private final String mqueueUrl = new MessageQueueCredentials().generateUrl(MQUEUE_JOB_METRICS_EXCHANGE_NAME, MQUEUE_JOB_METRICS_EXCHANGE_PARAMS) + "&routingKey=tokens.chemaxon"; protected static final ServiceDescriptor[] SERVICE_DESCRIPTOR_CALCULATORS = new ServiceDescriptor[]{ createServiceDescriptor( "chemaxon.calculators.verify", "Verify structure (ChemAxon)", "Verify that the molecules are valid according to ChemAxon's Marvin", new String[]{"verify", "chemaxon"}, "icons/properties_add.png", new String[]{"/Chemistry/Toolkits/ChemAxon/Verify", "/Chemistry/Verify"}, "asyncHttp", "verify", 0f, new OptionDescriptor[] {OptionDescriptor.IS_FILTER, OptionDescriptor.FILTER_MODE}), createServiceDescriptor( "chemaxon.calculators.logp", "LogP (CXN)", "LogP using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-predictors/#logp_logd", new String[]{"logp", "partitioning", "molecularproperties", "chemaxon"}, "icons/properties_add.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Partioning"}, "asyncHttp", "logp", 0.001f, null), createServiceDescriptor( "chemaxon.calculators.atomcount", "Atom Count (CXN)", "Atom Count using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-calculations/#topology_analysis", new String[]{"atomcount", "topology", "molecularproperties", "chemaxon"}, "icons/properties_add.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Topological"}, "asyncHttp", "atomCount", 0f, null), createServiceDescriptor( "chemaxon.calculators.lipinski", "Lipinski (CXN)", "Lipinski properties using ChemAxon calculators", new String[]{"lipinski", "filter", "druglike", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "lipinski", 0.002f, createLipinskiOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.druglikefilter", "Drug-like Filter (CXN)", "Drug-like filter using ChemAxon calculators", new String[]{"druglike", "filter", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "drugLikeFilter", 0.0025f, createDrugLikeFilterOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.ghosefilter", "Ghose Filter (CXN)", "Ghose filter using ChemAxon calculators", new String[]{"ghose", "filter", "druglike", "molecularproperties", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/GhoseFilter"}, "asyncHttp", "ghosefilter", 0.0025f, createGhoseFilterOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.ruleofthreefilter", "Rule of 3 Filter (CXN)", "Astex Rule of 3 filter using ChemAxon calculators", new String[]{"ruleofthree", "ro3", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "leadlike", "molecularproperties", "filter", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"}, "asyncHttp", "ruleOfThreeFilter", 0.0025f, createRuleOfThreeOptionDescriptors()), createServiceDescriptor( "chemaxon.calculators.reosfilter", "REOS (CXN)", "Rapid Elimination Of Swill (REOS) using CXN", new String[]{"reos", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "charge", "formalcharge", "leadlike", "molecularproperties", "filter", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Calculators", "/Chemistry/Calculators/DrugLike"}, "asyncHttp", "reosFilter", 0.0025f, createReosFilterOptionDescriptors())//, // createServiceDescriptor( // "chemaxon.calculators.chemterms", // "CXN Chemical Terms", // "Property prediction using a user definable Chemical Terms expression. See http://docs.chemaxon.com/display/chemicalterms/Chemical+Terms+Home", // new String[]{"molecularproperties", "chemaxon"}, // new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/General"}, // "asyncHttp", // "chemTerms", // 0.01f, // new ServicePropertyDescriptor[]{ // new ServicePropertyDescriptor(ServicePropertyDescriptor.Type.STRING, KEY_CT_EXPR, LABEL_CT_EXPR, DESC_CT_EXPR) // }) }; static private OptionDescriptor[] createLipinskiOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 500f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createDrugLikeFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 400f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.RING_COUNT, "Ring count", "Ring count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(1, null))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rotatable bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createGhoseFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-0.4f, 5.6f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "MolWeight", "molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(160f, 480f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ATOM_COUNT, "Atom count", "Atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(20, 70))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLAR_REFRACTIVITY, "Refractivity", "Molar Refractivity").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(40f, 130f))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createRuleOfThreeOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 3.0f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 300f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3))); return list.toArray(new OptionDescriptor[0]); } static private OptionDescriptor[] createReosFilterOptionDescriptors() { List<OptionDescriptor> list = new ArrayList<>(); list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false)); list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results") .withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS") .withMinMaxValues(1,1)); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT, "Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(200f, 500f))); list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP, "LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-5.0f, 5.0f))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT, "HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT, "HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.FORMAL_CHARGE, "Formal charge", "Formal charge").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(-2, 2))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT, "Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 8))); list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HEAVY_ATOM_COUNT, "Heavy atom count", "Heavy atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(15, 50))); return list.toArray(new OptionDescriptor[0]); } private static final ServiceDescriptor[] SERVICE_DESCRIPTOR_DESCRIPTORS = new ServiceDescriptor[]{ createServiceDescriptor( "chemaxon.screening.ecpf4", "ECFP4 Screen (CXN)", "Virtual screening using ChemAxon ECFP4 fingerprints. See http://www.chemaxon.com/products/screen/", new String[]{"virtualscreening", "screening", "ecfp", "ecfp4", "moleculardescriptors", "fingerprints", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"}, "asyncHttp", "screening/ecfp4", 0.001f, new OptionDescriptor[]{ new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false), new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL), new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f) }), createServiceDescriptor( "chemaxon.screening.pharmacophore", "Pharmacophore Screen (CXN)", "Virtual screening using ChemAxon 2D pharmacophore fingerprints. See http://www.chemaxon.com/products/screen/", new String[]{"virtualscreening", "screening", "parmacophore", "moleculardescriptors", "fingerprints", "chemaxon"}, "icons/filter_molecules.png", new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"}, "asyncHttp", "screening/pharmacophore", 0.004f, new OptionDescriptor[]{ new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false), new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL), new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f) }), createServiceDescriptor( "chemaxon.clustering.sperex", "SpereEx Clustering (CXN)", "Sphere exclusion clustering using ChemAxon ECFP4 fingerprints. See http://www.chemaxon.com/products/jklustor/", new String[]{"clustering", "ecfp", "ecfp4", "chemaxon"}, "icons/clustering.png", new String[]{"/Vendors/ChemAxon/Clustering", "Chemistry/Clustering"}, "asyncHttp", "clustering/spherex/ecfp4", 0.002f, new OptionDescriptor[]{ new OptionDescriptor<>(Integer.class, KEY_MIN_CLUSTERS, LABEL_MIN_CLUSTERS, DESC_MIN_CLUSTERS).withDefaultValue(5), new OptionDescriptor<>(Integer.class, KEY_MAX_CLUSTERS, LABEL_MAX_CLUSTERS, DESC_MAX_CLUSTERS).withDefaultValue(10) }) }; static ServiceDescriptor createServiceDescriptor(String serviceDescriptorId, String name, String desc, String[] tags, String icon, String[] paths, String modeId, String endpoint, float cost, OptionDescriptor[] props) { return new ServiceDescriptor( serviceDescriptorId, name, desc, tags, null, paths, "Tim Dudgeon <[email protected]>", null, new String[]{"public"}, MoleculeObject.class, // inputClass MoleculeObject.class, // outputClass DataType.STREAM, // inputType DataType.STREAM, // outputType icon, new AccessMode[]{ new AccessMode( modeId, "Immediate execution", "Execute as an asynchronous REST web service", endpoint, true, // a relative URL null, null, cost, new ServiceDescriptor.LicenseToken[]{ServiceDescriptor.LicenseToken.CHEMAXON}, props, StepDefinitionConstants.MoleculeServiceThinExecutor.CLASSNAME) } ); } @Override public void configure() throws Exception { restConfiguration().component("servlet").host("0.0.0.0"); // send usage metrics to the message queue from(ROUTE_STATS) .marshal().json(JsonLibrary.Jackson) .to(mqueueUrl); /* These are the REST endpoints - exposed as public web services */ rest("ping") .get().description("Simple ping service to check things are running") .produces("text/plain") .route() .transform(constant("OK\n")).endRest(); rest("v1/calculators").description("Property calculation services using ChemAxon") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") // // service descriptor .get().description("ServiceDescriptors for ChemAxon calculators") .bindingMode(RestBindingMode.json) .produces("application/json") .route() .process((Exchange exch) -> { exch.getIn().setBody(SERVICE_DESCRIPTOR_CALCULATORS); }) .endRest() // .post("verify").description("Verify as Marvin molecules") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_STRUCTURE_VERIFY, resolver, ROUTE_STATS)) .endRest() // .post("logp").description("Calculate the logP for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LOGP, resolver, ROUTE_STATS)) .endRest() // .post("atomCount").description("Calculate the atom count for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_ATOM_COUNT, resolver, ROUTE_STATS)) .endRest() // .post("lipinski").description("Calculate the Lipinski properties for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LIPINSKI, resolver, ROUTE_STATS)) .endRest() // .post("drugLikeFilter").description("Apply a drug like filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_DRUG_LIKE_FILTER, resolver, ROUTE_STATS)) .endRest() // .post("ghoseFilter").description("Apply a Ghose filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_GHOSE_FILTER, resolver, ROUTE_STATS)) .endRest() // .post("ruleOfThreeFilter").description("Apply a Rule of 3 filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_RULE_OF_THREE, resolver, ROUTE_STATS)) .endRest() // .post("reosFilter").description("Apply a REOS filter to the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_REOS, resolver, ROUTE_STATS)) .endRest() // .post("chemTerms").description("Calculate a chemical terms expression for the supplied MoleculeObjects") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_CHEMTERMS, resolver, ROUTE_STATS)) .endRest(); rest("v1/descriptors").description("Screening and clustering services using ChemAxon") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") // // service descriptor .get().description("ServiceDescriptors for ChemAxon descriptors") .bindingMode(RestBindingMode.json) .produces("application/json") .route() .process((Exchange exch) -> { exch.getIn().setBody(SERVICE_DESCRIPTOR_DESCRIPTORS); }) .endRest() // .post("screening/ecfp4").description("Screen using ECFP4 fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_ECFP4, resolver, ROUTE_STATS)) .endRest() // .post("screening/pharmacophore").description("Screen using pharmacophore fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_PHARMACOPHORE, resolver, ROUTE_STATS)) .endRest() // .post("clustering/spherex/ecfp4").description("Sphere exclusion clustering using ECFP4 fingerprints") .route() .process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_CLUSTERING_SPHEREX_ECFP4, resolver, ROUTE_STATS)) .endRest(); rest("v1/reactor").description("Library enumeration using ChemAxon Reactor") .bindingMode(RestBindingMode.off) .consumes("application/json") .produces("application/json") .post("react").description("Simple enumeration") .route() .process(new JsonToDatasetProcessor(MoleculeObject.class)) .process(new ReactorProcessor("/chemaxon_reaction_library.zip", ROUTE_STATS)) .process(new DatasetToJsonProcessor(MoleculeObject.class)) .endRest(); } }
consistent naming and icons
components/chem-services-chemaxon-basic/src/main/java/org/squonk/chemaxon/services/ChemaxonRestRouteBuilder.java
consistent naming and icons
Java
apache-2.0
542b789878df979090cedf05356d0c428535f51a
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012 Shared Learning Collaborative, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.ingestion.transformation.normalization.did; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.slc.sli.common.domain.NaturalKeyDescriptor; import org.slc.sli.common.util.uuid.DeterministicUUIDGeneratorStrategy; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.NeutralRecord; import org.slc.sli.ingestion.NeutralRecordEntity; import org.slc.sli.ingestion.landingzone.validation.TestErrorReport; import org.slc.sli.ingestion.validation.ErrorReport; /** * * Integrated JUnit tests to check to check the schema parser and * DeterministicIdResolver in combination * * @author jtully * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) public class DidReferenceResolutionTest { @Autowired DeterministicIdResolver didResolver; private static final String TENANT_ID = "tenant_id"; @Test public void resolvesAssessmentRefDidInAssessmentItemCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/assessmentItem.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("assessmentTitle", "Fraction Homework 123"); naturalKeys.put("gradeLevelAssessed", "Fifth grade"); naturalKeys.put("version", "1"); naturalKeys.put("academicSubject", ""); // apparently, empty optional natural key field is default to empty string checkId(entity, "AssessmentReference", naturalKeys, "assessment"); } @Test public void resolvesAssessmentRefDidInStudentAssessmentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAssessment.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("AssessmentTitle", "Fraction Homework 123"); naturalKeys.put("GradeLevelAssessed", "Fifth grade"); naturalKeys.put("Version", "1"); naturalKeys.put("AcademicSubject", ""); // apparently, empty optional natural key field is default to empty string checkId(entity, "assessmentId", naturalKeys, "assessment"); } @Test public void resolvesEdOrgRefDidInAttendanceEventCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/attendanceEvent.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "schoolId", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInCohortCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/cohort.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrgReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInCourseCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/course.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSchoolReferenceDidsInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/courseOffering.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", edOrgNaturalKeys, "educationOrganization"); } @Test public void resolvesSessionRefDidsInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/courseOffering.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesResponsibilitySchoolReferenceEdOrgRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someResponsibilitySchoolReference"); checkId(entity, "ResponsibilitySchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesAssignmentSchoolReferenceEdOrgRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someAssignmentSchoolReference"); checkId(entity, "AssignmentSchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesDisciplineIncidentReferenceDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> disciplineIncidentNaturalKeys = new HashMap<String, String>(); disciplineIncidentNaturalKeys.put("schoolId", edOrgId); disciplineIncidentNaturalKeys.put("disciplineActionIdentifier", "theIncident"); checkId(entity, "DisciplineIncidentReference", disciplineIncidentNaturalKeys, "disciplineIncident"); } @Test public void resolvesDisciplineIncidentReferenceDidInStudentDisciplineIncidentAssocCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentDisciplineIncidentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> disciplineIncidentNaturalKeys = new HashMap<String, String>(); disciplineIncidentNaturalKeys.put("schoolId", edOrgId); disciplineIncidentNaturalKeys.put("disciplineActionIdentifier", "theIncident"); checkId(entity, "DisciplineIncidentReference", disciplineIncidentNaturalKeys, "disciplineIncident"); } @Test public void resolvesEdOrgRefDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentCompetencyObjectiveCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetencyObjective.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInSessionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/session.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSchoolRefDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSessionRefDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(naturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesSessionRefDidInStudentAcademicRecordCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAcademicRecord.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(naturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesEdOrgRefDidInSchoolCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/school.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someLEAOrganizationID"); checkId(entity, "LocalEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInGraduationPlanCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/graduationPlan.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test @Ignore public void resolvesLEAEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someLEAOrganizationID"); checkId(entity, "LocalEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test @Ignore public void resolvesEducationServiceCenterEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someEducationServiceCenterID"); checkId(entity, "EducationServiceCenterReference", naturalKeys, "educationOrganization"); } @Test public void resolvesStateEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someSEAOrganizationID"); checkId(entity, "StateEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStaffEducationOrgAssignmentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someEdOrg"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolveStaffDidInStaffEducationOrganizationAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInDisciplineIncidentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineIncident.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInStaffProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesCohortDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("educationOrgId", "STANDARD-SEA"); String edOrgDID = generateExpectedDid (edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("cohortIdentifier", "ACC-TEST-COH-1"); naturalKeys.put("educationOrgId", edOrgDID); checkId(entity, "CohortReference", naturalKeys, "cohort"); } @Test public void resolvesCohortDidInStudentCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("educationOrgId", "STANDARD-SEA"); String edOrgDID = generateExpectedDid (edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("cohortIdentifier", "ACC-TEST-COH-1"); naturalKeys.put("educationOrgId", edOrgDID); checkId(entity, "CohortReference", naturalKeys, "cohort"); } @Test public void resolvesCourseDidInCourseTranscriptCorrectly() throws JsonParseException, JsonMappingException, IOException { ErrorReport errorReport = new TestErrorReport(); Entity courseTranscriptEntity = loadEntity("didTestEntities/courseTranscript.json"); didResolver.resolveInternalIds(courseTranscriptEntity, TENANT_ID, errorReport); Map<String, Object> courseTranscriptBody = courseTranscriptEntity.getBody(); Object courseTranscriptResolvedRef = courseTranscriptBody.get("CourseReference"); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "testSchoolId"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueCourseId", "testCourseId"); String courseReferenceDID = generateExpectedDid(naturalKeys, TENANT_ID, "course", null); Assert.assertEquals(courseReferenceDID, courseTranscriptResolvedRef); } @Test public void resolvesCourseDidInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { ErrorReport errorReport = new TestErrorReport(); Entity courseOfferingEntity = loadEntity("didTestEntities/courseOffering.json"); didResolver.resolveInternalIds(courseOfferingEntity, TENANT_ID, errorReport); Map<String, Object> courseOfferingBody = courseOfferingEntity.getBody(); Object courseOfferingResolvedRef = courseOfferingBody.get("CourseReference"); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "testSchoolId"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueCourseId", "testCourseId"); String courseReferenceDID = generateExpectedDid(naturalKeys, TENANT_ID, "course", null); Assert.assertEquals(courseReferenceDID, courseOfferingResolvedRef); } @Test public void resolvesCourseOfferingDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("stateOrganizationId", "state organization id 1"); String sessionEdOrgDid = generateExpectedDid(edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", sessionEdOrgDid); sessionNaturalKeys.put("sessionName", "session name"); String sessionDid = generateExpectedDid(sessionNaturalKeys, TENANT_ID, "session", null); edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("stateOrganizationId", "state organization id 2"); String edOrgDid = generateExpectedDid(edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("localCourseCode", "local course code"); naturalKeys.put("schoolId", edOrgDid); naturalKeys.put("sessionId", sessionDid); checkId(entity, "CourseOfferingReference", naturalKeys, "courseOffering"); } @Test public void resolvesStudentCompetencyObjectiveDidInStudentCompetencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentCompetencyObjectiveId", "student competency objective id"); checkId(entity, "StudentCompetencyObjectiveReference", naturalKeys, "studentCompetencyObjective"); } @Test public void resolvesLearningStandardDidInLearningObjectiveCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/learningObjective.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("learningStandardId.identificationCode", "0123456789"); checkId(entity, "LearningStandardReference", naturalKeys, "learningStandard"); } @Test public void resolvesStudentSectionAssociationDidInGradeCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/grade.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // because we don't have a full entity structure it thinks section is the parent, so use sectionDid String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesStudentSectionAssociationDidInStudentCompetencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // because we don't have a full entity structure it thinks section is the parent, so use sectionDid String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesStudentSectionAssociationDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // section is the parent entity, so use sectionDid when generating expected DID String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesSectionDidInGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/gradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInStudentSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesStudentRefDidInStudentCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentDisciplineIncidentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentDisciplineIncidentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentParentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentParentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInAttendanceCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/attendance.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInReportCardCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/reportCard.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentAcademicRecordCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAcademicRecord.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentAssessmentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAssessment.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); // checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStaffRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInDisciplineIncidentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineIncident.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffEducationOrganizationAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesGradebookEntryRefDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("gradebookEntryId", "Unit test"); naturalKeys.put("dateAssigned", "2011-09-15"); naturalKeys.put("sectionId", sectionDid); // section is the parent entity, so use sectionDid when generating expected DID String refId = generateExpectedDid(naturalKeys, TENANT_ID, "gradebookEntry", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("GradebookEntryReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesParentDidInStudentParentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentParentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("parentUniqueStateId", "testParentId"); checkId(entity, "ParentReference", naturalKeys, "parent"); } // generate the expected deterministic ids to validate against private String generateExpectedDid(Map<String, String> naturalKeys, String tenantId, String entityType, String parentId) throws JsonParseException, JsonMappingException, IOException { NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, parentId); return new DeterministicUUIDGeneratorStrategy().generateId(nkd); } // validate reference resolution @SuppressWarnings("unchecked") private void checkId(Entity entity, String referenceField, Map<String, String> naturalKeys, String collectionName) throws JsonParseException, JsonMappingException, IOException { String expectedDid = generateExpectedDid(naturalKeys, TENANT_ID, collectionName, null); Map<String, Object> body = entity.getBody(); Object resolvedRef = null; try { resolvedRef = PropertyUtils.getProperty(body, referenceField); } catch (Exception e) { Assert.fail("Exception thrown accessing resolved reference: " + e); } Assert.assertNotNull("Expected non-null reference", resolvedRef); if (resolvedRef instanceof List) { List<Object> refs = (List<Object>) resolvedRef; Assert.assertEquals(1, refs.size()); Assert.assertEquals(expectedDid, refs.get(0)); } else { Assert.assertEquals(expectedDid, resolvedRef); } } // load a sample NeutralRecordEntity from a json file private Entity loadEntity(String fname) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); Resource jsonFile = new ClassPathResource(fname); NeutralRecord nr = mapper.readValue(jsonFile.getInputStream(), NeutralRecord.class); return new NeutralRecordEntity(nr); } }
sli/ingestion/ingestion-core/src/test/java/org/slc/sli/ingestion/transformation/normalization/did/DidReferenceResolutionTest.java
/* * Copyright 2012 Shared Learning Collaborative, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.ingestion.transformation.normalization.did; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.slc.sli.common.domain.NaturalKeyDescriptor; import org.slc.sli.common.util.uuid.DeterministicUUIDGeneratorStrategy; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.NeutralRecord; import org.slc.sli.ingestion.NeutralRecordEntity; import org.slc.sli.ingestion.landingzone.validation.TestErrorReport; import org.slc.sli.ingestion.validation.ErrorReport; /** * * Integrated JUnit tests to check to check the schema parser and * DeterministicIdResolver in combination * * @author jtully * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) public class DidReferenceResolutionTest { @Autowired DeterministicIdResolver didResolver; private static final String TENANT_ID = "tenant_id"; @Test public void resolvesAssessmentRefDidInAssessmentItemCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/assessmentItem.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("assessmentTitle", "Fraction Homework 123"); naturalKeys.put("gradeLevelAssessed", "Fifth grade"); naturalKeys.put("version", "1"); naturalKeys.put("academicSubject", ""); // apparently, empty optional natural key field is default to empty string checkId(entity, "AssessmentReference", naturalKeys, "assessment"); } @Test public void resolvesAssessmentRefDidInStudentAssessmentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAssessment.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("AssessmentTitle", "Fraction Homework 123"); naturalKeys.put("GradeLevelAssessed", "Fifth grade"); naturalKeys.put("Version", "1"); naturalKeys.put("AcademicSubject", ""); // apparently, empty optional natural key field is default to empty string checkId(entity, "assessmentId", naturalKeys, "assessment"); } @Test public void resolvesEdOrgRefDidInAttendanceEventCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/attendanceEvent.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "schoolId", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInCohortCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/cohort.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrgReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInCourseCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/course.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSchoolReferenceDidsInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/courseOffering.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", edOrgNaturalKeys, "educationOrganization"); } @Test public void resolvesSessionRefDidsInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/courseOffering.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesResponsibilitySchoolReferenceEdOrgRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someResponsibilitySchoolReference"); checkId(entity, "ResponsibilitySchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesAssignmentSchoolReferenceEdOrgRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someAssignmentSchoolReference"); checkId(entity, "AssignmentSchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesDisciplineIncidentReferenceDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> disciplineIncidentNaturalKeys = new HashMap<String, String>(); disciplineIncidentNaturalKeys.put("schoolId", edOrgId); disciplineIncidentNaturalKeys.put("disciplineActionIdentifier", "theIncident"); checkId(entity, "DisciplineIncidentReference", disciplineIncidentNaturalKeys, "disciplineIncident"); } @Test public void resolvesDisciplineIncidentReferenceDidInStudentDisciplineIncidentAssocCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentDisciplineIncidentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edOrgNaturalKeys = new HashMap<String, String>(); edOrgNaturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(edOrgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> disciplineIncidentNaturalKeys = new HashMap<String, String>(); disciplineIncidentNaturalKeys.put("schoolId", edOrgId); disciplineIncidentNaturalKeys.put("disciplineActionIdentifier", "theIncident"); checkId(entity, "DisciplineIncidentReference", disciplineIncidentNaturalKeys, "disciplineIncident"); } @Test public void resolvesEdOrgRefDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStudentCompetencyObjectiveCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetencyObjective.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInSessionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/session.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSchoolRefDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "SchoolReference", naturalKeys, "educationOrganization"); } @Test public void resolvesSessionRefDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(naturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesSessionRefDidInStudentAcademicRecordCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAcademicRecord.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); String edOrgId = generateExpectedDid(naturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", edOrgId); sessionNaturalKeys.put("sessionId", "theSessionName"); checkId(entity, "SessionReference", sessionNaturalKeys, "session"); } @Test public void resolvesEdOrgRefDidInSchoolCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/school.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someLEAOrganizationID"); checkId(entity, "LocalEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInGraduationPlanCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/graduationPlan.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "testSchoolId"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test @Ignore public void resolvesLEAEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someLEAOrganizationID"); checkId(entity, "LocalEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test @Ignore public void resolvesEducationServiceCenterEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someEducationServiceCenterID"); checkId(entity, "EducationServiceCenterReference", naturalKeys, "educationOrganization"); } @Test public void resolvesStateEdOrgRefDidInLocalEducationAgencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/localEducationAgency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someSEAOrganizationID"); checkId(entity, "StateEducationAgencyReference", naturalKeys, "educationOrganization"); } @Test public void resolvesEdOrgRefDidInStaffEducationOrgAssignmentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("stateOrganizationId", "someEdOrg"); checkId(entity, "EducationOrganizationReference", naturalKeys, "educationOrganization"); } @Test public void resolveStaffDidInStaffEducationOrganizationAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInDisciplineIncidentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineIncident.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInStaffProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolveStaffDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesCohortDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("educationOrgId", "STANDARD-SEA"); String edOrgDID = generateExpectedDid (edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("cohortIdentifier", "ACC-TEST-COH-1"); naturalKeys.put("educationOrgId", edOrgDID); checkId(entity, "CohortReference", naturalKeys, "cohort"); } @Test public void resolvesCohortDidInStudentCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("educationOrgId", "STANDARD-SEA"); String edOrgDID = generateExpectedDid (edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("cohortIdentifier", "ACC-TEST-COH-1"); naturalKeys.put("educationOrgId", edOrgDID); checkId(entity, "CohortReference", naturalKeys, "cohort"); } @Test public void resolvesCourseOfferingDidInSectionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/section.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("stateOrganizationId", "state organization id 1"); String sessionEdOrgDid = generateExpectedDid(edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sessionNaturalKeys = new HashMap<String, String>(); sessionNaturalKeys.put("schoolId", sessionEdOrgDid); sessionNaturalKeys.put("sessionName", "session name"); String sessionDid = generateExpectedDid(sessionNaturalKeys, TENANT_ID, "session", null); edorgNaturalKeys = new HashMap<String, String>(); edorgNaturalKeys.put("stateOrganizationId", "state organization id 2"); String edOrgDid = generateExpectedDid(edorgNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("localCourseCode", "local course code"); naturalKeys.put("schoolId", edOrgDid); naturalKeys.put("sessionId", sessionDid); checkId(entity, "CourseOfferingReference", naturalKeys, "courseOffering"); } @Test public void resolvesStudentCompetencyObjectiveDidInStudentCompetencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentCompetencyObjectiveId", "student competency objective id"); checkId(entity, "StudentCompetencyObjectiveReference", naturalKeys, "studentCompetencyObjective"); } @Test public void resolvesLearningStandardDidInLearningObjectiveCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/learningObjective.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("learningStandardId.identificationCode", "0123456789"); checkId(entity, "LearningStandardReference", naturalKeys, "learningStandard"); } @Test public void resolvesStudentSectionAssociationDidInGradeCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/grade.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // because we don't have a full entity structure it thinks section is the parent, so use sectionDid String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesStudentSectionAssociationDidInStudentCompetencyCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCompetency.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // because we don't have a full entity structure it thinks section is the parent, so use sectionDid String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesCourseDidInCourseTranscriptCorrectly() throws JsonParseException, JsonMappingException, IOException { ErrorReport errorReport = new TestErrorReport(); Entity courseTranscriptEntity = loadEntity("didTestEntities/courseTranscript.json"); didResolver.resolveInternalIds(courseTranscriptEntity, TENANT_ID, errorReport); Map<String, Object> courseTranscriptBody = courseTranscriptEntity.getBody(); Object courseTranscriptResolvedRef = courseTranscriptBody.get("CourseReference"); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "testSchoolId"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueCourseId", "testCourseId"); String courseReferenceDID = generateExpectedDid(naturalKeys, TENANT_ID, "course", null); Assert.assertEquals(courseReferenceDID, courseTranscriptResolvedRef); } @Test public void resolvesCourseDidInCourseOfferingCorrectly() throws JsonParseException, JsonMappingException, IOException { ErrorReport errorReport = new TestErrorReport(); Entity courseOfferingEntity = loadEntity("didTestEntities/courseOffering.json"); didResolver.resolveInternalIds(courseOfferingEntity, TENANT_ID, errorReport); Map<String, Object> courseOfferingBody = courseOfferingEntity.getBody(); Object courseOfferingResolvedRef = courseOfferingBody.get("CourseReference"); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "testSchoolId"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueCourseId", "testCourseId"); String courseReferenceDID = generateExpectedDid(naturalKeys, TENANT_ID, "course", null); Assert.assertEquals(courseReferenceDID, courseOfferingResolvedRef); } @Test public void resolvesStudentSectionAssociationDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> studentNaturalKeys = new HashMap<String, String>(); studentNaturalKeys.put("studentUniqueStateId", "800000025"); String studentDid = generateExpectedDid(studentNaturalKeys, TENANT_ID, "student", null); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentId", studentDid); naturalKeys.put("sectionId", sectionDid); naturalKeys.put("beginDate", "2011-09-01"); // section is the parent entity, so use sectionDid when generating expected DID String refId = generateExpectedDid(naturalKeys, TENANT_ID, "studentSectionAssociation", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("StudentSectionAssociationReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesSectionDidInGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/gradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInStudentSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesSectionDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("schoolId", schoolId); naturalKeys.put("uniqueSectionCode", "this section"); checkId(entity, "SectionReference", naturalKeys, "section"); } @Test public void resolvesStudentRefDidInStudentCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentDisciplineIncidentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentDisciplineIncidentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentParentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentParentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInAttendanceCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/attendance.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInReportCardCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/reportCard.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentAcademicRecordCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAcademicRecord.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStudentRefDidInStudentAssessmentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentAssessment.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("studentUniqueStateId", "100000000"); // checkId(entity, "StudentReference", naturalKeys, "student"); } @Test public void resolvesStaffRefDidInDisciplineActionCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineAction.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInDisciplineIncidentCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/disciplineIncident.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffCohortAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffCohortAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffEducationOrganizationAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffEducationOrganizationAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInStaffProgramAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/staffProgramAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "StaffReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInTeacherSchoolAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSchoolAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesStaffRefDidInTeacherSectionAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/teacherSectionAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("staffUniqueStateId", "jjackson"); checkId(entity, "TeacherReference", naturalKeys, "staff"); } @Test public void resolvesGradebookEntryRefDidInStudentGradebookEntryCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentGradebookEntry.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> schoolNaturalKeys = new HashMap<String, String>(); schoolNaturalKeys.put("stateOrganizationId", "this school"); String schoolId = generateExpectedDid(schoolNaturalKeys, TENANT_ID, "educationOrganization", null); Map<String, String> sectionNaturalKeys = new HashMap<String, String>(); sectionNaturalKeys.put("schoolId", schoolId); sectionNaturalKeys.put("uniqueSectionCode", "this section"); String sectionDid = generateExpectedDid(sectionNaturalKeys, TENANT_ID, "section", null); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("gradebookEntryId", "Unit test"); naturalKeys.put("dateAssigned", "2011-09-15"); naturalKeys.put("sectionId", sectionDid); // section is the parent entity, so use sectionDid when generating expected DID String refId = generateExpectedDid(naturalKeys, TENANT_ID, "gradebookEntry", sectionDid); Map<String, Object> body = entity.getBody(); Object resolvedRef = body.get("GradebookEntryReference"); Assert.assertEquals(refId, resolvedRef); } @Test public void resolvesParentDidInStudentParentAssociationCorrectly() throws JsonParseException, JsonMappingException, IOException { Entity entity = loadEntity("didTestEntities/studentParentAssociation.json"); ErrorReport errorReport = new TestErrorReport(); didResolver.resolveInternalIds(entity, TENANT_ID, errorReport); Map<String, String> naturalKeys = new HashMap<String, String>(); naturalKeys.put("parentUniqueStateId", "testParentId"); checkId(entity, "ParentReference", naturalKeys, "parent"); } // generate the expected deterministic ids to validate against private String generateExpectedDid(Map<String, String> naturalKeys, String tenantId, String entityType, String parentId) throws JsonParseException, JsonMappingException, IOException { NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(naturalKeys, tenantId, entityType, parentId); return new DeterministicUUIDGeneratorStrategy().generateId(nkd); } // validate reference resolution @SuppressWarnings("unchecked") private void checkId(Entity entity, String referenceField, Map<String, String> naturalKeys, String collectionName) throws JsonParseException, JsonMappingException, IOException { String expectedDid = generateExpectedDid(naturalKeys, TENANT_ID, collectionName, null); Map<String, Object> body = entity.getBody(); Object resolvedRef = null; try { resolvedRef = PropertyUtils.getProperty(body, referenceField); } catch (Exception e) { Assert.fail("Exception thrown accessing resolved reference: " + e); } Assert.assertNotNull("Expected non-null reference", resolvedRef); if (resolvedRef instanceof List) { List<Object> refs = (List<Object>) resolvedRef; Assert.assertEquals(1, refs.size()); Assert.assertEquals(expectedDid, refs.get(0)); } else { Assert.assertEquals(expectedDid, resolvedRef); } } // load a sample NeutralRecordEntity from a json file private Entity loadEntity(String fname) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); Resource jsonFile = new ClassPathResource(fname); NeutralRecord nr = mapper.readValue(jsonFile.getInputStream(), NeutralRecord.class); return new NeutralRecordEntity(nr); } }
[DE2214] reorder courseReference tests
sli/ingestion/ingestion-core/src/test/java/org/slc/sli/ingestion/transformation/normalization/did/DidReferenceResolutionTest.java
[DE2214] reorder courseReference tests
Java
apache-2.0
62295c6d1bb6e0dfbdb343438d79890a986c2df1
0
calotocen/Canal
/* * Copyright 2015 calotocen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package canal; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; /** * エントリーポイントを定義するクラスである。 */ public class Main extends Application { /** ルートノード */ private static Group st_root; /** アクティブな画面 */ private static Screen st_screen; /** * JavaFX アプリケーションのエントリポイントである。 * * @param stage アプリケーションのプライマリステージ。 */ @Override public void start(Stage stage) { // ルートペイン,およびシーンを生成する。 st_root = new Group(); Scene scene = new Scene(st_root); // 画面をタイトル画面に切り替える。 changeScreen(0); // リサイズを禁止する場合は,次のコードを有効にする。 // リサイズを禁止すると最適なウィンドウサイズが自動的に設定されないので, // 明示的にサイズを指定する必要がある。 // stage.setResizable(false); // stage.setWidth(Configuration.SCREEN_WIDTH + Configuration.WINDOW_BORDER_WIDTH * 2); // stage.setHeight(Configuration.SCREEN_HEIGHT + Configuration.WINDOW_BORDER_HEIGHT * 2 + Configuration.TITLE_BAR_HEIGHT); // ステージにシーンを設定し,ステージを表示する。 stage.setScene(scene); stage.show(); } /** * アプリケーションのエントリポイントである。 * * @param args コマンドライン引数。 */ public static void main(String[] args) { // JavaFX アプリケーションを起動する launch(args); } /** * ゲームを開始する。 */ public static void startGame() { // 画面をゲーム画面 (1面) に切り替える。 changeScreen(1); } /** * 画面を切り替える。 * * @param newScreenNumber 画面番号。 */ public static void changeScreen(int newScreenNumber) { // 画面を停止する。 if (st_screen != null) { st_screen.stop(); } if (newScreenNumber == 0) { // 画面をタイトル画面に切り替える。 GameContext.initialize(); st_screen = new TitleScreen(); } else if (newScreenNumber <= Levels.size()) { // ゲームコンテキストを更新後, // 画面をゲーム画面に切り替える。 Level level = Levels.get(newScreenNumber); GameContext.setLevelNumber(newScreenNumber); GameContext.setState(GameContext.State.PLAYING); GameContext.setRemainingTime(Configuration.INITIAL_REMAINING_TIME); GameContext.setPlayer(level.getPlayer()); GameContext.setEnemies(level.getEnemies()); GameContext.setTerritory(level.getTerritory()); GameContext.setExpeditionLine(null); st_screen = new GameScreen(); } else { // 画面をリザルト画面に切り替える。 st_screen = new ResultScreen(); } // ルートペインに画面を設定する。 st_root.getChildren().clear(); st_root.getChildren().add(st_screen); // 画面を開始する。 st_screen.start(); } }
src/canal/Main.java
/* * Copyright 2015 calotocen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package canal; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; /** * エントリーポイントを定義するクラスである。 */ public class Main extends Application { /** ルートノード */ private static Group st_root; /** アクティブな画面 */ private static Screen st_screen; /** * JavaFX アプリケーションのエントリポイントである。 * * @param stage アプリケーションのプライマリステージ。 */ @Override public void start(Stage stage) throws Exception { // ルートペイン,およびシーンを生成する。 st_root = new Group(); Scene scene = new Scene(st_root); // 画面をタイトル画面に切り替える。 changeScreen(0); // リサイズを禁止する場合は,次のコードを有効にする。 // リサイズを禁止すると最適なウィンドウサイズが自動的に設定されないので, // 明示的にサイズを指定する必要がある。 // stage.setResizable(false); // stage.setWidth(Configuration.SCREEN_WIDTH + Configuration.WINDOW_BORDER_WIDTH * 2); // stage.setHeight(Configuration.SCREEN_HEIGHT + Configuration.WINDOW_BORDER_HEIGHT * 2 + Configuration.TITLE_BAR_HEIGHT); // ステージにシーンを設定し,ステージを表示する。 stage.setScene(scene); stage.show(); } /** * アプリケーションのエントリポイントである。 * * @param args コマンドライン引数。 */ public static void main(String[] args) { // JavaFX アプリケーションを起動する launch(args); } /** * ゲームを開始する。 */ public static void startGame() { // 画面をゲーム画面 (1面) に切り替える。 changeScreen(1); } /** * 画面を切り替える。 * * @param newScreenNumber 画面番号。 */ public static void changeScreen(int newScreenNumber) { // 画面を停止する。 if (st_screen != null) { st_screen.stop(); } if (newScreenNumber == 0) { // 画面をタイトル画面に切り替える。 GameContext.initialize(); st_screen = new TitleScreen(); } else if (newScreenNumber <= Levels.size()) { // ゲームコンテキストを更新後, // 画面をゲーム画面に切り替える。 Level level = Levels.get(newScreenNumber); GameContext.setLevelNumber(newScreenNumber); GameContext.setState(GameContext.State.PLAYING); GameContext.setRemainingTime(Configuration.INITIAL_REMAINING_TIME); GameContext.setPlayer(level.getPlayer()); GameContext.setEnemies(level.getEnemies()); GameContext.setTerritory(level.getTerritory()); GameContext.setExpeditionLine(null); st_screen = new GameScreen(); } else { // 画面をリザルト画面に切り替える。 st_screen = new ResultScreen(); } // ルートペインに画面を設定する。 st_root.getChildren().clear(); st_root.getChildren().add(st_screen); // 画面を開始する。 st_screen.start(); } }
不要な例外のスロー宣言を削除した。
src/canal/Main.java
不要な例外のスロー宣言を削除した。
Java
apache-2.0
dabe810666c7078903df97ff9f47e9b78f4f28e9
0
javalite/activejdbc,javalite/activejdbc,javalite/activejdbc,javalite/activejdbc
/* Copyright 2009-2014 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activeweb; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.javalite.common.Convert; import org.javalite.common.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.javalite.common.Collections.map; /** * @author Igor Polevoy */ public class HttpSupport { private Logger logger = LoggerFactory.getLogger(getClass().getName()); private List<FormItem> formItems; protected void logInfo(String info){ logger.info(info); } protected void logDebug(String info){ logger.debug(info); } protected void logWarning(String info){ logger.warn(info); } protected void logWarning(String info, Throwable e){ logger.warn(info, e); } protected void logError(String info){ logger.error(info); } protected void logError(Throwable e){ logger.error("", e); } protected void logError(String info, Throwable e){ logger.error(info, e); } /** * Assigns a value for a view. * * @param name name of value * @param value value. */ protected void assign(String name, Object value) { KeyWords.check(name); Context.getValues().put(name, value); } /** * Alias to {@link #assign(String, Object)}. * * @param name name of object to be passed to view * @param value object to be passed to view */ protected void view(String name, Object value) { assign(name, value); } /** * Convenience method, calls {@link #assign(String, Object)} internally. * The keys in teh map are converted to String values. * * @param values map with values to pass to view. */ protected void view(Map values){ for(Object key:values.keySet() ){ assign(key.toString(), values.get(key)); } } /** * Convenience method to pass multiple names and corresponding values to a view. * * @param values - pairs of names and values. such as: name1, value1, name2, value2, etc. Number of arguments must be even. */ protected void view(Object ... values){ view(map(values)); } /** * Flash method to display multiple flash messages. * Takes in a map of names and values for a flash. * Keys act like names, and values act like... ehr.. values. * * @see #flash(String, Object) * * @param values values to flash. */ protected void flash(Map values){ for(Object key:values.keySet() ){ flash(key.toString(), values.get(key)); } } /** * Flash method to display multiple flash messages. * Takes in a vararg of values for flash. Number of arguments must be even. * Format: name, value, name, value, etc. * * @see #flash(String, Object) * @param values values to flash. */ protected void flash(Object ... values){ flash(map(values)); } /** * Sets a flash name for a flash with a body. * Here is a how to use a tag with a body: * * <pre> * &lt;@flash name=&quot;warning&quot;&gt; &lt;div class=&quot;warning&quot;&gt;${message}&lt;/div&gt; &lt;/@flash&gt; * </pre> * * If body refers to variables (as in this example), then such variables need to be passed in to the template as usual using * the {@link #view(String, Object)} method. * * @param name name of a flash */ @SuppressWarnings("unchecked") protected void flash(String name){ flash(name, null); } /** * Sends value to flash. Flash survives one more request. Using flash is typical * for POST/GET pattern, * * @param name name of value to flash * @param value value to live for one more request in current session. */ @SuppressWarnings("unchecked") protected void flash(String name, Object value) { if (session().get("flasher") == null) { session().put("flasher", new HashMap()); } ((Map) session().get("flasher")).put(name, value); } public class HttpBuilder { private ControllerResponse controllerResponse; private HttpBuilder(ControllerResponse controllerResponse){ this.controllerResponse = controllerResponse; } protected ControllerResponse getControllerResponse() { return controllerResponse; } /** * Sets content type of response. * These can be "text/html". Value "text/html" is set by default. * * @param contentType content type value. * @return instance of RenderBuilder */ public HttpBuilder contentType(String contentType) { controllerResponse.setContentType(contentType); return this; } /** * Sets a HTTP header on response. * * @param name name of header. * @param value value of header. * @return instance of RenderBuilder */ public HttpBuilder header(String name, String value){ Context.getHttpResponse().setHeader(name, value); return this; } /** * Overrides HTTP status with a different value. * For values and more information, look here: * <a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html'>HTTP Status Codes</a>. * * By default, the status is set to 200, OK. * * @param status HTTP status code. */ public void status(int status){ controllerResponse.setStatus(status); } } public class RenderBuilder extends HttpBuilder { private RenderBuilder(RenderTemplateResponse response){ super(response); } /** * Use this method to override a default layout configured. * * @param layout name of another layout. * @return instance of RenderBuilder */ public RenderBuilder layout(String layout){ getRenderTemplateResponse().setLayout(layout); return this; } protected RenderTemplateResponse getRenderTemplateResponse(){ return (RenderTemplateResponse)getControllerResponse(); } /** * Call this method to turn off all layouts. The view will be rendered raw - no layouts. * @return instance of RenderBuilder */ public RenderBuilder noLayout(){ getRenderTemplateResponse().setLayout(null); return this; } /** * Sets a format for the current request. This is a intermediate extension for the template file. For instance, * if the name of template file is document.xml.ftl, then the "xml" part is set with this method, the * "document" is a template name, and "ftl" extension is assumed in case you use FreeMarker template manager. * * @param format template format * @return instance of RenderBuilder */ public RenderBuilder format(String format){ ControllerResponse response = Context.getControllerResponse(); if(response instanceof RenderTemplateResponse){ ((RenderTemplateResponse)response).setFormat(format); } return this; } } /** * Renders results with a template. * * This call must be the last call in the action. * * @param template - template name, must be "absolute", starting with slash, * such as: "/controller_dir/action_template". * @param values map with values to pass to view. * @return instance of {@link RenderBuilder}, which is used to provide additional parameters. */ protected RenderBuilder render(String template, Map values) { RenderTemplateResponse resp = new RenderTemplateResponse(values, template, Context.getFormat()); Context.setControllerResponse(resp); return new RenderBuilder(resp); } /** * Redirects to a an action of this controller, or an action of a different controller. * This method does not expect a full URL. * * @param path - expected to be a path within the application. * @return instance of {@link HttpSupport.HttpBuilder} to accept additional information. */ protected HttpBuilder redirect(String path) { RedirectResponse resp = new RedirectResponse(path); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to another URL (usually another site). * * @param url absolute URL: <code>http://domain/path...</code>. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect(URL url) { RedirectResponse resp = new RedirectResponse(url); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the <code>defaultReference</code>. * * @param defaultReference where to redirect - can be absolute or relative; this will be used in case * the request does not provide a "Referrer" header. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer(String defaultReference) { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? defaultReference: referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the root of the application. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer() { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? Context.getHttpRequest().getContextPath(): referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action, Object id){ return redirect(controllerClass, map("action", action, "id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Object id){ return redirect(controllerClass, map("id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action){ return redirect(controllerClass, map("action", action)); } /** * Redirects to the same controller, and action "index". This is equivalent to * <pre> * redirect(BooksController.class); * </pre> * given that the current controller is <code>BooksController</code>. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect() { return redirect(getRoute().getController().getClass()); } /** * Redirects to given controller, action "index" without any parameters. * * @param controllerClass controller class where to send redirect. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass){ return redirect(controllerClass, new HashMap()); } /** * Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in * the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as * well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as: * <pre> * <code> * /controller/action/id * </code> * </pre> * for regular controllers, and: * <pre> * <code> * /controller/id/action * </code> * </pre> * for RESTful controllers. For RESTful controllers, the action names are limited to those described in * {@link org.javalite.activeweb.annotations.RESTful} and allowed on a GET URLs, which are: "edit_form" and "new_form". * * <p/> * The map may contain any number of other key/value pairs, which will be converted to a query string for * the redirect URI. Example: * <p/> * Method: * <pre> * <code> * redirect(app.controllers.PersonController.class, org.javalite.common.Collections.map("action", "show", "id", 123, "format", "json", "restrict", "true")); * </code> * </pre> * will generate the following URI: * <pre> * <code> * /person/show/123?format=json&restrict=true * </code> * </pre> * * This method will also perform URL - encoding of special characters if necessary. * * * @param controllerClass controller class * @param params map with request parameters. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){ String controllerPath = Router.getControllerPath(controllerClass); String contextPath = Context.getHttpRequest().getContextPath(); String action = params.get("action") != null? params.get("action").toString() : null; String id = params.get("id") != null? params.get("id").toString() : null; boolean restful= AppController.restful(controllerClass); params.remove("action"); params.remove("id"); String uri = contextPath + Router.generate(controllerPath, action, id, restful, params); RedirectResponse resp = new RedirectResponse(uri); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services * and to support AJAX. * * @param text text of response. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder respond(String text){ DirectResponse resp = new DirectResponse(text); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for downloading files. This method will force the browser to find a handler(external program) * for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header * "Content-Disposition" based on a file name. * * @param file file to download. * @return builder instance. * @throws FileNotFoundException thrown if file not found. */ protected HttpBuilder sendFile(File file) throws FileNotFoundException { try{ StreamResponse resp = new StreamResponse(new FileInputStream(file)); Context.setControllerResponse(resp); HttpBuilder builder = new HttpBuilder(resp); builder.header("Content-Disposition", "attachment; filename=" + file.getName()); return builder; }catch(Exception e){ throw new ControllerException(e); } } /** * Convenience method to get file content from <code>multipart/form-data</code> request. * * @param fieldName name of form field from the <code>multipart/form-data</code> request corresponding to the uploaded file. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return <code>InputStream</code> from which to read content of uploaded file or null if FileItem with this name is not found. */ protected org.javalite.activeweb.FileItem getFile(String fieldName, List<FormItem> formItems){ for (FormItem formItem : formItems) { if(formItem instanceof org.javalite.activeweb.FileItem && formItem.getFieldName().equals(fieldName)){ return (org.javalite.activeweb.FileItem)formItem; } } return null; } /** * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @return value of request parameter. * @see org.javalite.activeweb.RequestUtils#param(String) */ protected String param(String name){ return RequestUtils.param(name); } /** * Convenience method to get a parameter in case <code>multipart/form-data</code> request was used. * * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return value of request parameter. * @see org.javalite.activeweb.RequestUtils#param(String) */ protected String param(String name, List<FormItem> formItems){ return RequestUtils.param(name, formItems); } /** * Tests if a request parameter exists. Disregards the value completely - this * can be empty string, but as long as parameter does exist, this method returns true. * * @param name name of request parameter to test. * @return true if parameter exists, false if not. */ protected boolean exists(String name){ return RequestUtils.exists(name); } /** * Synonym of {@link #exists(String)}. * * @param name name of request parameter to test. * @return true if parameter exists, false if not. */ protected boolean requestHas(String name){ return RequestUtils.requestHas(name); } /** * Returns local host name on which request was received. * * @return local host name on which request was received. */ protected String host() { return RequestUtils.host(); } /** * Returns local IP address on which request was received. * * @return local IP address on which request was received. */ protected String ipAddress() { return RequestUtils.ipAddress(); } /** * This method returns a protocol of a request to web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Proto</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #protocol()} method is used. * * @return protocol of web server request if <code>X-Forwarded-Proto</code> header is found, otherwise current * protocol. */ protected String getRequestProtocol(){ return RequestUtils.getRequestProtocol(); } /** * This method returns a port of a web server if this Java container is fronted by one, such that * it sets a header <code>X-Forwarded-Port</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #port()} method is used. * * @return port of web server request if <code>X-Forwarded-Port</code> header is found, otherwise port of the Java container. */ protected int getRequestPort(){ return RequestUtils.getRequestPort(); } /** * Returns port on which the of the server received current request. * * @return port on which the of the server received current request. */ protected int port(){ return RequestUtils.port(); } /** * Returns protocol of request, for example: HTTP/1.1. * * @return protocol of request */ protected String protocol(){ return RequestUtils.protocol(); } //TODO: provide methods for: X-Forwarded-Proto and X-Forwarded-Port /** * This method returns a host name of a web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Host</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #host()} method is used. * * @return host name of web server if <code>X-Forwarded-Host</code> header is found, otherwise local host name. */ protected String getRequestHost() { return RequestUtils.getRequestHost(); } /** * Returns IP address that the web server forwarded request for. * * @return IP address that the web server forwarded request for. */ protected String ipForwardedFor() { return RequestUtils.ipForwardedFor(); } /** * Returns value of ID if one is present on a URL. Id is usually a part of a URI, such as: <code>/controller/action/id</code>. * This depends on a type of a URI, and whether controller is RESTful or not. * * @return ID value from URI is one exists, null if not. */ protected String getId(){ return RequestUtils.getId(); } /** * Returns a collection of uploaded files from a multi-part port request. * Uses request encoding if one provided, and sets no limit on the size of upload. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles() { return uploadedFiles(null, -1); } /** * Returns a collection of uploaded files from a multi-part port request. * Sets no limit on the size of upload. * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles(String encoding) { return uploadedFiles(encoding, -1); } /** * Returns a collection of uploaded files from a multi-part port request. * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * @param maxFileSize maximum file size in the upload in bytes. -1 indicates no limit. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) { HttpServletRequest req = Context.getHttpRequest(); Iterator<FormItem> iterator; if(req instanceof AWMockMultipartHttpServletRequest){//running inside a test, and simulating upload. iterator = ((AWMockMultipartHttpServletRequest)req).getFormItemIterator(); }else{ if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); ServletFileUpload upload = new ServletFileUpload(); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(maxFileSize); try { FileItemIterator it = upload.getItemIterator(Context.getHttpRequest()); iterator = new FormItemIterator(it); } catch (Exception e) { throw new ControllerException(e); } } return iterator; } /** * Convenience method, calls {@link #multipartFormItems(String)}. Does not set encoding before reading request. * @see #multipartFormItems(String) * @return a collection of uploaded files/fields from a multi-part request. */ protected List<FormItem> multipartFormItems() { return multipartFormItems(null); } /** * Returns a collection of uploaded files and form fields from a multi-part request. * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>. * As a result, it is recommended to add the following to your web.xml file: * * <pre> * &lt;listener&gt; * &lt;listener-class&gt; * org.apache.commons.fileupload.servlet.FileCleanerCleanup * &lt;/listener-class&gt; * &lt;/listener&gt; *</pre> * * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a> * * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept files * smaller of larger, create a file called <code>activeweb.properties</code>, add it to your classpath and * place this property to the file: * * <pre> * #max upload size * maxUploadSize = 20000000 * </pre> * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @return a collection of uploaded files from a multi-part request. */ protected List<FormItem> multipartFormItems(String encoding) { //we are thread safe, because controllers are pinned to a thread and discarded after each request. if(formItems != null ){ return formItems; } HttpServletRequest req = Context.getHttpRequest(); if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload. formItems = ((AWMockMultipartHttpServletRequest) req).getFormItems(); } else { if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(Configuration.getMaxUploadSize()); factory.setRepository(Configuration.getTmpDir()); ServletFileUpload upload = new ServletFileUpload(factory); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(Configuration.getMaxUploadSize()); try { List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(Context.getHttpRequest()); formItems = new ArrayList<FormItem>(); for (FileItem apacheItem : apacheFileItems) { ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem); if(f.isFormField()){ formItems.add(new FormItem(f)); }else{ formItems.add(new org.javalite.activeweb.FileItem(f)); } } return formItems; } catch (Exception e) { throw new ControllerException(e); } } return formItems; } /** * Returns multiple request values for a name. * * @param name name of multiple values from request. * @return multiple request values for a name. */ protected List<String> params(String name){ return RequestUtils.params(name); } /** * Returns an instance of <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. * * @return an instance <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. */ protected Map<String, String[]> params(){ return RequestUtils.params(); } /** * Convenience method to get parameters in case <code>multipart/form-data</code> request was used. * Returns multiple request values for a name. * * @param name name of multiple values from request. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return multiple request values for a name. */ protected List<String> params(String name, List<FormItem> formItems){ return RequestUtils.params(name, formItems); } /** * Returns a map parsed from a request if parameter names have a "hash" syntax: * * <pre> * &lt;input type=&quot;text&quot; name=&quot;account[name]&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;account[number]&quot; /&gt; * </pre> * * will result in a map where keys are names of hash elements, and values are values of these elements from request. * For the example above, the map will have these values: * * <pre> * { "name":"John", "number": "123" } * </pre> * * @param hashName - name of a hash. In the example above, it will be "account". * @return map with name/value pairs parsed from request. */ public Map<String, String> getMap(String hashName) { Map<String, String[]> params = params(); Map<String, String> hash = new HashMap<String, String>(); for(String key:params.keySet()){ if(key.startsWith(hashName)){ String name = parseHashName(key); if(name != null){ hash.put(name, param(key)); } } } return hash; } /** * Convenience method to get parameter map in case <code>multipart/form-data</code> request was used. * This method will skip files, and will only return form fields that are not files. * * Returns a map parsed from a request if parameter names have a "hash" syntax: * * <pre> * &lt;input type=&quot;text&quot; name=&quot;account[name]&quot; /&gt; * &lt;input type=&quot;text&quot; name=&quot;account[number]&quot; /&gt; * </pre> * * will result in a map where keys are names of hash elements, and values are values of these elements from request. * For the example above, the map will have these values: * * <pre> * { "name":"John", "number": "123" } * </pre> * * @param hashName - name of a hash. In the example above, it will be "account". * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return map with name/value pairs parsed from request. */ public Map<String, String> getMap(String hashName, List<FormItem> formItems) { Map<String, String> hash = new HashMap<String, String>(); for(FormItem item:formItems){ if(item.getFieldName().startsWith(hashName) && !item.isFile()){ String name = parseHashName(item.getFieldName()); if(name != null){ hash.put(name, item.getStreamAsString()); } } } return hash; } private static Pattern hashPattern = Pattern.compile("\\[.*\\]"); /** * Parses name from hash syntax. * * @param param something like this: <code>person[account]</code> * @return name of hash key:<code>account</code> */ private static String parseHashName(String param) { Matcher matcher = hashPattern.matcher(param); String name = null; while (matcher.find()){ name = matcher.group(0); } return name == null? null : name.substring(1, name.length() - 1); } public static void main(String[] args){ System.out.println(HttpSupport.parseHashName("account[name]")); } /** * Sets character encoding for request. Has to be called before reading any parameters of getting input * stream. * @param encoding encoding to be set. * * @throws UnsupportedEncodingException */ protected void setRequestEncoding(String encoding) throws UnsupportedEncodingException { Context.getHttpRequest().setCharacterEncoding(encoding); } /** * Sets character encoding for response. * * @param encoding encoding to be set. */ protected void setResponseEncoding(String encoding) { Context.getHttpResponse().setCharacterEncoding(encoding); } /** * Sets character encoding on the response. * * @param encoding character encoding for response. */ protected void setEncoding(String encoding){ Context.setEncoding(encoding); } /** * Synonym for {@link #setEncoding(String)} * * @param encoding encoding of response to client */ protected void encoding(String encoding){ setEncoding(encoding); } /** * Controllers can override this method to return encoding they require. Encoding set in method {@link #setEncoding(String)} * trumps this setting. * * @return null. If this method is not overridden and encoding is not set from an action or filter, * encoding will be set according to container implementation. */ protected String getEncoding(){ return null; } /** * Sets content length of response. * * @param length content length of response. */ protected void setContentLength(int length){ Context.getHttpResponse().setContentLength(length); } /** * Sets locale on response. * * @param locale locale for response. */ protected void setLocale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Same as {@link #setLocale(java.util.Locale)} * * @param locale locale for response */ protected void locale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Returns locale of request. * * @return locale of request. */ protected Locale locale(){ return RequestUtils.locale(); } /** * Same as {@link #locale()}. * * @return locale of request. */ protected Locale getLocale(){ return RequestUtils.getLocale(); } /** * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(){ return RequestUtils.params1st(); } /** * Convenience method to get first parameter values in case <code>multipart/form-data</code> request was used. * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(List<FormItem> formItems){ return RequestUtils.params1st(formItems); } /** * Returns reference to a current session. Creates a new session of one does not exist. * @return reference to a current session. */ protected SessionFacade session(){ return new SessionFacade(); } /** * Convenience method, sets an object on a session. Equivalent of: * <pre> * <code> * session().put(name, value) * </code> * </pre> * * @param name name of object * @param value object itself. */ protected void session(String name, Serializable value){ session().put(name, value); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * session().get(name) * </code> * </pre> * * @param name name of object, * @return session object. */ protected Object sessionObject(String name){ return session(name); } /** * Synonym of {@link #sessionObject(String)}. * * @param name name of session attribute * @return value of session attribute of null if not found */ protected Object session(String name){ Object val = session().get(name); return val == null ? null : val; } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * String val = (String)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected String sessionString(String name){ return Convert.toString(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Integer val = (Integer)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Integer sessionInteger(String name){ return Convert.toInteger(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Boolean val = (Boolean)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Boolean sessionBoolean(String name){ return Convert.toBoolean(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Double val = (Double)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Double sessionDouble(String name){ return Convert.toDouble(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Float val = (Float)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Float sessionFloat(String name){ return Convert.toFloat(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Long val = (Long)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Long sessionLong(String name){ return Convert.toLong(session(name)); } /** * Returns true if session has named object, false if not. * * @param name name of object. * @return true if session has named object, false if not. */ protected boolean sessionHas(String name){ return session().get(name) != null; } /** * Returns collection of all cookies browser sent. * * @return collection of all cookies browser sent. */ public List<Cookie> cookies(){ return RequestUtils.cookies(); } /** * Returns a cookie by name, null if not found. * * @param name name of a cookie. * @return a cookie by name, null if not found. */ public Cookie cookie(String name){ return RequestUtils.cookie(name); } /** * Convenience method, returns cookie value. * * @param name name of cookie. * @return cookie value. */ protected String cookieValue(String name){ return RequestUtils.cookieValue(name); } /** * Sends cookie to browse with response. * * @param cookie cookie to send. */ public void sendCookie(Cookie cookie){ Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Sends cookie to browse with response. * * @param name name of cookie * @param value value of cookie. */ public void sendCookie(String name, String value) { Context.getHttpResponse().addCookie(Cookie.toServletCookie(new Cookie(name, value))); } /** * Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years. * * @param name name of cookie * @param value value of cookie. */ public void sendPermanentCookie(String name, String value) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(60*60*24*365*20); Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Returns a path of the request. It does not include protocol, host, port or context. Just a path. * Example: <code>/controller/action/id</code> * * @return a path of the request. */ protected String path(){ return RequestUtils.path(); } /** * Returns a full URL of the request, all except a query string. * * @return a full URL of the request, all except a query string. */ protected String url(){ return RequestUtils.url(); } /** * Returns query string of the request. * * @return query string of the request. */ protected String queryString(){ return RequestUtils.queryString(); } /** * Returns an HTTP method from the request. * * @return an HTTP method from the request. */ protected String method(){ return RequestUtils.method(); } /** * True if this request uses HTTP GET method, false otherwise. * * @return True if this request uses HTTP GET method, false otherwise. */ protected boolean isGet() { return RequestUtils.isGet(); } /** * True if this request uses HTTP POST method, false otherwise. * * @return True if this request uses HTTP POST method, false otherwise. */ protected boolean isPost() { return RequestUtils.isPost(); } /** * True if this request uses HTTP PUT method, false otherwise. * * @return True if this request uses HTTP PUT method, false otherwise. */ protected boolean isPut() { return RequestUtils.isPut(); } /** * True if this request uses HTTP DELETE method, false otherwise. * * @return True if this request uses HTTP DELETE method, false otherwise. */ protected boolean isDelete() { return RequestUtils.isDelete(); } private boolean isMethod(String method){ return RequestUtils.isMethod(method); } /** * True if this request uses HTTP HEAD method, false otherwise. * * @return True if this request uses HTTP HEAD method, false otherwise. */ protected boolean isHead() { return RequestUtils.isHead(); } /** * Provides a context of the request - usually an app name (as seen on URL of request). Example: * <code>/mywebapp</code> * * @return a context of the request - usually an app name (as seen on URL of request). */ protected String context(){ return RequestUtils.context(); } /** * Returns URI, or a full path of request. This does not include protocol, host or port. Just context and path. * Examlpe: <code>/mywebapp/controller/action/id</code> * @return URI, or a full path of request. */ protected String uri(){ return RequestUtils.uri(); } /** * Host name of the requesting client. * * @return host name of the requesting client. */ protected String remoteHost(){ return RequestUtils.remoteHost(); } /** * IP address of the requesting client. * * @return IP address of the requesting client. */ protected String remoteAddress(){ return RequestUtils.remoteAddress(); } /** * Returns a request header by name. * * @param name name of header * @return header value. */ protected String header(String name){ return RequestUtils.header(name); } /** * Returns all headers from a request keyed by header name. * * @return all headers from a request keyed by header name. */ protected Map<String, String> headers(){ return RequestUtils.headers(); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, String value){ Context.getHttpResponse().addHeader(name, value); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, Object value){ if(value == null) throw new NullPointerException("value cannot be null"); header(name, value.toString()); } /** * Streams content of the <code>reader</code> to the HTTP client. * * @param in input stream to read bytes from. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder streamOut(InputStream in) { StreamResponse resp = new StreamResponse(in); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns * the absolute file path on the server's filesystem would be served by a request for * "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. * <p/> * The real path returned will be in a form appropriate to the computer and operating system on which the servlet * <p/> * container is running, including the proper path separators. This method returns null if the servlet container * cannot translate the virtual path to a real path for any reason (such as when the content is being made * available from a .war archive). * * <p/> * JavaDoc copied from: <a href="http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29"> * http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29</a> * * @param path a String specifying a virtual path * @return a String specifying the real path, or null if the translation cannot be performed */ protected String getRealPath(String path) { return Context.getFilterConfig().getServletContext().getRealPath(path); } /** * Use to send raw data to HTTP client. Content type and headers will not be set. * Response code will be set to 200. * * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(){ return outputStream(null, null, 200); } /** * Use to send raw data to HTTP client. Status will be set to 200. * * @param contentType content type * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType) { return outputStream(contentType, null, 200); } /** * Use to send raw data to HTTP client. * * @param contentType content type * @param headers set of headers. * @param status status. * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType, Map headers, int status) { try { Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getOutputStream(); }catch(Exception e){ throw new ControllerException(e); } } /** * Produces a writer for sending raw data to HTTP clients. * * Content type content type not be set on the response. Headers will not be send to client. Status will be * set to 200. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(){ return writer(null, null, 200); } /** * Produces a writer for sending raw data to HTTP clients. * * @param contentType content type. If null - will not be set on the response * @param headers headers. If null - will not be set on the response * @param status will be sent to browser. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(String contentType, Map headers, int status){ try{ Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getWriter(); }catch(Exception e){ throw new ControllerException(e); } } /** * Returns true if any named request parameter is blank. * * @param names names of request parameters. * @return true if any request parameter is blank. */ protected boolean blank(String ... names){ //TODO: write test, move elsewhere - some helper for(String name:names){ if(Util.blank(param(name))){ return true; } } return false; } /** * Returns true if this request is Ajax. * * @return true if this request is Ajax. */ protected boolean isXhr(){ return RequestUtils.isXhr(); } /** * Helper method, returns user-agent header of the request. * * @return user-agent header of the request. */ protected String userAgent(){ return RequestUtils.userAgent(); } /** * Synonym for {@link #isXhr()}. */ protected boolean xhr(){ return RequestUtils.xhr(); } /** * Returns instance of {@link AppContext}. * * @return instance of {@link AppContext}. */ protected AppContext appContext(){ return RequestUtils.appContext(); } /** * Returns a format part of the URI, or null if URI does not have a format part. * A format part is defined as part of URI that is trailing after a last dot, as in: * * <code>/books.xml</code>, here "xml" is a format. * * @return format part of the URI, or nul if URI does not have it. */ protected String format(){ return RequestUtils.format(); } /** * Returns instance of {@link Route} to be used for potential conditional logic inside controller filters. * * @return instance of {@link Route} */ protected Route getRoute(){ return RequestUtils.getRoute(); } /** * Will merge a template and return resulting string. This method is used for just merging some text with dynamic values. * Once you have the result, you can send it by email, external web service, save it to a database, etc. * * @param template name of template - same as in regular templates. Example: <code>"/email-templates/welcome"</code>. * @param values values to be merged into template. * @return merged string */ protected String merge(String template, Map values){ StringWriter stringWriter = new StringWriter(); Configuration.getTemplateManager().merge(values, template, stringWriter); return stringWriter.toString(); } /** * Returns response headers * * @return map with response headers. */ public Map<String, String> getResponseHeaders(){ Collection<String> names = Context.getHttpResponse().getHeaderNames(); Map<String, String> headers = new HashMap<String, String>(); for (String name : names) { headers.put(name, Context.getHttpResponse().getHeader(name)); } return headers; } }
activeweb/src/main/java/org/javalite/activeweb/HttpSupport.java
/* Copyright 2009-2014 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activeweb; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.javalite.common.Convert; import org.javalite.common.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.javalite.common.Collections.map; /** * @author Igor Polevoy */ public class HttpSupport { private Logger logger = LoggerFactory.getLogger(getClass().getName()); private List<FormItem> formItems; protected void logInfo(String info){ logger.info(info); } protected void logDebug(String info){ logger.debug(info); } protected void logWarning(String info){ logger.warn(info); } protected void logWarning(String info, Throwable e){ logger.warn(info, e); } protected void logError(String info){ logger.error(info); } protected void logError(Throwable e){ logger.error("", e); } protected void logError(String info, Throwable e){ logger.error(info, e); } /** * Assigns a value for a view. * * @param name name of value * @param value value. */ protected void assign(String name, Object value) { KeyWords.check(name); Context.getValues().put(name, value); } /** * Alias to {@link #assign(String, Object)}. * * @param name name of object to be passed to view * @param value object to be passed to view */ protected void view(String name, Object value) { assign(name, value); } /** * Convenience method, calls {@link #assign(String, Object)} internally. * The keys in teh map are converted to String values. * * @param values map with values to pass to view. */ protected void view(Map values){ for(Object key:values.keySet() ){ assign(key.toString(), values.get(key)); } } /** * Convenience method to pass multiple names and corresponding values to a view. * * @param values - pairs of names and values. such as: name1, value1, name2, value2, etc. Number of arguments must be even. */ protected void view(Object ... values){ view(map(values)); } /** * Flash method to display multiple flash messages. * Takes in a map of names and values for a flash. * Keys act like names, and values act like... ehr.. values. * * @see #flash(String, Object) * * @param values values to flash. */ protected void flash(Map values){ for(Object key:values.keySet() ){ flash(key.toString(), values.get(key)); } } /** * Flash method to display multiple flash messages. * Takes in a vararg of values for flash. Number of arguments must be even. * Format: name, value, name, value, etc. * * @see #flash(String, Object) * @param values values to flash. */ protected void flash(Object ... values){ flash(map(values)); } /** * Sets a flash name for a flash with a body. * Here is a how to use a tag with a body: * * <pre> * &lt;@flash name=&quot;warning&quot;&gt; &lt;div class=&quot;warning&quot;&gt;${message}&lt;/div&gt; &lt;/@flash&gt; * </pre> * * If body refers to variables (as in this example), then such variables need to be passed in to the template as usual using * the {@link #view(String, Object)} method. * * @param name name of a flash */ @SuppressWarnings("unchecked") protected void flash(String name){ flash(name, null); } /** * Sends value to flash. Flash survives one more request. Using flash is typical * for POST/GET pattern, * * @param name name of value to flash * @param value value to live for one more request in current session. */ @SuppressWarnings("unchecked") protected void flash(String name, Object value) { if (session().get("flasher") == null) { session().put("flasher", new HashMap()); } ((Map) session().get("flasher")).put(name, value); } public class HttpBuilder { private ControllerResponse controllerResponse; private HttpBuilder(ControllerResponse controllerResponse){ this.controllerResponse = controllerResponse; } protected ControllerResponse getControllerResponse() { return controllerResponse; } /** * Sets content type of response. * These can be "text/html". Value "text/html" is set by default. * * @param contentType content type value. * @return instance of RenderBuilder */ public HttpBuilder contentType(String contentType) { controllerResponse.setContentType(contentType); return this; } /** * Sets a HTTP header on response. * * @param name name of header. * @param value value of header. * @return instance of RenderBuilder */ public HttpBuilder header(String name, String value){ Context.getHttpResponse().setHeader(name, value); return this; } /** * Overrides HTTP status with a different value. * For values and more information, look here: * <a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html'>HTTP Status Codes</a>. * * By default, the status is set to 200, OK. * * @param status HTTP status code. */ public void status(int status){ controllerResponse.setStatus(status); } } public class RenderBuilder extends HttpBuilder { private RenderBuilder(RenderTemplateResponse response){ super(response); } /** * Use this method to override a default layout configured. * * @param layout name of another layout. * @return instance of RenderBuilder */ public RenderBuilder layout(String layout){ getRenderTemplateResponse().setLayout(layout); return this; } protected RenderTemplateResponse getRenderTemplateResponse(){ return (RenderTemplateResponse)getControllerResponse(); } /** * Call this method to turn off all layouts. The view will be rendered raw - no layouts. * @return instance of RenderBuilder */ public RenderBuilder noLayout(){ getRenderTemplateResponse().setLayout(null); return this; } /** * Sets a format for the current request. This is a intermediate extension for the template file. For instance, * if the name of template file is document.xml.ftl, then the "xml" part is set with this method, the * "document" is a template name, and "ftl" extension is assumed in case you use FreeMarker template manager. * * @param format template format * @return instance of RenderBuilder */ public RenderBuilder format(String format){ ControllerResponse response = Context.getControllerResponse(); if(response instanceof RenderTemplateResponse){ ((RenderTemplateResponse)response).setFormat(format); } return this; } } /** * Renders results with a template. * * This call must be the last call in the action. * * @param template - template name, must be "absolute", starting with slash, * such as: "/controller_dir/action_template". * @param values map with values to pass to view. * @return instance of {@link RenderBuilder}, which is used to provide additional parameters. */ protected RenderBuilder render(String template, Map values) { RenderTemplateResponse resp = new RenderTemplateResponse(values, template, Context.getFormat()); Context.setControllerResponse(resp); return new RenderBuilder(resp); } /** * Redirects to a an action of this controller, or an action of a different controller. * This method does not expect a full URL. * * @param path - expected to be a path within the application. * @return instance of {@link HttpSupport.HttpBuilder} to accept additional information. */ protected HttpBuilder redirect(String path) { RedirectResponse resp = new RedirectResponse(path); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to another URL (usually another site). * * @param url absolute URL: <code>http://domain/path...</code>. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect(URL url) { RedirectResponse resp = new RedirectResponse(url); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the <code>defaultReference</code>. * * @param defaultReference where to redirect - can be absolute or relative; this will be used in case * the request does not provide a "Referrer" header. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer(String defaultReference) { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? defaultReference: referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the root of the application. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer() { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? Context.getHttpRequest().getContextPath(): referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action, Object id){ return redirect(controllerClass, map("action", action, "id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Object id){ return redirect(controllerClass, map("id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action){ return redirect(controllerClass, map("action", action)); } /** * Redirects to the same controller, and action "index". This is equivalent to * <pre> * redirect(BooksController.class); * </pre> * given that the current controller is <code>BooksController</code>. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect() { return redirect(getRoute().getController().getClass()); } /** * Redirects to given controller, action "index" without any parameters. * * @param controllerClass controller class where to send redirect. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass){ return redirect(controllerClass, new HashMap()); } /** * Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in * the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as * well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as: * <pre> * <code> * /controller/action/id * </code> * </pre> * for regular controllers, and: * <pre> * <code> * /controller/id/action * </code> * </pre> * for RESTful controllers. For RESTful controllers, the action names are limited to those described in * {@link org.javalite.activeweb.annotations.RESTful} and allowed on a GET URLs, which are: "edit_form" and "new_form". * * <p/> * The map may contain any number of other key/value pairs, which will be converted to a query string for * the redirect URI. Example: * <p/> * Method: * <pre> * <code> * redirect(app.controllers.PersonController.class, org.javalite.common.Collections.map("action", "show", "id", 123, "format", "json", "restrict", "true")); * </code> * </pre> * will generate the following URI: * <pre> * <code> * /person/show/123?format=json&restrict=true * </code> * </pre> * * This method will also perform URL - encoding of special characters if necessary. * * * @param controllerClass controller class * @param params map with request parameters. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){ String controllerPath = Router.getControllerPath(controllerClass); String contextPath = Context.getHttpRequest().getContextPath(); String action = params.get("action") != null? params.get("action").toString() : null; String id = params.get("id") != null? params.get("id").toString() : null; boolean restful= AppController.restful(controllerClass); params.remove("action"); params.remove("id"); String uri = contextPath + Router.generate(controllerPath, action, id, restful, params); RedirectResponse resp = new RedirectResponse(uri); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services * and to support AJAX. * * @param text text of response. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder respond(String text){ DirectResponse resp = new DirectResponse(text); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for downloading files. This method will force the browser to find a handler(external program) * for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header * "Content-Disposition" based on a file name. * * @param file file to download. * @return builder instance. * @throws FileNotFoundException thrown if file not found. */ protected HttpBuilder sendFile(File file) throws FileNotFoundException { try{ StreamResponse resp = new StreamResponse(new FileInputStream(file)); Context.setControllerResponse(resp); HttpBuilder builder = new HttpBuilder(resp); builder.header("Content-Disposition", "attachment; filename=" + file.getName()); return builder; }catch(Exception e){ throw new ControllerException(e); } } /** * Convenience method to get file content from <code>multipart/form-data</code> request. * * @param fieldName name of form field from the <code>multipart/form-data</code> request corresponding to the uploaded file. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return <code>InputStream</code> from which to read content of uploaded file or null if FileItem with this name is not found. */ protected org.javalite.activeweb.FileItem getFile(String fieldName, List<FormItem> formItems){ for (FormItem formItem : formItems) { if(formItem instanceof org.javalite.activeweb.FileItem && formItem.getFieldName().equals(fieldName)){ return (org.javalite.activeweb.FileItem)formItem; } } return null; } /** * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @return value of request parameter. * @see org.javalite.activeweb.RequestUtils#param(String) */ protected String param(String name){ return RequestUtils.param(name); } /** * Convenience method to get a parameter in case <code>multipart/form-data</code> request was used. * * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return value of request parameter. * @see org.javalite.activeweb.RequestUtils#param(String) */ protected String param(String name, List<FormItem> formItems){ return RequestUtils.param(name, formItems); } /** * Tests if a request parameter exists. Disregards the value completely - this * can be empty string, but as long as parameter does exist, this method returns true. * * @param name name of request parameter to test. * @return true if parameter exists, false if not. */ protected boolean exists(String name){ return RequestUtils.exists(name); } /** * Synonym of {@link #exists(String)}. * * @param name name of request parameter to test. * @return true if parameter exists, false if not. */ protected boolean requestHas(String name){ return RequestUtils.requestHas(name); } /** * Returns local host name on which request was received. * * @return local host name on which request was received. */ protected String host() { return RequestUtils.host(); } /** * Returns local IP address on which request was received. * * @return local IP address on which request was received. */ protected String ipAddress() { return RequestUtils.ipAddress(); } /** * This method returns a protocol of a request to web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Proto</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #protocol()} method is used. * * @return protocol of web server request if <code>X-Forwarded-Proto</code> header is found, otherwise current * protocol. */ protected String getRequestProtocol(){ return RequestUtils.getRequestProtocol(); } /** * This method returns a port of a web server if this Java container is fronted by one, such that * it sets a header <code>X-Forwarded-Port</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #port()} method is used. * * @return port of web server request if <code>X-Forwarded-Port</code> header is found, otherwise port of the Java container. */ protected int getRequestPort(){ return RequestUtils.getRequestPort(); } /** * Returns port on which the of the server received current request. * * @return port on which the of the server received current request. */ protected int port(){ return RequestUtils.port(); } /** * Returns protocol of request, for example: HTTP/1.1. * * @return protocol of request */ protected String protocol(){ return RequestUtils.protocol(); } //TODO: provide methods for: X-Forwarded-Proto and X-Forwarded-Port /** * This method returns a host name of a web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Host</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #host()} method is used. * * @return host name of web server if <code>X-Forwarded-Host</code> header is found, otherwise local host name. */ protected String getRequestHost() { return RequestUtils.getRequestHost(); } /** * Returns IP address that the web server forwarded request for. * * @return IP address that the web server forwarded request for. */ protected String ipForwardedFor() { return RequestUtils.ipForwardedFor(); } /** * Returns value of ID if one is present on a URL. Id is usually a part of a URI, such as: <code>/controller/action/id</code>. * This depends on a type of a URI, and whether controller is RESTful or not. * * @return ID value from URI is one exists, null if not. */ protected String getId(){ return RequestUtils.getId(); } /** * Returns a collection of uploaded files from a multi-part port request. * Uses request encoding if one provided, and sets no limit on the size of upload. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles() { return uploadedFiles(null, -1); } /** * Returns a collection of uploaded files from a multi-part port request. * Sets no limit on the size of upload. * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles(String encoding) { return uploadedFiles(encoding, -1); } /** * Returns a collection of uploaded files from a multi-part port request. * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * @param maxFileSize maximum file size in the upload in bytes. -1 indicates no limit. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) { HttpServletRequest req = Context.getHttpRequest(); Iterator<FormItem> iterator; if(req instanceof AWMockMultipartHttpServletRequest){//running inside a test, and simulating upload. iterator = ((AWMockMultipartHttpServletRequest)req).getFormItemIterator(); }else{ if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); ServletFileUpload upload = new ServletFileUpload(); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(maxFileSize); try { FileItemIterator it = upload.getItemIterator(Context.getHttpRequest()); iterator = new FormItemIterator(it); } catch (Exception e) { throw new ControllerException(e); } } return iterator; } /** * Convenience method, calls {@link #multipartFormItems(String)}. Does not set encoding before reading request. * @see #multipartFormItems(String) * @return a collection of uploaded files/fields from a multi-part request. */ protected List<FormItem> multipartFormItems() { return multipartFormItems(null); } /** * Returns a collection of uploaded files and form fields from a multi-part request. * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>. * As a result, it is recommended to add the following to your web.xml file: * * <pre> * &lt;listener&gt; * &lt;listener-class&gt; * org.apache.commons.fileupload.servlet.FileCleanerCleanup * &lt;/listener-class&gt; * &lt;/listener&gt; *</pre> * * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a> * * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept files * smaller of larger, create a file called <code>activeweb.properties</code>, add it to your classpath and * place this property to the file: * * <pre> * #max upload size * maxUploadSize = 20000000 * </pre> * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @return a collection of uploaded files from a multi-part request. */ protected List<FormItem> multipartFormItems(String encoding) { //we are thread safe, because controllers are pinned to a thread and discarded after each request. if(formItems != null ){ return formItems; } HttpServletRequest req = Context.getHttpRequest(); if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload. formItems = ((AWMockMultipartHttpServletRequest) req).getFormItems(); } else { if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(Configuration.getMaxUploadSize()); factory.setRepository(Configuration.getTmpDir()); ServletFileUpload upload = new ServletFileUpload(factory); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(Configuration.getMaxUploadSize()); try { List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(Context.getHttpRequest()); formItems = new ArrayList<FormItem>(); for (FileItem apacheItem : apacheFileItems) { ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem); if(f.isFormField()){ formItems.add(new FormItem(f)); }else{ formItems.add(new org.javalite.activeweb.FileItem(f)); } } return formItems; } catch (Exception e) { throw new ControllerException(e); } } return formItems; } /** * Returns multiple request values for a name. * * @param name name of multiple values from request. * @return multiple request values for a name. */ protected List<String> params(String name){ return RequestUtils.params(name); } /** * Returns an instance of <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. * * @return an instance <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. */ protected Map<String, String[]> params(){ return RequestUtils.params(); } /** * Convenience method to get parameters in case <code>multipart/form-data</code> request was used. * Returns multiple request values for a name. * * @param name name of multiple values from request. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return multiple request values for a name. */ protected List<String> params(String name, List<FormItem> formItems){ return RequestUtils.params(name, formItems); } /** * Returns a map parsed from a request if parameter names have a "hash" syntax: * * <pre> * &lt;input type=&quot;text&quot; name=&quot;account[name]&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;account[number]&quot; /&gt; * </pre> * * will result in a map where keys are names of hash elements, and values are values of these elements from request. * For the example above, the map will have these values: * * <pre> * { "name":"John", "number": "123" } * </pre> * * @param hashName - name of a hash. In the example above, it will be "account". * @return map with name/value pairs parsed from request. */ public Map<String, String> getMap(String hashName) { Map<String, String[]> params = params(); Map<String, String> hash = new HashMap<String, String>(); for(String key:params.keySet()){ if(key.startsWith(hashName)){ String name = parseHashName(key); if(name != null){ hash.put(name, param(key)); } } } return hash; } /** * Convenience method to get parameter map in case <code>multipart/form-data</code> request was used. * This method will skip files, and will only return form fields that are not files. * * Returns a map parsed from a request if parameter names have a "hash" syntax: * * <pre> * &lt;input type=&quot;text&quot; name=&quot;account[name]&quot; /&gt; * &lt;input type=&quot;text&quot; name=&quot;account[number]&quot; /&gt; * </pre> * * will result in a map where keys are names of hash elements, and values are values of these elements from request. * For the example above, the map will have these values: * * <pre> * { "name":"John", "number": "123" } * </pre> * * @param hashName - name of a hash. In the example above, it will be "account". * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return map with name/value pairs parsed from request. */ public Map<String, String> getMap(String hashName, List<FormItem> formItems) { Map<String, String> hash = new HashMap<String, String>(); for(FormItem item:formItems){ if(item.getFieldName().startsWith(hashName) && item instanceof FormItem){ String name = parseHashName(item.getFieldName()); if(name != null){ hash.put(name, item.getStreamAsString()); } } } return hash; } private static Pattern hashPattern = Pattern.compile("\\[.*\\]"); /** * Parses name from hash syntax. * * @param param something like this: <code>person[account]</code> * @return name of hash key:<code>account</code> */ private static String parseHashName(String param) { Matcher matcher = hashPattern.matcher(param); String name = null; while (matcher.find()){ name = matcher.group(0); } return name == null? null : name.substring(1, name.length() - 1); } public static void main(String[] args){ System.out.println(HttpSupport.parseHashName("account[name]")); } /** * Sets character encoding for request. Has to be called before reading any parameters of getting input * stream. * @param encoding encoding to be set. * * @throws UnsupportedEncodingException */ protected void setRequestEncoding(String encoding) throws UnsupportedEncodingException { Context.getHttpRequest().setCharacterEncoding(encoding); } /** * Sets character encoding for response. * * @param encoding encoding to be set. */ protected void setResponseEncoding(String encoding) { Context.getHttpResponse().setCharacterEncoding(encoding); } /** * Sets character encoding on the response. * * @param encoding character encoding for response. */ protected void setEncoding(String encoding){ Context.setEncoding(encoding); } /** * Synonym for {@link #setEncoding(String)} * * @param encoding encoding of response to client */ protected void encoding(String encoding){ setEncoding(encoding); } /** * Controllers can override this method to return encoding they require. Encoding set in method {@link #setEncoding(String)} * trumps this setting. * * @return null. If this method is not overridden and encoding is not set from an action or filter, * encoding will be set according to container implementation. */ protected String getEncoding(){ return null; } /** * Sets content length of response. * * @param length content length of response. */ protected void setContentLength(int length){ Context.getHttpResponse().setContentLength(length); } /** * Sets locale on response. * * @param locale locale for response. */ protected void setLocale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Same as {@link #setLocale(java.util.Locale)} * * @param locale locale for response */ protected void locale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Returns locale of request. * * @return locale of request. */ protected Locale locale(){ return RequestUtils.locale(); } /** * Same as {@link #locale()}. * * @return locale of request. */ protected Locale getLocale(){ return RequestUtils.getLocale(); } /** * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(){ return RequestUtils.params1st(); } /** * Convenience method to get first parameter values in case <code>multipart/form-data</code> request was used. * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * @param formItems form items retrieved from <code>multipart/form-data</code> request. * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(List<FormItem> formItems){ return RequestUtils.params1st(formItems); } /** * Returns reference to a current session. Creates a new session of one does not exist. * @return reference to a current session. */ protected SessionFacade session(){ return new SessionFacade(); } /** * Convenience method, sets an object on a session. Equivalent of: * <pre> * <code> * session().put(name, value) * </code> * </pre> * * @param name name of object * @param value object itself. */ protected void session(String name, Serializable value){ session().put(name, value); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * session().get(name) * </code> * </pre> * * @param name name of object, * @return session object. */ protected Object sessionObject(String name){ return session(name); } /** * Synonym of {@link #sessionObject(String)}. * * @param name name of session attribute * @return value of session attribute of null if not found */ protected Object session(String name){ Object val = session().get(name); return val == null ? null : val; } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * String val = (String)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected String sessionString(String name){ return Convert.toString(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Integer val = (Integer)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Integer sessionInteger(String name){ return Convert.toInteger(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Boolean val = (Boolean)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Boolean sessionBoolean(String name){ return Convert.toBoolean(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Double val = (Double)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Double sessionDouble(String name){ return Convert.toDouble(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Float val = (Float)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Float sessionFloat(String name){ return Convert.toFloat(session(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Long val = (Long)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Long sessionLong(String name){ return Convert.toLong(session(name)); } /** * Returns true if session has named object, false if not. * * @param name name of object. * @return true if session has named object, false if not. */ protected boolean sessionHas(String name){ return session().get(name) != null; } /** * Returns collection of all cookies browser sent. * * @return collection of all cookies browser sent. */ public List<Cookie> cookies(){ return RequestUtils.cookies(); } /** * Returns a cookie by name, null if not found. * * @param name name of a cookie. * @return a cookie by name, null if not found. */ public Cookie cookie(String name){ return RequestUtils.cookie(name); } /** * Convenience method, returns cookie value. * * @param name name of cookie. * @return cookie value. */ protected String cookieValue(String name){ return RequestUtils.cookieValue(name); } /** * Sends cookie to browse with response. * * @param cookie cookie to send. */ public void sendCookie(Cookie cookie){ Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Sends cookie to browse with response. * * @param name name of cookie * @param value value of cookie. */ public void sendCookie(String name, String value) { Context.getHttpResponse().addCookie(Cookie.toServletCookie(new Cookie(name, value))); } /** * Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years. * * @param name name of cookie * @param value value of cookie. */ public void sendPermanentCookie(String name, String value) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(60*60*24*365*20); Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Returns a path of the request. It does not include protocol, host, port or context. Just a path. * Example: <code>/controller/action/id</code> * * @return a path of the request. */ protected String path(){ return RequestUtils.path(); } /** * Returns a full URL of the request, all except a query string. * * @return a full URL of the request, all except a query string. */ protected String url(){ return RequestUtils.url(); } /** * Returns query string of the request. * * @return query string of the request. */ protected String queryString(){ return RequestUtils.queryString(); } /** * Returns an HTTP method from the request. * * @return an HTTP method from the request. */ protected String method(){ return RequestUtils.method(); } /** * True if this request uses HTTP GET method, false otherwise. * * @return True if this request uses HTTP GET method, false otherwise. */ protected boolean isGet() { return RequestUtils.isGet(); } /** * True if this request uses HTTP POST method, false otherwise. * * @return True if this request uses HTTP POST method, false otherwise. */ protected boolean isPost() { return RequestUtils.isPost(); } /** * True if this request uses HTTP PUT method, false otherwise. * * @return True if this request uses HTTP PUT method, false otherwise. */ protected boolean isPut() { return RequestUtils.isPut(); } /** * True if this request uses HTTP DELETE method, false otherwise. * * @return True if this request uses HTTP DELETE method, false otherwise. */ protected boolean isDelete() { return RequestUtils.isDelete(); } private boolean isMethod(String method){ return RequestUtils.isMethod(method); } /** * True if this request uses HTTP HEAD method, false otherwise. * * @return True if this request uses HTTP HEAD method, false otherwise. */ protected boolean isHead() { return RequestUtils.isHead(); } /** * Provides a context of the request - usually an app name (as seen on URL of request). Example: * <code>/mywebapp</code> * * @return a context of the request - usually an app name (as seen on URL of request). */ protected String context(){ return RequestUtils.context(); } /** * Returns URI, or a full path of request. This does not include protocol, host or port. Just context and path. * Examlpe: <code>/mywebapp/controller/action/id</code> * @return URI, or a full path of request. */ protected String uri(){ return RequestUtils.uri(); } /** * Host name of the requesting client. * * @return host name of the requesting client. */ protected String remoteHost(){ return RequestUtils.remoteHost(); } /** * IP address of the requesting client. * * @return IP address of the requesting client. */ protected String remoteAddress(){ return RequestUtils.remoteAddress(); } /** * Returns a request header by name. * * @param name name of header * @return header value. */ protected String header(String name){ return RequestUtils.header(name); } /** * Returns all headers from a request keyed by header name. * * @return all headers from a request keyed by header name. */ protected Map<String, String> headers(){ return RequestUtils.headers(); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, String value){ Context.getHttpResponse().addHeader(name, value); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, Object value){ if(value == null) throw new NullPointerException("value cannot be null"); header(name, value.toString()); } /** * Streams content of the <code>reader</code> to the HTTP client. * * @param in input stream to read bytes from. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder streamOut(InputStream in) { StreamResponse resp = new StreamResponse(in); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns * the absolute file path on the server's filesystem would be served by a request for * "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. * <p/> * The real path returned will be in a form appropriate to the computer and operating system on which the servlet * <p/> * container is running, including the proper path separators. This method returns null if the servlet container * cannot translate the virtual path to a real path for any reason (such as when the content is being made * available from a .war archive). * * <p/> * JavaDoc copied from: <a href="http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29"> * http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29</a> * * @param path a String specifying a virtual path * @return a String specifying the real path, or null if the translation cannot be performed */ protected String getRealPath(String path) { return Context.getFilterConfig().getServletContext().getRealPath(path); } /** * Use to send raw data to HTTP client. Content type and headers will not be set. * Response code will be set to 200. * * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(){ return outputStream(null, null, 200); } /** * Use to send raw data to HTTP client. Status will be set to 200. * * @param contentType content type * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType) { return outputStream(contentType, null, 200); } /** * Use to send raw data to HTTP client. * * @param contentType content type * @param headers set of headers. * @param status status. * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType, Map headers, int status) { try { Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getOutputStream(); }catch(Exception e){ throw new ControllerException(e); } } /** * Produces a writer for sending raw data to HTTP clients. * * Content type content type not be set on the response. Headers will not be send to client. Status will be * set to 200. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(){ return writer(null, null, 200); } /** * Produces a writer for sending raw data to HTTP clients. * * @param contentType content type. If null - will not be set on the response * @param headers headers. If null - will not be set on the response * @param status will be sent to browser. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(String contentType, Map headers, int status){ try{ Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getWriter(); }catch(Exception e){ throw new ControllerException(e); } } /** * Returns true if any named request parameter is blank. * * @param names names of request parameters. * @return true if any request parameter is blank. */ protected boolean blank(String ... names){ //TODO: write test, move elsewhere - some helper for(String name:names){ if(Util.blank(param(name))){ return true; } } return false; } /** * Returns true if this request is Ajax. * * @return true if this request is Ajax. */ protected boolean isXhr(){ return RequestUtils.isXhr(); } /** * Helper method, returns user-agent header of the request. * * @return user-agent header of the request. */ protected String userAgent(){ return RequestUtils.userAgent(); } /** * Synonym for {@link #isXhr()}. */ protected boolean xhr(){ return RequestUtils.xhr(); } /** * Returns instance of {@link AppContext}. * * @return instance of {@link AppContext}. */ protected AppContext appContext(){ return RequestUtils.appContext(); } /** * Returns a format part of the URI, or null if URI does not have a format part. * A format part is defined as part of URI that is trailing after a last dot, as in: * * <code>/books.xml</code>, here "xml" is a format. * * @return format part of the URI, or nul if URI does not have it. */ protected String format(){ return RequestUtils.format(); } /** * Returns instance of {@link Route} to be used for potential conditional logic inside controller filters. * * @return instance of {@link Route} */ protected Route getRoute(){ return RequestUtils.getRoute(); } /** * Will merge a template and return resulting string. This method is used for just merging some text with dynamic values. * Once you have the result, you can send it by email, external web service, save it to a database, etc. * * @param template name of template - same as in regular templates. Example: <code>"/email-templates/welcome"</code>. * @param values values to be merged into template. * @return merged string */ protected String merge(String template, Map values){ StringWriter stringWriter = new StringWriter(); Configuration.getTemplateManager().merge(values, template, stringWriter); return stringWriter.toString(); } /** * Returns response headers * * @return map with response headers. */ public Map<String, String> getResponseHeaders(){ Collection<String> names = Context.getHttpResponse().getHeaderNames(); Map<String, String> headers = new HashMap<String, String>(); for (String name : names) { headers.put(name, Context.getHttpResponse().getHeader(name)); } return headers; } }
activeweb-187 HttpSupport.getMap() must skip uploaded files
activeweb/src/main/java/org/javalite/activeweb/HttpSupport.java
activeweb-187 HttpSupport.getMap() must skip uploaded files
Java
apache-2.0
28bb651bd13ec6dec8c57520621e6e29d1f4d208
0
tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient
/* * Copyright 2016 Theo Pearson-Bray * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tpb.projects.project; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.DragEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.commonsware.cwac.pager.PageDescriptor; import com.commonsware.cwac.pager.v4.ArrayPagerAdapter; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.google.firebase.analytics.FirebaseAnalytics; import com.tpb.projects.R; import com.tpb.projects.data.APIHandler; import com.tpb.projects.data.Editor; import com.tpb.projects.data.Loader; import com.tpb.projects.data.SettingsActivity; import com.tpb.projects.data.auth.GitHubSession; import com.tpb.projects.data.models.Card; import com.tpb.projects.data.models.Column; import com.tpb.projects.data.models.Issue; import com.tpb.projects.data.models.Project; import com.tpb.projects.data.models.Repository; import com.tpb.projects.dialogs.CardDialog; import com.tpb.projects.dialogs.NewIssueDialog; import com.tpb.projects.util.Analytics; import com.tpb.projects.util.ShortcutDialog; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by theo on 19/12/16. */ public class ProjectActivity extends AppCompatActivity implements Loader.ProjectLoader { private static final String TAG = ProjectActivity.class.getSimpleName(); private static final String URL = "https://github.com/tpb1908/AndroidProjectsClient/blob/master/app/src/main/java/com/tpb/projects/project/ProjectActivity.java"; private FirebaseAnalytics mAnalytics; @BindView(R.id.project_toolbar) Toolbar mToolbar; @BindView(R.id.project_name) TextView mName; @BindView(R.id.project_refresher) SwipeRefreshLayout mRefresher; @BindView(R.id.project_column_pager) ViewPager mColumnPager; @BindView(R.id.project_fab_menu) FloatingActionMenu mMenu; @BindView(R.id.project_add_card) FloatingActionButton mAddCard; @BindView(R.id.project_add_column) FloatingActionButton mAddColumn; @BindView(R.id.project_add_issue) FloatingActionButton mAddIssue; private SearchView mSearchView; private ColumnPagerAdapter mAdapter; private int mCurrentPosition = -1; private MenuItem mSearchItem; private Loader mLoader; Project mProject; private Editor mEditor; private NavigationDragListener mNavListener; private Repository.AccessLevel mAccessLevel = Repository.AccessLevel.NONE; private int mLoadCount; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SettingsActivity.Preferences prefs = SettingsActivity.Preferences.getPreferences(this); setTheme(prefs.isDarkThemeEnabled() ? R.style.AppTheme_Dark : R.style.AppTheme); setContentView(R.layout.activity_project); ButterKnife.bind(this); mAnalytics = FirebaseAnalytics.getInstance(this); mAnalytics.setAnalyticsCollectionEnabled(prefs.areAnalyticsEnabled()); final Intent launchIntent = getIntent(); mLoader = new Loader(this); mEditor = new Editor(this); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); if(launchIntent.hasExtra(getString(R.string.parcel_project))) { projectLoaded(launchIntent.getParcelableExtra(getString(R.string.parcel_project))); mAccessLevel = (Repository.AccessLevel) launchIntent.getSerializableExtra(getString(R.string.intent_access_level)); if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { new Handler().postDelayed(() -> mMenu.showMenuButton(true), 400); } } else { final String repo = launchIntent.getStringExtra(getString(R.string.intent_repo)); final int number = launchIntent.getIntExtra(getString(R.string.intent_project_number), 1); //We have to load all of the projects to get the id that we want mLoader.loadProjects(new Loader.ProjectsLoader() { int projectLoadAttempts = 0; @Override public void projectsLoaded(Project[] projects) { for(Project p : projects) { if(number == p.getNumber()) { projectLoaded(p); checkAccess(p); return; } } Toast.makeText(ProjectActivity.this, R.string.error_project_not_found, Toast.LENGTH_LONG).show(); finish(); } @Override public void projectsLoadError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(projectLoadAttempts < 5) { projectLoadAttempts++; mLoader.loadProjects(this, repo); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } } }, repo); } getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); mAdapter = new ColumnPagerAdapter(getSupportFragmentManager(), new ArrayList<>()); mColumnPager.setAdapter(mAdapter); mColumnPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mCurrentPosition = position; Log.i(TAG, "onPageSelected: Page changed to " + position); if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { showFab(); } } @Override public void onPageScrollStateChanged(int state) { if(state == ViewPager.SCROLL_STATE_DRAGGING) { mRefresher.setEnabled(false); } else if(state == ViewPager.SCROLL_STATE_IDLE) { mRefresher.setEnabled(true); } } }); mRefresher.setRefreshing(true); mMenu.hideMenuButton(false); //Hide the button so that we can show it later mMenu.setClosedOnTouchOutside(true); mRefresher.setOnRefreshListener(() -> mLoader.loadProject(ProjectActivity.this, mProject.getId())); mNavListener = new NavigationDragListener(); mRefresher.setOnDragListener(mNavListener); } private void checkAccess(Project project) { mLoader.checkAccessToRepository(new Loader.AccessCheckListener() { int accessCheckAttempts = 0; @Override public void accessCheckComplete(Repository.AccessLevel accessLevel) { Log.i(TAG, "accessCheckComplete: " + accessLevel); mAccessLevel = accessLevel; if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { mMenu.showMenuButton(true); } else { mMenu.hideMenuButton(false); } for(int i = 0; i < mAdapter.getCount(); i++) { if(mAdapter.getExistingFragment(i) != null) { mAdapter.getExistingFragment(i).setAccessLevel(mAccessLevel); } } } @Override public void accessCheckError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(accessCheckAttempts < 5) { accessCheckAttempts++; mLoader.checkAccessToRepository(this, GitHubSession.getSession(ProjectActivity.this).getUserLogin(), project.getRepoPath()); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } } }, GitHubSession.getSession(this).getUserLogin(), project.getRepoPath()); } void showFab() { mMenu.showMenuButton(true); } void hideFab() { mMenu.hideMenuButton(true); } @Override public void projectLoaded(Project project) { Log.i(TAG, "projectLoaded: Owner url " + project.getOwnerUrl()); mProject = project; mLoader.loadLabels(null, mProject.getRepoPath()); mName.setText(project.getName()); final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_PROJECT_LOADED, bundle); mLoadCount = 0; mLoader.loadColumns(new Loader.ColumnsLoader() { @Override public void columnsLoaded(Column[] columns) { if(columns.length > 0) { mAddCard.setVisibility(View.INVISIBLE); mAddIssue.setVisibility(View.INVISIBLE); int id = 0; if(mCurrentPosition != -1) { id = mAdapter.getCurrentFragment().mColumn.getId(); } mCurrentPosition = 0; mAdapter.columns = new ArrayList<>(Arrays.asList(columns)); if(mAdapter.getCount() != 0) { for(int i = mAdapter.getCount() - 1; i >= 0; i--) mAdapter.remove(i); } for(int i = 0; i < columns.length; i++) { mAdapter.add(new ColumnPageDescriptor(columns[i])); if(columns[i].getId() == id) { mCurrentPosition = i; } } mColumnPager.setOffscreenPageLimit(mAdapter.getCount()); if(mCurrentPosition >= mAdapter.getCount()) { mCurrentPosition = mAdapter.getCount() - 1; //If the end column has been deleted } mColumnPager.setCurrentItem(mCurrentPosition, true); mColumnPager.postDelayed(() -> mColumnPager.setVisibility(View.VISIBLE), 300); } else { mAddCard.setVisibility(View.GONE); mAddIssue.setVisibility(View.GONE); } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_SUCCESS); bundle.putInt(Analytics.KEY_COLUMN_COUNT, columns.length + 1); mAnalytics.logEvent(Analytics.TAG_COLUMNS_LOADED, bundle); } @Override public void columnsLoadError(APIHandler.APIError error) { final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMNS_LOADED, bundle); } }, project.getId()); } @Override public void projectLoadError(APIHandler.APIError error) { final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_PROJECT_LOADED, bundle); } void loadIssue(Loader.IssueLoader loader, int issueId, Column column) { mLoader.loadIssue(loader, mProject.getRepoPath(), issueId, mAdapter.indexOf(column.getId()) == mCurrentPosition); } @OnClick(R.id.project_add_column) void addColumn() { mMenu.close(true); final AlertDialog dialog = new AlertDialog.Builder(this) .setView(R.layout.dialog_new_column) .setTitle(R.string.title_new_column) .setNegativeButton(R.string.action_cancel, null) .create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.action_ok), (di, w) -> { }); //Null is ambiguous so we pass empty lambda dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> { final EditText editor = (EditText) dialog.findViewById(R.id.project_new_column); final String text = editor.getText().toString(); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm.isActive()) { imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } if(!text.isEmpty()) { mRefresher.setRefreshing(true); mEditor.addColumn(new Editor.ColumnAdditionListener() { int addColumnAttempts = 0; @Override public void columnAdded(Column column) { mAddCard.setVisibility(View.INVISIBLE); mAddIssue.setVisibility(View.INVISIBLE); mAdapter.columns.add(column); mAdapter.add(new ColumnPageDescriptor(column)); mColumnPager.setCurrentItem(mAdapter.getCount(), true); mRefresher.setRefreshing(false); final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_COLUMN_ADD, bundle); } @Override public void columnAdditionError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(addColumnAttempts < 5) { addColumnAttempts++; mEditor.addColumn(this, mProject.getId(), text); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMN_ADD, bundle); } }, mProject.getId(), text); dialog.dismiss(); } else { Toast.makeText(this, R.string.error_no_column_title, Toast.LENGTH_SHORT).show(); } }); dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v -> { final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm.isActive()) { imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } dialog.dismiss(); }); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } @OnClick(R.id.project_add_issue) void addIssue() { mMenu.close(true); final NewIssueDialog newDialog = new NewIssueDialog(); newDialog.setListener(new NewIssueDialog.IssueDialogListener() { @Override public void issueCreated(Issue issue) { mAdapter.getCurrentFragment().createIssueCard(issue); } @Override public void issueCreationCancelled() { } }); final Bundle c = new Bundle(); c.putString(getString(R.string.intent_repo), mProject.getRepoPath()); newDialog.setArguments(c); newDialog.show(getSupportFragmentManager(), TAG); } void deleteColumn(Column column) { new AlertDialog.Builder(this, R.style.DialogAnimation) .setTitle(R.string.title_delete_column) .setMessage(R.string.text_delete_column_warning) .setNegativeButton(R.string.action_cancel, null) .setPositiveButton(R.string.action_ok, (dialogInterface, i) -> { mRefresher.setRefreshing(true); mEditor.deleteColumn(new Editor.ColumnDeletionListener() { int deleteColumnAttempts = 0; @Override public void columnDeleted() { mAdapter.remove(mCurrentPosition); mAdapter.columns.remove(mCurrentPosition); mRefresher.setRefreshing(false); if(mAdapter.columns.size() == 0) { mAddCard.setVisibility(View.GONE); mAddIssue.setVisibility(View.GONE); } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_COLUMN_DELETE, bundle); } @Override public void columnDeletionError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(deleteColumnAttempts < 5) { deleteColumnAttempts++; mEditor.deleteColumn(this, column.getId()); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMN_DELETE, bundle); } }, column.getId()); }).show(); } /** * @param tag id of the column being moved * @param dropTag id of the column being dropped onto * @param direction side of the drop column to drop to true=left false=right */ void moveColumn(int tag, int dropTag, boolean direction) { final int from = mAdapter.indexOf(tag); final int to; if(direction) { Log.i(TAG, "moveColumn: Dropping to the left"); to = Math.max(0, mAdapter.indexOf(dropTag) - 1); } else { to = Math.min(mAdapter.getCount() - 1, mAdapter.indexOf(dropTag) + 1); } Log.i(TAG, "moveColumn: From " + from + ", to " + to); mAdapter.move(from, to); mAdapter.columns.add(to, mAdapter.columns.remove(from)); mColumnPager.setCurrentItem(to, true); mEditor.moveColumn(new Editor.ColumnMovementListener() { @Override public void columnMoved(int columnId) { } @Override public void columnMovementError(APIHandler.APIError error) { } }, tag, dropTag, to); } @OnClick(R.id.project_add_card) void addCard() { mMenu.close(true); final CardDialog dialog = new CardDialog(); final ArrayList<Integer> ids = new ArrayList<>(); for(int i = 0; i < mAdapter.getCount(); i++) { for(Card c : mAdapter.getExistingFragment(i).getCards()) { if(c.hasIssue()) ids.add(c.getIssue().getId()); } } final Bundle bundle = new Bundle(); bundle.putString(getString(R.string.intent_repo), mProject.getRepoPath()); bundle.putIntegerArrayList(getString(R.string.intent_int_arraylist), ids); dialog.setArguments(bundle); mAdapter.getCurrentFragment().showCardDialog(dialog); } void deleteCard(Card card, boolean showWarning) { final Editor.CardDeletionListener listener = new Editor.CardDeletionListener() { @Override public void cardDeleted(Card card) { mRefresher.setRefreshing(false); mAdapter.getCurrentFragment().removeCard(card); Snackbar.make(findViewById(R.id.project_coordinator), getString(R.string.text_note_deleted), Snackbar.LENGTH_LONG) .setAction(getString(R.string.action_undo), view -> mAdapter.getCurrentFragment().recreateCard(card)) .show(); } @Override public void cardDeletionError(APIHandler.APIError error) { } }; if(showWarning) { final Dialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.title_delete_card) .setMessage(R.string.text_delete_note_warning) .setNegativeButton(R.string.action_cancel, null) .setPositiveButton(R.string.action_ok, (dialogInterface, i) -> { mRefresher.setRefreshing(true); mEditor.deleteCard(listener, card); }).create(); dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; dialog.show(); } else { mRefresher.setRefreshing(true); mEditor.deleteCard(listener, card); } } private long lastPageChange; private void dragLeft() { if(mCurrentPosition > 0 && System.nanoTime() - lastPageChange > 5E8) { mColumnPager.setCurrentItem(mCurrentPosition - 1, true); lastPageChange = System.nanoTime(); } } private void dragRight() { if(mCurrentPosition < mAdapter.getCount() && System.nanoTime() - lastPageChange > 5E8) { mColumnPager.setCurrentItem(mCurrentPosition + 1, true); lastPageChange = System.nanoTime(); } } public void onToolbarBackPressed(View view) { onBackPressed(); } void notifyFragmentLoaded() { mLoadCount++; if(mLoadCount == mAdapter.getCount()) { mRefresher.setRefreshing(false); } } @Override public void onBackPressed() { if(mMenu.isOpened()) { mMenu.close(true); } else { /* This seems to fix the problem with RecyclerView view detaching Quick and dirty way of removing the views */ mColumnPager.setAdapter(new ColumnPagerAdapter(getSupportFragmentManager(), new ArrayList<>())); mMenu.hideMenuButton(true); super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_activity_search, menu); mSearchItem = menu.findItem(R.id.menu_action_search); if(mSearchItem != null) { mSearchView = (SearchView) mSearchItem.getActionView(); } if(mSearchView != null) { mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { Log.i(TAG, "onQueryTextSubmit: " + query); return false; } @Override public boolean onQueryTextChange(String newText) { Log.i(TAG, "onQueryTextChange: " + newText); return false; } }); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(ProjectActivity.this, SettingsActivity.class)); break; case R.id.menu_source: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(URL))); break; case R.id.menu_share: final Intent share = new Intent(); share.setAction(Intent.ACTION_SEND); share.putExtra(Intent.EXTRA_TEXT, "https://github.com/" + mProject.getRepoPath() + "/projects/" + Integer.toString(mProject.getNumber())); share.setType("text/plain"); startActivity(share); break; case R.id.menu_save_to_homescreen: final ShortcutDialog dialog = new ShortcutDialog(); final Bundle args = new Bundle(); args.putInt(getString(R.string.intent_title_res), R.string.title_save_project_shortcut); args.putString(getString(R.string.intent_name), mProject.getName()); dialog.setArguments(args); dialog.setListener((name, iconFlag) -> { final Intent i = new Intent(getApplicationContext(), ProjectActivity.class); i.putExtra(getString(R.string.intent_repo), mProject.getRepoPath()); i.putExtra(getString(R.string.intent_project_number), mProject.getNumber()); final Intent add = new Intent(); add.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i); add.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); add.putExtra("duplicate", false); add.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher)); add.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); getApplicationContext().sendBroadcast(add); }); dialog.show(getSupportFragmentManager(), TAG); break; case R.id.menu_action_search: if(mAdapter.getCount() > 0) { final SearchView.SearchAutoComplete searchSrc = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text); searchSrc.setThreshold(1); final ProjectSearchAdapter searchAdapter = new ProjectSearchAdapter(this, mAdapter.getAllCards()); searchSrc.setAdapter(searchAdapter); searchSrc.setOnItemClickListener((adapterView, view, i, l) -> { mSearchItem.collapseActionView(); mAdapter.moveTo(searchAdapter.getItem(i)); }); } } return true; } @Override protected void onResume() { super.onResume(); mAnalytics.setAnalyticsCollectionEnabled(SettingsActivity.Preferences.getPreferences(this).areAnalyticsEnabled()); } class NavigationDragListener implements View.OnDragListener { @Override public boolean onDrag(View view, DragEvent event) { if(event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { final DisplayMetrics metrics = getResources().getDisplayMetrics(); if(event.getX() / metrics.widthPixels > 0.85f) { dragRight(); } else if(event.getX() / metrics.widthPixels < 0.15f) { dragLeft(); } } switch(event.getAction()) { case DragEvent.ACTION_DRAG_EXITED: Log.i(TAG, "onDrag: Exited"); break; case DragEvent.ACTION_DRAG_ENDED: Log.i(TAG, "onDrag: Ended"); break; case DragEvent.ACTION_DROP: Log.i(TAG, "onDrag: Dropped"); break; } return true; } } private class ColumnPagerAdapter extends ArrayPagerAdapter<ColumnFragment> { private ArrayList<Column> columns = new ArrayList<>(); ColumnPagerAdapter(FragmentManager manager, List<PageDescriptor> descriptors) { super(manager, descriptors); } int indexOf(int id) { for(int i = 0; i < columns.size(); i++) { if(columns.get(i).getId() == id) return i; } return -1; } ArrayList<Card> getAllCards() { final ArrayList<Card> cards = new ArrayList<>(); for(int i = 0; i < getCount(); i++) { cards.addAll(getExistingFragment(i).getCards()); } return cards; } void moveTo(Card card) { for(int i = 0; i < getCount(); i++) { if(getExistingFragment(i).attemptMoveTo(card)) { mColumnPager.setCurrentItem(i, true); break; } } } @Override protected ColumnFragment createFragment(PageDescriptor pageDescriptor) { return ColumnFragment.getInstance(((ColumnPageDescriptor) pageDescriptor).mColumn, mNavListener, mAccessLevel, columns.indexOf(((ColumnPageDescriptor) pageDescriptor).mColumn) == mCurrentPosition); } } private static class ColumnPageDescriptor implements PageDescriptor { private Column mColumn; ColumnPageDescriptor(Column column) { mColumn = column; } @Override public String getFragmentTag() { return Integer.toString(mColumn.getId()); } @Override public String getTitle() { return mColumn.getName(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mColumn, flags); } ColumnPageDescriptor(Parcel in) { this.mColumn = in.readParcelable(Column.class.getClassLoader()); } public static final Creator<ColumnPageDescriptor> CREATOR = new Creator<ColumnPageDescriptor>() { @Override public ColumnPageDescriptor createFromParcel(Parcel source) { return new ColumnPageDescriptor(source); } @Override public ColumnPageDescriptor[] newArray(int size) { return new ColumnPageDescriptor[size]; } }; } }
app/src/main/java/com/tpb/projects/project/ProjectActivity.java
/* * Copyright 2016 Theo Pearson-Bray * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tpb.projects.project; import android.app.Dialog; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.DragEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.commonsware.cwac.pager.PageDescriptor; import com.commonsware.cwac.pager.v4.ArrayPagerAdapter; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.google.firebase.analytics.FirebaseAnalytics; import com.tpb.projects.R; import com.tpb.projects.data.APIHandler; import com.tpb.projects.data.Editor; import com.tpb.projects.data.Loader; import com.tpb.projects.data.SettingsActivity; import com.tpb.projects.data.auth.GitHubSession; import com.tpb.projects.data.models.Card; import com.tpb.projects.data.models.Column; import com.tpb.projects.data.models.Issue; import com.tpb.projects.data.models.Project; import com.tpb.projects.data.models.Repository; import com.tpb.projects.dialogs.CardDialog; import com.tpb.projects.dialogs.NewIssueDialog; import com.tpb.projects.util.Analytics; import com.tpb.projects.util.ShortcutDialog; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by theo on 19/12/16. */ public class ProjectActivity extends AppCompatActivity implements Loader.ProjectLoader { private static final String TAG = ProjectActivity.class.getSimpleName(); private static final String URL = "https://github.com/tpb1908/AndroidProjectsClient/blob/master/app/src/main/java/com/tpb/projects/project/ProjectActivity.java"; private FirebaseAnalytics mAnalytics; @BindView(R.id.project_toolbar) Toolbar mToolbar; @BindView(R.id.project_name) TextView mName; @BindView(R.id.project_refresher) SwipeRefreshLayout mRefresher; @BindView(R.id.project_column_pager) ViewPager mColumnPager; @BindView(R.id.project_fab_menu) FloatingActionMenu mMenu; @BindView(R.id.project_add_card) FloatingActionButton mAddCard; @BindView(R.id.project_add_column) FloatingActionButton mAddColumn; @BindView(R.id.project_add_issue) FloatingActionButton mAddIssue; private SearchView mSearchView; private ColumnPagerAdapter mAdapter; private int mCurrentPosition = -1; private Loader mLoader; Project mProject; private Editor mEditor; private NavigationDragListener mNavListener; private Repository.AccessLevel mAccessLevel = Repository.AccessLevel.NONE; private int mLoadCount; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SettingsActivity.Preferences prefs = SettingsActivity.Preferences.getPreferences(this); setTheme(prefs.isDarkThemeEnabled() ? R.style.AppTheme_Dark : R.style.AppTheme); setContentView(R.layout.activity_project); ButterKnife.bind(this); mAnalytics = FirebaseAnalytics.getInstance(this); mAnalytics.setAnalyticsCollectionEnabled(prefs.areAnalyticsEnabled()); final Intent launchIntent = getIntent(); mLoader = new Loader(this); mEditor = new Editor(this); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); if(launchIntent.hasExtra(getString(R.string.parcel_project))) { projectLoaded(launchIntent.getParcelableExtra(getString(R.string.parcel_project))); mAccessLevel = (Repository.AccessLevel) launchIntent.getSerializableExtra(getString(R.string.intent_access_level)); if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { new Handler().postDelayed(() -> mMenu.showMenuButton(true), 400); } } else { final String repo = launchIntent.getStringExtra(getString(R.string.intent_repo)); final int number = launchIntent.getIntExtra(getString(R.string.intent_project_number), 1); //We have to load all of the projects to get the id that we want mLoader.loadProjects(new Loader.ProjectsLoader() { int projectLoadAttempts = 0; @Override public void projectsLoaded(Project[] projects) { for(Project p : projects) { if(number == p.getNumber()) { projectLoaded(p); checkAccess(p); return; } } Toast.makeText(ProjectActivity.this, R.string.error_project_not_found, Toast.LENGTH_LONG).show(); finish(); } @Override public void projectsLoadError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(projectLoadAttempts < 5) { projectLoadAttempts++; mLoader.loadProjects(this, repo); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } } }, repo); } getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); mAdapter = new ColumnPagerAdapter(getSupportFragmentManager(), new ArrayList<>()); mColumnPager.setAdapter(mAdapter); mColumnPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mCurrentPosition = position; Log.i(TAG, "onPageSelected: Page changed to " + position); if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { showFab(); } } @Override public void onPageScrollStateChanged(int state) { if(state == ViewPager.SCROLL_STATE_DRAGGING) { mRefresher.setEnabled(false); } else if(state == ViewPager.SCROLL_STATE_IDLE) { mRefresher.setEnabled(true); } } }); mRefresher.setRefreshing(true); mMenu.hideMenuButton(false); //Hide the button so that we can show it later mMenu.setClosedOnTouchOutside(true); mRefresher.setOnRefreshListener(() -> mLoader.loadProject(ProjectActivity.this, mProject.getId())); mNavListener = new NavigationDragListener(); mRefresher.setOnDragListener(mNavListener); } private void checkAccess(Project project) { mLoader.checkAccessToRepository(new Loader.AccessCheckListener() { int accessCheckAttempts = 0; @Override public void accessCheckComplete(Repository.AccessLevel accessLevel) { Log.i(TAG, "accessCheckComplete: " + accessLevel); mAccessLevel = accessLevel; if(mAccessLevel == Repository.AccessLevel.ADMIN || mAccessLevel == Repository.AccessLevel.WRITE) { mMenu.showMenuButton(true); } else { mMenu.hideMenuButton(false); } for(int i = 0; i < mAdapter.getCount(); i++) { if(mAdapter.getExistingFragment(i) != null) { mAdapter.getExistingFragment(i).setAccessLevel(mAccessLevel); } } } @Override public void accessCheckError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(accessCheckAttempts < 5) { accessCheckAttempts++; mLoader.checkAccessToRepository(this, GitHubSession.getSession(ProjectActivity.this).getUserLogin(), project.getRepoPath()); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } } }, GitHubSession.getSession(this).getUserLogin(), project.getRepoPath()); } void showFab() { mMenu.showMenuButton(true); } void hideFab() { mMenu.hideMenuButton(true); } @Override public void projectLoaded(Project project) { Log.i(TAG, "projectLoaded: Owner url " + project.getOwnerUrl()); mProject = project; mLoader.loadLabels(null, mProject.getRepoPath()); mName.setText(project.getName()); final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_PROJECT_LOADED, bundle); mLoadCount = 0; mLoader.loadColumns(new Loader.ColumnsLoader() { @Override public void columnsLoaded(Column[] columns) { if(columns.length > 0) { mAddCard.setVisibility(View.INVISIBLE); mAddIssue.setVisibility(View.INVISIBLE); int id = 0; if(mCurrentPosition != -1) { id = mAdapter.getCurrentFragment().mColumn.getId(); } mCurrentPosition = 0; mAdapter.columns = new ArrayList<>(Arrays.asList(columns)); if(mAdapter.getCount() != 0) { for(int i = mAdapter.getCount() - 1; i >= 0; i--) mAdapter.remove(i); } for(int i = 0; i < columns.length; i++) { mAdapter.add(new ColumnPageDescriptor(columns[i])); if(columns[i].getId() == id) { mCurrentPosition = i; } } mColumnPager.setOffscreenPageLimit(mAdapter.getCount()); if(mCurrentPosition >= mAdapter.getCount()) { mCurrentPosition = mAdapter.getCount() - 1; //If the end column has been deleted } mColumnPager.setCurrentItem(mCurrentPosition, true); mColumnPager.postDelayed(() -> mColumnPager.setVisibility(View.VISIBLE), 300); } else { mAddCard.setVisibility(View.GONE); mAddIssue.setVisibility(View.GONE); } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_SUCCESS); bundle.putInt(Analytics.KEY_COLUMN_COUNT, columns.length + 1); mAnalytics.logEvent(Analytics.TAG_COLUMNS_LOADED, bundle); } @Override public void columnsLoadError(APIHandler.APIError error) { final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMNS_LOADED, bundle); } }, project.getId()); } @Override public void projectLoadError(APIHandler.APIError error) { final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_LOAD_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_PROJECT_LOADED, bundle); } void loadIssue(Loader.IssueLoader loader, int issueId, Column column) { mLoader.loadIssue(loader, mProject.getRepoPath(), issueId, mAdapter.indexOf(column.getId()) == mCurrentPosition); } @OnClick(R.id.project_add_column) void addColumn() { mMenu.close(true); final AlertDialog dialog = new AlertDialog.Builder(this) .setView(R.layout.dialog_new_column) .setTitle(R.string.title_new_column) .setNegativeButton(R.string.action_cancel, null) .create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.action_ok), (di, w) -> { }); //Null is ambiguous so we pass empty lambda dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> { final EditText editor = (EditText) dialog.findViewById(R.id.project_new_column); final String text = editor.getText().toString(); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm.isActive()) { imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } if(!text.isEmpty()) { mRefresher.setRefreshing(true); mEditor.addColumn(new Editor.ColumnAdditionListener() { int addColumnAttempts = 0; @Override public void columnAdded(Column column) { mAddCard.setVisibility(View.INVISIBLE); mAddIssue.setVisibility(View.INVISIBLE); mAdapter.columns.add(column); mAdapter.add(new ColumnPageDescriptor(column)); mColumnPager.setCurrentItem(mAdapter.getCount(), true); mRefresher.setRefreshing(false); final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_COLUMN_ADD, bundle); } @Override public void columnAdditionError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(addColumnAttempts < 5) { addColumnAttempts++; mEditor.addColumn(this, mProject.getId(), text); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMN_ADD, bundle); } }, mProject.getId(), text); dialog.dismiss(); } else { Toast.makeText(this, R.string.error_no_column_title, Toast.LENGTH_SHORT).show(); } }); dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v -> { final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(imm.isActive()) { imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } dialog.dismiss(); }); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } @OnClick(R.id.project_add_issue) void addIssue() { mMenu.close(true); final NewIssueDialog newDialog = new NewIssueDialog(); newDialog.setListener(new NewIssueDialog.IssueDialogListener() { @Override public void issueCreated(Issue issue) { mAdapter.getCurrentFragment().createIssueCard(issue); } @Override public void issueCreationCancelled() { } }); final Bundle c = new Bundle(); c.putString(getString(R.string.intent_repo), mProject.getRepoPath()); newDialog.setArguments(c); newDialog.show(getSupportFragmentManager(), TAG); } void deleteColumn(Column column) { new AlertDialog.Builder(this, R.style.DialogAnimation) .setTitle(R.string.title_delete_column) .setMessage(R.string.text_delete_column_warning) .setNegativeButton(R.string.action_cancel, null) .setPositiveButton(R.string.action_ok, (dialogInterface, i) -> { mRefresher.setRefreshing(true); mEditor.deleteColumn(new Editor.ColumnDeletionListener() { int deleteColumnAttempts = 0; @Override public void columnDeleted() { mAdapter.remove(mCurrentPosition); mAdapter.columns.remove(mCurrentPosition); mRefresher.setRefreshing(false); if(mAdapter.columns.size() == 0) { mAddCard.setVisibility(View.GONE); mAddIssue.setVisibility(View.GONE); } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_SUCCESS); mAnalytics.logEvent(Analytics.TAG_COLUMN_DELETE, bundle); } @Override public void columnDeletionError(APIHandler.APIError error) { if(error == APIHandler.APIError.NO_CONNECTION) { mRefresher.setRefreshing(false); Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); } else { if(deleteColumnAttempts < 5) { deleteColumnAttempts++; mEditor.deleteColumn(this, column.getId()); } else { Toast.makeText(ProjectActivity.this, error.resId, Toast.LENGTH_SHORT).show(); mRefresher.setRefreshing(false); } } final Bundle bundle = new Bundle(); bundle.putString(Analytics.KEY_EDIT_STATUS, Analytics.VALUE_FAILURE); mAnalytics.logEvent(Analytics.TAG_COLUMN_DELETE, bundle); } }, column.getId()); }).show(); } /** * @param tag id of the column being moved * @param dropTag id of the column being dropped onto * @param direction side of the drop column to drop to true=left false=right */ void moveColumn(int tag, int dropTag, boolean direction) { final int from = mAdapter.indexOf(tag); final int to; if(direction) { Log.i(TAG, "moveColumn: Dropping to the left"); to = Math.max(0, mAdapter.indexOf(dropTag) - 1); } else { to = Math.min(mAdapter.getCount() - 1, mAdapter.indexOf(dropTag) + 1); } Log.i(TAG, "moveColumn: From " + from + ", to " + to); mAdapter.move(from, to); mAdapter.columns.add(to, mAdapter.columns.remove(from)); mColumnPager.setCurrentItem(to, true); mEditor.moveColumn(new Editor.ColumnMovementListener() { @Override public void columnMoved(int columnId) { } @Override public void columnMovementError(APIHandler.APIError error) { } }, tag, dropTag, to); } @OnClick(R.id.project_add_card) void addCard() { mMenu.close(true); final CardDialog dialog = new CardDialog(); final ArrayList<Integer> ids = new ArrayList<>(); for(int i = 0; i < mAdapter.getCount(); i++) { for(Card c : mAdapter.getExistingFragment(i).getCards()) { if(c.hasIssue()) ids.add(c.getIssue().getId()); } } final Bundle bundle = new Bundle(); bundle.putString(getString(R.string.intent_repo), mProject.getRepoPath()); bundle.putIntegerArrayList(getString(R.string.intent_int_arraylist), ids); dialog.setArguments(bundle); mAdapter.getCurrentFragment().showCardDialog(dialog); } void deleteCard(Card card, boolean showWarning) { final Editor.CardDeletionListener listener = new Editor.CardDeletionListener() { @Override public void cardDeleted(Card card) { mRefresher.setRefreshing(false); mAdapter.getCurrentFragment().removeCard(card); Snackbar.make(findViewById(R.id.project_coordinator), getString(R.string.text_note_deleted), Snackbar.LENGTH_LONG) .setAction(getString(R.string.action_undo), view -> mAdapter.getCurrentFragment().recreateCard(card)) .show(); } @Override public void cardDeletionError(APIHandler.APIError error) { } }; if(showWarning) { final Dialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.title_delete_card) .setMessage(R.string.text_delete_note_warning) .setNegativeButton(R.string.action_cancel, null) .setPositiveButton(R.string.action_ok, (dialogInterface, i) -> { mRefresher.setRefreshing(true); mEditor.deleteCard(listener, card); }).create(); dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; dialog.show(); } else { mRefresher.setRefreshing(true); mEditor.deleteCard(listener, card); } } private long lastPageChange; private void dragLeft() { if(mCurrentPosition > 0 && System.nanoTime() - lastPageChange > 5E8) { mColumnPager.setCurrentItem(mCurrentPosition - 1, true); lastPageChange = System.nanoTime(); } } private void dragRight() { if(mCurrentPosition < mAdapter.getCount() && System.nanoTime() - lastPageChange > 5E8) { mColumnPager.setCurrentItem(mCurrentPosition + 1, true); lastPageChange = System.nanoTime(); } } public void onToolbarBackPressed(View view) { onBackPressed(); } void notifyFragmentLoaded() { mLoadCount++; if(mLoadCount == mAdapter.getCount()) { mRefresher.setRefreshing(false); } } @Override public void onBackPressed() { if(mMenu.isOpened()) { mMenu.close(true); } else { /* This seems to fix the problem with RecyclerView view detaching Quick and dirty way of removing the views */ mColumnPager.setAdapter(new ColumnPagerAdapter(getSupportFragmentManager(), new ArrayList<>())); mMenu.hideMenuButton(true); super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_activity_search, menu); final MenuItem searchItem = menu.findItem(R.id.menu_action_search); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); if(searchItem != null) { mSearchView = (SearchView) searchItem.getActionView(); } if(mSearchView != null) { mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { Log.i(TAG, "onQueryTextSubmit: " + query); return false; } @Override public boolean onQueryTextChange(String newText) { Log.i(TAG, "onQueryTextChange: " + newText); return false; } }); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(ProjectActivity.this, SettingsActivity.class)); break; case R.id.menu_source: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(URL))); break; case R.id.menu_share: final Intent share = new Intent(); share.setAction(Intent.ACTION_SEND); share.putExtra(Intent.EXTRA_TEXT, "https://github.com/" + mProject.getRepoPath() + "/projects/" + Integer.toString(mProject.getNumber())); share.setType("text/plain"); startActivity(share); break; case R.id.menu_save_to_homescreen: final ShortcutDialog dialog = new ShortcutDialog(); final Bundle args = new Bundle(); args.putInt(getString(R.string.intent_title_res), R.string.title_save_project_shortcut); args.putString(getString(R.string.intent_name), mProject.getName()); dialog.setArguments(args); dialog.setListener((name, iconFlag) -> { final Intent i = new Intent(getApplicationContext(), ProjectActivity.class); i.putExtra(getString(R.string.intent_repo), mProject.getRepoPath()); i.putExtra(getString(R.string.intent_project_number), mProject.getNumber()); final Intent add = new Intent(); add.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i); add.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); add.putExtra("duplicate", false); add.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher)); add.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); getApplicationContext().sendBroadcast(add); }); dialog.show(getSupportFragmentManager(), TAG); break; case R.id.menu_action_search: if(mAdapter.getCount() > 0) { final SearchView.SearchAutoComplete searchSrc = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text); searchSrc.setThreshold(1); final ProjectSearchAdapter searchAdapter = new ProjectSearchAdapter(this, mAdapter.getAllCards()); searchSrc.setAdapter(searchAdapter); searchSrc.setOnItemClickListener((adapterView, view, i, l) -> mAdapter.moveTo(searchAdapter.getItem(i))); } } return true; } @Override protected void onResume() { super.onResume(); mAnalytics.setAnalyticsCollectionEnabled(SettingsActivity.Preferences.getPreferences(this).areAnalyticsEnabled()); } class NavigationDragListener implements View.OnDragListener { @Override public boolean onDrag(View view, DragEvent event) { if(event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { final DisplayMetrics metrics = getResources().getDisplayMetrics(); if(event.getX() / metrics.widthPixels > 0.85f) { dragRight(); } else if(event.getX() / metrics.widthPixels < 0.15f) { dragLeft(); } } switch(event.getAction()) { case DragEvent.ACTION_DRAG_EXITED: Log.i(TAG, "onDrag: Exited"); break; case DragEvent.ACTION_DRAG_ENDED: Log.i(TAG, "onDrag: Ended"); break; case DragEvent.ACTION_DROP: Log.i(TAG, "onDrag: Dropped"); break; } return true; } } private class ColumnPagerAdapter extends ArrayPagerAdapter<ColumnFragment> { private ArrayList<Column> columns = new ArrayList<>(); ColumnPagerAdapter(FragmentManager manager, List<PageDescriptor> descriptors) { super(manager, descriptors); } int indexOf(int id) { for(int i = 0; i < columns.size(); i++) { if(columns.get(i).getId() == id) return i; } return -1; } ArrayList<Card> getAllCards() { final ArrayList<Card> cards = new ArrayList<>(); for(int i = 0; i < getCount(); i++) { cards.addAll(getExistingFragment(i).getCards()); } return cards; } void moveTo(Card card) { for(int i = 0; i < getCount(); i++) { if(getExistingFragment(i).attemptMoveTo(card)) { mColumnPager.setCurrentItem(i, true); break; } } } @Override protected ColumnFragment createFragment(PageDescriptor pageDescriptor) { return ColumnFragment.getInstance(((ColumnPageDescriptor) pageDescriptor).mColumn, mNavListener, mAccessLevel, columns.indexOf(((ColumnPageDescriptor) pageDescriptor).mColumn) == mCurrentPosition); } } private static class ColumnPageDescriptor implements PageDescriptor { private Column mColumn; ColumnPageDescriptor(Column column) { mColumn = column; } @Override public String getFragmentTag() { return Integer.toString(mColumn.getId()); } @Override public String getTitle() { return mColumn.getName(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mColumn, flags); } ColumnPageDescriptor(Parcel in) { this.mColumn = in.readParcelable(Column.class.getClassLoader()); } public static final Creator<ColumnPageDescriptor> CREATOR = new Creator<ColumnPageDescriptor>() { @Override public ColumnPageDescriptor createFromParcel(Parcel source) { return new ColumnPageDescriptor(source); } @Override public ColumnPageDescriptor[] newArray(int size) { return new ColumnPageDescriptor[size]; } }; } }
Closed ProjectActivity search on suggestion selected.
app/src/main/java/com/tpb/projects/project/ProjectActivity.java
Closed ProjectActivity search on suggestion selected.
Java
apache-2.0
049d46f9977f59dc2df7c92531f57c68e9d98f17
0
ador/ProteinPatternSearch
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(); } } }
java/src/main/java/protka/main/CreateArffFromFragmentStats.java
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" }; public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: CreateArffFromFragmentStats prop.properties"); return; } PropertyHandler propHandler = new PropertyHandler(requiredProps); FileInputStream is; FileOutputStream os; try { Properties properties = propHandler.readPropertiesFile(args[0]); if (propHandler.checkProps(properties)) { 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(); } } }
Fix: creating output result dir for clustering results
java/src/main/java/protka/main/CreateArffFromFragmentStats.java
Fix: creating output result dir for clustering results
Java
apache-2.0
4a6219bf57c0aaff8e7f5a81002570e3ea25eb0e
0
natzei/bitcoinj,bitcoinj/bitcoinj,bitcoinj/bitcoinj,natzei/bitcoinj
/* * Copyright 2014 The bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import com.google.common.base.Joiner; import org.bitcoinj.protocols.payments.PaymentSession; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.RFC4519Style; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.List; /** * X509Utils provides tools for working with X.509 certificates and keystores, as used in the BIP 70 payment protocol. * For more details on this, see {@link PaymentSession}, the article "Working with * the payment protocol" on the bitcoinj website, or the Bitcoin developer guide. */ public class X509Utils { /** * Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see * in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but * can also be the org (O) field, org+location+country if withLocation is set, or the email * address for S/MIME certificates. */ @Nullable public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException { X500Name name = new X500Name(certificate.getSubjectX500Principal().getName()); String commonName = null, org = null, location = null, country = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); String val = ((ASN1String) pair.getValue()).getString(); ASN1ObjectIdentifier type = pair.getType(); if (type.equals(RFC4519Style.cn)) commonName = val; else if (type.equals(RFC4519Style.o)) org = val; else if (type.equals(RFC4519Style.l)) location = val; else if (type.equals(RFC4519Style.c)) country = val; } String altName = null; try { final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) for (final List<?> subjectAlternativeName : subjectAlternativeNames) if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name altName = (String) subjectAlternativeName.get(1); } catch (CertificateParsingException e) { // swallow } if (org != null) { return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org; } else if (commonName != null) { return commonName; } else { return altName; } } /** Returns a key store loaded from the given stream. Just a convenience around the Java APIs. */ public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is) throws KeyStoreException { try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null); return keystore; } catch (IOException | GeneralSecurityException x) { throw new KeyStoreException(x); } finally { try { is.close(); } catch (IOException x) { // Ignored. } } } }
core/src/main/java/org/bitcoinj/crypto/X509Utils.java
/* * Copyright 2014 The bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import com.google.common.base.Joiner; import org.bitcoinj.protocols.payments.PaymentSession; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.RFC4519Style; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.List; /** * X509Utils provides tools for working with X.509 certificates and keystores, as used in the BIP 70 payment protocol. * For more details on this, see {@link PaymentSession}, the article "Working with * the payment protocol" on the bitcoinj website, or the Bitcoin developer guide. */ public class X509Utils { /** * Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see * in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but * can also be the org (O) field, org+location+country if withLocation is set, or the email * address for S/MIME certificates. */ @Nullable public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException { X500Name name = new X500Name(certificate.getSubjectX500Principal().getName()); String commonName = null, org = null, location = null, country = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); String val = ((ASN1String) pair.getValue()).getString(); ASN1ObjectIdentifier type = pair.getType(); if (type.equals(RFC4519Style.cn)) commonName = val; else if (type.equals(RFC4519Style.o)) org = val; else if (type.equals(RFC4519Style.l)) location = val; else if (type.equals(RFC4519Style.c)) country = val; } final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); String altName = null; if (subjectAlternativeNames != null) for (final List<?> subjectAlternativeName : subjectAlternativeNames) if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name altName = (String) subjectAlternativeName.get(1); if (org != null) { return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org; } else if (commonName != null) { return commonName; } else { return altName; } } /** Returns a key store loaded from the given stream. Just a convenience around the Java APIs. */ public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is) throws KeyStoreException { try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null); return keystore; } catch (IOException | GeneralSecurityException x) { throw new KeyStoreException(x); } finally { try { is.close(); } catch (IOException x) { // Ignored. } } } }
X509Utils: handle CertificateParsingException in getDisplayNameFromCertificate() if certificate has no SubjectAltName extension This fix makes the method compatible with JDK 18. Previously, it relied on the method returning `null` if the extension is not present.
core/src/main/java/org/bitcoinj/crypto/X509Utils.java
X509Utils: handle CertificateParsingException in getDisplayNameFromCertificate() if certificate has no SubjectAltName extension
Java
apache-2.0
395f96568cd2e668924d4ed0f61209f5de97b65b
0
lovecc0923/asmack,lizhangqu/asmack,lovecc0923/asmack,ZachGoldberg/asmack,Flowdalic/asmack,chuangWu/asmack,ZachGoldberg/asmack,chuangWu/asmack,tks-dp/asmack,Flowdalic/asmack,lizhangqu/asmack,tks-dp/asmack
package org.jivesoftware.smack; import java.util.logging.Logger; import org.jivesoftware.smack.util.DNSUtil; import org.jivesoftware.smack.util.dns.DNSJavaResolver; import org.xbill.DNS.ResolverConfig; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; public class SmackAndroid { private static final Logger LOGGER = Logger.getLogger(SmackAndroid.class.getName()); private static SmackAndroid sSmackAndroid = null; private BroadcastReceiver mConnectivityChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { LOGGER.fine("ConnectivityChange received, calling ResolverConfig.refresh()"); ResolverConfig.refresh(); } }; private static boolean receiverRegistered = false; private Context mCtx; private SmackAndroid(Context ctx) { mCtx = ctx; DNSUtil.setDNSResolver(DNSJavaResolver.getInstance()); } /** * Init Smack for Android. Make sure to call * SmackAndroid.onDestroy() in all the exit code paths of your * application. */ public static synchronized SmackAndroid init(Context ctx) { if (sSmackAndroid == null) { sSmackAndroid = new SmackAndroid(ctx); } sSmackAndroid.maybeRegisterReceiver(); return sSmackAndroid; } /** * Cleanup all components initialized by init(). Make sure to call * this method in all the exit code paths of your application. */ public synchronized void onDestroy() { LOGGER.fine("onDestroy: receiverRegistered=" + receiverRegistered); if (receiverRegistered) { mCtx.unregisterReceiver(mConnectivityChangedReceiver); receiverRegistered = false; } } private void maybeRegisterReceiver() { LOGGER.fine("maybeRegisterReceiver: receiverRegistered=" + receiverRegistered); if (!receiverRegistered) { mCtx.registerReceiver(mConnectivityChangedReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); receiverRegistered = true; } } }
static-src/custom/org/jivesoftware/smack/SmackAndroid.java
package org.jivesoftware.smack; import org.jivesoftware.smack.util.DNSUtil; import org.jivesoftware.smack.util.dns.DNSJavaResolver; import org.xbill.DNS.ResolverConfig; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; public class SmackAndroid { private static SmackAndroid sSmackAndroid = null; private BroadcastReceiver mConnectivityChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ResolverConfig.refresh(); } }; private static boolean receiverRegistered = false; private Context mCtx; private SmackAndroid(Context ctx) { mCtx = ctx; DNSUtil.setDNSResolver(DNSJavaResolver.getInstance()); } /** * Init Smack for Android. Make sure to call * SmackAndroid.onDestroy() in all the exit code paths of your * application. */ public static synchronized SmackAndroid init(Context ctx) { if (sSmackAndroid == null) { sSmackAndroid = new SmackAndroid(ctx); } sSmackAndroid.maybeRegisterReceiver(); return sSmackAndroid; } /** * Cleanup all components initialized by init(). Make sure to call * this method in all the exit code paths of your application. */ public synchronized void onDestroy() { if (receiverRegistered) { mCtx.unregisterReceiver(mConnectivityChangedReceiver); receiverRegistered = false; } } private void maybeRegisterReceiver() { if (!receiverRegistered) { mCtx.registerReceiver(mConnectivityChangedReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); receiverRegistered = true; } } }
Add JUL to SmackAndroid
static-src/custom/org/jivesoftware/smack/SmackAndroid.java
Add JUL to SmackAndroid
Java
apache-2.0
e379e78e6deae302afd9078f0c6432837f1c6765
0
vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/vector-android
/* * Copyright 2014 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import org.matrix.androidsdk.MXSession; import im.vector.Matrix; import im.vector.R; /** * */ public class PillView extends LinearLayout { private static final String LOG_TAG = PillView.class.getSimpleName(); private TextView mTextView; private View mPillLayout; /** * constructors **/ public PillView(Context context) { super(context); initView(); } public PillView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public PillView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } /** * Common initialisation method. */ private void initView() { View.inflate(getContext(), R.layout.pill_view, this); mTextView = findViewById(R.id.pill_text_view); mPillLayout = findViewById(R.id.pill_layout); } /** * Tells if a pill can be displayed for this url. * * @param url the url * @return true if a pill can be made. */ public static boolean isPillable(String url) { boolean isSupported = (null != url) && url.startsWith("https://matrix.to/#/"); if (isSupported) { String linkedItem = url.substring("https://matrix.to/#/".length()); isSupported = MXSession.isRoomAlias(linkedItem) || MXSession.isUserId(linkedItem); } return isSupported; } /** * Update the pills text. * * @param text the pills * @param url the URL */ public void setText(CharSequence text, String url) { mTextView.setText(text.toString()); TypedArray a = getContext().getTheme().obtainStyledAttributes(new int[]{MXSession.isRoomAlias(text.toString()) ? R.attr.pill_background_room_alias : R.attr.pill_background_user_id}); int attributeResourceId = a.getResourceId(0, 0); a.recycle(); mPillLayout.setBackground(ContextCompat.getDrawable(getContext(), attributeResourceId)); a = getContext().getTheme().obtainStyledAttributes(new int[]{MXSession.isRoomAlias(text.toString()) ? R.attr.pill_text_color_room_alias : R.attr.pill_text_color_user_id}); attributeResourceId = a.getResourceId(0, 0); a.recycle(); mTextView.setTextColor(ContextCompat.getColor(getContext(), attributeResourceId)); } /** * Set the highlight status * * @param isHighlighted */ public void setHighlighted(boolean isHighlighted) { if (isHighlighted) { mPillLayout.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.pill_background_bing)); mTextView.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); } } /** * @return a snapshot of the view */ public Drawable getDrawable() { try { if (null == getDrawingCache()) { setDrawingCacheEnabled(true); measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); buildDrawingCache(true); } if (null != getDrawingCache()) { Bitmap bitmap = Bitmap.createBitmap(getDrawingCache()); return new BitmapDrawable(getContext().getResources(), bitmap); } } catch (Exception e) { Log.e(LOG_TAG, "## getDrawable() : failed " + e.getMessage()); } return null; } }
vector/src/main/java/im/vector/view/PillView.java
/* * Copyright 2014 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import org.matrix.androidsdk.MXSession; import im.vector.R; /** * */ public class PillView extends LinearLayout { private static final String LOG_TAG = PillView.class.getSimpleName(); private TextView mTextView; private View mPillLayout; /** * constructors **/ public PillView(Context context) { super(context); initView(); } public PillView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public PillView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } /** * Common initialisation method. */ private void initView() { View.inflate(getContext(), R.layout.pill_view, this); mTextView = findViewById(R.id.pill_text_view); mPillLayout = findViewById(R.id.pill_layout); } /** * Tells if a pill can be displayed for this url. * * @param url the url * @return true if a pill can be made. */ public static boolean isPillable(String url) { return (null != url) && url.startsWith("https://matrix.to"); } /** * Update the pills text. * * @param text the pills * @param url the URL */ public void setText(CharSequence text, String url) { mTextView.setText(text.toString()); TypedArray a = getContext().getTheme().obtainStyledAttributes(new int[]{MXSession.isRoomAlias(text.toString()) ? R.attr.pill_background_room_alias : R.attr.pill_background_user_id}); int attributeResourceId = a.getResourceId(0, 0); a.recycle(); mPillLayout.setBackground(ContextCompat.getDrawable(getContext(), attributeResourceId)); a = getContext().getTheme().obtainStyledAttributes(new int[]{MXSession.isRoomAlias(text.toString()) ? R.attr.pill_text_color_room_alias : R.attr.pill_text_color_user_id}); attributeResourceId = a.getResourceId(0, 0); a.recycle(); mTextView.setTextColor(ContextCompat.getColor(getContext(), attributeResourceId)); } /** * Set the highlight status * * @param isHighlighted */ public void setHighlighted(boolean isHighlighted) { if (isHighlighted) { mPillLayout.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.pill_background_bing)); mTextView.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); } } /** * @return a snapshot of the view */ public Drawable getDrawable() { try { if (null == getDrawingCache()) { setDrawingCacheEnabled(true); measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); buildDrawingCache(true); } if (null != getDrawingCache()) { Bitmap bitmap = Bitmap.createBitmap(getDrawingCache()); return new BitmapDrawable(getContext().getResources(), bitmap); } } catch (Exception e) { Log.e(LOG_TAG, "## getDrawable() : failed " + e.getMessage()); } return null; } }
Fix some unexpected pills
vector/src/main/java/im/vector/view/PillView.java
Fix some unexpected pills
Java
apache-2.0
434801f6ebd353702b8c96cd7c228adc335c3309
0
stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.auth; import alpine.model.LdapUser; import alpine.model.ManagedUser; import alpine.model.UserPrincipal; import alpine.persistence.AlpineQueryManager; /** * Resolves a UserPrincipal based on the pre-configured resolution order. * * @author Steve Springett * @since 1.0.0 */ public class UserPrincipalResolver { private String username; private UserPrincipal principal; private boolean initialized; public UserPrincipalResolver(String username) { this.username = username; } /** * Resolves a UserPrincipal. Default order resolution is to first match * on ManagedUser then on LdapUser. This may be configurable in a future * release. * @return a UserPrincipal if found, null if not found * @since 1.0.0 */ public UserPrincipal resolve() { initialized = true; try (AlpineQueryManager qm = new AlpineQueryManager()) { UserPrincipal principal = qm.getManagedUser(username); if (principal != null) { this.principal = principal; return principal; } return this.principal = qm.getLdapUser(username); } } /** * Returns whether or not the resolved UserPrincipal is an LdapUser or not. * @return true if LdapUser, false if not * @since 1.0.0 */ public boolean isLdapUser() { if (!initialized) { resolve(); } return principal != null && principal instanceof LdapUser; } /** * Returns whether or not the resolved UserPrincipal is a ManagedUser or not. * @return true if ManagedUser, false if not * @since 1.0.0 */ public boolean isManagedUser() { if (!initialized) { resolve(); } return principal != null && principal instanceof ManagedUser; } }
alpine/src/main/java/alpine/auth/UserPrincipalResolver.java
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.auth; import alpine.model.LdapUser; import alpine.model.ManagedUser; import alpine.model.UserPrincipal; import alpine.persistence.AlpineQueryManager; /** * Resolves a UserPrincipal based on the pre-configured resolution order. * * @author Steve Springett * @since 1.0.0 */ public class UserPrincipalResolver { private String username; private UserPrincipal principal; public UserPrincipalResolver(String username) { this.username = username; } /** * Resolves a UserPrincipal. Default order resolution is to first match * on ManagedUser then on LdapUser. This may be configurable in a future * release. * @return a UserPrincipal if found, null if not found * @since 1.0.0 */ public UserPrincipal resolve() { try (AlpineQueryManager qm = new AlpineQueryManager()) { UserPrincipal principal = qm.getManagedUser(username); if (principal != null) { this.principal = principal; return principal; } return this.principal = qm.getLdapUser(username); } } /** * Returns whether or not the resolved UserPrincipal is an LdapUser or not. * Requires that {@link #resolve()} is called first. * @return true if LdapUser, false if not * @since 1.0.0 */ public boolean isLdapUser() { return principal != null && principal instanceof LdapUser; } /** * Returns whether or not the resolved UserPrincipal is a ManagedUser or not. * Requires that {@link #resolve()} is called first. * @return true if ManagedUser, false if not * @since 1.0.0 */ public boolean isManagedUser() { return principal != null && principal instanceof ManagedUser; } }
Added class init
alpine/src/main/java/alpine/auth/UserPrincipalResolver.java
Added class init
Java
apache-2.0
643bbda787f6f4d5a94ec0346f86e1d64ac0a6e0
0
oktadeveloper/okta-aws-cli-assume-role,oktadeveloper/okta-aws-cli-assume-role,oktadeveloper/okta-aws-cli-assume-role
package com.okta.tools.saml; import com.okta.tools.authentication.BrowserAuthentication; import com.okta.tools.OktaAwsCliEnvironment; import com.okta.tools.authentication.OktaAuthentication; import com.okta.tools.helpers.CookieHelper; import org.apache.http.HttpStatus; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class OktaSaml { private final OktaAwsCliEnvironment environment; private final CookieHelper cookieHelper; public OktaSaml(OktaAwsCliEnvironment environment, CookieHelper cookieHelper) { this.environment = environment; this.cookieHelper = cookieHelper; } public String getSamlResponse() throws IOException { OktaAuthentication authentication = new OktaAuthentication(environment); if (reuseSession()) { return getSamlResponseForAwsRefresh(); } else if (environment.browserAuth) { try { return BrowserAuthentication.login(environment); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { String oktaSessionToken = authentication.getOktaSessionToken(); return getSamlResponseForAws(oktaSessionToken); } } private String getSamlResponseForAws(String oktaSessionToken) throws IOException { Document document = launchOktaAwsAppWithSessionToken(environment.oktaAwsAppUrl, oktaSessionToken); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsRefresh() throws IOException { Document document = launchOktaAwsApp(environment.oktaAwsAppUrl); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsFromDocument(Document document) { Elements samlResponseInputElement = document.select("form input[name=SAMLResponse]"); if (samlResponseInputElement.isEmpty()) { if (isPasswordAuthenticationChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for re-authentication'. \nPlease contact your administrator."); } else if (isPromptForFactorChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for factor'. \nPlease contact your administrator."); } else { Elements errorContent = document.getElementsByClass("error-content"); Elements errorHeadline = errorContent.select("h1"); if (errorHeadline.hasText()) { throw new RuntimeException(errorHeadline.text()); } else { throw new RuntimeException("You do not have access to AWS through Okta. \nPlease contact your administrator."); } } } return samlResponseInputElement.attr("value"); } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed if Okta significantly changes the app-level re-auth page private boolean isPasswordAuthenticationChallenge(Document document) { return document.getElementById("password-verification-challenge") != null; } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed if Okta significantly changes the app-level MFA page private boolean isPromptForFactorChallenge(Document document) { return document.getElementById("okta-sign-in") != null; } private Document launchOktaAwsAppWithSessionToken(String appUrl, String oktaSessionToken) throws IOException { return launchOktaAwsApp(appUrl + "?onetimetoken=" + oktaSessionToken); } private Document launchOktaAwsApp(String appUrl) throws IOException { HttpGet httpget = new HttpGet(appUrl); CookieStore cookieStore = cookieHelper.loadCookies(); try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).useSystemProperties().build(); CloseableHttpResponse oktaAwsAppResponse = httpClient.execute(httpget)) { if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 500) { throw new RuntimeException("Server error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } else if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException("Client error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } cookieHelper.storeCookies(cookieStore); return Jsoup.parse( oktaAwsAppResponse.getEntity().getContent(), StandardCharsets.UTF_8.name(), appUrl ); } } private boolean reuseSession() throws JSONException, IOException { CookieStore cookieStore = cookieHelper.loadCookies(); Optional<String> sidCookie = cookieStore.getCookies().stream().filter(cookie -> "sid".equals(cookie.getName())).findFirst().map(Cookie::getValue); if (!sidCookie.isPresent()) { return false; } HttpPost httpPost = new HttpPost("https://" + environment.oktaOrg + "/api/v1/sessions/me/lifecycle/refresh"); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Cookie", "sid=" + sidCookie.get()); try (CloseableHttpClient httpClient = HttpClients.createSystem()) { CloseableHttpResponse authnResponse = httpClient.execute(httpPost); return authnResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } } }
src/main/java/com/okta/tools/saml/OktaSaml.java
package com.okta.tools.saml; import com.okta.tools.authentication.BrowserAuthentication; import com.okta.tools.OktaAwsCliEnvironment; import com.okta.tools.authentication.OktaAuthentication; import com.okta.tools.helpers.CookieHelper; import org.apache.http.HttpStatus; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class OktaSaml { private final OktaAwsCliEnvironment environment; private final CookieHelper cookieHelper; public OktaSaml(OktaAwsCliEnvironment environment, CookieHelper cookieHelper) { this.environment = environment; this.cookieHelper = cookieHelper; } public String getSamlResponse() throws IOException { OktaAuthentication authentication = new OktaAuthentication(environment); if (reuseSession()) { return getSamlResponseForAwsRefresh(); } else if (environment.browserAuth) { try { return BrowserAuthentication.login(environment); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { String oktaSessionToken = authentication.getOktaSessionToken(); return getSamlResponseForAws(oktaSessionToken); } } private String getSamlResponseForAws(String oktaSessionToken) throws IOException { Document document = launchOktaAwsAppWithSessionToken(environment.oktaAwsAppUrl, oktaSessionToken); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsRefresh() throws IOException { Document document = launchOktaAwsApp(environment.oktaAwsAppUrl); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsFromDocument(Document document) { Elements samlResponseInputElement = document.select("form input[name=SAMLResponse]"); if (samlResponseInputElement.isEmpty()) { if (isPasswordAuthenticationChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for re-authentication'. \nPlease contact your administrator."); } else if (isPromptForFactorChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for factor'. \nPlease contact your administrator."); } else { Elements errorContent = document.getElementsByClass("error-content"); Elements errorHeadline = errorContent.select("h1"); if (errorHeadline.hasText()) { throw new RuntimeException(errorHeadline.text()); } else { throw new RuntimeException("You do not have access to AWS through Okta. \nPlease contact your administrator."); } } } return samlResponseInputElement.attr("value"); } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed Okta significantly changes the app-level re-auth page private boolean isPasswordAuthenticationChallenge(Document document) { return document.getElementById("password-verification-challenge") != null; } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed if Okta significantly changes the app-level MFA page private boolean isPromptForFactorChallenge(Document document) { return document.getElementById("okta-sign-in") != null; } private Document launchOktaAwsAppWithSessionToken(String appUrl, String oktaSessionToken) throws IOException { return launchOktaAwsApp(appUrl + "?onetimetoken=" + oktaSessionToken); } private Document launchOktaAwsApp(String appUrl) throws IOException { HttpGet httpget = new HttpGet(appUrl); CookieStore cookieStore = cookieHelper.loadCookies(); try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).useSystemProperties().build(); CloseableHttpResponse oktaAwsAppResponse = httpClient.execute(httpget)) { if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 500) { throw new RuntimeException("Server error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } else if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException("Client error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } cookieHelper.storeCookies(cookieStore); return Jsoup.parse( oktaAwsAppResponse.getEntity().getContent(), StandardCharsets.UTF_8.name(), appUrl ); } } private boolean reuseSession() throws JSONException, IOException { CookieStore cookieStore = cookieHelper.loadCookies(); Optional<String> sidCookie = cookieStore.getCookies().stream().filter(cookie -> "sid".equals(cookie.getName())).findFirst().map(Cookie::getValue); if (!sidCookie.isPresent()) { return false; } HttpPost httpPost = new HttpPost("https://" + environment.oktaOrg + "/api/v1/sessions/me/lifecycle/refresh"); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Cookie", "sid=" + sidCookie.get()); try (CloseableHttpClient httpClient = HttpClients.createSystem()) { CloseableHttpResponse authnResponse = httpClient.execute(httpPost); return authnResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } } }
:art: Address @randomsamples' code review
src/main/java/com/okta/tools/saml/OktaSaml.java
:art: Address @randomsamples' code review
Java
bsd-3-clause
6fd0bac450349a82a9d7e79de6a5109c76ba9530
0
owlcollab/owltools,fbastian/owltools,fbastian/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools,owlcollab/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools,fbastian/owltools,dhimmel/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools,dhimmel/owltools,dhimmel/owltools,owlcollab/owltools
package owltools.sim2; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.HypergeometricDistributionImpl; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics; import org.apache.commons.math3.stat.descriptive.StatisticalSummaryValues; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import org.semanticweb.owlapi.model.AxiomType; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.OWLReasoner; import owltools.mooncat.ontologymetadata.OntologySetMetadata; import owltools.sim2.SimpleOwlSim.Metric; import owltools.sim2.SimpleOwlSim.SimConfigurationProperty; import owltools.sim2.scores.ElementPairScores; public abstract class AbstractOwlSim implements OwlSim { private Logger LOG = Logger.getLogger(AbstractOwlSim.class); long totalTimeSimJ = 0; long totalCallsSimJ = 0; long totalTimeLCSIC = 0; long totalCallsLCSIC = 0; long totalTimeGIC = 0; long totalCallsGIC = 0; public SimStats simStats = new SimStats(); protected boolean isDisableLCSCache = false; protected OWLReasoner reasoner; protected Integer corpusSize; // number of individuals in domain protected boolean isLCSCacheFullyPopulated = false; protected boolean isNoLookupForLCSCache = false; private Properties simProperties; public SummaryStatistics overallStats; public StatsPerIndividual overallSummaryStatsPerIndividual = new StatsPerIndividual(); public HashMap<OWLClass,StatsPerIndividual> subgraphSummaryStatsPerIndividual = new HashMap<OWLClass,StatsPerIndividual>(); public SummaryStatistics simStatsPerIndividual = new SummaryStatistics(); public HashMap<String,SummaryStatistics> metricStatMeans = new HashMap<String,SummaryStatistics>(); public HashMap<String,SummaryStatistics> metricStatMaxes = new HashMap<String,SummaryStatistics>(); public HashMap<String,SummaryStatistics> metricStatMins = new HashMap<String,SummaryStatistics>(); @Override public OWLOntology getSourceOntology() { return getReasoner().getRootOntology(); } @Override public OWLReasoner getReasoner() { return reasoner; } public boolean isNoLookupForLCSCache() { return isNoLookupForLCSCache; } public void setNoLookupForLCSCache(boolean isNoLookupForLCSCache) { this.isNoLookupForLCSCache = isNoLookupForLCSCache; } public boolean isDisableLCSCache() { return isDisableLCSCache; } public void setDisableLCSCache(boolean isDisableLCSCache) { this.isDisableLCSCache = isDisableLCSCache; } @Override public Properties getSimProperties() { return simProperties; } @Override public void setSimProperties(Properties simProperties) { this.simProperties = simProperties; } public SimStats getSimStats() { return simStats; } public void setSimStats(SimStats simStats) { this.simStats = simStats; } protected long tdelta(long prev) { return System.currentTimeMillis() - prev; } /** * */ public void showTimings() { LOG.info("Timings:"); if (totalCallsSimJ > 0) { LOG.info("t(SimJ) ms = "+totalTimeSimJ + " / "+totalCallsSimJ + " = " + totalTimeSimJ / (double) totalCallsSimJ); } if (totalCallsLCSIC > 0) { LOG.info("t(LCS) ms = "+totalTimeLCSIC + " / "+totalCallsLCSIC + " = " + totalTimeLCSIC / (double) totalCallsLCSIC); } if (totalCallsGIC > 0) { LOG.info("t(GIC) ms = "+totalTimeGIC + " / "+totalCallsGIC + " = " + totalTimeGIC / (double) totalCallsGIC); } } public void showTimingsAndReset() { showTimings(); totalTimeSimJ = 0; totalCallsSimJ = 0; totalTimeLCSIC = 0; totalCallsLCSIC = 0; totalTimeGIC = 0; totalCallsGIC = 0; } @Override public void precomputeAttributeAllByAll() throws UnknownOWLClassException { LOG.info("precomputing attribute all x all"); long t = System.currentTimeMillis(); Set<OWLClass> cset = this.getAllAttributeClasses(); int n=0; for (OWLClass c : cset ) { n++; if (n % 100 == 0) { LOG.info("Cached LCS for "+n+" / "+cset.size()+" attributes"); } for (OWLClass d : cset ) { getLowestCommonSubsumerWithIC(c, d); } } LOG.info("Time precomputing attribute all x all = "+tdelta(t)); showTimingsAndReset(); } @Override public Set<Node<OWLClass>> getNamedSubsumers(OWLClass a) { return getReasoner().getSuperClasses(a, false).getNodes(); } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getCorpusSize() */ public int getCorpusSize() { if (corpusSize == null) { corpusSize = getAllElements().size(); } return corpusSize; } /* (non-Javadoc) * @see owltools.sim2.OwlSim#setCorpusSize(int) */ public void setCorpusSize(int size) { corpusSize = size; } // Note: inefficient for graphs with multiple parentage, due to // use of unmemoized recursion protected Set<List<OWLClass>> getPaths(OWLClass c, OWLClass d) { Set<List<OWLClass>> paths = new HashSet<List<OWLClass>>(); for (Node<OWLClass> node : getReasoner().getSuperClasses(c, true)) { if (node.contains(d)) { ArrayList<OWLClass> path = new ArrayList<OWLClass>(); path.add(d); path.add(c); paths.add(path); } else { OWLClass nc = node.getRepresentativeElement(); if (getReasoner().getSuperClasses(nc, false).getFlattened().contains(d)) { Set<List<OWLClass>> ppaths = getPaths(nc, d); for (List<OWLClass> ppath : ppaths) { ArrayList<OWLClass> path = new ArrayList<OWLClass>(ppath); path.add(c); paths.add(path); } } else { // veered off path } } } return paths; } protected int getMinimumDistanceToAncestor(OWLClass c, OWLClass d) { int minDist = 0; for (List<OWLClass> path : getPaths(c,d)) { int dist = path.size()-1; if (dist<minDist) minDist = dist; } return minDist; } protected int getMinimumDistanceViaMICA(OWLClass c, OWLClass d) throws UnknownOWLClassException { int minDist = 0; for (OWLClass a : getLowestCommonSubsumerWithIC(c, d).attributeClassSet) { int dist = getMinimumDistanceToAncestor(c,a) + getMinimumDistanceToAncestor(d,a); if (dist<minDist) minDist = dist; } return minDist; } public void getICSimDisj(OWLClass c, OWLClass d) { } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getLowestCommonSubsumerWithLinScore(org.semanticweb.owlapi.model.OWLClass, org.semanticweb.owlapi.model.OWLClass) * * Note this is uncached - subclasses may wish to impement caching */ public ScoreAttributeSetPair getLowestCommonSubsumerWithLinScore(OWLClass c, OWLClass d) throws UnknownOWLClassException { ScoreAttributeSetPair sap = this.getLowestCommonSubsumerWithIC(c, d); sap.score = (sap.score * 2) / (getInformationContentForAttribute(c) + getInformationContentForAttribute(d)); return sap; } // may be less performant than direct computation public int getAttributeJaccardSimilarityAsPercent(OWLClass a, OWLClass b) throws UnknownOWLClassException { return (int) (getAttributeJaccardSimilarity(a, b) * 100); } // may be less performant than direct computation public int getElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { return (int) (getElementJaccardSimilarity(i, j) * 100); } // may be less performant than direct computation public int getAsymmetricAttributeJaccardSimilarityAsPercent(OWLClass a, OWLClass b) throws UnknownOWLClassException { return (int) (getAsymmetricAttributeJaccardSimilarity(a, b) * 100); } // may be less performant than direct computation public int getAsymmetricElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { return (int) (getAsymmetricElementJaccardSimilarity(i, j) * 100); } @Override public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws Exception { ElementPairScores ijscores = new ElementPairScores(i,j); //populateSimilarityMatrix(i, j, s); ijscores.simGIC = getElementGraphInformationContentSimilarity(i, j); ijscores.simjScore = getElementJaccardSimilarity(i, j); ijscores.asymmetricSimjScore = getAsymmetricElementJaccardSimilarity(i, j); ijscores.inverseAsymmetricSimjScore = getAsymmetricElementJaccardSimilarity(j, i); // WAS this deprecated function: // ScoreAttributeSetPair bma = this.getSimilarityBestMatchAverage(i, j, Metric.IC_MCS, Direction.A_TO_B); ScoreAttributeSetPair bmaI = this.getSimilarityBestMatchAverageAsym(i, j, Metric.IC_MCS); ijscores.bmaAsymIC = bmaI.score; if (i!=j) { //we were skipping the inverse calculation before -- intentional? ScoreAttributeSetPair bmaJ = this.getSimilarityBestMatchAverageAsym(j, i, Metric.IC_MCS); ijscores.bmaInverseAsymIC = bmaJ.score; ijscores.bmaSymIC = (bmaI.score + bmaJ.score) / 2; } else { ijscores.bmaInverseAsymIC = bmaI.score; ijscores.bmaSymIC = bmaI.score; } return ijscores; } public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace) throws Exception { Set<OWLClass> atts = getAttributesForElement(i); List<ElementPairScores> matches = findMatches(atts, targetIdSpace); for (ElementPairScores m : matches) { m.i = i; } return matches; } public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception { Set<OWLClass> atts = getAttributesForElement(i); List<ElementPairScores> matches = findMatches(atts, targetIdSpace, minSimJPct, minMaxIC); for (ElementPairScores m : matches) { m.i = i; } return matches; } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getEntropy() */ @Override public Double getEntropy() throws UnknownOWLClassException { return getEntropy(getAllAttributeClasses()); } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getEntropy(java.util.Set) */ @Override public Double getEntropy(Set<OWLClass> cset) throws UnknownOWLClassException { double e = 0.0; for (OWLClass c : cset) { int freq = getNumElementsForAttribute(c); if (freq == 0) continue; double p = ((double) freq) / getCorpusSize(); e += p * Math.log(p) ; } return -e / Math.log(2); } @Override public void dispose() { } // CACHES public final String icIRIString = "http://owlsim.org/ontology/ic"; // TODO @Override public OWLOntology cacheInformationContentInOntology() throws OWLOntologyCreationException, UnknownOWLClassException { OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager(); OWLDataFactory df = mgr.getOWLDataFactory(); OWLOntology o = mgr.createOntology(); OWLAnnotationProperty p = df.getOWLAnnotationProperty(IRI.create(icIRIString)); for (OWLClass c : getSourceOntology().getClassesInSignature()) { Double ic = getInformationContentForAttribute(c); if (ic != null) { mgr.addAxiom(o, df.getOWLAnnotationAssertionAxiom(p, c.getIRI(), df.getOWLLiteral(ic))); } } return o; } protected abstract void setInformtionContectForAttribute(OWLClass c, Double v); protected abstract void clearInformationContentCache(); @Override public void setInformationContentFromOntology(OWLOntology o) { OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager(); OWLDataFactory df = mgr.getOWLDataFactory(); clearInformationContentCache(); //icCache = new HashMap<OWLClass, Double>(); for (OWLAnnotationAssertionAxiom ax : o.getAxioms(AxiomType.ANNOTATION_ASSERTION)) { if (ax.getProperty().getIRI().toString().equals(icIRIString)) { OWLLiteral lit = (OWLLiteral) ax.getValue(); OWLClass c = df.getOWLClass((IRI) ax.getSubject()); Double v = lit.parseDouble(); setInformtionContectForAttribute(c, v); } } } public void saveState(String fileName) throws IOException { LOG.warn("not implemented"); } public void saveLCSCache(String fileName) throws IOException { saveLCSCache(fileName, null); } protected final String prefix = "http://purl.obolibrary.org/obo/"; protected String getShortId(OWLClass c) { IRI x = ((OWLClass) c).getIRI(); return x.toString().replace(prefix, ""); // todo - do not hardcode } protected OWLClass getOWLClassFromShortId(String id) { // todo - standardize this if (id.equals("http://www.w3.org/2002/07/owl#Thing") || id.equals("Thing") || id.equals("owl:Thing")) { return getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); } return getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLClass(IRI.create(prefix + id)); } // // ENRICHMENT // public EnrichmentConfig enrichmentConfig; public EnrichmentConfig getEnrichmentConfig() { return enrichmentConfig; } public void setEnrichmentConfig(EnrichmentConfig enrichmentConfig) { this.enrichmentConfig = enrichmentConfig; } private void addEnrichmentResult(EnrichmentResult result, List<EnrichmentResult> results) throws UnknownOWLClassException { if (result == null) return; if (enrichmentConfig != null) { if (enrichmentConfig.pValueCorrectedCutoff != null && result.pValueCorrected > enrichmentConfig.pValueCorrectedCutoff) { return; } if (enrichmentConfig.attributeInformationContentCutoff != null && this.getInformationContentForAttribute(result.enrichedClass) < enrichmentConfig.attributeInformationContentCutoff) { return; } } LOG.info(result); results.add(result); } public List<EnrichmentResult> calculateAllByAllEnrichment() throws MathException, UnknownOWLClassException { OWLClass thing = this.getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); return calculateAllByAllEnrichment(thing, thing, thing); } /** * @param populationClass * @param pc1 * - sample set root class * @param pc2 * - enriched set root class * @return enrichment results * @throws MathException * @throws UnknownOWLClassException */ public List<EnrichmentResult> calculateAllByAllEnrichment( OWLClass populationClass, OWLClass pc1, OWLClass pc2) throws MathException, UnknownOWLClassException { List<EnrichmentResult> results = new Vector<EnrichmentResult>(); OWLClass nothing = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLNothing(); for (OWLClass sampleSetClass : getReasoner().getSubClasses(pc1, false) .getFlattened()) { if (sampleSetClass.equals(nothing)) { continue; } int sampleSetSize = getNumElementsForAttribute(sampleSetClass); LOG.info("sample set class:" + sampleSetClass + " size="+sampleSetSize); if (sampleSetSize < 2) continue; List<EnrichmentResult> resultsInner = new Vector<EnrichmentResult>(); for (OWLClass enrichedClass : this.getReasoner() .getSubClasses(pc2, false).getFlattened()) { if (enrichedClass.equals(nothing)) continue; //LOG.info(" population class:" + enrichedClass + " size="+getNumElementsForAttribute(enrichedClass)); if (getNumElementsForAttribute(enrichedClass) < 2) continue; if (sampleSetClass.equals(enrichedClass) || this.getNamedSubsumers(enrichedClass).contains(sampleSetClass) || this.getNamedSubsumers(sampleSetClass).contains(enrichedClass)) { continue; } EnrichmentResult result = calculatePairwiseEnrichment(populationClass, sampleSetClass, enrichedClass); addEnrichmentResult(result, resultsInner); } // LOG.info("sorting results:"+resultsInner.size()); Collections.sort(resultsInner); // LOG.info("sorted results:"+resultsInner.size()); results.addAll(resultsInner); } LOG.info("enrichment completed"); // Collections.sort(results); results = filterEnrichmentResults(results); return results; } public List<EnrichmentResult> filterEnrichmentResults(List<EnrichmentResult> resultsIn) { // assume sorted by p-value LOG.info("Sorting: "+resultsIn.size()+" results"); List<EnrichmentResult> resultsOut = new ArrayList<EnrichmentResult>(); // map from all sample set classes to all better enriched classes Map<OWLClass,Set<OWLClass>> betters = new HashMap<OWLClass,Set<OWLClass>>(); for (int i=0; i<resultsIn.size(); i++) { EnrichmentResult r = resultsIn.get(i); OWLClass sc = r.sampleSetClass; OWLClass ec = r.enrichedClass; //LOG.info(" R: "+r); if (!betters.containsKey(sc)) { betters.put(sc, new HashSet<OWLClass>()); } boolean isRedundant = false; // everything that came before will have a higher score; // for the given sample class, find the enriched classes // that are better; if any of these is more specific than the // current ec under consideration, skip it for (OWLClass bc : betters.get(sc)) { for (Node<OWLClass> bca : getNamedSubsumers(bc)) { //LOG.info("T: "+bca+" of "+bc+" SC="+sc); if (bca.contains(ec)) { isRedundant = true; LOG.info(" Redundant: "+sc+" "+ec+" with:"+bc); break; } } if (isRedundant) break; } if (!isRedundant) { resultsOut.add(r); } betters.get(sc).add(ec); } return resultsOut; } /** * @param populationClass * @param sampleSetClass * @return results * @throws MathException * @throws UnknownOWLClassException */ public List<EnrichmentResult> calculateEnrichment(OWLClass populationClass, OWLClass sampleSetClass) throws MathException, UnknownOWLClassException { List<EnrichmentResult> results = new Vector<EnrichmentResult>(); for (OWLClass enrichedClass : this.getReasoner() .getSubClasses(populationClass, false).getFlattened()) { LOG.info("Enrichment test for: " + enrichedClass + " vs " + populationClass); results.add(calculatePairwiseEnrichment(populationClass, sampleSetClass, enrichedClass)); } Collections.sort(results); return results; } /** * @param populationClass * @param sampleSetClass * @param enrichedClass * @return enrichment result * @throws MathException * @throws UnknownOWLClassException */ public EnrichmentResult calculatePairwiseEnrichment(OWLClass populationClass, OWLClass sampleSetClass, OWLClass enrichedClass) throws MathException, UnknownOWLClassException { // LOG.info("Hyper :"+populationClass // +" "+sampleSetClass+" "+enrichedClass); int populationClassSize; if (populationClass != null) { populationClassSize = getNumElementsForAttribute(populationClass); } else { populationClassSize = getCorpusSize(); populationClass = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); } int sampleSetClassSize = getNumElementsForAttribute(sampleSetClass); int enrichedClassSize = getNumElementsForAttribute(enrichedClass); // LOG.info("Hyper :"+populationClassSize // +" "+sampleSetClassSize+" "+enrichedClassSize); Set<OWLNamedIndividual> eiSet = getElementsForAttribute(sampleSetClass); eiSet.retainAll(this.getElementsForAttribute(enrichedClass)); int eiSetSize = eiSet.size(); if (eiSetSize == 0) { return null; } //LOG.info(" shared elements: "+eiSet.size()+" for "+enrichedClass); HypergeometricDistributionImpl hg = new HypergeometricDistributionImpl( populationClassSize, sampleSetClassSize, enrichedClassSize); /* * LOG.info("popsize="+getNumElementsForAttribute(populationClass)); * LOG.info("sampleSetSize="+getNumElementsForAttribute(sampleSetClass)); * LOG.info("enrichedClass="+getNumElementsForAttribute(enrichedClass)); */ // LOG.info("both="+eiSet.size()); double p = hg.cumulativeProbability(eiSet.size(), Math.min(sampleSetClassSize, enrichedClassSize)); double pCorrected = p * getCorrectionFactor(populationClass); return new EnrichmentResult(sampleSetClass, enrichedClass, p, pCorrected, populationClassSize, sampleSetClassSize, enrichedClassSize, eiSetSize); } // hardcode bonferoni for now Integer correctionFactor = null; // todo - robust cacheing private int getCorrectionFactor(OWLClass populationClass) throws UnknownOWLClassException { if (correctionFactor == null) { int n = 0; for (OWLClass sc : this.getReasoner() .getSubClasses(populationClass, false).getFlattened()) { //LOG.info("testing count for " + sc); if (getNumElementsForAttribute(sc) > 1) { n++; //LOG.info(" ++testing count for " + sc); } } correctionFactor = n; } return correctionFactor; } /** * @param c * @param d * @return P(c|d) = P(c^d|d) * @throws UnknownOWLClassException */ @Override public double getConditionalProbability(OWLClass c, OWLClass d) throws UnknownOWLClassException { Set<OWLNamedIndividual> cis = this.getElementsForAttribute(c); Set<OWLNamedIndividual> dis = this.getElementsForAttribute(d); cis.retainAll(dis); return cis.size() / (double) dis.size(); } // PROPS protected String getProperty(SimConfigurationProperty p) { if (simProperties == null) { return null; } return simProperties.getProperty(p.toString()); } protected Double getPropertyAsDouble(SimConfigurationProperty p) { String v = getProperty(p); if (v == null) return null; return Double.valueOf(v); } protected Double getPropertyAsDouble(SimConfigurationProperty p, Double dv) { Double v = getPropertyAsDouble(p); if (v==null) return dv; return v; } protected Boolean getPropertyAsBoolean(SimConfigurationProperty p) { String v = getProperty(p); if (v == null) { return false; } return Boolean.valueOf(v); } public void computeSystemStats() throws UnknownOWLClassException { Set<OWLNamedIndividual> insts = this.getAllElements(); LOG.info("Computing system stats for " + insts.size() + " individuals"); LOG.info("Creating singular stat scores for all IDspaces"); Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); this.overallStats = new SummaryStatistics(); int counter = 0; for (OWLNamedIndividual i : insts) { counter++; SummaryStatistics statsPerIndividual = computeIndividualStats(i); //put this individual into the aggregate if (statsPerIndividual.getN() == 0) { LOG.error("No annotations found for Individual "+i.toStringID()); } else { aggregate.add(statsPerIndividual); } //TODO: put this individual into an idSpace aggregate // String idSpace = i.getIRI().getNamespace(); this.overallStats.addValue(statsPerIndividual.getMean()); if (counter % 1000 == 0) { LOG.info("Finished "+counter+" individuals"); } } // this.aggregateStatsPerIndividual = AggregateSummaryStatistics.aggregate(aggregate); StatsPerIndividual myStats = new StatsPerIndividual(); myStats.mean = getSummaryStatisticsForCollection(aggregate,Stat.MEAN); myStats.sum = getSummaryStatisticsForCollection(aggregate,Stat.SUM); myStats.min = getSummaryStatisticsForCollection(aggregate,Stat.MIN); myStats.max = getSummaryStatisticsForCollection(aggregate,Stat.MAX); myStats.n = getSummaryStatisticsForCollection(aggregate,Stat.N); myStats.aggregate = AggregateSummaryStatistics.aggregate(aggregate); this.overallSummaryStatsPerIndividual = myStats; LOG.info("Finished computing overall statsPerIndividual:\n"+this.getSummaryStatistics().toString()); } public void computeSystemStatsForSubgraph(OWLClass c) throws UnknownOWLClassException { Set<OWLNamedIndividual> insts = this.getAllElements(); LOG.info("Computing system stats for subgraph rooted at" + c.toString() +" with "+ insts.size() + " individuals"); // LOG.info("Creating singular stat scores for all IDspaces"); Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); SummaryStatistics subgraphStats = new SummaryStatistics(); for (OWLNamedIndividual i : insts) { SummaryStatistics statsPerIndividual = computeIndividualStatsForSubgraph(i,c); //put this individual into the aggregate if (statsPerIndividual.getN() == 0) { //LOG.info("No annotations found in this subgraph for Individual "+i.toStringID()); } else { //LOG.info(statsPerIndividual.getN()+" Annotations found in this subgraph for Individual "+i.toStringID()); aggregate.add(statsPerIndividual); } //TODO: put this individual into an idSpace aggregate //String idSpace = i.getIRI().getNamespace(); subgraphStats.addValue(statsPerIndividual.getMean()); } StatsPerIndividual myStats = new StatsPerIndividual(); myStats.mean = getSummaryStatisticsForCollection(aggregate,Stat.MEAN); myStats.sum = getSummaryStatisticsForCollection(aggregate,Stat.SUM); myStats.min = getSummaryStatisticsForCollection(aggregate,Stat.MIN); myStats.max = getSummaryStatisticsForCollection(aggregate,Stat.MAX); myStats.n = getSummaryStatisticsForCollection(aggregate,Stat.N); this.subgraphSummaryStatsPerIndividual.put(c, myStats); LOG.info("Finished omputing system stats for subgraph rooted at" + c.toString()); } /** * This function will take an aggregated collection of Summary Statistics * and will generate a derived {@link SummaryStatistic} based on a flag for the * desired summation. This is particularly helpful for finding out the * means of the individual statistics of the collection. * For example, if you wanted to find out the mean of means of the collection * you would call this function like <p> * getSummaryStatisticsForCollection(aggregate,1).getMean(); <p> * Or if you wanted to determine the max number of annotations per * individual, you could call: <p> * getSummaryStatisticsForCollection(aggregate,5).getMax(); <p> * The stat flag should be set to the particular individual statistic that should * be summarized over. * * @param aggregate The aggregated collection of summary statistics * @param stat Integer flag for the statistic (1:mean ; 2:sum; 3:min; 4:max; 5:N) * @return {@link SummaryStatistics} of the selected statistic */ public SummaryStatistics getSummaryStatisticsForCollection(Collection<SummaryStatistics> aggregate, Stat stat) { //LOG.info("Computing stats over collection of "+aggregate.size()+" elements ("+stat+"):"); //TODO: turn stat into enum int x = 0; //To save memory, I am using SummaryStatistics, which does not store the values, //but this could be changed to DescriptiveStatistics to see values //as well as other statistical functions like distributions SummaryStatistics stats = new SummaryStatistics(); Double v = 0.0; ArrayList<String> vals = new ArrayList(); for (SummaryStatistics s : aggregate) { switch (stat) { case MEAN : v= s.getMean(); stats.addValue(s.getMean()); break; case SUM : v=s.getSum(); stats.addValue(s.getSum()); break; case MIN : v=s.getMin(); stats.addValue(s.getMin()); break; case MAX : v=s.getMax(); stats.addValue(s.getMax()); break; case N : v= ((int)s.getN())*1.0; stats.addValue(s.getN()); break; }; //vals.add(v.toString()); }; //LOG.info("vals: "+vals.toString()); return stats; } public SummaryStatistics computeIndividualStats(OWLNamedIndividual i) throws UnknownOWLClassException { //LOG.info("Computing individual stats for "+i.toString()); return this.computeAttributeSetSimilarityStats(this.getAttributesForElement(i)); } public SummaryStatistics computeIndividualStatsForSubgraph(OWLNamedIndividual i,OWLClass c) throws UnknownOWLClassException { return this.computeAttributeSetSimilarityStatsForSubgraph(this.getAttributesForElement(i),c); } public SummaryStatistics computeAttributeSetSimilarityStats(Set<OWLClass> atts) { SummaryStatistics statsPerAttSet = new SummaryStatistics(); // Set<OWLClass> allClasses = getSourceOntology().getClassesInSignature(true); OWLDataFactory g = getSourceOntology().getOWLOntologyManager().getOWLDataFactory(); for (OWLClass c : atts) { Double ic; try { ic = this.getInformationContentForAttribute(c); if (ic == null) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC if (g.getOWLClass(c.getIRI()) != null) { ic = this.getSummaryStatistics().max.getMax(); } else { throw new UnknownOWLClassException(c); } } if (ic.isInfinite() || ic.isNaN()) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC //a different option would be to skip adding this value, //but i'm not sure that's wise ic = this.getSummaryStatistics().max.getMax(); } //LOG.info("IC for "+c.toString()+"is: "+ic); statsPerAttSet.addValue(ic); } catch (UnknownOWLClassException e) { //This is an extra catch here, but really it should be caught upstream. LOG.info("Unknown class "+c.toStringID()+" submitted for summary stats. Removed from calculation."); continue; } } return statsPerAttSet; } public SummaryStatistics computeAttributeSetSimilarityStatsForSubgraph(Set<OWLClass> atts, OWLClass sub) { SummaryStatistics statsPerAttSet = new SummaryStatistics(); // Set<OWLClass> allClasses = getSourceOntology().getClassesInSignature(true); OWLDataFactory g = getSourceOntology().getOWLOntologyManager().getOWLDataFactory(); for (OWLClass c : atts) { Double ic; try { //check if sub is an inferred superclass of the current annotated class //TODO check if i need all of these; this might be expensive and unnecessary if (getReasoner().getSuperClasses(c, false).containsEntity(sub) || getReasoner().getEquivalentClasses(c).contains(sub)) { ic = this.getInformationContentForAttribute(c); if (ic == null) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC if (g.getOWLClass(c.getIRI()) != null) { ic = this.getSummaryStatistics().max.getMax(); } else { throw new UnknownOWLClassException(c); } } if (ic.isInfinite() || ic.isNaN()) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC ic = this.getSummaryStatistics().max.getMax(); } //LOG.info("IC for "+c.toString()+"is: "+ic); statsPerAttSet.addValue(ic); } else { //LOG.info("tossing "+c.toString()+"; not a subclass of "+sub.toString()); } } catch (UnknownOWLClassException e) { //This is an extra catch here, but really it should be caught upstream. LOG.info("Unknown class "+c.toStringID()+" submitted for summary stats. Removed from calculation."); continue; } } return statsPerAttSet; } public StatisticalSummaryValues getSystemStats() { // return this.aggregateStatsPerIndividual; return this.overallSummaryStatsPerIndividual.aggregate; } public StatsPerIndividual getSummaryStatistics() { return this.overallSummaryStatsPerIndividual; } public StatsPerIndividual getSummaryStatistics(OWLClass c) { return this.subgraphSummaryStatsPerIndividual.get(c); } public SummaryStatistics getSimStatistics() { SummaryStatistics s = new SummaryStatistics(); //for each metric, we need the min/max/average return s; } public SummaryStatistics computeIndividualSimilarityStats(OWLNamedIndividual i) throws UnknownOWLClassException { SummaryStatistics s = new SummaryStatistics(); return s; } public HashMap<String,SummaryStatistics> getMetricStats(Stat stat) { HashMap<String,SummaryStatistics> s = new HashMap<String,SummaryStatistics>(); switch(stat) { case MIN : s = this.metricStatMins; break; case MAX : s = this.metricStatMaxes; break; case MEAN : s = this.metricStatMeans; break; } return s; } public double calculateOverallAnnotationSufficiencyForIndividual(OWLNamedIndividual i) throws UnknownOWLClassException { return calculateOverallAnnotationSufficiencyForAttributeSet(this.getAttributesForElement(i)); } public double calculateSubgraphAnnotationSufficiencyForIndividual(OWLNamedIndividual i, OWLClass c) throws UnknownOWLClassException { return calculateSubgraphAnnotationSufficiencyForAttributeSet(this.getAttributesForElement(i), c); } public double calculateOverallAnnotationSufficiencyForAttributeSet(Set<OWLClass> atts) throws UnknownOWLClassException { SummaryStatistics stats = computeAttributeSetSimilarityStats(atts); if ((this.getSummaryStatistics() == null) || Double.isNaN(this.getSummaryStatistics().mean.getMean())) { LOG.info("Stats have not been computed yet - doing this now"); this.computeSystemStats(); } // score = mean(atts)/mean(overall) + max(atts)/max(overall) + sum(atts)/mean(sum(overall)) double overall_score = 0.0; Double mean_score = stats.getMean(); Double max_score = stats.getMax(); Double sum_score = stats.getSum(); if (!(mean_score.isNaN() || max_score.isNaN() || sum_score.isNaN())) { mean_score = StatUtils.min(new double[]{(mean_score / this.overallSummaryStatsPerIndividual.mean.getMean()),1.0}); max_score = StatUtils.min(new double[]{(max_score / this.overallSummaryStatsPerIndividual.max.getMax()),1.0}); sum_score = StatUtils.min(new double[]{(sum_score / this.overallSummaryStatsPerIndividual.sum.getMean()),1.0}); overall_score = (mean_score + max_score + sum_score) / 3; } LOG.info("Overall mean: "+mean_score + " max: "+max_score + " sum:"+sum_score + " combined:"+overall_score); return overall_score; } public double calculateSubgraphAnnotationSufficiencyForAttributeSet(Set<OWLClass> atts, OWLClass c) throws UnknownOWLClassException { SummaryStatistics stats = computeAttributeSetSimilarityStatsForSubgraph(atts,c); //TODO: compute statsPerIndividual for this subgraph if ((this.overallSummaryStatsPerIndividual == null ) || (Double.isNaN(this.overallSummaryStatsPerIndividual.max.getMean()))) { LOG.info("Stats have not been computed yet - doing this now"); this.computeSystemStats(); } if (!(this.subgraphSummaryStatsPerIndividual.containsKey(c))) { //only do this once for the whole system, per class requested this.computeSystemStatsForSubgraph(c); } // score = mean(atts)/mean(overall) + max(atts)/max(overall) + sum(atts)/mean(sum(overall)) //TODO: need to normalize this based on the whole corpus double score = 0.0; Double mean_score = stats.getMean(); Double max_score = stats.getMax(); Double sum_score = stats.getSum(); if (!(mean_score.isNaN() || max_score.isNaN() || sum_score.isNaN())) { mean_score = StatUtils.min(new double[]{(mean_score / this.subgraphSummaryStatsPerIndividual.get(c).mean.getMean()),1.0}); max_score = StatUtils.min(new double[]{(max_score / this.subgraphSummaryStatsPerIndividual.get(c).max.getMax()),1.0}); sum_score = StatUtils.min(new double[]{(sum_score / this.subgraphSummaryStatsPerIndividual.get(c).sum.getMean()),1.0}); score = (mean_score + max_score + sum_score) / 3; } LOG.info(getShortId(c)+" n: "+stats.getN()+" mean: "+mean_score + " max: "+max_score + " sum:"+sum_score + " combined:"+score); return score; } public void calculateCombinedScore(ElementPairScores s, double maxMaxIC, double maxBMA) { int maxMaxIC100 = (int)(maxMaxIC * 100); int maxBMA100 = (int)(maxBMA * 100); if (maxMaxIC == 0 || maxBMA == 0) { return; } int pctMaxScore = ((int) (s.maxIC * 10000)) / maxMaxIC100; //TODO should this be using maxBMA100? int pctAvgScore = ((int) (s.bmaSymIC * 10000)) / maxBMA100; s.combinedScore = (pctMaxScore + pctAvgScore)/2; } public OwlSimMetadata getMetadata() { OwlSimMetadata md = new OwlSimMetadata(); md.ontologySet = new OntologySetMetadata(this.getSourceOntology()); md.individualCount = getAllElements().size(); return md; } }
OWLTools-Sim/src/main/java/owltools/sim2/AbstractOwlSim.java
package owltools.sim2; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import org.apache.commons.io.IOUtils; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.HypergeometricDistributionImpl; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics; import org.apache.commons.math3.stat.descriptive.StatisticalSummary; import org.apache.commons.math3.stat.descriptive.StatisticalSummaryValues; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import org.semanticweb.elk.reasoner.saturation.conclusions.ForwardLink.ThisBackwardLinkRule; import org.semanticweb.owlapi.model.AxiomType; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.OWLReasoner; import owltools.graph.OWLGraphWrapper; import owltools.mooncat.ontologymetadata.OntologySetMetadata; import owltools.sim2.OwlSim.ScoreAttributeSetPair; import owltools.sim2.SimpleOwlSim.Direction; import owltools.sim2.SimpleOwlSim.Metric; import owltools.sim2.SimpleOwlSim.ScoreAttributePair; import owltools.sim2.SimpleOwlSim.SimConfigurationProperty; import owltools.sim2.scores.ElementPairScores; import owltools.util.ClassExpressionPair; public abstract class AbstractOwlSim implements OwlSim { private Logger LOG = Logger.getLogger(AbstractOwlSim.class); long totalTimeSimJ = 0; long totalCallsSimJ = 0; long totalTimeLCSIC = 0; long totalCallsLCSIC = 0; long totalTimeGIC = 0; long totalCallsGIC = 0; public SimStats simStats = new SimStats(); protected boolean isDisableLCSCache = false; protected OWLReasoner reasoner; protected Integer corpusSize; // number of individuals in domain protected boolean isLCSCacheFullyPopulated = false; protected boolean isNoLookupForLCSCache = false; private Properties simProperties; public SummaryStatistics overallStats; public StatsPerIndividual overallSummaryStatsPerIndividual = new StatsPerIndividual(); public HashMap<OWLClass,StatsPerIndividual> subgraphSummaryStatsPerIndividual = new HashMap<OWLClass,StatsPerIndividual>(); public SummaryStatistics simStatsPerIndividual = new SummaryStatistics(); public HashMap<String,SummaryStatistics> metricStatMeans = new HashMap<String,SummaryStatistics>(); public HashMap<String,SummaryStatistics> metricStatMaxes = new HashMap<String,SummaryStatistics>(); public HashMap<String,SummaryStatistics> metricStatMins = new HashMap<String,SummaryStatistics>(); @Override public OWLOntology getSourceOntology() { return getReasoner().getRootOntology(); } @Override public OWLReasoner getReasoner() { return reasoner; } public boolean isNoLookupForLCSCache() { return isNoLookupForLCSCache; } public void setNoLookupForLCSCache(boolean isNoLookupForLCSCache) { this.isNoLookupForLCSCache = isNoLookupForLCSCache; } public boolean isDisableLCSCache() { return isDisableLCSCache; } public void setDisableLCSCache(boolean isDisableLCSCache) { this.isDisableLCSCache = isDisableLCSCache; } @Override public Properties getSimProperties() { return simProperties; } @Override public void setSimProperties(Properties simProperties) { this.simProperties = simProperties; } public SimStats getSimStats() { return simStats; } public void setSimStats(SimStats simStats) { this.simStats = simStats; } protected long tdelta(long prev) { return System.currentTimeMillis() - prev; } /** * */ public void showTimings() { LOG.info("Timings:"); if (totalCallsSimJ > 0) { LOG.info("t(SimJ) ms = "+totalTimeSimJ + " / "+totalCallsSimJ + " = " + totalTimeSimJ / (double) totalCallsSimJ); } if (totalCallsLCSIC > 0) { LOG.info("t(LCS) ms = "+totalTimeLCSIC + " / "+totalCallsLCSIC + " = " + totalTimeLCSIC / (double) totalCallsLCSIC); } if (totalCallsGIC > 0) { LOG.info("t(GIC) ms = "+totalTimeGIC + " / "+totalCallsGIC + " = " + totalTimeGIC / (double) totalCallsGIC); } } public void showTimingsAndReset() { showTimings(); totalTimeSimJ = 0; totalCallsSimJ = 0; totalTimeLCSIC = 0; totalCallsLCSIC = 0; totalTimeGIC = 0; totalCallsGIC = 0; } @Override public void precomputeAttributeAllByAll() throws UnknownOWLClassException { LOG.info("precomputing attribute all x all"); long t = System.currentTimeMillis(); Set<OWLClass> cset = this.getAllAttributeClasses(); int n=0; for (OWLClass c : cset ) { n++; if (n % 100 == 0) { LOG.info("Cached LCS for "+n+" / "+cset.size()+" attributes"); } for (OWLClass d : cset ) { getLowestCommonSubsumerWithIC(c, d); } } LOG.info("Time precomputing attribute all x all = "+tdelta(t)); showTimingsAndReset(); } @Override public Set<Node<OWLClass>> getNamedSubsumers(OWLClass a) { return getReasoner().getSuperClasses(a, false).getNodes(); } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getCorpusSize() */ public int getCorpusSize() { if (corpusSize == null) { corpusSize = getAllElements().size(); } return corpusSize; } /* (non-Javadoc) * @see owltools.sim2.OwlSim#setCorpusSize(int) */ public void setCorpusSize(int size) { corpusSize = size; } // Note: inefficient for graphs with multiple parentage, due to // use of unmemoized recursion protected Set<List<OWLClass>> getPaths(OWLClass c, OWLClass d) { Set<List<OWLClass>> paths = new HashSet<List<OWLClass>>(); for (Node<OWLClass> node : getReasoner().getSuperClasses(c, true)) { if (node.contains(d)) { ArrayList<OWLClass> path = new ArrayList<OWLClass>(); path.add(d); path.add(c); paths.add(path); } else { OWLClass nc = node.getRepresentativeElement(); if (getReasoner().getSuperClasses(nc, false).getFlattened().contains(d)) { Set<List<OWLClass>> ppaths = getPaths(nc, d); for (List<OWLClass> ppath : ppaths) { ArrayList<OWLClass> path = new ArrayList<OWLClass>(ppath); path.add(c); paths.add(path); } } else { // veered off path } } } return paths; } protected int getMinimumDistanceToAncestor(OWLClass c, OWLClass d) { int minDist = 0; for (List<OWLClass> path : getPaths(c,d)) { int dist = path.size()-1; if (dist<minDist) minDist = dist; } return minDist; } protected int getMinimumDistanceViaMICA(OWLClass c, OWLClass d) throws UnknownOWLClassException { int minDist = 0; for (OWLClass a : getLowestCommonSubsumerWithIC(c, d).attributeClassSet) { int dist = getMinimumDistanceToAncestor(c,a) + getMinimumDistanceToAncestor(d,a); if (dist<minDist) minDist = dist; } return minDist; } public void getICSimDisj(OWLClass c, OWLClass d) { } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getLowestCommonSubsumerWithLinScore(org.semanticweb.owlapi.model.OWLClass, org.semanticweb.owlapi.model.OWLClass) * * Note this is uncached - subclasses may wish to impement caching */ public ScoreAttributeSetPair getLowestCommonSubsumerWithLinScore(OWLClass c, OWLClass d) throws UnknownOWLClassException { ScoreAttributeSetPair sap = this.getLowestCommonSubsumerWithIC(c, d); sap.score = (sap.score * 2) / (getInformationContentForAttribute(c) + getInformationContentForAttribute(d)); return sap; } // may be less performant than direct computation public int getAttributeJaccardSimilarityAsPercent(OWLClass a, OWLClass b) throws UnknownOWLClassException { return (int) (getAttributeJaccardSimilarity(a, b) * 100); } // may be less performant than direct computation public int getElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { return (int) (getElementJaccardSimilarity(i, j) * 100); } // may be less performant than direct computation public int getAsymmetricAttributeJaccardSimilarityAsPercent(OWLClass a, OWLClass b) throws UnknownOWLClassException { return (int) (getAsymmetricAttributeJaccardSimilarity(a, b) * 100); } // may be less performant than direct computation public int getAsymmetricElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { return (int) (getAsymmetricElementJaccardSimilarity(i, j) * 100); } @Override public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws Exception { ElementPairScores ijscores = new ElementPairScores(i,j); //populateSimilarityMatrix(i, j, s); ijscores.simGIC = getElementGraphInformationContentSimilarity(i, j); ijscores.simjScore = getElementJaccardSimilarity(i, j); ijscores.asymmetricSimjScore = getAsymmetricElementJaccardSimilarity(i, j); ijscores.inverseAsymmetricSimjScore = getAsymmetricElementJaccardSimilarity(j, i); // WAS this deprecated function: // ScoreAttributeSetPair bma = this.getSimilarityBestMatchAverage(i, j, Metric.IC_MCS, Direction.A_TO_B); ScoreAttributeSetPair bmaI = this.getSimilarityBestMatchAverageAsym(i, j, Metric.IC_MCS); ijscores.bmaAsymIC = bmaI.score; if (i!=j) { //we were skipping the inverse calculation before -- intentional? ScoreAttributeSetPair bmaJ = this.getSimilarityBestMatchAverageAsym(j, i, Metric.IC_MCS); ijscores.bmaInverseAsymIC = bmaJ.score; ijscores.bmaSymIC = (bmaI.score + bmaJ.score) / 2; } else { ijscores.bmaInverseAsymIC = bmaI.score; ijscores.bmaSymIC = bmaI.score; } return ijscores; } public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace) throws Exception { Set<OWLClass> atts = getAttributesForElement(i); List<ElementPairScores> matches = findMatches(atts, targetIdSpace); for (ElementPairScores m : matches) { m.i = i; } return matches; } public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception { Set<OWLClass> atts = getAttributesForElement(i); List<ElementPairScores> matches = findMatches(atts, targetIdSpace, minSimJPct, minMaxIC); for (ElementPairScores m : matches) { m.i = i; } return matches; } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getEntropy() */ @Override public Double getEntropy() throws UnknownOWLClassException { return getEntropy(getAllAttributeClasses()); } /* (non-Javadoc) * @see owltools.sim2.OwlSim#getEntropy(java.util.Set) */ @Override public Double getEntropy(Set<OWLClass> cset) throws UnknownOWLClassException { double e = 0.0; for (OWLClass c : cset) { int freq = getNumElementsForAttribute(c); if (freq == 0) continue; double p = ((double) freq) / getCorpusSize(); e += p * Math.log(p) ; } return -e / Math.log(2); } @Override public void dispose() { } // CACHES public final String icIRIString = "http://owlsim.org/ontology/ic"; // TODO @Override public OWLOntology cacheInformationContentInOntology() throws OWLOntologyCreationException, UnknownOWLClassException { OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager(); OWLDataFactory df = mgr.getOWLDataFactory(); OWLOntology o = mgr.createOntology(); OWLAnnotationProperty p = df.getOWLAnnotationProperty(IRI.create(icIRIString)); for (OWLClass c : getSourceOntology().getClassesInSignature()) { Double ic = getInformationContentForAttribute(c); if (ic != null) { mgr.addAxiom(o, df.getOWLAnnotationAssertionAxiom(p, c.getIRI(), df.getOWLLiteral(ic))); } } return o; } protected abstract void setInformtionContectForAttribute(OWLClass c, Double v); protected abstract void clearInformationContentCache(); @Override public void setInformationContentFromOntology(OWLOntology o) { OWLOntologyManager mgr = getSourceOntology().getOWLOntologyManager(); OWLDataFactory df = mgr.getOWLDataFactory(); clearInformationContentCache(); //icCache = new HashMap<OWLClass, Double>(); for (OWLAnnotationAssertionAxiom ax : o.getAxioms(AxiomType.ANNOTATION_ASSERTION)) { if (ax.getProperty().getIRI().toString().equals(icIRIString)) { OWLLiteral lit = (OWLLiteral) ax.getValue(); OWLClass c = df.getOWLClass((IRI) ax.getSubject()); Double v = lit.parseDouble(); setInformtionContectForAttribute(c, v); } } } public void saveState(String fileName) throws IOException { LOG.warn("not implemented"); } public void saveLCSCache(String fileName) throws IOException { saveLCSCache(fileName, null); } protected final String prefix = "http://purl.obolibrary.org/obo/"; protected String getShortId(OWLClass c) { IRI x = ((OWLClass) c).getIRI(); return x.toString().replace(prefix, ""); // todo - do not hardcode } protected OWLClass getOWLClassFromShortId(String id) { // todo - standardize this if (id.equals("http://www.w3.org/2002/07/owl#Thing") || id.equals("Thing") || id.equals("owl:Thing")) { return getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); } return getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLClass(IRI.create(prefix + id)); } // // ENRICHMENT // public EnrichmentConfig enrichmentConfig; public EnrichmentConfig getEnrichmentConfig() { return enrichmentConfig; } public void setEnrichmentConfig(EnrichmentConfig enrichmentConfig) { this.enrichmentConfig = enrichmentConfig; } private void addEnrichmentResult(EnrichmentResult result, List<EnrichmentResult> results) throws UnknownOWLClassException { if (result == null) return; if (enrichmentConfig != null) { if (enrichmentConfig.pValueCorrectedCutoff != null && result.pValueCorrected > enrichmentConfig.pValueCorrectedCutoff) { return; } if (enrichmentConfig.attributeInformationContentCutoff != null && this.getInformationContentForAttribute(result.enrichedClass) < enrichmentConfig.attributeInformationContentCutoff) { return; } } LOG.info(result); results.add(result); } public List<EnrichmentResult> calculateAllByAllEnrichment() throws MathException, UnknownOWLClassException { OWLClass thing = this.getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); return calculateAllByAllEnrichment(thing, thing, thing); } /** * @param populationClass * @param pc1 * - sample set root class * @param pc2 * - enriched set root class * @return enrichment results * @throws MathException * @throws UnknownOWLClassException */ public List<EnrichmentResult> calculateAllByAllEnrichment( OWLClass populationClass, OWLClass pc1, OWLClass pc2) throws MathException, UnknownOWLClassException { List<EnrichmentResult> results = new Vector<EnrichmentResult>(); OWLClass nothing = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLNothing(); for (OWLClass sampleSetClass : getReasoner().getSubClasses(pc1, false) .getFlattened()) { if (sampleSetClass.equals(nothing)) { continue; } int sampleSetSize = getNumElementsForAttribute(sampleSetClass); LOG.info("sample set class:" + sampleSetClass + " size="+sampleSetSize); if (sampleSetSize < 2) continue; List<EnrichmentResult> resultsInner = new Vector<EnrichmentResult>(); for (OWLClass enrichedClass : this.getReasoner() .getSubClasses(pc2, false).getFlattened()) { if (enrichedClass.equals(nothing)) continue; //LOG.info(" population class:" + enrichedClass + " size="+getNumElementsForAttribute(enrichedClass)); if (getNumElementsForAttribute(enrichedClass) < 2) continue; if (sampleSetClass.equals(enrichedClass) || this.getNamedSubsumers(enrichedClass).contains(sampleSetClass) || this.getNamedSubsumers(sampleSetClass).contains(enrichedClass)) { continue; } EnrichmentResult result = calculatePairwiseEnrichment(populationClass, sampleSetClass, enrichedClass); addEnrichmentResult(result, resultsInner); } // LOG.info("sorting results:"+resultsInner.size()); Collections.sort(resultsInner); // LOG.info("sorted results:"+resultsInner.size()); results.addAll(resultsInner); } LOG.info("enrichment completed"); // Collections.sort(results); results = filterEnrichmentResults(results); return results; } public List<EnrichmentResult> filterEnrichmentResults(List<EnrichmentResult> resultsIn) { // assume sorted by p-value LOG.info("Sorting: "+resultsIn.size()+" results"); List<EnrichmentResult> resultsOut = new ArrayList<EnrichmentResult>(); // map from all sample set classes to all better enriched classes Map<OWLClass,Set<OWLClass>> betters = new HashMap<OWLClass,Set<OWLClass>>(); for (int i=0; i<resultsIn.size(); i++) { EnrichmentResult r = resultsIn.get(i); OWLClass sc = r.sampleSetClass; OWLClass ec = r.enrichedClass; //LOG.info(" R: "+r); if (!betters.containsKey(sc)) { betters.put(sc, new HashSet<OWLClass>()); } boolean isRedundant = false; // everything that came before will have a higher score; // for the given sample class, find the enriched classes // that are better; if any of these is more specific than the // current ec under consideration, skip it for (OWLClass bc : betters.get(sc)) { for (Node<OWLClass> bca : getNamedSubsumers(bc)) { //LOG.info("T: "+bca+" of "+bc+" SC="+sc); if (bca.contains(ec)) { isRedundant = true; LOG.info(" Redundant: "+sc+" "+ec+" with:"+bc); break; } } if (isRedundant) break; } if (!isRedundant) { resultsOut.add(r); } betters.get(sc).add(ec); } return resultsOut; } /** * @param populationClass * @param sampleSetClass * @return results * @throws MathException * @throws UnknownOWLClassException */ public List<EnrichmentResult> calculateEnrichment(OWLClass populationClass, OWLClass sampleSetClass) throws MathException, UnknownOWLClassException { List<EnrichmentResult> results = new Vector<EnrichmentResult>(); for (OWLClass enrichedClass : this.getReasoner() .getSubClasses(populationClass, false).getFlattened()) { LOG.info("Enrichment test for: " + enrichedClass + " vs " + populationClass); results.add(calculatePairwiseEnrichment(populationClass, sampleSetClass, enrichedClass)); } Collections.sort(results); return results; } /** * @param populationClass * @param sampleSetClass * @param enrichedClass * @return enrichment result * @throws MathException * @throws UnknownOWLClassException */ public EnrichmentResult calculatePairwiseEnrichment(OWLClass populationClass, OWLClass sampleSetClass, OWLClass enrichedClass) throws MathException, UnknownOWLClassException { // LOG.info("Hyper :"+populationClass // +" "+sampleSetClass+" "+enrichedClass); int populationClassSize; if (populationClass != null) { populationClassSize = getNumElementsForAttribute(populationClass); } else { populationClassSize = getCorpusSize(); populationClass = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); } int sampleSetClassSize = getNumElementsForAttribute(sampleSetClass); int enrichedClassSize = getNumElementsForAttribute(enrichedClass); // LOG.info("Hyper :"+populationClassSize // +" "+sampleSetClassSize+" "+enrichedClassSize); Set<OWLNamedIndividual> eiSet = getElementsForAttribute(sampleSetClass); eiSet.retainAll(this.getElementsForAttribute(enrichedClass)); int eiSetSize = eiSet.size(); if (eiSetSize == 0) { return null; } //LOG.info(" shared elements: "+eiSet.size()+" for "+enrichedClass); HypergeometricDistributionImpl hg = new HypergeometricDistributionImpl( populationClassSize, sampleSetClassSize, enrichedClassSize); /* * LOG.info("popsize="+getNumElementsForAttribute(populationClass)); * LOG.info("sampleSetSize="+getNumElementsForAttribute(sampleSetClass)); * LOG.info("enrichedClass="+getNumElementsForAttribute(enrichedClass)); */ // LOG.info("both="+eiSet.size()); double p = hg.cumulativeProbability(eiSet.size(), Math.min(sampleSetClassSize, enrichedClassSize)); double pCorrected = p * getCorrectionFactor(populationClass); return new EnrichmentResult(sampleSetClass, enrichedClass, p, pCorrected, populationClassSize, sampleSetClassSize, enrichedClassSize, eiSetSize); } // hardcode bonferoni for now Integer correctionFactor = null; // todo - robust cacheing private int getCorrectionFactor(OWLClass populationClass) throws UnknownOWLClassException { if (correctionFactor == null) { int n = 0; for (OWLClass sc : this.getReasoner() .getSubClasses(populationClass, false).getFlattened()) { //LOG.info("testing count for " + sc); if (getNumElementsForAttribute(sc) > 1) { n++; //LOG.info(" ++testing count for " + sc); } } correctionFactor = n; } return correctionFactor; } /** * @param c * @param d * @return P(c|d) = P(c^d|d) * @throws UnknownOWLClassException */ @Override public double getConditionalProbability(OWLClass c, OWLClass d) throws UnknownOWLClassException { Set<OWLNamedIndividual> cis = this.getElementsForAttribute(c); Set<OWLNamedIndividual> dis = this.getElementsForAttribute(d); cis.retainAll(dis); return cis.size() / (double) dis.size(); } // PROPS protected String getProperty(SimConfigurationProperty p) { if (simProperties == null) { return null; } return simProperties.getProperty(p.toString()); } protected Double getPropertyAsDouble(SimConfigurationProperty p) { String v = getProperty(p); if (v == null) return null; return Double.valueOf(v); } protected Double getPropertyAsDouble(SimConfigurationProperty p, Double dv) { Double v = getPropertyAsDouble(p); if (v==null) return dv; return v; } protected Boolean getPropertyAsBoolean(SimConfigurationProperty p) { String v = getProperty(p); if (v == null) { return false; } return Boolean.valueOf(v); } public void computeSystemStats() throws UnknownOWLClassException { Set<OWLNamedIndividual> insts = this.getAllElements(); LOG.info("Computing system stats for " + insts.size() + " individuals"); LOG.info("Creating singular stat scores for all IDspaces"); Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); this.overallStats = new SummaryStatistics(); int counter = 0; for (OWLNamedIndividual i : insts) { counter++; SummaryStatistics statsPerIndividual = computeIndividualStats(i); //put this individual into the aggregate if (statsPerIndividual.getN() == 0) { LOG.error("No annotations found for Individual "+i.toStringID()); } else { aggregate.add(statsPerIndividual); } //TODO: put this individual into an idSpace aggregate // String idSpace = i.getIRI().getNamespace(); this.overallStats.addValue(statsPerIndividual.getMean()); if (counter % 1000 == 0) { LOG.info("Finished "+counter+" individuals"); } } // this.aggregateStatsPerIndividual = AggregateSummaryStatistics.aggregate(aggregate); StatsPerIndividual myStats = new StatsPerIndividual(); myStats.mean = getSummaryStatisticsForCollection(aggregate,Stat.MEAN); myStats.sum = getSummaryStatisticsForCollection(aggregate,Stat.SUM); myStats.min = getSummaryStatisticsForCollection(aggregate,Stat.MIN); myStats.max = getSummaryStatisticsForCollection(aggregate,Stat.MAX); myStats.n = getSummaryStatisticsForCollection(aggregate,Stat.N); myStats.aggregate = AggregateSummaryStatistics.aggregate(aggregate); this.overallSummaryStatsPerIndividual = myStats; LOG.info("Finished computing overall statsPerIndividual:\n"+this.getSummaryStatistics().toString()); } public void computeSystemStatsForSubgraph(OWLClass c) throws UnknownOWLClassException { Set<OWLNamedIndividual> insts = this.getAllElements(); LOG.info("Computing system stats for subgraph rooted at" + c.toString() +" with "+ insts.size() + " individuals"); // LOG.info("Creating singular stat scores for all IDspaces"); Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); SummaryStatistics subgraphStats = new SummaryStatistics(); for (OWLNamedIndividual i : insts) { SummaryStatistics statsPerIndividual = computeIndividualStatsForSubgraph(i,c); //put this individual into the aggregate if (statsPerIndividual.getN() == 0) { //LOG.info("No annotations found in this subgraph for Individual "+i.toStringID()); } else { //LOG.info(statsPerIndividual.getN()+" Annotations found in this subgraph for Individual "+i.toStringID()); aggregate.add(statsPerIndividual); } //TODO: put this individual into an idSpace aggregate //String idSpace = i.getIRI().getNamespace(); subgraphStats.addValue(statsPerIndividual.getMean()); } StatsPerIndividual myStats = new StatsPerIndividual(); myStats.mean = getSummaryStatisticsForCollection(aggregate,Stat.MEAN); myStats.sum = getSummaryStatisticsForCollection(aggregate,Stat.SUM); myStats.min = getSummaryStatisticsForCollection(aggregate,Stat.MIN); myStats.max = getSummaryStatisticsForCollection(aggregate,Stat.MAX); myStats.n = getSummaryStatisticsForCollection(aggregate,Stat.N); this.subgraphSummaryStatsPerIndividual.put(c, myStats); LOG.info("Finished omputing system stats for subgraph rooted at" + c.toString()); } /** * This function will take an aggregated collection of Summary Statistics * and will generate a derived {@link SummaryStatistic} based on a flag for the * desired summation. This is particularly helpful for finding out the * means of the individual statistics of the collection. * For example, if you wanted to find out the mean of means of the collection * you would call this function like <p> * getSummaryStatisticsForCollection(aggregate,1).getMean(); <p> * Or if you wanted to determine the max number of annotations per * individual, you could call: <p> * getSummaryStatisticsForCollection(aggregate,5).getMax(); <p> * The stat flag should be set to the particular individual statistic that should * be summarized over. * * @param aggregate The aggregated collection of summary statistics * @param stat Integer flag for the statistic (1:mean ; 2:sum; 3:min; 4:max; 5:N) * @return {@link SummaryStatistics} of the selected statistic */ public SummaryStatistics getSummaryStatisticsForCollection(Collection<SummaryStatistics> aggregate, Stat stat) { //LOG.info("Computing stats over collection of "+aggregate.size()+" elements ("+stat+"):"); //TODO: turn stat into enum int x = 0; //To save memory, I am using SummaryStatistics, which does not store the values, //but this could be changed to DescriptiveStatistics to see values //as well as other statistical functions like distributions SummaryStatistics stats = new SummaryStatistics(); Double v = 0.0; ArrayList<String> vals = new ArrayList(); for (SummaryStatistics s : aggregate) { switch (stat) { case MEAN : v= s.getMean(); stats.addValue(s.getMean()); break; case SUM : v=s.getSum(); stats.addValue(s.getSum()); break; case MIN : v=s.getMin(); stats.addValue(s.getMin()); break; case MAX : v=s.getMax(); stats.addValue(s.getMax()); break; case N : v= ((int)s.getN())*1.0; stats.addValue(s.getN()); break; }; //vals.add(v.toString()); }; //LOG.info("vals: "+vals.toString()); return stats; } public SummaryStatistics computeIndividualStats(OWLNamedIndividual i) throws UnknownOWLClassException { //LOG.info("Computing individual stats for "+i.toString()); return this.computeAttributeSetSimilarityStats(this.getAttributesForElement(i)); } public SummaryStatistics computeIndividualStatsForSubgraph(OWLNamedIndividual i,OWLClass c) throws UnknownOWLClassException { return this.computeAttributeSetSimilarityStatsForSubgraph(this.getAttributesForElement(i),c); } public SummaryStatistics computeAttributeSetSimilarityStats(Set<OWLClass> atts) { SummaryStatistics statsPerAttSet = new SummaryStatistics(); // Set<OWLClass> allClasses = getSourceOntology().getClassesInSignature(true); OWLDataFactory g = getSourceOntology().getOWLOntologyManager().getOWLDataFactory(); for (OWLClass c : atts) { Double ic; try { ic = this.getInformationContentForAttribute(c); if (ic == null) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC if (g.getOWLClass(c.getIRI()) != null) { ic = this.getSummaryStatistics().max.getMax(); } else { throw new UnknownOWLClassException(c); } } if (ic.isInfinite() || ic.isNaN()) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC //a different option would be to skip adding this value, //but i'm not sure that's wise ic = this.getSummaryStatistics().max.getMax(); } //LOG.info("IC for "+c.toString()+"is: "+ic); statsPerAttSet.addValue(ic); } catch (UnknownOWLClassException e) { //This is an extra catch here, but really it should be caught upstream. LOG.info("Unknown class "+c.toStringID()+" submitted for summary stats. Removed from calculation."); continue; } } return statsPerAttSet; } public SummaryStatistics computeAttributeSetSimilarityStatsForSubgraph(Set<OWLClass> atts, OWLClass sub) { SummaryStatistics statsPerAttSet = new SummaryStatistics(); // Set<OWLClass> allClasses = getSourceOntology().getClassesInSignature(true); OWLDataFactory g = getSourceOntology().getOWLOntologyManager().getOWLDataFactory(); OWLGraphWrapper gwrap = new OWLGraphWrapper(getSourceOntology()); for (OWLClass c : atts) { Double ic; try { //check if sub is an inferred superclass of the current annotated class //TODO check if i need all of these; this might be expensive and unnecessary if (gwrap.getAncestorsReflexive(c).contains(sub) || getReasoner().getSuperClasses(c, false).containsEntity(sub) || getReasoner().getEquivalentClasses(c).contains(sub)) { ic = this.getInformationContentForAttribute(c); if (ic == null) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC if (g.getOWLClass(c.getIRI()) != null) { ic = this.getSummaryStatistics().max.getMax(); } else { throw new UnknownOWLClassException(c); } } if (ic.isInfinite() || ic.isNaN()) { //If a class hasn't been annotated in the loaded corpus, we will //assume that it is very rare, and assign MaxIC ic = this.getSummaryStatistics().max.getMax(); } //LOG.info("IC for "+c.toString()+"is: "+ic); statsPerAttSet.addValue(ic); } else { //LOG.info("tossing "+c.toString()+"; not a subclass of "+sub.toString()); } } catch (UnknownOWLClassException e) { //This is an extra catch here, but really it should be caught upstream. LOG.info("Unknown class "+c.toStringID()+" submitted for summary stats. Removed from calculation."); continue; } } return statsPerAttSet; } public StatisticalSummaryValues getSystemStats() { // return this.aggregateStatsPerIndividual; return this.overallSummaryStatsPerIndividual.aggregate; } public StatsPerIndividual getSummaryStatistics() { return this.overallSummaryStatsPerIndividual; } public StatsPerIndividual getSummaryStatistics(OWLClass c) { return this.subgraphSummaryStatsPerIndividual.get(c); } public SummaryStatistics getSimStatistics() { SummaryStatistics s = new SummaryStatistics(); //for each metric, we need the min/max/average return s; } public SummaryStatistics computeIndividualSimilarityStats(OWLNamedIndividual i) throws UnknownOWLClassException { SummaryStatistics s = new SummaryStatistics(); return s; } public HashMap<String,SummaryStatistics> getMetricStats(Stat stat) { HashMap<String,SummaryStatistics> s = new HashMap<String,SummaryStatistics>(); switch(stat) { case MIN : s = this.metricStatMins; break; case MAX : s = this.metricStatMaxes; break; case MEAN : s = this.metricStatMeans; break; } return s; } public double calculateOverallAnnotationSufficiencyForIndividual(OWLNamedIndividual i) throws UnknownOWLClassException { return calculateOverallAnnotationSufficiencyForAttributeSet(this.getAttributesForElement(i)); } public double calculateSubgraphAnnotationSufficiencyForIndividual(OWLNamedIndividual i, OWLClass c) throws UnknownOWLClassException { return calculateSubgraphAnnotationSufficiencyForAttributeSet(this.getAttributesForElement(i), c); } public double calculateOverallAnnotationSufficiencyForAttributeSet(Set<OWLClass> atts) throws UnknownOWLClassException { SummaryStatistics stats = computeAttributeSetSimilarityStats(atts); if ((this.getSummaryStatistics() == null) || Double.isNaN(this.getSummaryStatistics().mean.getMean())) { LOG.info("Stats have not been computed yet - doing this now"); this.computeSystemStats(); } // score = mean(atts)/mean(overall) + max(atts)/max(overall) + sum(atts)/mean(sum(overall)) double overall_score = 0.0; Double mean_score = stats.getMean(); Double max_score = stats.getMax(); Double sum_score = stats.getSum(); if (!(mean_score.isNaN() || max_score.isNaN() || sum_score.isNaN())) { mean_score = StatUtils.min(new double[]{(mean_score / this.overallSummaryStatsPerIndividual.mean.getMean()),1.0}); max_score = StatUtils.min(new double[]{(max_score / this.overallSummaryStatsPerIndividual.max.getMax()),1.0}); sum_score = StatUtils.min(new double[]{(sum_score / this.overallSummaryStatsPerIndividual.sum.getMean()),1.0}); overall_score = (mean_score + max_score + sum_score) / 3; } LOG.info("Overall mean: "+mean_score + " max: "+max_score + " sum:"+sum_score + " combined:"+overall_score); return overall_score; } public double calculateSubgraphAnnotationSufficiencyForAttributeSet(Set<OWLClass> atts, OWLClass c) throws UnknownOWLClassException { SummaryStatistics stats = computeAttributeSetSimilarityStatsForSubgraph(atts,c); //TODO: compute statsPerIndividual for this subgraph if ((this.overallSummaryStatsPerIndividual == null ) || (Double.isNaN(this.overallSummaryStatsPerIndividual.max.getMean()))) { LOG.info("Stats have not been computed yet - doing this now"); this.computeSystemStats(); } if (!(this.subgraphSummaryStatsPerIndividual.containsKey(c))) { //only do this once for the whole system, per class requested this.computeSystemStatsForSubgraph(c); } // score = mean(atts)/mean(overall) + max(atts)/max(overall) + sum(atts)/mean(sum(overall)) //TODO: need to normalize this based on the whole corpus double score = 0.0; Double mean_score = stats.getMean(); Double max_score = stats.getMax(); Double sum_score = stats.getSum(); if (!(mean_score.isNaN() || max_score.isNaN() || sum_score.isNaN())) { mean_score = StatUtils.min(new double[]{(mean_score / this.subgraphSummaryStatsPerIndividual.get(c).mean.getMean()),1.0}); max_score = StatUtils.min(new double[]{(max_score / this.subgraphSummaryStatsPerIndividual.get(c).max.getMax()),1.0}); sum_score = StatUtils.min(new double[]{(sum_score / this.subgraphSummaryStatsPerIndividual.get(c).sum.getMean()),1.0}); score = (mean_score + max_score + sum_score) / 3; } LOG.info(getShortId(c)+" n: "+stats.getN()+" mean: "+mean_score + " max: "+max_score + " sum:"+sum_score + " combined:"+score); return score; } public void calculateCombinedScore(ElementPairScores s, double maxMaxIC, double maxBMA) { int maxMaxIC100 = (int)(maxMaxIC * 100); int maxBMA100 = (int)(maxBMA * 100); if (maxMaxIC == 0 || maxBMA == 0) { return; } int pctMaxScore = ((int) (s.maxIC * 10000)) / maxMaxIC100; //TODO should this be using maxBMA100? int pctAvgScore = ((int) (s.bmaSymIC * 10000)) / maxBMA100; s.combinedScore = (pctMaxScore + pctAvgScore)/2; } public OwlSimMetadata getMetadata() { OwlSimMetadata md = new OwlSimMetadata(); md.ontologySet = new OntologySetMetadata(this.getSourceOntology()); md.individualCount = getAllElements().size(); return md; } }
Removed dependency on OWLGraphWrapper - this is a cause of inefficiency. OGW required mainly for working with crossSpeciesPheno.obo, which uses alt_ids for equivalent classes. alt_ids are invisible to an OWL reasoner. If we need this again, we will add a step to expand CSP alt_ids ==> equivalentClasses git-svn-id: f705032614e1ff11fed11a7e506afa6fa6966044@2157 18f1da76-1bb4-b526-5913-e828fe20442d
OWLTools-Sim/src/main/java/owltools/sim2/AbstractOwlSim.java
Removed dependency on OWLGraphWrapper - this is a cause of inefficiency.
Java
mit
4f97e19558e760b799279dc1ad93b84d12081b95
0
lehmann/ArtigoMSM_UFSC
package br.ufsc.lehmann.survey; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import com.google.common.base.Stopwatch; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import br.ufsc.core.IMeasureDistance; import br.ufsc.core.ITrainable; import br.ufsc.core.trajectory.SemanticTrajectory; import br.ufsc.ftsm.base.TrajectorySimilarityCalculator; import br.ufsc.lehmann.msm.artigo.classifiers.validation.Validation; import br.ufsc.lehmann.msm.artigo.clusterers.ClusteringResult; import br.ufsc.lehmann.msm.artigo.clusterers.util.DistanceMatrix.Tuple; import br.ufsc.lehmann.msm.artigo.problems.BasicSemantic; import br.ufsc.lehmann.msm.artigo.problems.IDataReader; import br.ufsc.lehmann.testexecution.Dataset; import br.ufsc.lehmann.testexecution.Datasets; import br.ufsc.lehmann.testexecution.ExecutionPOJO; import br.ufsc.lehmann.testexecution.Groundtruth; import br.ufsc.lehmann.testexecution.Measure; import br.ufsc.lehmann.testexecution.Measures; public abstract class AbstractPairClassClusteringEvaluation { protected void executeDescriptor(String fileName) { ExecutionPOJO execution; try { execution = new Gson().fromJson(new FileReader(fileName), ExecutionPOJO.class); } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { throw new RuntimeException(e); } Dataset dataset = execution.getDataset(); Measure measure = execution.getMeasure(); Groundtruth groundtruth = execution.getGroundtruth(); List<TrajectorySimilarityCalculator<SemanticTrajectory>> similarityCalculator = Measures.createMeasures(measure); BasicSemantic<Object> groundtruthSemantic = new BasicSemantic<>(groundtruth.getIndex().intValue()); IDataReader dataReader = Datasets.createDataset(dataset); List<SemanticTrajectory> data = dataReader.read(); List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairedClasses = pairClasses(data, groundtruthSemantic); for (TrajectorySimilarityCalculator<SemanticTrajectory> calculator : similarityCalculator) { Validation validation = new Validation(groundtruthSemantic, (IMeasureDistance<SemanticTrajectory>) calculator); Stopwatch w = Stopwatch.createStarted(); int errorCount = 0; for (Tuple<Tuple<Object, Object>, List<SemanticTrajectory>> tuple : pairedClasses) { List<SemanticTrajectory> pairData = tuple.getLast(); if(calculator instanceof ITrainable) { ((ITrainable) calculator).train(pairData); } double[][] distances = new double[pairData.size()][pairData.size()]; IMeasureDistance<SemanticTrajectory> measurer = (IMeasureDistance<SemanticTrajectory>) calculator; for (int i = 0; i < pairData.size(); i++) { distances[i][i] = 0; final int finalI = i; IntStream.iterate(0, j -> j + 1).limit(i).parallel().forEach((j) -> { distances[finalI][j] = measurer.distance(pairData.get(finalI), pairData.get(j)); distances[j][finalI] = distances[finalI][j]; }); } ClusteringResult result = validation.cluster(pairData.toArray(new SemanticTrajectory[pairData.size()]), distances, 2); List<List<SemanticTrajectory>> clusteres = result.getClusteres(); for (List<SemanticTrajectory> cluster : clusteres) { Stream<Object> classesInCluster = cluster.stream().map(t -> groundtruthSemantic.getData(t, 0)).distinct(); //se o cluster contiver mais de uma classe este cluster est errado if(classesInCluster.count() != 1) { errorCount++; break; } } } System.out.printf("Elapsed time %d miliseconds\n", w.elapsed(TimeUnit.MILLISECONDS)); System.out.printf("Parameters: '%s'\n", calculator.parametrization()); System.out.printf("Total pair-clusters: '%s'\n", pairedClasses.size()); System.out.printf("Correct pair-clusters: '%s'\n", pairedClasses.size() - errorCount); w = w.stop(); } } private List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairClasses(List<SemanticTrajectory> data, BasicSemantic<Object> semantic) { List<Object> allDistinctClasses = data.stream().map(t -> semantic.getData(t, 0)).distinct().collect(Collectors.toList()); List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> ret = new ArrayList<>(allDistinctClasses.size() * 2); for (int i = 0; i < allDistinctClasses.size(); i++) { for (int j = i + 1; j < allDistinctClasses.size(); j++) { Tuple<Object, Object> pair = new Tuple<>(allDistinctClasses.get(i), allDistinctClasses.get(j)); int finalI = i; int finalJ = j; List<SemanticTrajectory> stream = data.stream().filter(t -> Arrays.asList(allDistinctClasses.get(finalI), allDistinctClasses.get(finalJ)).contains(semantic.getData(t, 0))).collect(Collectors.toList()); ret.add(new Tuple<>(pair, stream)); } } return ret; } }
artigo/src/test/java/br/ufsc/lehmann/survey/AbstractPairClassClusteringEvaluation.java
package br.ufsc.lehmann.survey; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import com.google.common.base.Stopwatch; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import br.ufsc.core.IMeasureDistance; import br.ufsc.core.ITrainable; import br.ufsc.core.trajectory.SemanticTrajectory; import br.ufsc.ftsm.base.TrajectorySimilarityCalculator; import br.ufsc.lehmann.msm.artigo.classifiers.validation.Validation; import br.ufsc.lehmann.msm.artigo.clusterers.ClusteringResult; import br.ufsc.lehmann.msm.artigo.clusterers.util.DistanceMatrix.Tuple; import br.ufsc.lehmann.msm.artigo.problems.BasicSemantic; import br.ufsc.lehmann.msm.artigo.problems.IDataReader; import br.ufsc.lehmann.testexecution.Dataset; import br.ufsc.lehmann.testexecution.Datasets; import br.ufsc.lehmann.testexecution.ExecutionPOJO; import br.ufsc.lehmann.testexecution.Groundtruth; import br.ufsc.lehmann.testexecution.Measure; import br.ufsc.lehmann.testexecution.Measures; public abstract class AbstractPairClassClusteringEvaluation { protected void executeDescriptor(String fileName) { ExecutionPOJO execution; try { execution = new Gson().fromJson(new FileReader(fileName), ExecutionPOJO.class); } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { throw new RuntimeException(e); } Dataset dataset = execution.getDataset(); Measure measure = execution.getMeasure(); Groundtruth groundtruth = execution.getGroundtruth(); List<TrajectorySimilarityCalculator<SemanticTrajectory>> similarityCalculator = Measures.createMeasures(measure); BasicSemantic<Object> groundtruthSemantic = new BasicSemantic<>(groundtruth.getIndex().intValue()); IDataReader dataReader = Datasets.createDataset(dataset); List<SemanticTrajectory> data = dataReader.read(); List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairedClasses = pairClasses(data, groundtruthSemantic); for (TrajectorySimilarityCalculator<SemanticTrajectory> calculator : similarityCalculator) { Validation validation = new Validation(groundtruthSemantic, (IMeasureDistance<SemanticTrajectory>) calculator); Stopwatch w = Stopwatch.createStarted(); int errorCount = 0; for (Tuple<Tuple<Object, Object>, List<SemanticTrajectory>> tuple : pairedClasses) { List<SemanticTrajectory> pairData = tuple.getLast(); if(calculator instanceof ITrainable) { ((ITrainable) calculator).train(pairData); } double[][] distances = new double[pairData.size()][pairData.size()]; IMeasureDistance<SemanticTrajectory> measurer = (IMeasureDistance<SemanticTrajectory>) calculator; for (int i = 0; i < pairData.size(); i++) { distances[i][i] = 0; final int finalI = i; IntStream.iterate(0, j -> j + 1).limit(i).parallel().forEach((j) -> { distances[finalI][j] = measurer.distance(pairData.get(finalI), pairData.get(j)); distances[j][finalI] = distances[finalI][j]; }); } ClusteringResult result = validation.cluster(pairData.toArray(new SemanticTrajectory[pairData.size()]), distances, 2); List<List<SemanticTrajectory>> clusteres = result.getClusteres(); for (List<SemanticTrajectory> cluster : clusteres) { Stream<Object> classesInCluster = cluster.stream().map(t -> groundtruthSemantic.getData(t, 0)).distinct(); //se o cluster contiver mais de uma classe este cluster est errado if(classesInCluster.count() != 1) { errorCount++; } } } System.out.printf("Elapsed time %d miliseconds\n", w.elapsed(TimeUnit.MILLISECONDS)); System.out.printf("Parameters: '%s'\n", calculator.parametrization()); System.out.printf("Total clusters: '%s'\n", pairedClasses.size() * 2); System.out.printf("Correct clusters: '%s'\n", (pairedClasses.size() * 2) - errorCount); w = w.stop(); } } private List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> pairClasses(List<SemanticTrajectory> data, BasicSemantic<Object> semantic) { List<Object> allDistinctClasses = data.stream().map(t -> semantic.getData(t, 0)).distinct().collect(Collectors.toList()); List<Tuple<Tuple<Object, Object>, List<SemanticTrajectory>>> ret = new ArrayList<>(allDistinctClasses.size() * 2); for (int i = 0; i < allDistinctClasses.size(); i++) { for (int j = i + 1; j < allDistinctClasses.size(); j++) { Tuple<Object, Object> pair = new Tuple<>(allDistinctClasses.get(i), allDistinctClasses.get(j)); int finalI = i; int finalJ = j; List<SemanticTrajectory> stream = data.stream().filter(t -> Arrays.asList(allDistinctClasses.get(finalI), allDistinctClasses.get(finalJ)).contains(semantic.getData(t, 0))).collect(Collectors.toList()); ret.add(new Tuple<>(pair, stream)); } } return ret; } }
Fixing pair-clustering validation
artigo/src/test/java/br/ufsc/lehmann/survey/AbstractPairClassClusteringEvaluation.java
Fixing pair-clustering validation
Java
mit
d61f5733dfa2c0a0134a17e1ebd9b15dc5bf3d93
0
spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror
package kawa.lang; import codegen.*; /** * Class used to implement "let" syntax (and variants) for Scheme. * @author Per Bothner */ public class LetExp extends ScopeExp { Expression[] inits; public Expression body; public LetExp (Expression[] i) { inits = i; } public Object eval (Environment env) throws UnboundSymbol, WrongArguments, WrongType, GenericError { throw new GenericError ("internal error - LetExp.eval called"); } /* Recursive helper routine, to store the values on the stack * into the variables in vars, in reverse order. */ private final void store_rest (Compilation comp, Variable vars) { if (vars != null) { store_rest (comp, vars.nextVar ()); SetExp.compile_store ((Declaration) vars, comp); } } public void compile (Compilation comp, int flags) { /* Compile all the initializations, leaving the results on the stack (in reverse order). */ for (int i = 0; i < inits.length; i++) inits[i].compile (comp, 0); comp.method.enterScope (scope); /* Assign the initial values to the proper variables, in reverse order. */ store_rest (comp, firstVar ()); body.compile_with_linenumber (comp, flags); comp.method.pop_scope (); } public void print (java.io.PrintStream ps) { ps.print("(#%let ("); Variable var = firstVar (); int i = 0; for (; var != null; var = var.nextVar ()) { if (i > 0) ps.print(" "); ps.print("("); ps.print(((Declaration) var).string_name()); ps.print(" "); if (var.isArtificial ()) ps.print ("<artificial>"); else { if (inits[i] == null) ps.print ("<null>"); else inits[i].print (ps); i++; } ps.print(")"); } ps.print(") "); body.print (ps); ps.print(")"); } }
kawa/lang/LetExp.java
package kawa.lang; import codegen.*; /** * Class used to implement "let" syntax (and variants) for Scheme. * @author Per Bothner */ public class LetExp extends ScopeExp { Expression[] inits; public Expression body; public LetExp (Expression[] i) { inits = i; } public Object eval (Environment env) throws UnboundSymbol, WrongArguments, WrongType, GenericError { throw new GenericError ("internal error - LetExp.eval called"); } /* Recursive helper routine, to store the values on the stack * into the variables in vars, in reverse order. */ private final void store_rest (Compilation comp, Variable vars) { if (vars != null) { store_rest (comp, vars.nextVar ()); SetExp.compile_store ((Declaration) vars, comp); } } public void compile (Compilation comp, int flags) { /* Compile all they initializations, leaving the results on the stack (in reverse order). */ for (int i = 0; i < inits.length; i++) inits[i].compile (comp, 0); comp.method.enterScope (scope); /* Assign the initial values to the proper variables, in reverse order. */ store_rest (comp, firstVar ()); body.compile_with_linenumber (comp, flags); comp.method.pop_scope (); } public void print (java.io.PrintStream ps) { ps.print("(#%let ("); Variable var = firstVar (); int i = 0; for (; var != null; var = var.nextVar ()) { if (i > 0) ps.print(" "); ps.print("("); ps.print(((Declaration) var).string_name()); ps.print(" "); if (var.isArtificial ()) ps.print ("<artificial>"); else { if (inits[i] == null) ps.print ("<null>"); else inits[i].print (ps); i++; } ps.print(")"); } ps.print(") "); body.print (ps); ps.print(")"); } }
Fix typo in comment. git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@327 5e0a886f-7f45-49c5-bc19-40643649e37f
kawa/lang/LetExp.java
Fix typo in comment.
Java
mit
dfd5501132bce578a94b541df3508fe071b53f73
0
bruno-medeiros/toml4j,mwanji/toml4j
package com.moandjiezana.toml; import static com.moandjiezana.toml.ValueConverterUtils.INVALID; import static com.moandjiezana.toml.ValueConverterUtils.parse; import static com.moandjiezana.toml.ValueConverterUtils.parser; import java.util.List; import java.util.regex.Pattern; class TomlParser { private static final Pattern MULTILINE_ARRAY_REGEX = Pattern.compile("\\s*\\[([^\\]]*)"); private static final Pattern MULTILINE_ARRAY_REGEX_END = Pattern.compile("\\s*\\]"); private static final ValueConverters VALUE_ANALYSIS = new ValueConverters(); private final Results results = new Results(); Results run(String tomlString) { if (tomlString.isEmpty()) { return results; } String[] lines = tomlString.split("[\\n\\r]"); StringBuilder multilineBuilder = new StringBuilder(); Multiline multiline = Multiline.NONE; String key = null; String value = null; for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (line != null && multiline != Multiline.STRING) { line = line.trim(); } if (isComment(line) || line.isEmpty()) { continue; } if (isTableArray(line)) { String tableName = getTableArrayName(line); if (tableName != null) { results.startTableArray(tableName); String afterTableName = line.substring(tableName.length() + 4); if (!isComment(afterTableName)) { results.errors.append("Invalid table array definition: " + line + "\n\n"); } } else { results.errors.append("Invalid table array definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && isTable(line)) { String tableName = getTableName(line); if (tableName != null) { results.startTables(tableName); } else { results.errors.append("Invalid table definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && !line.contains("=")) { results.errors.append("Invalid key definition: " + line); continue; } String[] pair = line.split("=", 2); if (multiline.isNotMultiline() && MULTILINE_ARRAY_REGEX.matcher(pair[1].trim()).matches()) { multiline = Multiline.ARRAY; key = pair[0].trim(); multilineBuilder.append(removeComment(pair[1])); continue; } if (multiline.isNotMultiline() && pair[1].trim().startsWith("\"\"\"")) { multiline = Multiline.STRING; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf("\"\"\"", 3) > -1) { multiline = Multiline.NONE; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } if (multiline == Multiline.ARRAY) { String lineWithoutComment = removeComment(line); multilineBuilder.append(lineWithoutComment); if (MULTILINE_ARRAY_REGEX_END.matcher(lineWithoutComment).matches()) { multiline = Multiline.NONE; value = multilineBuilder.toString(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } else if (multiline == Multiline.STRING) { multilineBuilder.append(line); if (line.contains("\"\"\"")) { multiline = Multiline.NONE; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else { key = pair[0].trim(); value = pair[1].trim(); } if (!isKeyValid(key)) { results.errors.append("Invalid key name: " + key + "\n"); continue; } Object convertedValue = VALUE_ANALYSIS.convert(value); if (convertedValue != INVALID) { results.addValue(key, convertedValue); } else { results.errors.append("Invalid key/value: " + key + " = " + value + "\n"); } } return results; } private boolean isTableArray(String line) { return line.startsWith("[["); } private String getTableArrayName(String line) { List<Object> resultValue = parse(parser().TableArray(), line); if (resultValue == null) { return null; } return (String) resultValue.get(0); } private boolean isTable(String line) { return line.startsWith("["); } private String getTableName(String line) { List<Object> resultValue = parse(parser().Table(), line); if (resultValue == null) { return null; } return (String) resultValue.get(0); } private boolean isKeyValid(String key) { if (key.contains("#") || key.trim().isEmpty()) { return false; } return true; } private boolean isComment(String line) { if (line == null || line.isEmpty()) { return true; } char[] chars = line.toCharArray(); for (char c : chars) { if (Character.isWhitespace(c)) { continue; } return c == '#'; } return false; } private String removeComment(String line) { line = line.trim(); if (line.startsWith("\"")) { int startOfComment = line.indexOf('#', line.lastIndexOf('"')); if (startOfComment > -1) { return line.substring(0, startOfComment - 1).trim(); } } else { int startOfComment = line.indexOf('#'); if (startOfComment > -1) { return line.substring(0, startOfComment - 1).trim(); } } return line; } private static enum Multiline { NONE, ARRAY, STRING; public boolean isNotMultiline() { return this == NONE; } } }
src/main/java/com/moandjiezana/toml/TomlParser.java
package com.moandjiezana.toml; import static com.moandjiezana.toml.ValueConverterUtils.INVALID; import static com.moandjiezana.toml.ValueConverterUtils.parse; import static com.moandjiezana.toml.ValueConverterUtils.parser; import java.util.List; import java.util.regex.Pattern; class TomlParser { private static final Pattern MULTILINE_ARRAY_REGEX = Pattern.compile("\\s*\\[([^\\]]*)"); private static final Pattern MULTILINE_ARRAY_REGEX_END = Pattern.compile("\\s*\\]"); private static final ValueConverters VALUE_ANALYSIS = new ValueConverters(); private final Results results = new Results(); Results run(String tomlString) { if (tomlString.isEmpty()) { return results; } String[] lines = tomlString.split("[\\n\\r]"); StringBuilder multilineBuilder = new StringBuilder(); boolean multiline = false; boolean multilineString = false; String key = null; String value = null; for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (line != null && !multilineString) { line = line.trim(); } if (isComment(line) || line.isEmpty()) { continue; } if (isTableArray(line)) { String tableName = getTableArrayName(line); if (tableName != null) { results.startTableArray(tableName); String afterTableName = line.substring(tableName.length() + 4); if (!isComment(afterTableName)) { results.errors.append("Invalid table array definition: " + line + "\n\n"); } } else { results.errors.append("Invalid table array definition: " + line + "\n\n"); } continue; } if (!multiline && !multilineString && isTable(line)) { String tableName = getTableName(line); if (tableName != null) { results.startTables(tableName); } else { results.errors.append("Invalid table definition: " + line + "\n\n"); } continue; } if (!multiline && !multilineString && !line.contains("=")) { results.errors.append("Invalid key definition: " + line); continue; } String[] pair = line.split("=", 2); if (!multiline && !multilineString && MULTILINE_ARRAY_REGEX.matcher(pair[1].trim()).matches()) { multiline = true; key = pair[0].trim(); multilineBuilder.append(removeComment(pair[1])); continue; } if (!multiline && !multilineString && pair[1].trim().startsWith("\"\"\"")) { multilineString = true; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf("\"\"\"", 3) > -1) { multilineString = false; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } if (multiline) { String lineWithoutComment = removeComment(line); multilineBuilder.append(lineWithoutComment); if (MULTILINE_ARRAY_REGEX_END.matcher(lineWithoutComment).matches()) { multiline = false; value = multilineBuilder.toString(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } else if (multilineString) { multilineBuilder.append(line); if (line.contains("\"\"\"")) { multilineString = false; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else { key = pair[0].trim(); value = pair[1].trim(); } if (!isKeyValid(key)) { results.errors.append("Invalid key name: " + key + "\n"); continue; } Object convertedValue = VALUE_ANALYSIS.convert(value); if (convertedValue != INVALID) { results.addValue(key, convertedValue); } else { results.errors.append("Invalid key/value: " + key + " = " + value + "\n"); } } return results; } private boolean isTableArray(String line) { return line.startsWith("[["); } private String getTableArrayName(String line) { List<Object> resultValue = parse(parser().TableArray(), line); if (resultValue == null) { return null; } return (String) resultValue.get(0); } private boolean isTable(String line) { return line.startsWith("["); } private String getTableName(String line) { List<Object> resultValue = parse(parser().Table(), line); if (resultValue == null) { return null; } return (String) resultValue.get(0); } private boolean isKeyValid(String key) { if (key.contains("#") || key.trim().isEmpty()) { return false; } return true; } private boolean isComment(String line) { if (line == null || line.isEmpty()) { return true; } char[] chars = line.toCharArray(); for (char c : chars) { if (Character.isWhitespace(c)) { continue; } return c == '#'; } return false; } private String removeComment(String line) { line = line.trim(); if (line.startsWith("\"")) { int startOfComment = line.indexOf('#', line.lastIndexOf('"')); if (startOfComment > -1) { return line.substring(0, startOfComment - 1).trim(); } } else { int startOfComment = line.indexOf('#'); if (startOfComment > -1) { return line.substring(0, startOfComment - 1).trim(); } } return line; } }
Introduced Multiline enum to clean TomlParser up a bit
src/main/java/com/moandjiezana/toml/TomlParser.java
Introduced Multiline enum to clean TomlParser up a bit
Java
mit
c1ab72c77f807c59bdfde9357d0cde277856b6dd
0
lanwen/github-plugin,recena/github-plugin,jenkinsci/github-plugin,recena/github-plugin,recena/github-plugin,jenkinsci/github-plugin,lanwen/github-plugin,lanwen/github-plugin,jenkinsci/github-plugin
package org.jenkinsci.plugins.github; import hudson.Plugin; import hudson.init.InitMilestone; import hudson.init.Initializer; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; import org.jenkinsci.plugins.github.migration.Migrator; import javax.annotation.Nonnull; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; /** * Main entry point for this plugin * <p> * Launches migration from old config versions * Contains helper method to get global plugin configuration - {@link #configuration()} * * @author lanwen (Merkushev Kirill) */ public class GitHubPlugin extends Plugin { /** * Launched before plugin starts * Adds alias for {@link GitHubPlugin} to simplify resulting xml. */ public static void addXStreamAliases() { Migrator.enableCompatibilityAliases(); Migrator.enableAliases(); } /** * Launches migration after all extensions have been augmented as we need to ensure that the credentials plugin * has been initialized. * We need ensure that migrator will run after xstream aliases will be added. * @see <a href="https://issues.jenkins-ci.org/browse/JENKINS-36446>JENKINS-36446</a> */ @Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED) public static void runMigrator() throws Exception { new Migrator().migrate(); } @Override public void start() throws Exception { addXStreamAliases(); } /** * Shortcut method for getting instance of {@link GitHubPluginConfig}. * * @return configuration of plugin */ @Nonnull public static GitHubPluginConfig configuration() { return defaultIfNull( GitHubPluginConfig.all().get(GitHubPluginConfig.class), GitHubPluginConfig.EMPTY_CONFIG ); } }
src/main/java/org/jenkinsci/plugins/github/GitHubPlugin.java
package org.jenkinsci.plugins.github; import hudson.Plugin; import hudson.init.Initializer; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; import org.jenkinsci.plugins.github.migration.Migrator; import javax.annotation.Nonnull; import static hudson.init.InitMilestone.PLUGINS_PREPARED; import static hudson.init.InitMilestone.PLUGINS_STARTED; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; /** * Main entry point for this plugin * <p> * Launches migration from old config versions * Contains helper method to get global plugin configuration - {@link #configuration()} * * @author lanwen (Merkushev Kirill) */ public class GitHubPlugin extends Plugin { /** * Launched before plugin starts * Adds alias for {@link GitHubPlugin} to simplify resulting xml. */ public static void addXStreamAliases() { Migrator.enableCompatibilityAliases(); Migrator.enableAliases(); } /** * Launches migration after plugin already initialized. * We need ensure that migrator will run after xstream aliases will be added. */ @Initializer(after = PLUGINS_PREPARED, before = PLUGINS_STARTED) public static void runMigrator() throws Exception { new Migrator().migrate(); } @Override public void start() throws Exception { addXStreamAliases(); } /** * Shortcut method for getting instance of {@link GitHubPluginConfig}. * * @return configuration of plugin */ @Nonnull public static GitHubPluginConfig configuration() { return defaultIfNull( GitHubPluginConfig.all().get(GitHubPluginConfig.class), GitHubPluginConfig.EMPTY_CONFIG ); } }
[FIXED JENKINS-36446] Ensure all plugin extensions are initialized before migration (#150)
src/main/java/org/jenkinsci/plugins/github/GitHubPlugin.java
[FIXED JENKINS-36446] Ensure all plugin extensions are initialized before migration (#150)
Java
mit
17af5ad482956c94c8fe6415184d1b896c1c1a16
0
JosuaKrause/BusVis,JosuaKrause/BusVis
package infovis.embed; import static infovis.VecUtil.*; import infovis.ctrl.Controller; import infovis.data.BusLine; import infovis.data.BusStation; import infovis.data.BusStation.Neighbor; import infovis.data.BusTime; import infovis.embed.pol.Interpolator; import infovis.routing.RoutingManager; import infovis.routing.RoutingManager.CallBack; import infovis.routing.RoutingResult; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Weights the station network after the distance from one start station. * * @author Joschi <[email protected]> */ public final class StationDistance implements Weighter, NodeDrawer { /** * The backing map for the spring nodes. */ private final Map<SpringNode, BusStation> map; /** * The reverse backing map for the spring nodes. */ private final Map<BusStation, SpringNode> rev; /** * The routes from the bus station. */ protected volatile Map<BusStation, RoutingResult> routes; /** * The current reference time. */ protected BusTime time = new BusTime(12, 0); /** * The change time for lines. */ protected int changeTime = 5; /** * The start bus station or <code>null</code> if there is none. */ protected BusStation from; /** * The factor to scale the distances. */ private double factor = .1; /** * The controller. */ protected final Controller ctrl; /** * Creates a station distance without a reference station. * * @param ctrl The controller. */ public StationDistance(final Controller ctrl) { this.ctrl = ctrl; routes = Collections.EMPTY_MAP; map = new HashMap<SpringNode, BusStation>(); rev = new HashMap<BusStation, SpringNode>(); for(final BusStation s : ctrl.getStations()) { final SpringNode node = new SpringNode(); node.setPosition(s.getDefaultX(), s.getDefaultY()); map.put(node, s); rev.put(s, node); } } /** * The predicted next bus station. */ protected volatile BusStation predict; /** * The current waiter thread. */ protected volatile Thread currentCalculator; /** * The fading bus station. */ protected BusStation fadeOut; /** * The fading start time. */ protected long fadingStart; /** * The fading end time. */ protected long fadingEnd; /** * Whether we do fade currently. */ protected boolean fade; /** * The routing manager. */ private final RoutingManager rm = RoutingManager.newInstance(); /** * The animator to be notified when something has changed. */ private Animator animator; /** * Sets the values for the distance. * * @param from The reference station. * @param time The reference time. * @param changeTime The change time. */ public void set(final BusStation from, final BusTime time, final int changeTime) { predict = from; if(from == null) { putSettings(Collections.EMPTY_MAP, from, time, changeTime); return; } final CallBack<Collection<RoutingResult>> cb = new CallBack<Collection<RoutingResult>>() { @Override public void callBack(final Collection<RoutingResult> result) { final Set<BusStation> all = new HashSet<BusStation>( Arrays.asList(ctrl.getAllStations())); final Map<BusStation, RoutingResult> route = new HashMap<BusStation, RoutingResult>(); for(final RoutingResult r : result) { final BusStation end = r.getEnd(); route.put(end, r); all.remove(end); } for(final BusStation s : all) { route.put(s, new RoutingResult(from, s)); } putSettings(route, from, time, changeTime); } }; rm.findRoutes(from, null, time != null ? time : BusTime.now(), changeTime, ctrl.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR, ctrl.getRoutingAlgorithm(), cb); } /** * Puts the new settings. * * @param route The routes. * @param from The start station. * @param time The start time. * @param changeTime The change time. */ protected synchronized void putSettings(final Map<BusStation, RoutingResult> route, final BusStation from, final BusTime time, final int changeTime) { routes = route; if(from != StationDistance.this.from) { fadeOut = StationDistance.this.from; fadingStart = System.currentTimeMillis(); fadingEnd = fadingStart + Interpolator.NORMAL; fade = true; } changes = ((time != null && StationDistance.this.time != null) && (StationDistance.this.time != time || StationDistance.this.changeTime != changeTime)) ? FAST_ANIMATION_CHANGE : NORMAL_CHANGE; StationDistance.this.from = from; StationDistance.this.time = time; StationDistance.this.changeTime = changeTime; animator.forceNextFrame(); } @Override public void setAnimator(final Animator animator) { this.animator = animator; } /** * Whether the weights have changed. */ protected volatile int changes; @Override public int changes() { final int res = changes; changes = NO_CHANGE; return res; } /** * Signals undefined changes. */ public void changeUndefined() { set(from, time, changeTime); } /** * Setter. * * @param from Sets the reference station. */ public void setFrom(final BusStation from) { set(from, time, changeTime); } /** * Getter. * * @return The reference station. */ public BusStation getFrom() { return from; } /** * Setter. * * @param time Sets the reference time. */ public void setTime(final BusTime time) { set(from, time, changeTime); } /** * Getter. * * @return The reference time. */ public BusTime getTime() { return time; } /** * Setter. * * @param changeTime Sets the change time. */ public void setChangeTime(final int changeTime) { set(from, time, changeTime); } /** * Getter. * * @return The change time. */ public int getChangeTime() { return changeTime; } /** * Setter. * * @param factor Sets the distance factor. */ public void setFactor(final double factor) { this.factor = factor; } /** * Getter. * * @return The distance factor. */ public double getFactor() { return factor; } /** * The minimal distance between nodes. */ private double minDist = 15; /** * Setter. * * @param minDist Sets the minimal distance between nodes. */ public void setMinDist(final double minDist) { this.minDist = minDist; } /** * Getter. * * @return The minimal distance between nodes. */ public double getMinDist() { return minDist; } @Override public double weight(final SpringNode f, final SpringNode t) { if(from == null || t == f) return 0; final BusStation fr = map.get(f); if(fr.equals(from)) return 0; final BusStation to = map.get(t); if(to.equals(from)) return factor * routes.get(fr).minutes(); return -minDist; } @Override public boolean hasWeight(final SpringNode f, final SpringNode t) { if(from == null || t == f) return false; final BusStation fr = map.get(f); if(fr.equals(from)) return false; final BusStation to = map.get(t); if(to.equals(from)) return !routes.get(fr).isNotReachable(); return true; } @Override public Iterable<SpringNode> nodes() { return map.keySet(); } @Override public double springConstant() { return 0.75; } @Override public void drawEdges(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final RoutingResult route = routes.get(station); if(route != null && route.isNotReachable()) return; final double x1 = n.getX(); final double y1 = n.getY(); for(final Neighbor edge : station.getNeighbors()) { final BusStation neighbor = edge.station; final SpringNode node = rev.get(neighbor); final RoutingResult otherRoute = routes.get(neighbor); if(otherRoute != null && otherRoute.isNotReachable()) { continue; } final double x2 = node.getX(); final double y2 = node.getY(); int counter = 0; for(final BusLine line : edge.lines) { g.setStroke(new BasicStroke(edge.lines.length - counter, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); g.setColor(line.getColor()); g.draw(new Line2D.Double(x1, y1, x2, y2)); ++counter; } } } @Override public void drawNode(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final RoutingResult route = routes.get(station); if(route != null && route.isNotReachable()) return; final Graphics2D g2 = (Graphics2D) g.create(); g2.setColor(!station.equals(from) ? Color.WHITE : Color.RED); final Shape shape = nodeClickArea(n, true); g2.fill(shape); g2.setStroke(new BasicStroke(.5f)); g2.setColor(Color.BLACK); g2.draw(shape); g2.dispose(); } @Override public void drawLabel(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final double x = n.getX(); final double y = n.getY(); if(station.getNeighbors().length == 2) return; final Graphics2D gfx = (Graphics2D) g.create(); gfx.setColor(Color.BLACK); gfx.translate(x, y); gfx.drawString(station.getName(), 0, 0); gfx.dispose(); } @Override public void dragNode(final SpringNode n, final double startX, final double startY, final double dx, final double dy) { final BusStation station = map.get(n); if(!station.equals(from)) { ctrl.selectStation(station); } n.setPosition(startX + dx, startY + dy); } @Override public void selectNode(final SpringNode n) { final BusStation station = map.get(n); if(!station.equals(from)) { ctrl.selectStation(station); } } @Override public Shape nodeClickArea(final SpringNode n, final boolean real) { final BusStation station = map.get(n); final double r = Math.max(2, station.getMaxDegree() / 2); final double x = real ? n.getX() : n.getPredictX(); final double y = real ? n.getY() : n.getPredictY(); return new Ellipse2D.Double(x - r, y - r, r * 2, r * 2); } @Override public void drawBackground(final Graphics2D g) { final SpringNode ref = getReferenceNode(); if(ref == null && !fade) return; Point2D center; double alpha; if(fade) { final long time = System.currentTimeMillis(); final double t = ((double) time - fadingStart) / ((double) fadingEnd - fadingStart); final double f = Interpolator.SMOOTH.interpolate(t); final SpringNode n = f > 0.5 ? ref : rev.get(fadeOut); center = n != null ? n.getPos() : null; if(t >= 1.0) { alpha = 1; fadeOut = null; fade = false; } else { alpha = f > 0.5 ? (f - 0.5) * 2 : 1 - f * 2; } } else { center = ref.getPos(); alpha = 1; } if(center == null) return; boolean b = true; g.setColor(Color.WHITE); for(int i = MAX_INTERVAL; i > 0; --i) { final Shape circ = getCircle(i, center); final Graphics2D g2 = (Graphics2D) g.create(); if(b) { final double d = (MAX_INTERVAL - i + 2.0) / (MAX_INTERVAL + 2); final double curAlpha = alpha * d; g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) curAlpha)); g2.setColor(Color.LIGHT_GRAY); } b = !b; g2.fill(circ); g2.dispose(); } } @Override public boolean inAnimation() { return fade; } /** * The highest drawn circle interval. */ public static final int MAX_INTERVAL = 12; /** * Getter. * * @param i The interval. * @param center The center of the circle. * @return The circle. */ public Ellipse2D getCircle(final int i, final Point2D center) { final Point2D c = center != null ? center : getReferenceNode().getPos(); final double radius = factor * 5 * i; final double r2 = radius * 2; return new Ellipse2D.Double(c.getX() - radius, c.getY() - radius, r2, r2); } @Override public Point2D getDefaultPosition(final SpringNode node) { final BusStation station = map.get(node); return new Point2D.Double(station.getDefaultX(), station.getDefaultY()); } @Override public SpringNode getReferenceNode() { return from == null ? null : rev.get(from); } @Override public String getTooltipText(final SpringNode node) { final BusStation station = map.get(node); String dist; if(from != null && from != station) { final RoutingResult route = routes.get(station); if(!route.isNotReachable()) { dist = " (" + BusTime.minutesToString(route.minutes()) + ")"; } else { dist = " (not reachable)"; } } else { dist = ""; } return station.getName() + dist; } @Override public void moveMouse(final Point2D cur) { if(from != null) { ctrl.setTitle(BusTime.minutesToString((int) Math.ceil(getLength(subVec(cur, getReferenceNode().getPos())) / factor))); } else { ctrl.setTitle(null); } } /** * Getter. * * @param station The station. * @return The corresponding node. */ public SpringNode getNode(final BusStation station) { return station == null ? null : rev.get(station); } @Override public Rectangle2D getBoundingBox() { Rectangle2D bbox = null; final BusStation s = predict; if(s != null) { final Point2D pos = getNode(s).getPos(); bbox = getCircle(StationDistance.MAX_INTERVAL, pos).getBounds2D(); } else { for(final SpringNode n : nodes()) { final Rectangle2D b = nodeClickArea(n, false).getBounds2D(); if(bbox == null) { bbox = b; } else { bbox.add(b); } } } return bbox; } }
src/main/java/infovis/embed/StationDistance.java
package infovis.embed; import static infovis.VecUtil.*; import infovis.ctrl.Controller; import infovis.data.BusLine; import infovis.data.BusStation; import infovis.data.BusStation.Neighbor; import infovis.data.BusTime; import infovis.embed.pol.Interpolator; import infovis.routing.RoutingManager; import infovis.routing.RoutingManager.CallBack; import infovis.routing.RoutingResult; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Weights the station network after the distance from one start station. * * @author Joschi <[email protected]> */ public final class StationDistance implements Weighter, NodeDrawer { /** * The backing map for the spring nodes. */ private final Map<SpringNode, BusStation> map; /** * The reverse backing map for the spring nodes. */ private final Map<BusStation, SpringNode> rev; /** * The routes from the bus station. */ protected volatile Map<BusStation, RoutingResult> routes; /** * The current reference time. */ protected BusTime time = new BusTime(12, 0); /** * The change time for lines. */ protected int changeTime = 5; /** * The start bus station or <code>null</code> if there is none. */ protected BusStation from; /** * The factor to scale the distances. */ private double factor = .1; /** * The controller. */ protected final Controller ctrl; /** * Creates a station distance without a reference station. * * @param ctrl The controller. */ public StationDistance(final Controller ctrl) { this.ctrl = ctrl; routes = Collections.EMPTY_MAP; map = new HashMap<SpringNode, BusStation>(); rev = new HashMap<BusStation, SpringNode>(); for(final BusStation s : ctrl.getStations()) { final SpringNode node = new SpringNode(); node.setPosition(s.getDefaultX(), s.getDefaultY()); map.put(node, s); rev.put(s, node); } } /** * The predicted next bus station. */ protected volatile BusStation predict; /** * The current waiter thread. */ protected volatile Thread currentCalculator; /** * The fading bus station. */ protected BusStation fadeOut; /** * The fading start time. */ protected long fadingStart; /** * The fading end time. */ protected long fadingEnd; /** * Whether we do fade currently. */ protected boolean fade; /** * The routing manager. */ private final RoutingManager rm = RoutingManager.newInstance(); /** * The animator to be notified when something has changed. */ private Animator animator; /** * Sets the values for the distance. * * @param from The reference station. * @param time The reference time. * @param changeTime The change time. */ public void set(final BusStation from, final BusTime time, final int changeTime) { predict = from; if(from == null) { putSettings(Collections.EMPTY_MAP, from, time, changeTime); return; } final CallBack<Collection<RoutingResult>> cb = new CallBack<Collection<RoutingResult>>() { @Override public void callBack(final Collection<RoutingResult> result) { final Set<BusStation> all = new HashSet<BusStation>( Arrays.asList(ctrl.getAllStations())); final Map<BusStation, RoutingResult> route = new HashMap<BusStation, RoutingResult>(); for(final RoutingResult r : result) { final BusStation end = r.getEnd(); route.put(end, r); all.remove(end); } for(final BusStation s : all) { route.put(s, new RoutingResult(from, s)); } putSettings(route, from, time, changeTime); } }; rm.findRoutes(from, null, time != null ? time : BusTime.now(), changeTime, ctrl.getMaxTimeHours() * BusTime.MINUTES_PER_HOUR, ctrl.getRoutingAlgorithm(), cb); } /** * Puts the new settings. * * @param route The routes. * @param from The start station. * @param time The start time. * @param changeTime The change time. */ protected synchronized void putSettings(final Map<BusStation, RoutingResult> route, final BusStation from, final BusTime time, final int changeTime) { routes = route; if(from != StationDistance.this.from) { fadeOut = StationDistance.this.from; fadingStart = System.currentTimeMillis(); fadingEnd = fadingStart + Interpolator.NORMAL; fade = true; } changes = ((time != null && StationDistance.this.time != null) && (StationDistance.this.time != time || StationDistance.this.changeTime != changeTime)) ? FAST_ANIMATION_CHANGE : NORMAL_CHANGE; StationDistance.this.from = from; StationDistance.this.time = time; StationDistance.this.changeTime = changeTime; animator.forceNextFrame(); } @Override public void setAnimator(final Animator animator) { this.animator = animator; } /** * Whether the weights have changed. */ protected volatile int changes; @Override public int changes() { final int res = changes; changes = NO_CHANGE; return res; } /** * Signals undefined changes. */ public void changeUndefined() { set(from, time, changeTime); } /** * Setter. * * @param from Sets the reference station. */ public void setFrom(final BusStation from) { set(from, time, changeTime); } /** * Getter. * * @return The reference station. */ public BusStation getFrom() { return from; } /** * Setter. * * @param time Sets the reference time. */ public void setTime(final BusTime time) { set(from, time, changeTime); } /** * Getter. * * @return The reference time. */ public BusTime getTime() { return time; } /** * Setter. * * @param changeTime Sets the change time. */ public void setChangeTime(final int changeTime) { set(from, time, changeTime); } /** * Getter. * * @return The change time. */ public int getChangeTime() { return changeTime; } /** * Setter. * * @param factor Sets the distance factor. */ public void setFactor(final double factor) { this.factor = factor; } /** * Getter. * * @return The distance factor. */ public double getFactor() { return factor; } /** * The minimal distance between nodes. */ private double minDist = 15; /** * Setter. * * @param minDist Sets the minimal distance between nodes. */ public void setMinDist(final double minDist) { this.minDist = minDist; } /** * Getter. * * @return The minimal distance between nodes. */ public double getMinDist() { return minDist; } @Override public double weight(final SpringNode f, final SpringNode t) { if(from == null || t == f) return 0; final BusStation fr = map.get(f); if(fr.equals(from)) return 0; final BusStation to = map.get(t); if(to.equals(from)) return factor * routes.get(fr).minutes(); return -minDist; } @Override public boolean hasWeight(final SpringNode f, final SpringNode t) { if(from == null || t == f) return false; final BusStation fr = map.get(f); if(fr.equals(from)) return false; final BusStation to = map.get(t); if(to.equals(from)) return !routes.get(fr).isNotReachable(); return true; } @Override public Iterable<SpringNode> nodes() { return map.keySet(); } @Override public double springConstant() { return 0.75; } @Override public void drawEdges(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final RoutingResult route = routes.get(station); if(route != null && route.isNotReachable()) return; // // if(from != null) { // routes.get(station).getFrom(); // } // final double x1 = n.getX(); final double y1 = n.getY(); for(final Neighbor edge : station.getNeighbors()) { final BusStation neighbor = edge.station; final SpringNode node = rev.get(neighbor); final RoutingResult otherRoute = routes.get(neighbor); if(otherRoute != null && otherRoute.isNotReachable()) { continue; } final double x2 = node.getX(); final double y2 = node.getY(); int counter = 0; for(final BusLine line : edge.lines) { g.setStroke(new BasicStroke(edge.lines.length - counter, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); g.setColor(line.getColor()); g.draw(new Line2D.Double(x1, y1, x2, y2)); ++counter; } } } @Override public void drawNode(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final RoutingResult route = routes.get(station); if(route != null && route.isNotReachable()) return; final Graphics2D g2 = (Graphics2D) g.create(); g2.setColor(!station.equals(from) ? Color.WHITE : Color.RED); final Shape shape = nodeClickArea(n, true); g2.fill(shape); g2.setStroke(new BasicStroke(.5f)); g2.setColor(Color.BLACK); g2.draw(shape); g2.dispose(); } @Override public void drawLabel(final Graphics2D g, final SpringNode n) { final BusStation station = map.get(n); final double x = n.getX(); final double y = n.getY(); if(station.getNeighbors().length == 2) return; final Graphics2D gfx = (Graphics2D) g.create(); gfx.setColor(Color.BLACK); gfx.translate(x, y); gfx.drawString(station.getName(), 0, 0); gfx.dispose(); } @Override public void dragNode(final SpringNode n, final double startX, final double startY, final double dx, final double dy) { final BusStation station = map.get(n); if(!station.equals(from)) { ctrl.selectStation(station); } n.setPosition(startX + dx, startY + dy); } @Override public void selectNode(final SpringNode n) { final BusStation station = map.get(n); if(!station.equals(from)) { ctrl.selectStation(station); } } @Override public Shape nodeClickArea(final SpringNode n, final boolean real) { final BusStation station = map.get(n); final double r = Math.max(2, station.getMaxDegree() / 2); final double x = real ? n.getX() : n.getPredictX(); final double y = real ? n.getY() : n.getPredictY(); return new Ellipse2D.Double(x - r, y - r, r * 2, r * 2); } @Override public void drawBackground(final Graphics2D g) { final SpringNode ref = getReferenceNode(); if(ref == null && !fade) return; Point2D center; Color col; if(fade) { final long time = System.currentTimeMillis(); final double t = ((double) time - fadingStart) / ((double) fadingEnd - fadingStart); final double f = Interpolator.SMOOTH.interpolate(t); final SpringNode n = f > 0.5 ? ref : rev.get(fadeOut); center = n != null ? n.getPos() : null; final double split = f > 0.5 ? (f - 0.5) * 2 : 1 - f * 2; final int alpha = Math.max(0, Math.min((int) (split * 255), 255)); col = new Color(alpha << 24 | (Color.LIGHT_GRAY.getRGB() & 0x00ffffff), true); if(t >= 1.0) { fadeOut = null; fade = false; } } else { center = ref.getPos(); col = Color.LIGHT_GRAY; } if(center == null) return; boolean b = true; for(int i = MAX_INTERVAL; i > 0; --i) { final Shape circ = getCircle(i, center); final double d = (MAX_INTERVAL - i + 2.0) / (MAX_INTERVAL + 2); final int oldAlpha = col.getAlpha(); final int newAlpha = (int) Math.round(oldAlpha * d); final Color c = new Color(newAlpha << 24 | (col.getRGB() & 0x00ffffff), true); g.setColor(b ? c : Color.WHITE); b = !b; g.fill(circ); } } @Override public boolean inAnimation() { return fade; } /** * The highest drawn circle interval. */ public static final int MAX_INTERVAL = 12; /** * Getter. * * @param i The interval. * @param center The center of the circle. * @return The circle. */ public Ellipse2D getCircle(final int i, final Point2D center) { final Point2D c = center != null ? center : getReferenceNode().getPos(); final double radius = factor * 5 * i; final double r2 = radius * 2; return new Ellipse2D.Double(c.getX() - radius, c.getY() - radius, r2, r2); } @Override public Point2D getDefaultPosition(final SpringNode node) { final BusStation station = map.get(node); return new Point2D.Double(station.getDefaultX(), station.getDefaultY()); } @Override public SpringNode getReferenceNode() { return from == null ? null : rev.get(from); } @Override public String getTooltipText(final SpringNode node) { final BusStation station = map.get(node); String dist; if(from != null && from != station) { final RoutingResult route = routes.get(station); if(!route.isNotReachable()) { dist = " (" + BusTime.minutesToString(route.minutes()) + ")"; } else { dist = " (not reachable)"; } } else { dist = ""; } return station.getName() + dist; } @Override public void moveMouse(final Point2D cur) { if(from != null) { ctrl.setTitle(BusTime.minutesToString((int) Math.ceil(getLength(subVec(cur, getReferenceNode().getPos())) / factor))); } else { ctrl.setTitle(null); } } /** * Getter. * * @param station The station. * @return The corresponding node. */ public SpringNode getNode(final BusStation station) { return station == null ? null : rev.get(station); } @Override public Rectangle2D getBoundingBox() { Rectangle2D bbox = null; final BusStation s = predict; if(s != null) { final Point2D pos = getNode(s).getPos(); bbox = getCircle(StationDistance.MAX_INTERVAL, pos).getBounds2D(); } else { for(final SpringNode n : nodes()) { final Rectangle2D b = nodeClickArea(n, false).getBounds2D(); if(bbox == null) { bbox = b; } else { bbox.add(b); } } } return bbox; } }
using alpha composite for fading circles
src/main/java/infovis/embed/StationDistance.java
using alpha composite for fading circles
Java
mit
ad665927fbc4625238c7e481e570545f989363fb
0
ceciliavanin/Trabalho
package br.univel; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.stream.StreamResult; public class GravaXml { public String gravaXml (Object obj){ StringWriter out = new StringWriter(); JAXBContext context; Class<?> classe = obj.getClass(); try { context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(obj, new StreamResult(out)); String xml = out.toString(); FileWriter fw = new FileWriter(classe.getSimpleName() +".xml"); fw.write(xml); fw.close(); return out.toString(); } catch (JAXBException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } }
Trabalho154143/src/main/java/br/univel/GravaXml.java
package br.univel; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.stream.StreamResult; public class GravaXml { public String gravaXml (Object obj){ StringWriter out = new StringWriter(); JAXBContext context; Class<?> classe = obj.getClass(); try { context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(obj, new StreamResult(out)); String xml = out.toString(); FileWriter fw = new FileWriter(classe.getSimpleName() +".xml"); fw.write(xml); fw.close(); } catch (JAXBException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return out.toString(); } }
Cocertando classe GravaXml
Trabalho154143/src/main/java/br/univel/GravaXml.java
Cocertando classe GravaXml
Java
mit
7eb51dc5bbe315ff524d8ef7c772ac8f77a0f8f2
0
tkuhn/nanopub-server,tkuhn/nanopub-server
package ch.tkuhn.nanopub.server; import java.io.IOException; import javax.servlet.http.HttpServletResponse; public class MainPage extends Page { public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException { MainPage obj = new MainPage(req, httpResp); obj.show(); } public MainPage(ServerRequest req, HttpServletResponse httpResp) { super(req, httpResp); } public void show() throws IOException { String format; String ext = getReq().getExtension(); if ("json".equals(ext)) { format = "application/json"; } else if (ext == null || "html".equals(ext)) { String suppFormats = "application/json,text/html"; format = Utils.getMimeType(getHttpReq(), suppFormats); } else { getResp().sendError(400, "Invalid request: " + getReq().getFullRequest()); return; } if ("application/json".equals(format)) { println(ServerConf.getInfo().asJson()); } else { printHtmlHeader("Nanopub Server"); println("<h1>Nanopub Server</h1>"); String url = ServerConf.getInfo().getPublicUrl(); if (url == null || url.isEmpty()) { url = "<em>(unknown)</em>"; } else { url = "<a href=\"" + url + "\">" + url + "</a>"; } println("<p>Public URL: <span class=\"code\">" + url + "</span></p>"); String admin = ServerConf.getInfo().getAdmin(); if (admin == null || admin.isEmpty()) { admin = "<em>(unknown)</em>"; } else { admin = escapeHtml(admin); } println("<p>Administrator: " + admin + "</p>"); println("<p>Content:"); println("<ul>"); long npc = NanopubDb.get().getNanopubCollection().count(); println("<li><a href=\"+\">Nanopubs: " + npc + "</a></li>"); long peerc = NanopubDb.get().getPeerCollection().count(); println("<li><a href=\"peers\">Peers: " + peerc + "</a></li>"); println("</ul>"); println("<p>Actions:"); println("<ul>"); ServerInfo i = ServerConf.getInfo(); println("<li>Post nanopubs: <em>" + (i.isPostNanopubsEnabled() ? "" : "not") + " supported</em></li>"); println("<li>Post peers: <em>" + (i.isPostPeersEnabled() ? "" : "not") + " supported</em></li>"); println("</ul>"); println("<p>[ <a href=\".json\">json</a> ]</p>"); printHtmlFooter(); } getResp().setContentType(format); } }
src/main/java/ch/tkuhn/nanopub/server/MainPage.java
package ch.tkuhn.nanopub.server; import java.io.IOException; import javax.servlet.http.HttpServletResponse; public class MainPage extends Page { public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException { MainPage obj = new MainPage(req, httpResp); obj.show(); } public MainPage(ServerRequest req, HttpServletResponse httpResp) { super(req, httpResp); } public void show() throws IOException { String format; String ext = getReq().getExtension(); if ("json".equals(ext)) { format = "application/json"; } else if (ext == null || "html".equals(ext)) { String suppFormats = "application/json,text/html"; format = Utils.getMimeType(getHttpReq(), suppFormats); } else { getResp().sendError(400, "Invalid request: " + getReq().getFullRequest()); return; } if ("application/json".equals(format)) { println(ServerConf.getInfo().asJson()); } else { printHtmlHeader("Nanopub Server"); println("<h1>Nanopub Server</h1>"); String url = ServerConf.getInfo().getPublicUrl(); if (url == null || url.isEmpty()) { url = "<em>(unknown)</em>"; } else { url = "<a href=\"" + url + "\">" + url + "</a>"; } println("<p>Public URL: <span class=\"code\">" + url + "</span></p>"); String admin = ServerConf.getInfo().getAdmin(); if (admin == null || admin.isEmpty()) { admin = "<em>(unknown)</em>"; } else { admin = escapeHtml(admin); } println("<p>Administrator: " + admin + "</p>"); println("<p>Content:"); println("<ul>"); long npc = NanopubDb.get().getNanopubCollection().count(); println("<li><a href=\"+\">Nanopubs: " + npc + "</a></li>"); long peerc = NanopubDb.get().getPeerCollection().count(); println("<li><a href=\"peers\">Peers: " + peerc + "</a></li>"); println("</ul>"); println("<p>[ <a href=\".json\">json</a> ]</p>"); printHtmlFooter(); } getResp().setContentType(format); } }
Show available actions in HTML of main page
src/main/java/ch/tkuhn/nanopub/server/MainPage.java
Show available actions in HTML of main page
Java
mit
8563e36523ba80f11a5787a02a1fadff2c21df6c
0
hsz/idea-gitignore,hsz/idea-gitignore
/* * The MIT License (MIT) * * Copyright (c) 2017 hsz Jakub Chrzanowski <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mobi.hsz.idea.gitignore.util; import com.intellij.util.containers.ContainerUtil; import org.apache.commons.lang.builder.HashCodeBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Util class to speed up and limit regex operation on the files paths. * * @author Jakub Chrzanowski <[email protected]> * @since 1.3.1 */ public class MatcherUtil { /** Stores calculated matching results. */ private static final HashMap<Integer, Boolean> CACHE = ContainerUtil.newHashMap(); /** Private constructor to prevent creating {@link Icons} instance. */ private MatcherUtil() { } /** * Extracts alphanumeric parts from the regex pattern and checks if any of them is contained in the tested path. * Looking for the parts speed ups the matching and prevents from running whole regex on the string. * * @param matcher to explode * @param path to check * @return path matches the pattern */ public static boolean match(@Nullable Matcher matcher, @Nullable String path) { if (matcher == null || path == null) { return false; } int hashCode = new HashCodeBuilder().append(matcher.pattern()).append(path).toHashCode(); if (!CACHE.containsKey(hashCode)) { final String[] parts = getParts(matcher); boolean result = false; if (parts.length == 0 || matchAllParts(parts, path)) { try { result = matcher.reset(path).find(); } catch (StringIndexOutOfBoundsException ignored) { } } CACHE.put(hashCode, result); } return CACHE.get(hashCode); } /** * Checks if given path contains all of the path parts. * * @param parts that should be contained in path * @param path to check * @return path contains all parts */ public static boolean matchAllParts(@Nullable String[] parts, @Nullable String path) { if (parts == null || path == null) { return false; } int index = -1; for (String part : parts) { index = path.indexOf(part, index); if (index == -1) { return false; } } return true; } /** * Checks if given path contains any of the path parts. * * @param parts that should be contained in path * @param path to check * @return path contains any of the parts */ public static boolean matchAnyPart(@Nullable String[] parts, @Nullable String path) { if (parts == null || path == null) { return false; } for (String part : parts) { if (path.contains(part)) { return true; } } return false; } /** * Extracts alphanumeric parts from {@link Matcher} pattern. * * @param matcher to handle * @return extracted parts */ @NotNull public static String[] getParts(@Nullable Matcher matcher) { if (matcher == null) { return new String[0]; } return getParts(matcher.pattern()); } /** * Extracts alphanumeric parts from {@link Pattern}. * * @param pattern to handle * @return extracted parts */ @NotNull public static String[] getParts(@Nullable Pattern pattern) { if (pattern == null) { return new String[0]; } final List<String> parts = ContainerUtil.newArrayList(); final String sPattern = pattern.toString(); String part = ""; boolean inSquare = false; for (int i = 0; i < sPattern.length(); i++) { char ch = sPattern.charAt(i); if (!inSquare && Character.isLetterOrDigit(ch)) { part += sPattern.charAt(i); } else if (!part.isEmpty()) { parts.add(part); part = ""; } inSquare = ch != ']' && ((ch == '[') || inSquare); } return parts.toArray(new String[parts.size()]); } }
src/mobi/hsz/idea/gitignore/util/MatcherUtil.java
/* * The MIT License (MIT) * * Copyright (c) 2017 hsz Jakub Chrzanowski <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mobi.hsz.idea.gitignore.util; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Util class to speed up and limit regex operation on the files paths. * * @author Jakub Chrzanowski <[email protected]> * @since 1.3.1 */ public class MatcherUtil { /** Private constructor to prevent creating {@link Icons} instance. */ private MatcherUtil() { } /** * Extracts alphanumeric parts from the regex pattern and checks if any of them is contained in the tested path. * Looking for the parts speed ups the matching and prevents from running whole regex on the string. * * @param matcher to explode * @param path to check * @return path matches the pattern */ public static boolean match(@Nullable Matcher matcher, @Nullable String path) { if (matcher == null || path == null) { return false; } String[] parts = getParts(matcher); if (parts.length > 0 && !matchAllParts(parts, path)) { return false; } try { return matcher.reset(path).find(); } catch (StringIndexOutOfBoundsException e) { return false; } } /** * Checks if given path contains all of the path parts. * * @param parts that should be contained in path * @param path to check * @return path contains all parts */ public static boolean matchAllParts(@Nullable String[] parts, @Nullable String path) { if (parts == null || path == null) { return false; } int index = -1; for (String part : parts) { index = path.indexOf(part, index); if (index == -1) { return false; } } return true; } /** * Checks if given path contains any of the path parts. * * @param parts that should be contained in path * @param path to check * @return path contains any of the parts */ public static boolean matchAnyPart(@Nullable String[] parts, @Nullable String path) { if (parts == null || path == null) { return false; } for (String part : parts) { if (path.contains(part)) { return true; } } return false; } /** * Extracts alphanumeric parts from {@link Matcher} pattern. * * @param matcher to handle * @return extracted parts */ @NotNull public static String[] getParts(@Nullable Matcher matcher) { if (matcher == null) { return new String[0]; } return getParts(matcher.pattern()); } /** * Extracts alphanumeric parts from {@link Pattern}. * * @param pattern to handle * @return extracted parts */ @NotNull public static String[] getParts(@Nullable Pattern pattern) { if (pattern == null) { return new String[0]; } final List<String> parts = ContainerUtil.newArrayList(); final String sPattern = pattern.toString(); String part = ""; boolean inSquare = false; for (int i = 0; i < sPattern.length(); i++) { char ch = sPattern.charAt(i); if (!inSquare && Character.isLetterOrDigit(ch)) { part += sPattern.charAt(i); } else if (!part.isEmpty()) { parts.add(part); part = ""; } inSquare = ch != ']' && ((ch == '[') || inSquare); } return parts.toArray(new String[parts.size()]); } }
#415 - cache calculated matching results
src/mobi/hsz/idea/gitignore/util/MatcherUtil.java
#415 - cache calculated matching results
Java
mit
b7e7ac93bbd2f3fab2d1fa957dfaf286b4fa7290
0
JetBrains/ideavim,JetBrains/ideavim
package com.maddyhome.idea.vim.option; /* * IdeaVim - A Vim emulator plugin for IntelliJ Idea * Copyright (C) 2003 Rick Maddy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.StringTokenizer; import java.util.List; /** * This is an option that accepts an arbitrary list of values */ public class ListOption extends TextOption { /** * Creates the option * @param name The name of the option * @param abbrev The short name * @param dflt The option's default values * @param pattern A regular expression that is used to validate new values. null if no check needed */ ListOption(String name, String abbrev, String[] dflt, String pattern) { super(name, abbrev); this.dflt = new ArrayList(Arrays.asList(dflt)); this.value = new ArrayList(this.dflt); this.pattern = pattern; } /** * Gets the value of the option as a comma separated list of values * @return The option's value */ public String getValue() { StringBuffer res = new StringBuffer(); int cnt = 0; for (Iterator iterator = value.iterator(); iterator.hasNext(); cnt++) { String s = (String)iterator.next(); if (cnt > 0) { res.append(","); } res.append(s); } return res.toString(); } /** * Gets the option's values as a list * @return The option's values */ public List values() { return value; } /** * Determines if this option has all the values listed on the supplied value * @param val A comma separated list of values to look for * @return True if all the supplied values are set in this option, false if not */ public boolean contains(String val) { return value.containsAll(parseVals(val)); } /** * Sets this option to contain just the supplied values. If any of the supplied values are invalid then this * option is not updated at all. * @param val A comma separated list of values * @return True if all the supplied values were correct, false if not */ public boolean set(String val) { return set(parseVals(val)); } /** * Adds the supplied values to the current list of values. If any of the supplied values are invalid then this * option is not updated at all. * @param val A comma separated list of values * @return True if all the supplied values were correct, false if not */ public boolean append(String val) { return append(parseVals(val)); } /** * Adds the supplied values to the start of the current list of values. If any of the supplied values are invalid * then this option is not updated at all. * @param val A comma separated list of values * @return True if all the supplied values were correct, false if not */ public boolean prepend(String val) { return prepend(parseVals(val)); } /** * Removes the supplied values from the current list of values. If any of the supplied values are invalid then this * option is not updated at all. * @param val A comma separated list of values * @return True if all the supplied values were correct, false if not */ public boolean remove(String val) { return remove(parseVals(val)); } protected boolean set(ArrayList vals) { if (vals == null) { return false; } value = vals; fireOptionChangeEvent(); return true; } protected boolean append(ArrayList vals) { if (vals == null) { return false; } value.addAll(vals); fireOptionChangeEvent(); return true; } protected boolean prepend(ArrayList vals) { if (vals == null) { return false; } value.addAll(0, vals); fireOptionChangeEvent(); return true; } protected boolean remove(ArrayList vals) { if (vals == null) { return false; } value.removeAll(vals); fireOptionChangeEvent(); return true; } protected ArrayList parseVals(String val) { ArrayList res = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(val, ","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken().trim(); if (pattern == null || token.matches(pattern)) { res.add(token); } else { return null; } } return res; } /** * Checks to see if the current value of the option matches the default value * @return True if equal to default, false if not */ public boolean isDefault() { return dflt.equals(value); } /** * Resets the option to its default value */ public void resetDefault() { if (!dflt.equals(value)) { value = new ArrayList(dflt); fireOptionChangeEvent(); } } /** * Gets the string representation appropriate for output to :set all * @return The option as a string {name}={value list} */ public String toString() { StringBuffer res = new StringBuffer(); res.append(" "); res.append(getName()); res.append("="); res.append(getValue()); return res.toString(); } protected ArrayList dflt; protected ArrayList value; protected String pattern; }
src/com/maddyhome/idea/vim/option/ListOption.java
package com.maddyhome.idea.vim.option; /* * IdeaVim - A Vim emulator plugin for IntelliJ Idea * Copyright (C) 2003 Rick Maddy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.StringTokenizer; /** * */ public class ListOption extends TextOption { ListOption(String name, String abbrev, String[] dflt) { super(name, abbrev); this.dflt = new ArrayList(Arrays.asList(dflt)); this.value = new ArrayList(this.dflt); } public String getValue() { StringBuffer res = new StringBuffer(); int cnt = 0; for (Iterator iterator = value.iterator(); iterator.hasNext(); cnt++) { String s = (String)iterator.next(); if (cnt > 0) { res.append(","); } res.append(s); } return res.toString(); } public boolean contains(String val) { return value.containsAll(parseVals(val)); } public boolean set(String val) { return set(parseVals(val)); } public boolean append(String val) { return append(parseVals(val)); } public boolean prepend(String val) { return prepend(parseVals(val)); } public boolean remove(String val) { return remove(parseVals(val)); } protected boolean set(ArrayList vals) { value = vals; return true; } protected boolean append(ArrayList vals) { value.addAll(vals); return true; } protected boolean prepend(ArrayList vals) { value.addAll(0, vals); return true; } protected boolean remove(ArrayList vals) { value.removeAll(vals); return true; } protected ArrayList parseVals(String val) { ArrayList res = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken().trim(); res.add(token); } return res; } public boolean isDefault() { return dflt.equals(value); } public void resetDefault() { value = new ArrayList(dflt); } public String toString() { StringBuffer res = new StringBuffer(); res.append(" "); res.append(getName()); res.append("="); res.append(getValue()); return res.toString(); } protected ArrayList dflt; protected ArrayList value; }
*** empty log message ***
src/com/maddyhome/idea/vim/option/ListOption.java
*** empty log message ***
Java
agpl-3.0
f031628f830c881484316a4dfd44333fdfa1c044
0
juanibdn/jPOS,yinheli/jPOS,fayezasar/jPOS,barspi/jPOS,yinheli/jPOS,poynt/jPOS,c0deh4xor/jPOS,sebastianpacheco/jPOS,jpos/jPOS,poynt/jPOS,sebastianpacheco/jPOS,imam-san/jPOS-1,fayezasar/jPOS,chhil/jPOS,alcarraz/jPOS,imam-san/jPOS-1,c0deh4xor/jPOS,juanibdn/jPOS,bharavi/jPOS,alcarraz/jPOS,jpos/jPOS,atancasis/jPOS,juanibdn/jPOS,atancasis/jPOS,barspi/jPOS,yinheli/jPOS,chhil/jPOS,imam-san/jPOS-1,barspi/jPOS,bharavi/jPOS,alcarraz/jPOS,poynt/jPOS,bharavi/jPOS,jpos/jPOS,atancasis/jPOS,sebastianpacheco/jPOS,c0deh4xor/jPOS
/* * Copyright (c) 2000 jPOS.org. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the jPOS project * (http://www.jpos.org/)". Alternately, this acknowledgment may * appear in the software itself, if and wherever such third-party * acknowledgments normally appear. * * 4. The names "jPOS" and "jPOS.org" must not be used to endorse * or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "jPOS", * nor may "jPOS" appear in their name, without prior written * permission of the jPOS project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the jPOS Project. For more * information please see <http://www.jpos.org/>. */ package org.jpos.iso; import java.io.Externalizable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.util.BitSet; import java.util.Enumeration; import java.util.Hashtable; import org.jpos.iso.header.BaseHeader; import org.jpos.iso.packager.XMLPackager; import org.jpos.util.Loggeable; /** * implements <b>Composite</b> * whithin a <b>Composite pattern</b> * * @author [email protected] * @version $Id$ * @see ISOComponent * @see ISOField */ public class ISOMsg extends ISOComponent implements Cloneable, Loggeable, Externalizable { protected Hashtable fields; protected int maxField; protected ISOPackager packager; protected boolean dirty, maxFieldDirty; protected int direction; protected ISOHeader header; protected int fieldNumber = -1; public static final int INCOMING = 1; public static final int OUTGOING = 2; private static final long serialVersionUID = 4306251831901413975L; private WeakReference sourceRef; /** * Creates an ISOMsg */ public ISOMsg () { fields = new Hashtable (); maxField = -1; dirty = true; maxFieldDirty=true; direction = 0; header = null; } /** * Creates a nested ISOMsg */ public ISOMsg (int fieldNumber) { this(); setFieldNumber (fieldNumber); } /** * changes this Component field number<br> * Use with care, this method does not change * any reference held by a Composite. * @param fieldNumber new field number */ public void setFieldNumber (int fieldNumber) { this.fieldNumber = fieldNumber; } /** * Creates an ISOMsg with given mti * @param mti Msg's MTI */ public ISOMsg (String mti) { this(); try { setMTI (mti); } catch (ISOException e) { // should never happen } } /** * Sets the direction information related to this message * @param direction can be either ISOMsg.INCOMING or ISOMsg.OUTGOING */ public void setDirection(int direction) { this.direction = direction; } /** * Sets an optional message header image * @param b header image */ public void setHeader(byte[] b) { header = new BaseHeader (b); } public void setHeader (ISOHeader header) { this.header = header; } /** * get optional message header image * @return message header image (may be null) */ public byte[] getHeader() { return (header != null) ? header.pack() : null; } /** * Return this messages ISOHeader */ public ISOHeader getISOHeader() { return header; } /** * @return the direction (ISOMsg.INCOMING or ISOMsg.OUTGOING) * @see ISOChannel */ public int getDirection() { return direction; } /** * @return true if this message is an incoming message * @see ISOChannel */ public boolean isIncoming() { return direction == INCOMING; } /** * @return true if this message is an outgoing message * @see ISOChannel */ public boolean isOutgoing() { return direction == OUTGOING; } /** * @return the max field number associated with this message */ public int getMaxField() { if (maxFieldDirty) recalcMaxField(); return maxField; } private void recalcMaxField() { maxField = 0; for (Enumeration e = fields.keys(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj instanceof Integer) maxField = Math.max (maxField, ((Integer)obj).intValue()); } maxFieldDirty = false; } /** * @param p - a peer packager */ public void setPackager (ISOPackager p) { packager = p; } /** * @return the peer packager */ public ISOPackager getPackager () { return packager; } /** * Set a field within this message * @param c - a component */ public void set (ISOComponent c) throws ISOException { Integer i = (Integer) c.getKey(); fields.put (i, c); if (i.intValue() > maxField) maxField = i.intValue(); dirty = true; } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set(int fldno, String value) throws ISOException { if (value != null) { if (!(packager instanceof ISOBasePackager)) { // No packager is available, we can't tell what the field // might be, so treat as a String! set(new ISOField(fldno, value)); } else { // This ISOMsg has a packager, so use it Object obj = ((ISOBasePackager) packager).getFieldPackager(fldno); if (obj instanceof ISOBinaryFieldPackager) { set(new ISOBinaryField(fldno, ISOUtil.hex2byte(value))); } else { set(new ISOField(fldno, value)); } } } else unset(fldno); } /** * Creates an ISOBinaryField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set (int fldno, byte[] value) throws ISOException { if (value != null) set (new ISOBinaryField (fldno, value)); else unset (fldno); } /** * Unset a field if it exists, otherwise ignore. * @param fldno - the field number */ public void unset (int fldno) { if (fields.remove (new Integer (fldno)) != null) dirty = maxFieldDirty = true; } /** * Unsets several fields at once * @param flds - array of fields to be unset from this ISOMsg */ public void unset (int[] flds) { for (int i=0; i<flds.length; i++) unset (flds[i]); } /** * In order to interchange <b>Composites</b> and <b>Leafs</b> we use * getComposite(). A <b>Composite component</b> returns itself and * a Leaf returns null. * * @return ISOComponent */ public ISOComponent getComposite() { return this; } /** * setup BitMap * @exception ISOException */ public void recalcBitMap () throws ISOException { if (!dirty) return; BitSet bmap = new BitSet (((getMaxField()+62)>>6)<<6); for (int i=1; i<=maxField; i++) if (((ISOComponent) fields.get (new Integer (i))) != null) bmap.set (i); set (new ISOBitMap (-1, bmap)); dirty = false; } /** * clone fields */ public Hashtable getChildren() { return (Hashtable) fields.clone(); } /** * pack the message with the current packager * @return the packed message * @exception ISOException */ public byte[] pack() throws ISOException { synchronized (this) { recalcBitMap(); return packager.pack(this); } } /** * unpack a message * @param b - raw message * @return consumed bytes * @exception ISOException */ public int unpack(byte[] b) throws ISOException { synchronized (this) { return packager.unpack(this, b); } } public void unpack (InputStream in) throws IOException, ISOException { synchronized (this) { packager.unpack(this, in); } } /** * dump the message to a PrintStream. The output is sorta * XML, intended to be easily parsed. * <br> * Each component is responsible for its own dump function, * ISOMsg just calls dump on every valid field. * @param p - print stream * @param indent - optional indent string */ public void dump (PrintStream p, String indent) { ISOComponent c; p.print (indent + "<" + XMLPackager.ISOMSG_TAG); switch (direction) { case INCOMING: p.print (" direction=\"incoming\""); break; case OUTGOING: p.print (" direction=\"outgoing\""); break; } if (fieldNumber != -1) p.print (" "+XMLPackager.ID_ATTR +"=\""+fieldNumber +"\""); p.println (">"); String newIndent = indent + " "; if (header instanceof Loggeable) ((Loggeable) header).dump (p, newIndent); for (int i=0; i<=maxField; i++) { if ((c = (ISOComponent) fields.get (new Integer (i))) != null) c.dump (p, newIndent); // // Uncomment to include bitmaps within logs // // if (i == 0) { // if ((c = (ISOComponent) fields.get (new Integer (-1))) != null) // c.dump (p, newIndent); // } // } p.println (indent + "</" + XMLPackager.ISOMSG_TAG+">"); } /** * get the component associated with the given field number * @param fldno the Field Number * @return the Component */ public ISOComponent getComponent(int fldno) { return (ISOComponent) fields.get(new Integer(fldno)); } /** * Return the object value associated with the given field number * @param fldno the Field Number * @return the field Object */ public Object getValue(int fldno) throws ISOException { ISOComponent c = getComponent(fldno); return c != null ? c.getValue() : null; } /** * Return the String value associated with the given ISOField number * @param fldno the Field Number * @return field's String value */ public String getString (int fldno) { String s = null; if (hasField (fldno)) { try { Object obj = getValue(fldno); if (obj instanceof String) s = (String) obj; else if (obj instanceof byte[]) s = ISOUtil.hexString ((byte[]) obj); } catch (ISOException e) { // ignore ISOException - return null } } return s; } /** * Check if a given field is present * @param fldno the Field Number * @return boolean indicating the existence of the field */ public boolean hasField(int fldno) { return fields.get(new Integer(fldno)) != null; } /** * Check if all fields are present * @param fields an array of fields to check for presence * @return true if all fields are present */ public boolean hasFields (int[] fields) { for (int i=0; i<fields.length; i++) if (!hasField (fields[i])) return false; return true; } /** * Don't call setValue on an ISOMsg. You'll sure get * an ISOException. It's intended to be used on Leafs * @see ISOField * @see ISOException */ public void setValue(Object obj) throws ISOException { throw new ISOException ("setValue N/A in ISOMsg"); } public Object clone() { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = (Hashtable) fields.clone(); if (header != null) m.header = (ISOHeader) header.clone(); return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Partially clone an ISOMsg * @param fields int array of fields to go * @return new ISOMsg instance */ public Object clone(int[] fields) { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = new Hashtable(); for (int i=0; i<fields.length; i++) { if (hasField(fields[i])) { try { m.set (getComponent(fields[i])); } catch (ISOException e) { // it should never happen } } } return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * add all fields present on received parameter to this ISOMsg<br> * please note that received fields take precedence over * existing ones (simplifying card agent message creation * and template handling) * @param m ISOMsg to merge */ public void merge (ISOMsg m) { for (int i=0; i<=m.getMaxField(); i++) try { if (m.hasField(i)) set (m.getComponent(i)); } catch (ISOException e) { // should never happen } } /** * @return a string suitable for a log */ public String toString() { StringBuffer s = new StringBuffer(); if (isIncoming()) s.append("<-- "); else if (isOutgoing()) s.append("--> "); else s.append(" "); try { s.append((String) getValue(0)); if (hasField(11)) { s.append(' '); s.append((String) getValue(11)); } if (hasField(41)) { s.append(' '); s.append((String) getValue(41)); } } catch (ISOException e) { } return s.toString(); } public Object getKey() throws ISOException { if (fieldNumber != -1) return new Integer(fieldNumber); throw new ISOException ("This is not a subField"); } public Object getValue() { return this; } /** * @return true on inner messages */ public boolean isInner() { return fieldNumber > -1; } /** * @param mti new MTI * @exception ISOException if message is inner message */ public void setMTI (String mti) throws ISOException { if (isInner()) throw new ISOException ("can't setMTI on inner message"); set (new ISOField (0, mti)); } /** * moves a field (renumber) * @param oldFieldNumber old field number * @param newFieldNumber new field number * @throws ISOException */ public void move (int oldFieldNumber, int newFieldNumber) throws ISOException { ISOComponent c = getComponent (oldFieldNumber); unset (oldFieldNumber); if (c != null) { c.setFieldNumber (newFieldNumber); set (c); } else unset (newFieldNumber); } /** * @return current MTI * @exception ISOException on inner message or MTI not set */ public String getMTI() throws ISOException { if (isInner()) throw new ISOException ("can't getMTI on inner message"); else if (!hasField(0)) throw new ISOException ("MTI not available"); return (String) getValue(0); } /** * @return true if message "seems to be" a request * @exception ISOException on MTI not set */ public boolean isRequest() throws ISOException { return Character.getNumericValue(getMTI().charAt (2))%2 == 0; } /** * @return true if message "seems not to be" a request * @exception ISOException on MTI not set */ public boolean isResponse() throws ISOException { return !isRequest(); } /** * @return true if message is Retransmission * @exception ISOException on MTI not set */ public boolean isRetransmission() throws ISOException { return getMTI().charAt(3) == '1'; } /** * sets an appropiate response MTI. * * i.e. 0100 becomes 0110<br> * i.e. 0201 becomes 0210<br> * i.e. 1201 becomes 1210<br> * @exception ISOException on MTI not set or it is not a request */ public void setResponseMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request - can't set response MTI"); String mti = getMTI(); char c1 = mti.charAt(3); char c2 = '0'; switch (c1) { case '0' : case '1' : c2='0';break; case '2' : case '3' : c2='2';break; case '4' : case '5' : c2='4';break; } set (new ISOField (0, mti.substring(0,2) +(Character.getNumericValue(getMTI().charAt (2))+1) + c2 ) ); } /** * sets an appropiate retransmission MTI<br> * @exception ISOException on MTI not set or it is not a request */ public void setRetransmissionMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request"); set (new ISOField (0, getMTI().substring(0,3) + "1")); } protected void writeHeader (ObjectOutput out) throws IOException { int len = header.getLength(); if (len > 0) { out.writeByte ('H'); out.writeShort (len); out.write (header.pack()); } } protected void readHeader (ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully (b); setHeader (b); } protected void writePackager(ObjectOutput out) throws IOException { out.writeByte('P'); String pclass = ((Class) packager.getClass()).getName(); byte[] b = pclass.getBytes(); out.writeShort(b.length); out.write(b); } protected void readPackager(ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully(b); try { Class mypClass = Class.forName(new String(b)); ISOPackager myp = (ISOPackager) mypClass.newInstance(); setPackager(myp); } catch (Exception e) { setPackager(null); } } protected void writeDirection (ObjectOutput out) throws IOException { out.writeByte ('D'); out.writeByte (direction); } protected void readDirection (ObjectInput in) throws IOException, ClassNotFoundException { direction = in.readByte(); } public void writeExternal (ObjectOutput out) throws IOException { out.writeByte (0); // reserved for future expansion (version id) out.writeShort (fieldNumber); if (header != null) writeHeader (out); if (packager != null) writePackager(out); if (direction > 0) writeDirection (out); for (Enumeration e = fields.elements(); e.hasMoreElements(); ) { ISOComponent c = (ISOComponent) e.nextElement(); if (c instanceof ISOMsg) { out.writeByte ('M'); ((Externalizable) c).writeExternal (out); } else if (c instanceof ISOBinaryField) { out.writeByte ('B'); ((Externalizable) c).writeExternal (out); } else if (c instanceof ISOField) { out.writeByte ('F'); ((Externalizable) c).writeExternal (out); } } out.writeByte ('E'); } public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException { in.readByte(); // ignore version for now fieldNumber = in.readShort(); byte fieldType; ISOComponent c; try { while ((fieldType = in.readByte()) != 'E') { c = null; switch (fieldType) { case 'F': c = new ISOField (); break; case 'B': c = new ISOBinaryField (); break; case 'M': c = new ISOMsg (); break; case 'H': readHeader (in); break; case 'P': readPackager(in); break; case 'D': readDirection (in); break; default: throw new IOException ("malformed ISOMsg"); } if (c != null) { ((Externalizable)c).readExternal (in); set (c); } } } catch (ISOException e) { throw new IOException (e.getMessage()); } } /** * Let this ISOMsg object hold a weak reference to an ISOSource * (usually used to carry a reference to the incoming ISOChannel) * @param source an ISOSource */ public void setSource (ISOSource source) { this.sourceRef = new WeakReference (source); } /** * @return an ISOSource or null */ public ISOSource getSource () { return (sourceRef != null) ? (ISOSource) sourceRef.get () : null; } }
jpos6/modules/jpos/src/org/jpos/iso/ISOMsg.java
/* * Copyright (c) 2000 jPOS.org. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the jPOS project * (http://www.jpos.org/)". Alternately, this acknowledgment may * appear in the software itself, if and wherever such third-party * acknowledgments normally appear. * * 4. The names "jPOS" and "jPOS.org" must not be used to endorse * or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "jPOS", * nor may "jPOS" appear in their name, without prior written * permission of the jPOS project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the jPOS Project. For more * information please see <http://www.jpos.org/>. */ package org.jpos.iso; import java.io.Externalizable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.util.BitSet; import java.util.Enumeration; import java.util.Hashtable; import org.jpos.iso.header.BaseHeader; import org.jpos.iso.packager.XMLPackager; import org.jpos.util.Loggeable; /** * implements <b>Composite</b> * whithin a <b>Composite pattern</b> * * @author [email protected] * @version $Id$ * @see ISOComponent * @see ISOField */ public class ISOMsg extends ISOComponent implements Cloneable, Loggeable, Externalizable { protected Hashtable fields; protected int maxField; protected ISOPackager packager; protected boolean dirty, maxFieldDirty; protected int direction; protected ISOHeader header; protected int fieldNumber = -1; public static final int INCOMING = 1; public static final int OUTGOING = 2; private static final long serialVersionUID = 4306251831901413975L; private WeakReference sourceRef; /** * Creates an ISOMsg */ public ISOMsg () { fields = new Hashtable (); maxField = -1; dirty = true; maxFieldDirty=true; direction = 0; header = null; } /** * Creates a nested ISOMsg */ public ISOMsg (int fieldNumber) { this(); setFieldNumber (fieldNumber); } /** * changes this Component field number<br> * Use with care, this method does not change * any reference held by a Composite. * @param fieldNumber new field number */ public void setFieldNumber (int fieldNumber) { this.fieldNumber = fieldNumber; } /** * Creates an ISOMsg with given mti * @param mti Msg's MTI */ public ISOMsg (String mti) { this(); try { setMTI (mti); } catch (ISOException e) { // should never happen } } /** * Sets the direction information related to this message * @param direction can be either ISOMsg.INCOMING or ISOMsg.OUTGOING */ public void setDirection(int direction) { this.direction = direction; } /** * Sets an optional message header image * @param b header image */ public void setHeader(byte[] b) { header = new BaseHeader (b); } public void setHeader (ISOHeader header) { this.header = header; } /** * get optional message header image * @return message header image (may be null) */ public byte[] getHeader() { return (header != null) ? header.pack() : null; } /** * Return this messages ISOHeader */ public ISOHeader getISOHeader() { return header; } /** * @return the direction (ISOMsg.INCOMING or ISOMsg.OUTGOING) * @see ISOChannel */ public int getDirection() { return direction; } /** * @return true if this message is an incoming message * @see ISOChannel */ public boolean isIncoming() { return direction == INCOMING; } /** * @return true if this message is an outgoing message * @see ISOChannel */ public boolean isOutgoing() { return direction == OUTGOING; } /** * @return the max field number associated with this message */ public int getMaxField() { if (maxFieldDirty) recalcMaxField(); return maxField; } private void recalcMaxField() { maxField = 0; for (Enumeration e = fields.keys(); e.hasMoreElements(); ) { Object obj = e.nextElement(); if (obj instanceof Integer) maxField = Math.max (maxField, ((Integer)obj).intValue()); } maxFieldDirty = false; } /** * @param p - a peer packager */ public void setPackager (ISOPackager p) { packager = p; } /** * @return the peer packager */ public ISOPackager getPackager () { return packager; } /** * Set a field within this message * @param c - a component */ public void set (ISOComponent c) throws ISOException { Integer i = (Integer) c.getKey(); fields.put (i, c); if (i.intValue() > maxField) maxField = i.intValue(); dirty = true; } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set(int fldno, String value) throws ISOException { if (value != null) { if (!(packager instanceof ISOBasePackager)) { // No packager is available, we can't tell what the field // might be, so treat as a String! set(new ISOField(fldno, value)); } else { // This ISOMsg has a packager, so use it Object obj = ((ISOBasePackager) packager).getFieldPackager(fldno); if (obj instanceof ISOBinaryFieldPackager) { set(new ISOBinaryField(fldno, ISOUtil.hex2byte(value))); } else { set(new ISOField(fldno, value)); } } } else unset(fldno); } /** * Creates an ISOBinaryField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set (int fldno, byte[] value) throws ISOException { if (value != null) set (new ISOBinaryField (fldno, value)); else unset (fldno); } /** * Unset a field if it exists, otherwise ignore. * @param fldno - the field number */ public void unset (int fldno) { if (fields.remove (new Integer (fldno)) != null) dirty = maxFieldDirty = true; } /** * Unsets several fields at once * @param flds - array of fields to be unset from this ISOMsg */ public void unset (int[] flds) { for (int i=0; i<flds.length; i++) unset (flds[i]); } /** * In order to interchange <b>Composites</b> and <b>Leafs</b> we use * getComposite(). A <b>Composite component</b> returns itself and * a Leaf returns null. * * @return ISOComponent */ public ISOComponent getComposite() { return this; } /** * setup BitMap * @exception ISOException */ public void recalcBitMap () throws ISOException { if (!dirty) return; BitSet bmap = new BitSet (((getMaxField()+62)>>6)<<6); for (int i=1; i<=maxField; i++) if (((ISOComponent) fields.get (new Integer (i))) != null) bmap.set (i); set (new ISOBitMap (-1, bmap)); dirty = false; } /** * clone fields */ public Hashtable getChildren() { return (Hashtable) fields.clone(); } /** * pack the message with the current packager * @return the packed message * @exception ISOException */ public byte[] pack() throws ISOException { synchronized (this) { recalcBitMap(); return packager.pack(this); } } /** * unpack a message * @param b - raw message * @return consumed bytes * @exception ISOException */ public int unpack(byte[] b) throws ISOException { synchronized (this) { return packager.unpack(this, b); } } public void unpack (InputStream in) throws IOException, ISOException { synchronized (this) { packager.unpack(this, in); } } /** * dump the message to a PrintStream. The output is sorta * XML, intended to be easily parsed. * <br> * Each component is responsible for its own dump function, * ISOMsg just calls dump on every valid field. * @param p - print stream * @param indent - optional indent string */ public void dump (PrintStream p, String indent) { ISOComponent c; p.print (indent + "<" + XMLPackager.ISOMSG_TAG); switch (direction) { case INCOMING: p.print (" direction=\"incoming\""); break; case OUTGOING: p.print (" direction=\"outgoing\""); break; } if (fieldNumber != -1) p.print (" "+XMLPackager.ID_ATTR +"=\""+fieldNumber +"\""); p.println (">"); String newIndent = indent + " "; if (header instanceof Loggeable) ((Loggeable) header).dump (p, newIndent); for (int i=0; i<=maxField; i++) { if ((c = (ISOComponent) fields.get (new Integer (i))) != null) c.dump (p, newIndent); // // Uncomment to include bitmaps within logs // // if (i == 0) { // if ((c = (ISOComponent) fields.get (new Integer (-1))) != null) // c.dump (p, newIndent); // } // } p.println (indent + "</" + XMLPackager.ISOMSG_TAG+">"); } /** * get the component associated with the given field number * @param fldno the Field Number * @return the Component */ public ISOComponent getComponent(int fldno) { return (ISOComponent) fields.get(new Integer(fldno)); } /** * Return the object value associated with the given field number * @param fldno the Field Number * @return the field Object */ public Object getValue(int fldno) throws ISOException { ISOComponent c = getComponent(fldno); return c != null ? c.getValue() : null; } /** * Return the String value associated with the given ISOField number * @param fldno the Field Number * @return field's String value */ public String getString (int fldno) { String s = null; if (hasField (fldno)) { try { Object obj = getValue(fldno); if (obj instanceof String) s = new String ((String) obj); else if (obj instanceof byte[]) s = ISOUtil.hexString ((byte[]) obj); } catch (ISOException e) { // ignore ISOException - return null } } return s; } /** * Check if a given field is present * @param fldno the Field Number * @return boolean indicating the existence of the field */ public boolean hasField(int fldno) { return fields.get(new Integer(fldno)) != null; } /** * Check if all fields are present * @param fields an array of fields to check for presence * @return true if all fields are present */ public boolean hasFields (int[] fields) { for (int i=0; i<fields.length; i++) if (!hasField (fields[i])) return false; return true; } /** * Don't call setValue on an ISOMsg. You'll sure get * an ISOException. It's intended to be used on Leafs * @see ISOField * @see ISOException */ public void setValue(Object obj) throws ISOException { throw new ISOException ("setValue N/A in ISOMsg"); } public Object clone() { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = (Hashtable) fields.clone(); if (header != null) m.header = (ISOHeader) header.clone(); return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Partially clone an ISOMsg * @param fields int array of fields to go * @return new ISOMsg instance */ public Object clone(int[] fields) { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = new Hashtable(); for (int i=0; i<fields.length; i++) { if (hasField(fields[i])) { try { m.set (getComponent(fields[i])); } catch (ISOException e) { // it should never happen } } } return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * add all fields present on received parameter to this ISOMsg<br> * please note that received fields take precedence over * existing ones (simplifying card agent message creation * and template handling) * @param m ISOMsg to merge */ public void merge (ISOMsg m) { for (int i=0; i<=m.getMaxField(); i++) try { if (m.hasField(i)) set (m.getComponent(i)); } catch (ISOException e) { // should never happen } } /** * @return a string suitable for a log */ public String toString() { StringBuffer s = new StringBuffer(); if (isIncoming()) s.append("<-- "); else if (isOutgoing()) s.append("--> "); else s.append(" "); try { s.append((String) getValue(0)); if (hasField(11)) { s.append(' '); s.append((String) getValue(11)); } if (hasField(41)) { s.append(' '); s.append((String) getValue(41)); } } catch (ISOException e) { } return s.toString(); } public Object getKey() throws ISOException { if (fieldNumber != -1) return new Integer(fieldNumber); throw new ISOException ("This is not a subField"); } public Object getValue() { return this; } /** * @return true on inner messages */ public boolean isInner() { return fieldNumber > -1; } /** * @param mti new MTI * @exception ISOException if message is inner message */ public void setMTI (String mti) throws ISOException { if (isInner()) throw new ISOException ("can't setMTI on inner message"); set (new ISOField (0, mti)); } /** * moves a field (renumber) * @param oldFieldNumber old field number * @param newFieldNumber new field number * @throws ISOException */ public void move (int oldFieldNumber, int newFieldNumber) throws ISOException { ISOComponent c = getComponent (oldFieldNumber); unset (oldFieldNumber); if (c != null) { c.setFieldNumber (newFieldNumber); set (c); } else unset (newFieldNumber); } /** * @return current MTI * @exception ISOException on inner message or MTI not set */ public String getMTI() throws ISOException { if (isInner()) throw new ISOException ("can't getMTI on inner message"); else if (!hasField(0)) throw new ISOException ("MTI not available"); return (String) getValue(0); } /** * @return true if message "seems to be" a request * @exception ISOException on MTI not set */ public boolean isRequest() throws ISOException { return Character.getNumericValue(getMTI().charAt (2))%2 == 0; } /** * @return true if message "seems not to be" a request * @exception ISOException on MTI not set */ public boolean isResponse() throws ISOException { return !isRequest(); } /** * @return true if message is Retransmission * @exception ISOException on MTI not set */ public boolean isRetransmission() throws ISOException { return getMTI().charAt(3) == '1'; } /** * sets an appropiate response MTI. * * i.e. 0100 becomes 0110<br> * i.e. 0201 becomes 0210<br> * i.e. 1201 becomes 1210<br> * @exception ISOException on MTI not set or it is not a request */ public void setResponseMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request - can't set response MTI"); String mti = getMTI(); char c1 = mti.charAt(3); char c2 = '0'; switch (c1) { case '0' : case '1' : c2='0';break; case '2' : case '3' : c2='2';break; case '4' : case '5' : c2='4';break; } set (new ISOField (0, mti.substring(0,2) +(Character.getNumericValue(getMTI().charAt (2))+1) + c2 ) ); } /** * sets an appropiate retransmission MTI<br> * @exception ISOException on MTI not set or it is not a request */ public void setRetransmissionMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request"); set (new ISOField (0, getMTI().substring(0,3) + "1")); } protected void writeHeader (ObjectOutput out) throws IOException { int len = header.getLength(); if (len > 0) { out.writeByte ('H'); out.writeShort (len); out.write (header.pack()); } } protected void readHeader (ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully (b); setHeader (b); } protected void writePackager(ObjectOutput out) throws IOException { out.writeByte('P'); String pclass = ((Class) packager.getClass()).getName(); byte[] b = pclass.getBytes(); out.writeShort(b.length); out.write(b); } protected void readPackager(ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully(b); try { Class mypClass = Class.forName(new String(b)); ISOPackager myp = (ISOPackager) mypClass.newInstance(); setPackager(myp); } catch (Exception e) { setPackager(null); } } protected void writeDirection (ObjectOutput out) throws IOException { out.writeByte ('D'); out.writeByte (direction); } protected void readDirection (ObjectInput in) throws IOException, ClassNotFoundException { direction = in.readByte(); } public void writeExternal (ObjectOutput out) throws IOException { out.writeByte (0); // reserved for future expansion (version id) out.writeShort (fieldNumber); if (header != null) writeHeader (out); if (packager != null) writePackager(out); if (direction > 0) writeDirection (out); for (Enumeration e = fields.elements(); e.hasMoreElements(); ) { ISOComponent c = (ISOComponent) e.nextElement(); if (c instanceof ISOMsg) { out.writeByte ('M'); ((Externalizable) c).writeExternal (out); } else if (c instanceof ISOBinaryField) { out.writeByte ('B'); ((Externalizable) c).writeExternal (out); } else if (c instanceof ISOField) { out.writeByte ('F'); ((Externalizable) c).writeExternal (out); } } out.writeByte ('E'); } public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException { in.readByte(); // ignore version for now fieldNumber = in.readShort(); byte fieldType; ISOComponent c; try { while ((fieldType = in.readByte()) != 'E') { c = null; switch (fieldType) { case 'F': c = new ISOField (); break; case 'B': c = new ISOBinaryField (); break; case 'M': c = new ISOMsg (); break; case 'H': readHeader (in); break; case 'P': readPackager(in); break; case 'D': readDirection (in); break; default: throw new IOException ("malformed ISOMsg"); } if (c != null) { ((Externalizable)c).readExternal (in); set (c); } } } catch (ISOException e) { throw new IOException (e.getMessage()); } } /** * Let this ISOMsg object hold a weak reference to an ISOSource * (usually used to carry a reference to the incoming ISOChannel) * @param source an ISOSource */ public void setSource (ISOSource source) { this.sourceRef = new WeakReference (source); } /** * @return an ISOSource or null */ public ISOSource getSource () { return (sourceRef != null) ? (ISOSource) sourceRef.get () : null; } }
optimization: no need to create a new String
jpos6/modules/jpos/src/org/jpos/iso/ISOMsg.java
optimization: no need to create a new String
Java
agpl-3.0
98647bb05c0e6df72882b64bbfd7b3d39414695a
0
cogmission/htm.java-examples,numenta/htm.java-examples
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ package org.numenta.nupic.examples.qt; import gnu.trove.list.array.TIntArrayList; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.numenta.nupic.ComputeCycle; import org.numenta.nupic.Connections; import org.numenta.nupic.Parameters; import org.numenta.nupic.Parameters.KEY; import org.numenta.nupic.algorithms.CLAClassifier; import org.numenta.nupic.algorithms.SpatialPooler; import org.numenta.nupic.algorithms.TemporalMemory; //import org.numenta.nupic.algorithms.ClassifierResult; import org.numenta.nupic.encoders.ScalarEncoder; import org.numenta.nupic.model.Cell; import org.numenta.nupic.util.ArrayUtils; /** * Quick and dirty example of tying together a network of components. * This should hold off peeps until the Network API is complete. * (see: https://github.com/numenta/htm.java/wiki/Roadmap) * * <p>Warning: Sloppy sketchpad code, but it works!</p> * * <p><em><b> * To see the pretty printed test output and Classification results, * * UNCOMMENT ALL FUNCTIONAL (NON-LABEL) LINES BELOW! * * These are commented to avoid running during command line builds and * the ugly yellow "unused" markers that Eclipse puts on unused lines. * * </b></em></p> * * @author PDove * @author cogmission */ public class QuickTest { static boolean isResetting = true; /** * @param args the command line arguments */ public static void main(String[] args) { Parameters params = getParameters(); System.out.println(params); // Toggle this to switch between resetting on every week start day isResetting = true; //Layer components ScalarEncoder.Builder dayBuilder = ScalarEncoder.builder() .n(8) .w(3) .radius(1.0) .minVal(1.0) .maxVal(8) .periodic(true) .forced(true) .resolution(1); ScalarEncoder encoder = dayBuilder.build(); SpatialPooler sp = new SpatialPooler(); TemporalMemory tm = new TemporalMemory(); CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0); Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier); for(double i = 0, x = 0, j = 0;j < 1500;j = (i == 6 ? j + 1: j), i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length if (i == 0 && isResetting) { System.out.println("reset:"); tm.reset(layer.getMemory()); } // For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number) runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x); } } public static Parameters getParameters() { Parameters parameters = Parameters.getAllDefaultParameters(); parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 8 }); parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 }); parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6); //SpatialPooler specific parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);//3 parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);//0.5 parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false); parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0); parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0); parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0); parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005); parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015); parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05); parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1); parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1); parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1); parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10); parameters.setParameterByKey(KEY.MAX_BOOST, 10.0); parameters.setParameterByKey(KEY.SEED, 42); parameters.setParameterByKey(KEY.SP_VERBOSITY, 0); //Temporal Memory specific parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2); parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8); parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5); parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6); parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.1);//0.05 parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.1);//0.05 parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4); return parameters; } public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) { l.input(input, recordNum, sequenceNum); } public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) { Layer<Double> l = new LayerImpl(p, e, s, t, c); return l; } ////////////////// Preliminary Network API Toy /////////////////// interface Layer<T> { public void input(T value, int recordNum, int iteration); public int[] getPredicted(); public Connections getMemory(); public int[] getActual(); } /** * I'm going to make an actual Layer, this is just temporary so I can * work out the details while I'm completing this for Peter * * @author David Ray * */ static class LayerImpl implements Layer<Double> { private Parameters params; private Connections memory = new Connections(); private ScalarEncoder encoder; private SpatialPooler spatialPooler; private TemporalMemory temporalMemory; // private CLAClassifier classifier; private Map<String, Object> classification = new LinkedHashMap<String, Object>(); private int columnCount; private int cellsPerColumn; // private int theNum; private int[] predictedColumns; private int[] actual; private int[] lastPredicted; public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) { this.params = p; this.encoder = e; this.spatialPooler = s; this.temporalMemory = t; // this.classifier = c; params.apply(memory); spatialPooler.init(memory); temporalMemory.init(memory); columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index cellsPerColumn = memory.getCellsPerColumn(); } public String stringValue(Double valueIndex) { String recordOut = ""; BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN); switch(bdValue.intValue()) { case 1: recordOut = "Monday (1)";break; case 2: recordOut = "Tuesday (2)";break; case 3: recordOut = "Wednesday (3)";break; case 4: recordOut = "Thursday (4)";break; case 5: recordOut = "Friday (5)";break; case 6: recordOut = "Saturday (6)";break; case 7: recordOut = "Sunday (7)";break; } return recordOut; } @Override public void input(Double value, int recordNum, int sequenceNum) { // String recordOut = stringValue(value); if(value.intValue() == 1) { // theNum++; System.out.println("--------------------------------------------------------"); // System.out.println("Iteration: " + theNum); } // System.out.println("===== " + recordOut + " - Sequence Num: " + sequenceNum + " ====="); int[] output = new int[columnCount]; //Input through encoder // System.out.println("ScalarEncoder Input = " + value); int[] encoding = encoder.encode(value); // System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding)); int bucketIdx = encoder.getBucketIndices(value)[0]; //Input through spatial pooler spatialPooler.compute(memory, encoding, output, true, true); // System.out.println("SpatialPooler Output = " + Arrays.toString(output)); // Let the SpatialPooler train independently (warm up) first // if(theNum < 200) return; //Input through temporal memory int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1); ComputeCycle cc = temporalMemory.compute(memory, input, true); lastPredicted = predictedColumns; predictedColumns = getSDR(cc.predictiveCells()); //Get the predicted column indexes // int[] activeCellIndexes = Connections.asCellIndexes(cc.activeCells()).stream().mapToInt(i -> i).sorted().toArray(); //Get the active cells for classifier input // System.out.println("TemporalMemory Input = " + Arrays.toString(input)); // System.out.println("TemporalMemory Prediction = " + Arrays.toString(predictedColumns)); classification.put("bucketIdx", bucketIdx); classification.put("actValue", value); // ClassifierResult<Double> result = classifier.compute(recordNum, classification, activeCellIndexes, true, true); // System.out.print("CLAClassifier prediction = " + stringValue(result.getMostProbableValue(1))); // System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n"); System.out.println(""); } public int[] inflateSDR(int[] SDR, int len) { int[] retVal = new int[len]; for(int i : SDR) { retVal[i] = 1; } return retVal; } public int[] getSDR(Set<Cell> cells) { int[] retVal = new int[cells.size()]; int i = 0; for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) { retVal[i] = it.next().getIndex(); retVal[i] /= cellsPerColumn; // Get the column index } Arrays.sort(retVal); retVal = ArrayUtils.unique(retVal); return retVal; } /** * Returns the next predicted value. * * @return the SDR representing the prediction */ @Override public int[] getPredicted() { return lastPredicted; } /** * Returns the actual columns in time t + 1 to compare * with {@link #getPrediction()} which returns the prediction * at time t for time t + 1. * @return */ @Override public int[] getActual() { return actual; } /** * Simple getter for external reset * @return */ public Connections getMemory() { return memory; } } }
src/main/java/org/numenta/nupic/examples/qt/QuickTest.java
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ package org.numenta.nupic.examples.qt; import gnu.trove.list.array.TIntArrayList; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.numenta.nupic.ComputeCycle; import org.numenta.nupic.Connections; import org.numenta.nupic.Parameters; import org.numenta.nupic.Parameters.KEY; import org.numenta.nupic.algorithms.CLAClassifier; import org.numenta.nupic.algorithms.SpatialPooler; import org.numenta.nupic.algorithms.TemporalMemory; //import org.numenta.nupic.algorithms.ClassifierResult; import org.numenta.nupic.encoders.ScalarEncoder; import org.numenta.nupic.model.Cell; import org.numenta.nupic.util.ArrayUtils; /** * Quick and dirty example of tying together a network of components. * This should hold off peeps until the Network API is complete. * (see: https://github.com/numenta/htm.java/wiki/Roadmap) * * <p>Warning: Sloppy sketchpad code, but it works!</p> * * <p><em><b> * To see the pretty printed test output and Classification results, * * UNCOMMENT ALL FUNCTIONAL (NON-LABEL) LINES BELOW! * * These are commented to avoid running during command line builds and * the ugly yellow "unused" markers that Eclipse puts on unused lines. * * </b></em></p> * * @author PDove * @author cogmission */ public class QuickTest { static boolean isResetting = true; /** * @param args the command line arguments */ public static void main(String[] args) { Parameters params = getParameters(); System.out.println(params); // Toggle this to switch between resetting on every week start day isResetting = true; //Layer components ScalarEncoder.Builder dayBuilder = ScalarEncoder.builder() .n(12) .w(3) .radius(1.0) .minVal(1.0) .maxVal(8) .periodic(true) .forced(true) .resolution(1); ScalarEncoder encoder = dayBuilder.build(); SpatialPooler sp = new SpatialPooler(); TemporalMemory tm = new TemporalMemory(); CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0); Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier); for(double i = 0, x = 0, j = 0;j < 1500;j = (i == 6 ? j + 1: j), i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length if (i == 0 && isResetting) { System.out.println("reset:"); tm.reset(layer.getMemory()); } // For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number) runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x); } } public static Parameters getParameters() { Parameters parameters = Parameters.getAllDefaultParameters(); parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 12 }); parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 }); parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6); //SpatialPooler specific parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);//3 parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);//0.5 parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false); parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0); parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0); parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0); parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005); parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015); parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05); parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1); parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1); parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1); parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10); parameters.setParameterByKey(KEY.MAX_BOOST, 10.0); parameters.setParameterByKey(KEY.SEED, 42); parameters.setParameterByKey(KEY.SP_VERBOSITY, 0); //Temporal Memory specific parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2); parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8); parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5); parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6); parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.1);//0.05 parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.1);//0.05 parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4); return parameters; } public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) { l.input(input, recordNum, sequenceNum); } public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) { Layer<Double> l = new LayerImpl(p, e, s, t, c); return l; } ////////////////// Preliminary Network API Toy /////////////////// interface Layer<T> { public void input(T value, int recordNum, int iteration); public int[] getPredicted(); public Connections getMemory(); public int[] getActual(); } /** * I'm going to make an actual Layer, this is just temporary so I can * work out the details while I'm completing this for Peter * * @author David Ray * */ static class LayerImpl implements Layer<Double> { private Parameters params; private Connections memory = new Connections(); private ScalarEncoder encoder; private SpatialPooler spatialPooler; private TemporalMemory temporalMemory; // private CLAClassifier classifier; private Map<String, Object> classification = new LinkedHashMap<String, Object>(); private int columnCount; private int cellsPerColumn; // private int theNum; private int[] predictedColumns; private int[] actual; private int[] lastPredicted; public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) { this.params = p; this.encoder = e; this.spatialPooler = s; this.temporalMemory = t; // this.classifier = c; params.apply(memory); spatialPooler.init(memory); temporalMemory.init(memory); columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index cellsPerColumn = memory.getCellsPerColumn(); } public String stringValue(Double valueIndex) { String recordOut = ""; BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN); switch(bdValue.intValue()) { case 1: recordOut = "Monday (1)";break; case 2: recordOut = "Tuesday (2)";break; case 3: recordOut = "Wednesday (3)";break; case 4: recordOut = "Thursday (4)";break; case 5: recordOut = "Friday (5)";break; case 6: recordOut = "Saturday (6)";break; case 7: recordOut = "Sunday (7)";break; } return recordOut; } @Override public void input(Double value, int recordNum, int sequenceNum) { // String recordOut = stringValue(value); if(value.intValue() == 1) { // theNum++; System.out.println("--------------------------------------------------------"); // System.out.println("Iteration: " + theNum); } // System.out.println("===== " + recordOut + " - Sequence Num: " + sequenceNum + " ====="); int[] output = new int[columnCount]; //Input through encoder // System.out.println("ScalarEncoder Input = " + value); int[] encoding = encoder.encode(value); // System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding)); int bucketIdx = encoder.getBucketIndices(value)[0]; //Input through spatial pooler spatialPooler.compute(memory, encoding, output, true, true); // System.out.println("SpatialPooler Output = " + Arrays.toString(output)); // Let the SpatialPooler train independently (warm up) first // if(theNum < 200) return; //Input through temporal memory int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1); ComputeCycle cc = temporalMemory.compute(memory, input, true); lastPredicted = predictedColumns; predictedColumns = getSDR(cc.predictiveCells()); //Get the predicted column indexes // int[] activeColumns = getSDR(cc.activeCells()); //Get the active columns for classifier input // System.out.println("TemporalMemory Input = " + Arrays.toString(input)); // System.out.println("TemporalMemory Prediction = " + Arrays.toString(predictedColumns)); classification.put("bucketIdx", bucketIdx); classification.put("actValue", value); // ClassifierResult<Double> result = classifier.compute(recordNum, classification, activeColumns, true, true); // System.out.print("CLAClassifier prediction = " + stringValue(result.getMostProbableValue(1))); // System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n"); // System.out.println(""); } public int[] inflateSDR(int[] SDR, int len) { int[] retVal = new int[len]; for(int i : SDR) { retVal[i] = 1; } return retVal; } public int[] getSDR(Set<Cell> cells) { int[] retVal = new int[cells.size()]; int i = 0; for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) { retVal[i] = it.next().getIndex(); retVal[i] /= cellsPerColumn; // Get the column index } Arrays.sort(retVal); retVal = ArrayUtils.unique(retVal); return retVal; } /** * Returns the next predicted value. * * @return the SDR representing the prediction */ @Override public int[] getPredicted() { return lastPredicted; } /** * Returns the actual columns in time t + 1 to compare * with {@link #getPrediction()} which returns the prediction * at time t for time t + 1. * @return */ @Override public int[] getActual() { return actual; } /** * Simple getter for external reset * @return */ public Connections getMemory() { return memory; } } }
Changed to load active cell indexes
src/main/java/org/numenta/nupic/examples/qt/QuickTest.java
Changed to load active cell indexes
Java
lgpl-2.1
3336a656eacbab06c2c566eda1925d631c2b15e8
0
ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal
/* * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.counters; import VASSAL.build.GameModule; import VASSAL.build.module.BasicCommandEncoder; import VASSAL.build.module.Chatter; import VASSAL.build.module.GameState; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.build.module.properties.PropertyNameSource; import VASSAL.command.AddPiece; import VASSAL.command.ChangePiece; import VASSAL.command.Command; import VASSAL.command.RemovePiece; import VASSAL.command.SetPersistentPropertyCommand; import VASSAL.configure.ImageSelector; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.Localization; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.property.PersistentPropertyContainer; import VASSAL.search.AbstractImageFinder; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.imageop.ScaledImagePainter; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.InputEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Objects; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; /** * Basic class for representing a physical component of the game. Can be e.g. a counter, a card, or an overlay. * * Note like traits, BasicPiece implements GamePiece (via TranslatablePiece), but UNLIKE traits it is NOT a * Decorator, and thus must be treated specially. */ public class BasicPiece extends AbstractImageFinder implements TranslatablePiece, StateMergeable, PropertyNameSource, PersistentPropertyContainer, PropertyExporter { public static final String ID = "piece;"; // NON-NLS private static Highlighter highlighter; /** * Return information about the current location of the piece through getProperty(): * * LocationName - Current Location Name of piece as displayed in Chat Window CurrentX - Current X position CurrentY - * Current Y position CurrentMap - Current Map name or "" if not on a map CurrentBoard - Current Board name or "" if * not on a map CurrentZone - If the current map has a multi-zoned grid, then return the name of the Zone the piece is * in, or "" if the piece is not in any zone, or not on a map */ public static final String LOCATION_NAME = "LocationName"; // NON-NLS public static final String CURRENT_MAP = "CurrentMap"; // NON-NLS public static final String CURRENT_BOARD = "CurrentBoard"; // NON-NLS public static final String CURRENT_ZONE = "CurrentZone"; // NON-NLS public static final String CURRENT_X = "CurrentX"; // NON-NLS public static final String CURRENT_Y = "CurrentY"; // NON-NLS public static final String OLD_LOCATION_NAME = "OldLocationName"; // NON-NLS public static final String OLD_MAP = "OldMap"; // NON-NLS public static final String OLD_BOARD = "OldBoard"; // NON-NLS public static final String OLD_ZONE = "OldZone"; // NON-NLS public static final String OLD_X = "OldX"; // NON-NLS public static final String OLD_Y = "OldY"; // NON-NLS public static final String BASIC_NAME = "BasicName"; // NON-NLS public static final String PIECE_NAME = "PieceName"; // NON-NLS public static final String LOCALIZED_BASIC_NAME = "LocalizedBasicName"; //NON-NLS public static final String LOCALIZED_PIECE_NAME = "LocalizedPieceName"; //NON-NLS public static final String DECK_NAME = "DeckName"; // NON-NLS public static final String DECK_POSITION = "DeckPosition"; // NON-NLS public static final String CLICKED_X = "ClickedX"; // NON-NLS public static final String CLICKED_Y = "ClickedY"; // NON-NLS public static Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11); protected JPopupMenu popup; protected Rectangle imageBounds; protected ScaledImagePainter imagePainter = new ScaledImagePainter(); private Map map; private KeyCommand[] commands; private Stack parent; private Point pos = new Point(0, 0); private String id; /* * A set of properties used as scratch-pad storage by various Traits and processes. * These properties are ephemeral and not stored in the GameState. */ private java.util.Map<Object, Object> props; /* * A Set of properties that must be persisted in the GameState. * Will be created as lazily as possible since pieces that don't move will not need them, * The current code only supports String Keys and Values. Non-strings should be serialised * before set and de-serialised after get. */ private java.util.Map<Object, Object> persistentProps; /** @deprecated Moved into own traits, retained for backward compatibility */ @Deprecated private char cloneKey; /** @deprecated Moved into own traits, retained for backward compatibility */ @Deprecated private char deleteKey; /** @deprecated Replaced by #srcOp. */ @Deprecated protected Image image; // BasicPiece's own image protected String imageName; // BasicPiece image name private String commonName; // BasicPiece's name for the piece (aka "BasicName" property in Vassal Module) public BasicPiece() { this(ID + ";;;;"); } /** creates a BasicPiece by passing complete type information * @param type serialized type information (data about the piece which does not * change during the course of a game) ready to be processed by a {@link SequenceEncoder.Decoder} */ public BasicPiece(String type) { mySetType(type); } /** Sets the type information for this piece. See {@link Decorator#myGetType} * @param type a serialized configuration string to * set the "type information" of this piece, which is * information that doesn't change during the course of * a single game (e.g. Image Files, Context Menu strings, * etc). Typically ready to be processed e.g. by * SequenceEncoder.decode() */ @Override public void mySetType(String type) { final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); cloneKey = st.nextChar('\0'); deleteKey = st.nextChar('\0'); imageName = st.nextToken(); commonName = st.nextToken(); imagePainter.setImageName(imageName); imageBounds = null; // New image, clear the old imageBounds commands = null; } /** @return The "type information" of a piece or trait is information * that does not change during the course of a game. Image file * names, context menu strings, etc., all should be reflected * in the type. The type information is returned serialized string * form, ready to be decoded by a SequenceEncoder#decode. * @see BasicCommandEncoder */ @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(cloneKey > 0 ? String.valueOf(cloneKey) : "", ';'); return ID + se.append(deleteKey > 0 ? String.valueOf(deleteKey) : "") .append(imageName) .append(commonName).getValue(); } /** @param map Each GamePiece belongs to a single {@link Map} */ @Override public void setMap(Map map) { if (map != this.map) { commands = null; this.map = map; } } /** @return Each GamePiece belongs to a single {@link Map} */ @Override public Map getMap() { return getParent() == null ? map : getParent().getMap(); } /** * Properties can be associated with a piece -- many may be game-specific, but others * are standard, such as the LocationName property exposed by BasicPiece -- and can * be read through this interface. The properties may or may not need to be encoded in * the piece's {@link #getState} method. * * A request to getProperty() that reaches the BasicPiece will have already checked for * such a property key being available from any outer Decorator/Trait in the stack. Upon * reaching BasicPiece, the search hierarchy for a matching property now becomes: * * (1) Specific named properties supported by BasicPiece. These include BASIC_NAME, * PIECE_NAME, LOCATION_NAME, CURRENT_MAP, CURRENT_BOARD, CURRENT_ZONE, CURRENT_X, * CURRENT_Y. * (2) "Scratchpad" properties - see {@link #setProperty} for full details, but these are * highly temporary properties intended to remain valid only during the execution of a * single key command. * (3) Persistent properties - see {@link #setPersistentProperty} for full details, but * they are stored in the piece and "game state robust" - saved during save/load, and * propagated to other players' clients in a multiplayer game. * (4) The values of any visible "Global Property" in a Vassal module, checking the Zone * level first, then the map level, and finally the module level. * * <br><br>Thus, when using this interface a piece's own properties are preferred to those of * "Global Properties", and those in turn are searched Zone-first then Map, then Module. * @param key String key of property to be returned * @return Object containing new value of the specified property */ @Override public Object getProperty(Object key) { if (BASIC_NAME.equals(key)) { return getName(); } else if (LOCALIZED_BASIC_NAME.equals(key)) { return getLocalizedName(); } else return getPublicProperty(key); } /** * Properties (see {@link #getProperty}) visible in a masked (see {@link Obscurable}) piece, even when the piece is masked. * @param key String key of property to be returned. */ public Object getPublicProperty(Object key) { if (Properties.KEY_COMMANDS.equals(key)) { return getKeyCommands(); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().locationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (LOCALIZED_PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getLocalizedName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getConfigureName(); } else if (DECK_NAME.equals(key)) { return getParent() instanceof Deck ? ((Deck) getParent()).getDeckName() : ""; } else if (DECK_POSITION.equals(key)) { if (getParent() instanceof Deck) { final Deck deck = (Deck) getParent(); final int size = deck.getPieceCount(); final int pos = deck.indexOf(Decorator.getOutermost(this)); return String.valueOf(size - pos + 1); } else { return "0"; } } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { final Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { final Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getName(); } } return ""; } else if (CURRENT_X.equals(key)) { return String.valueOf(getPosition().x); } else if (CURRENT_Y.equals(key)) { return String.valueOf(getPosition().y); } else if (Properties.VISIBLE_STATE.equals(key)) { return ""; } // Check for a property in the scratch-pad properties Object prop = props == null ? null : props.get(key); // Check for a persistent property if (prop == null && persistentProps != null) { prop = persistentProps.get(key); } // Check for higher level properties. Each level if it exists will check the higher level if required. if (prop == null) { final Map map = getMap(); final Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getProperty(key); } else if (map != null) { prop = map.getProperty(key); } else { prop = GameModule.getGameModule().getProperty(key); } } return prop; } /** * Returns the localized text for a specified property if a translation is available, otherwise the non-localized version. * Searches the same hierarchy of properties as {@link #getProperty}. * @param key String key of property to be returned * @return localized text of property, if available, otherwise non-localized value */ @Override public Object getLocalizedProperty(Object key) { if (BASIC_NAME.equals(key)) { return getLocalizedName(); } else { return getLocalizedPublicProperty(key); } } /** * Returns the localized text for a specified property if a translation is available, otherwise the non-localized version, * but in both cases accounting for the unit's visibility (i.e. Mask/{@link Obscurable} Traits). * Searches the same hierarchy of properties as {@link #getProperty}. * @param key String key of property to be returned * @return Returns localized text of property, if available, otherwise non-localized value, accounting for Mask status. */ public Object getLocalizedPublicProperty(Object key) { if (List.of( Properties.KEY_COMMANDS, DECK_NAME, CURRENT_X, CURRENT_Y, Properties.VISIBLE_STATE ).contains(key)) { return getProperty(key); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().localizedLocationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (BASIC_NAME.equals(key)) { return getLocalizedName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getLocalizedConfigureName(); } else if (DECK_POSITION.equals(key)) { if (getParent() instanceof Deck) { final Deck deck = (Deck) getParent(); final int size = deck.getPieceCount(); final int pos = deck.indexOf(Decorator.getOutermost(this)); return String.valueOf(size - pos); } else { return "0"; } } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { final Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getLocalizedName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { final Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getLocalizedName(); } } return ""; } // Check for a property in the scratch-pad properties Object prop = props == null ? null : props.get(key); // Check for a persistent property if (prop == null && persistentProps != null) { prop = persistentProps.get(key); } // Check for higher level properties. Each level if it exists will check the higher level if required. if (prop == null) { final Map map = getMap(); final Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getLocalizedProperty(key); } else if (map != null) { prop = map.getLocalizedProperty(key); } else { prop = GameModule.getGameModule().getLocalizedProperty(key); } } return prop; } /** * Properties can be associated with a piece -- many may be game-specific, but others * are standard, such as the LocationName property exposed by BasicPiece -- and can * be set through this interface. The properties may or may not need to be encoded in * the piece's {@link #getState} method. * * A setProperty() call which reaches BasicPiece will already have passed through all of the outer * Decorator/Traits on the way in without finding one able to match the property. * * <br><br><b>NOTE:</b> Properties outside the piece CANNOT be set by this method (e.g. Global * Properties), even though they can be read by {@link #getProperty} -- in this the two methods are * not perfect mirrors. This method ALSO does not set persistent properties (they can only be set * by an explicit call to {@link #setPersistentProperty}). * * <br><br>BasicPiece <i>does</i>, however contain a "scratchpad" for temporary properties, and for * any call to this method that does not match a known property (which is, currently, ANY call which * reaches this method here in BasicPiece), a scratchpad property will be set. Scratchpad properties * are NOT saved when the game is saved, and NO arrangement is made to pass their values to other * players' machines. Thus they should only be used internally for highly temporary values during the * execution of a single key command. Their one other use is to store the piece's Unique ID -- and * although this value is obviously used over periods of time much longer than a single key command, * this is possible because the value is immutable and is refreshed to the same value whenever the * piece is re-created e.g. when loading a save. * * @param key String key of property to be changed * @param val Object containing new value of the property */ @Override public void setProperty(Object key, Object val) { if (props == null) { props = new HashMap<>(); } if (val == null) { props.remove(key); } else { props.put(key, val); } } /** * Setting a persistent property writes a property value into the piece (creating a new entry in the piece's persistent * property table if the specified key does not yet exist in it). Persistent properties are game-state-robust: they are * saved/restored with saved games, and are passed via {@link Command} to other players' clients in a multiplayer game. * The persistent property value can then be read from the piece via e.g. {@link #getProperty}. When reading back properties * out of a piece, the piece's built-in properties are checked first, then scratchpad properties (see {@link #setProperty}), * then external properties such as Global Properties. If <i>only</i> persistentProperties are to be searched, use * {@link #getPersistentProperty} instead. * * <br><br>In practical terms, setPersistentProperty is used mainly to implement the "Old" properties of BasicPiece (e.g. * "OldLocationName", "OldZone", "OldMap", "OldBoard", "OldX", "OldY"). A Persistent Property is indeed nearly identical * with {@link DynamicProperty} in storage/retrieval characteristics, and simply lacks the in-module interface for setting * values, etc. Module Designers are thus recommended to stick with Dynamic Property traits for these functions. * * @param key String key naming the persistent property to be set. If a corresponding persistent property does not exist it will be created. * @param newValue New value for the persistent property * @return a {@link Command} object which, when passed to another player's client via logfile, server, or saved game, will allow the * result of the "set" operation to be replicated. */ @Override public Command setPersistentProperty(Object key, Object newValue) { if (persistentProps == null) { persistentProps = new HashMap<>(); } final Object oldValue = newValue == null ? persistentProps.remove(key) : persistentProps.put(key, newValue); return Objects.equals(oldValue, newValue) ? null : new SetPersistentPropertyCommand(getId(), key, oldValue, newValue); } /** * @param key String key naming the persistent property whose value is to be returned. * @return the current value of a persistent property, or null if it doesn't exist. */ @Override public Object getPersistentProperty(Object key) { return persistentProps == null ? null : persistentProps.get(key); } /** * @param s Name of a module preference to be read * @return Value of the preference */ protected Object prefsValue(String s) { return GameModule.getGameModule().getPrefs().getValue(s); } /** * Draws the BasicPiece's image, if it has been set * @param g target Graphics object * @param x x-location of the center of the piece * @param y y-location of the center of the piece * @param obs the Component on which this piece is being drawn * @param zoom the scaling factor. */ @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { if (imageBounds == null) { imageBounds = boundingBox(); } imagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs); } /** * @return the set of key commands that will populate the a BasicPiece's right-click menu. * This will normally be an empty array in the present age of the world, but the ability to contain a * clone and delete command is retained for compatibility with Modules Of Ancient Times. * In the case of BasicPiece, this method also keeps track of whether move up/down/to-top/to-bottom commands are enabled. * * This method is chained from "outer" Decorator components of a larger logical game piece, in the process of generating * the complete list of key commands to build the right-click menu -- this process is originated by calling <code>getKeyCommands()</code> * on the piece's outermost Decorator/Trait. */ protected KeyCommand[] getKeyCommands() { if (commands == null) { final ArrayList<KeyCommand> l = new ArrayList<>(); final GamePiece target = Decorator.getOutermost(this); if (cloneKey > 0) { l.add(new KeyCommand(Resources.getString("Editor.Clone.clone"), KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK), target)); } if (deleteKey > 0) { l.add(new KeyCommand(Resources.getString("Editor.Delete.delete"), KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK), target)); } commands = l.toArray(new KeyCommand[0]); } final GamePiece outer = Decorator.getOutermost(this); // This code has no function that I can see? There is no way to add these Commands. // boolean canAdjustPosition = outer.getMap() != null && outer.getParent() != null && outer.getParent().topPiece() != getParent().bottomPiece(); // enableCommand("Move up", canAdjustPosition); // enableCommand("Move down", canAdjustPosition); // enableCommand("Move to top", canAdjustPosition); // enableCommand("Move to bottom", canAdjustPosition); enableCommand(Resources.getString("Editor.Clone.clone"), outer.getMap() != null); enableCommand(Resources.getString("Editor.Delete.delete"), outer.getMap() != null); return commands; } /** * @param name Name of internal-to-BasicPiece key command whose enabled status it to be set * @param enable true to enable, false to disable. */ private void enableCommand(String name, boolean enable) { for (final KeyCommand command : commands) { if (name.equals(command.getName())) { command.setEnabled(enable); } } } /** * @param stroke KeyStroke to query if corresponding internal-to-BasicPiece command is enabled * @return false if no Keystroke, true if not an internal-to-BasicPiece key command, and enabled status of key command otherwise. */ private boolean isEnabled(KeyStroke stroke) { if (stroke == null) { return false; } for (final KeyCommand command : commands) { if (stroke.equals(command.getKeyStroke())) { return command.isEnabled(); } } return true; } /** * @return piece's position on its map. */ @Override public Point getPosition() { return getParent() == null ? new Point(pos) : getParent().getPosition(); } /** * @param p Sets the location of this piece on its {@link Map} */ @Override public void setPosition(Point p) { if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } pos = p; if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } } /** * @return the parent {@link Stack} of which this piece is a member, or null if not a member of any Stack */ @Override public Stack getParent() { return parent; } /** * @param s sets the {@link Stack} to which this piece belongs. */ @Override public void setParent(Stack s) { parent = s; } /** * @return bounding box rectangle for BasicPiece's image, if an image has been specified. */ @Override public Rectangle boundingBox() { if (imageBounds == null) { imageBounds = ImageUtils.getBounds(imagePainter.getImageSize()); } return new Rectangle(imageBounds); } /** * @return the Shape of this piece, for purposes of selecting it by clicking on it with the mouse. In the case * of BasicPiece, this is equivalent to the boundingBox of the BasicPiece image, if one exists. Note that the * shape should be defined in reference to the piece's location, which is ordinarily the center of the basic * image. * * <br><br>For pieces that need a non-rectangular click volume, add a {@link NonRectangular} trait. */ @Override public Shape getShape() { return boundingBox(); } /** * @param c GamePiece to check if equal to this one * @return Equality check with specified game piece */ public boolean equals(GamePiece c) { return c == this; } /** * @return the name of this GamePiece. This is the name typed by the module designer in the configuration box * for the BasicPiece. */ @Override public String getName() { return commonName; } /** * @return the localized name of this GamePiece. This is the translated version of the name typed by the module designer * in the configuration box for the BasicPiece. It is used to fill the "BasicName" property. */ @Override public String getLocalizedName() { final String key = TranslatablePiece.PREFIX + getName(); return Localization.getInstance().translate(key, getName()); } /** * The primary way for the piece or trait to receive events. {@link KeyStroke} events are forward * to this method if they are received while the piece is selected (or as the result of e.g. a Global * Key Command being sent to the piece). The class implementing GamePiece can respond in any way it * likes. Actual key presses by the player, selected items from the right-click Context Menu, keystrokes * "applied on move" by a Map that the piece has just moved on, and Global Key Commands all send KeyStrokes * (and NamedKeyStrokes) which are passed to pieces and traits through this interface. * * <br><br>In the case of BasicPiece, if a key command gets here, that means it has already been seen by any and all of * its Traits ({@link Decorator}s), as BasicPiece is the innermost member of the Decorator stack. The key events * processed here by BasicPiece include the "move up"/"move down"/"move-to-top"/"move-to-bottom" stack-adjustment * commands, along with legacy support for cloning and deleting. * * @return a {@link Command} that, when executed, will make all changes to the game state (maps, pieces, other * pieces, etc) to duplicate what the piece did in response to this event on another machine. Often a * {@link ChangePiece} command, but for example if this keystroke caused the piece/trait to decide to fire * off a Global Key Command, then the Command returned would include the <i>entire</i> results of that, appended * as subcommands. * * @see VASSAL.build.module.map.ForwardToKeyBuffer */ @Override public Command keyEvent(KeyStroke stroke) { getKeyCommands(); if (!isEnabled(stroke)) { return null; } Command comm = null; final GamePiece outer = Decorator.getOutermost(this); if (cloneKey != 0 && KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) { final GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode(GameModule.getGameModule().encode(new AddPiece(outer)))).getTarget(); newPiece.setId(null); GameModule.getGameModule().getGameState().addPiece(newPiece); newPiece.setState(outer.getState()); comm = new AddPiece(newPiece); if (getMap() != null) { comm.append(getMap().placeOrMerge(newPiece, getPosition())); KeyBuffer.getBuffer().remove(outer); KeyBuffer.getBuffer().add(newPiece); if (GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) { final String name = outer.getLocalizedName(); final String loc = getMap().locationName(outer.getPosition()); final String s; if (loc != null) { s = Resources.getString("BasicPiece.clone_report_1", name, loc); } else { s = Resources.getString("BasicPiece.clone_report_2", name); } final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); report.execute(); comm = comm.append(report); } } } else if (deleteKey != 0 && KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) { comm = new RemovePiece(outer); if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) { final String name = outer.getLocalizedName(); final String loc = getMap().locationName(outer.getPosition()); final String s; if (loc != null) { s = Resources.getString("BasicPiece.delete_report_1", name, loc); } else { s = Resources.getString("BasicPiece.delete_report_2", name); } final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); comm = comm.append(report); } comm.execute(); } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) { if (parent != null) { final String oldState = parent.getState(); final int index = parent.indexOf(outer); if (index < parent.getPieceCount() - 1) { parent.insert(outer, index + 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) { if (parent != null) { final String oldState = parent.getState(); final int index = parent.indexOf(outer); if (index > 0) { parent.insert(outer, index - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) { parent = outer.getParent(); if (parent != null) { final String oldState = parent.getState(); if (parent.indexOf(outer) < parent.getPieceCount() - 1) { parent.insert(outer, parent.getPieceCount() - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) { parent = getParent(); if (parent != null) { final String oldState = parent.getState(); if (parent.indexOf(outer) > 0) { parent.insert(outer, 0); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } return comm; } /** * @return The "state information" is information that can change during * the course of a game. State information is saved when the game * is saved and is transferred between players on the server. For * example, the relative order of pieces in a stack is state * information, but whether the stack is expanded is not. * * <br><br>In the case of BasicPiece, the state information includes the current * map, x/y position, the unique Game Piece ID, and the keys and values * of any persistent properties (see {@link #setPersistentProperty}) */ @Override public String getState() { final SequenceEncoder se = new SequenceEncoder(';'); final String mapName = map == null ? "null" : map.getIdentifier(); // NON-NLS se.append(mapName); final Point p = getPosition(); se.append(p.x).append(p.y); se.append(getGpId()); se.append(persistentProps == null ? 0 : persistentProps.size()); // Persistent Property values will always be String (for now). if (persistentProps != null) { persistentProps.forEach((key, val) -> { se.append(key == null ? "" : key.toString()); se.append(val == null ? "" : val.toString()); }); } return se.getValue(); } /** * @param s New state information serialized in string form, ready * to be passed to a SequenceEncoder#decode. The "state information" is * information that can change during the course of a game. State information * is saved when the game is saved and is transferred between players on the * server. For example, the relative order of pieces in a stack is state * information, but whether the stack is expanded is not. * * <br><br>In the case of BasicPiece, the state information includes the current * map, x/y position, the unique Game Piece ID, and the keys and values * of any persistent properties (see {@link #setPersistentProperty}) */ @Override public void setState(String s) { final GamePiece outer = Decorator.getOutermost(this); final Map oldMap = getMap(); final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, ';'); final String mapId = st.nextToken(); Map newMap = null; if (!"null".equals(mapId)) { // NON-NLS newMap = Map.getMapById(mapId); if (newMap == null) { Decorator.reportDataError(this, Resources.getString("Error.not_found", "Map"), "mapId=" + mapId); // NON-NLS } } final Point newPos = new Point(st.nextInt(0), st.nextInt(0)); setPosition(newPos); if (newMap != oldMap) { if (newMap != null) { // This will remove from oldMap // and set the map to newMap newMap.addPiece(outer); } else { // oldMap can't possibly be null if we get to here oldMap.removePiece(outer); setMap(null); } } setGpId(st.nextToken("")); // Persistent Property values will always be String (for now). // Create the HashMap as lazily as possible, no point in creating it for pieces that never move if (persistentProps != null) { persistentProps.clear(); } final int propCount = st.nextInt(0); for (int i = 0; i < propCount; i++) { if (persistentProps == null) { persistentProps = new HashMap<>(); } final String key = st.nextToken(""); final String val = st.nextToken(""); persistentProps.put(key, val); } } /** * For BasicPiece, the "merge" of a new state simply involves copying in the * new one in its entirety -- if any difference is detected. * @param newState new serialized game state string * @param oldState old serialized game state string */ @Override public void mergeState(String newState, String oldState) { if (!newState.equals(oldState)) { setState(newState); } } /** * Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never * be changed by custom code. * @return unique ID for this piece * @see GameState#getNewPieceId */ @Override public String getId() { return id; } /** * Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never * be changed by custom code. * @param id sets unique ID for this piece * @see GameState#getNewPieceId */ @Override public void setId(String id) { this.id = id; } /** * @return the Highlighter instance for drawing selected pieces. Note that since this is a static method, all pieces in a * module will always use the same Highlighter */ public static Highlighter getHighlighter() { if (highlighter == null) { highlighter = new ColoredBorder(); } return highlighter; } /** * @param h Set the Highlighter for all pieces */ public static void setHighlighter(Highlighter h) { highlighter = h; } /** * @return Description of what this kind of piece is. Appears in PieceDefiner list of traits. */ @Override public String getDescription() { return Resources.getString("Editor.BasicPiece.trait_description"); } /** * @return the unique gamepiece ID for this piece, as stored in the Property "scratchpad" */ public String getGpId() { final String id = (String) getProperty(Properties.PIECE_ID); return id == null ? "" : id; } /** * @param id stores the unique gamepiece ID for this piece into the Property "scratchpad" */ public void setGpId(String id) { setProperty(Properties.PIECE_ID, id == null ? "" : id); } /** * @return the help file page for this type of piece. */ @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("BasicPiece.html"); // NON-NLS } /** * @return The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the * BasicPiece's type information in the Editor window. */ @Override public PieceEditor getEditor() { return new Ed(this); } /** * Test if this BasicPiece's Type and State are equal to another * This method is intended to be used by Unit Tests to verify that a trait * is unchanged after going through a process such as serialization/deserialization. * * @param o Object to compare this Decorator to * @return true if the Class, type and state all match */ public boolean testEquals(Object o) { // Check Class type if (! (o instanceof BasicPiece)) return false; final BasicPiece bp = (BasicPiece) o; // Check Type if (! Objects.equals(cloneKey, bp.cloneKey)) return false; if (! Objects.equals(deleteKey, bp.deleteKey)) return false; if (! Objects.equals(imageName, bp.imageName)) return false; if (! Objects.equals(commonName, bp.commonName)) return false; // Check State final String mapName1 = this.map == null ? "null" : this.map.getIdentifier(); // NON-NLS final String mapName2 = bp.map == null ? "null" : bp.map.getIdentifier(); // NON-NLS if (! Objects.equals(mapName1, mapName2)) return false; if (! Objects.equals(getPosition(), bp.getPosition())) return false; if (! Objects.equals(getGpId(), bp.getGpId())) return false; final int pp1 = persistentProps == null ? 0 : persistentProps.size(); final int pp2 = bp.persistentProps == null ? 0 : bp.persistentProps.size(); if (! Objects.equals(pp1, pp2)) return false; if (persistentProps != null && bp.persistentProps != null) { for (final Object key : persistentProps.keySet()) { if (!Objects.equals(persistentProps.get(key), bp.persistentProps.get(key))) return false; } } return true; } /** * The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the * BasicPiece's type information in the Editor window. */ private static class Ed implements PieceEditor { private TraitConfigPanel panel; private KeySpecifier cloneKeyInput; private KeySpecifier deleteKeyInput; private StringConfigurer pieceName; private ImageSelector picker; private final String state; /** * @param p to create PieceEditor for */ private Ed(BasicPiece p) { state = p.getState(); initComponents(p); } /** * @param p initializes the editor dialog for the specified BasicPiece */ private void initComponents(BasicPiece p) { panel = new TraitConfigPanel(); pieceName = new StringConfigurer(p.commonName); panel.add("Editor.name_label", pieceName); cloneKeyInput = new KeySpecifier(p.cloneKey); if (p.cloneKey != 0) { panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_clone"))); panel.add(cloneKeyInput); } deleteKeyInput = new KeySpecifier(p.deleteKey); if (p.deleteKey != 0) { panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_delete"))); panel.add(deleteKeyInput); } picker = new ImageSelector(p.imageName); panel.add("Editor.image_label", picker); } /** * @param p BasicPiece */ public void reset(BasicPiece p) { } /** * @return the Component for the BasicPiece configurer */ @Override public Component getControls() { return panel; } /** * @return the current state string for the BasicPiece */ @Override public String getState() { return state; } /** * @return the type information string for the BasicPiece based on the current values of the configurer fields */ @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(cloneKeyInput.getKey(), ';'); final String type = se.append(deleteKeyInput.getKey()).append(picker.getValueString()).append(pieceName.getValueString()).getValue(); return BasicPiece.ID + type; } } /** * @return String enumeration of type and state information. */ @Override public String toString() { return super.toString() + "[name=" + getName() + ",type=" + getType() + ",state=" + getState() + "]"; // NON-NLS } /** * @return Object encapsulating the internationalization data for the BasicPiece */ @Override public PieceI18nData getI18nData() { final PieceI18nData data = new PieceI18nData(this); data.add(commonName, Resources.getString("Editor.BasicPiece.basic_piece_name_description")); return data; } /** * @return Property names exposed by the Trait or Piece. In the case of BasicPiece, there are quite a few, mainly * dealing with past and present location. */ @Override public List<String> getPropertyNames() { final ArrayList<String> l = new ArrayList<>(); l.add(LOCATION_NAME); l.add(CURRENT_MAP); l.add(CURRENT_BOARD); l.add(CURRENT_ZONE); l.add(CURRENT_X); l.add(CURRENT_Y); l.add(OLD_LOCATION_NAME); l.add(OLD_MAP); l.add(OLD_BOARD); l.add(OLD_ZONE); l.add(OLD_X); l.add(OLD_Y); l.add(BASIC_NAME); l.add(PIECE_NAME); l.add(DECK_NAME); l.add(CLICKED_X); l.add(CLICKED_Y); return l; } /** * See {@link AbstractImageFinder} * Adds our image (if any) to the list of images * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { if (imageName != null) s.add(imageName); } }
vassal-app/src/main/java/VASSAL/counters/BasicPiece.java
/* * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.counters; import VASSAL.build.GameModule; import VASSAL.build.module.BasicCommandEncoder; import VASSAL.build.module.Chatter; import VASSAL.build.module.GameState; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.build.module.properties.PropertyNameSource; import VASSAL.command.AddPiece; import VASSAL.command.ChangePiece; import VASSAL.command.Command; import VASSAL.command.RemovePiece; import VASSAL.command.SetPersistentPropertyCommand; import VASSAL.configure.ImageSelector; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.Localization; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.property.PersistentPropertyContainer; import VASSAL.search.AbstractImageFinder; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.imageop.ScaledImagePainter; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.InputEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Objects; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; /** * Basic class for representing a physical component of the game. Can be e.g. a counter, a card, or an overlay. * * Note like traits, BasicPiece implements GamePiece (via TranslatablePiece), but UNLIKE traits it is NOT a * Decorator, and thus must be treated specially. */ public class BasicPiece extends AbstractImageFinder implements TranslatablePiece, StateMergeable, PropertyNameSource, PersistentPropertyContainer, PropertyExporter { public static final String ID = "piece;"; // NON-NLS private static Highlighter highlighter; /** * Return information about the current location of the piece through getProperty(): * * LocationName - Current Location Name of piece as displayed in Chat Window CurrentX - Current X position CurrentY - * Current Y position CurrentMap - Current Map name or "" if not on a map CurrentBoard - Current Board name or "" if * not on a map CurrentZone - If the current map has a multi-zoned grid, then return the name of the Zone the piece is * in, or "" if the piece is not in any zone, or not on a map */ public static final String LOCATION_NAME = "LocationName"; // NON-NLS public static final String CURRENT_MAP = "CurrentMap"; // NON-NLS public static final String CURRENT_BOARD = "CurrentBoard"; // NON-NLS public static final String CURRENT_ZONE = "CurrentZone"; // NON-NLS public static final String CURRENT_X = "CurrentX"; // NON-NLS public static final String CURRENT_Y = "CurrentY"; // NON-NLS public static final String OLD_LOCATION_NAME = "OldLocationName"; // NON-NLS public static final String OLD_MAP = "OldMap"; // NON-NLS public static final String OLD_BOARD = "OldBoard"; // NON-NLS public static final String OLD_ZONE = "OldZone"; // NON-NLS public static final String OLD_X = "OldX"; // NON-NLS public static final String OLD_Y = "OldY"; // NON-NLS public static final String BASIC_NAME = "BasicName"; // NON-NLS public static final String PIECE_NAME = "PieceName"; // NON-NLS public static final String DECK_NAME = "DeckName"; // NON-NLS public static final String DECK_POSITION = "DeckPosition"; // NON-NLS public static final String CLICKED_X = "ClickedX"; // NON-NLS public static final String CLICKED_Y = "ClickedY"; // NON-NLS public static Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11); protected JPopupMenu popup; protected Rectangle imageBounds; protected ScaledImagePainter imagePainter = new ScaledImagePainter(); private Map map; private KeyCommand[] commands; private Stack parent; private Point pos = new Point(0, 0); private String id; /* * A set of properties used as scratch-pad storage by various Traits and processes. * These properties are ephemeral and not stored in the GameState. */ private java.util.Map<Object, Object> props; /* * A Set of properties that must be persisted in the GameState. * Will be created as lazily as possible since pieces that don't move will not need them, * The current code only supports String Keys and Values. Non-strings should be serialised * before set and de-serialised after get. */ private java.util.Map<Object, Object> persistentProps; /** @deprecated Moved into own traits, retained for backward compatibility */ @Deprecated private char cloneKey; /** @deprecated Moved into own traits, retained for backward compatibility */ @Deprecated private char deleteKey; /** @deprecated Replaced by #srcOp. */ @Deprecated protected Image image; // BasicPiece's own image protected String imageName; // BasicPiece image name private String commonName; // BasicPiece's name for the piece (aka "BasicName" property in Vassal Module) public BasicPiece() { this(ID + ";;;;"); } /** creates a BasicPiece by passing complete type information * @param type serialized type information (data about the piece which does not * change during the course of a game) ready to be processed by a {@link SequenceEncoder.Decoder} */ public BasicPiece(String type) { mySetType(type); } /** Sets the type information for this piece. See {@link Decorator#myGetType} * @param type a serialized configuration string to * set the "type information" of this piece, which is * information that doesn't change during the course of * a single game (e.g. Image Files, Context Menu strings, * etc). Typically ready to be processed e.g. by * SequenceEncoder.decode() */ @Override public void mySetType(String type) { final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); cloneKey = st.nextChar('\0'); deleteKey = st.nextChar('\0'); imageName = st.nextToken(); commonName = st.nextToken(); imagePainter.setImageName(imageName); imageBounds = null; // New image, clear the old imageBounds commands = null; } /** @return The "type information" of a piece or trait is information * that does not change during the course of a game. Image file * names, context menu strings, etc., all should be reflected * in the type. The type information is returned serialized string * form, ready to be decoded by a SequenceEncoder#decode. * @see BasicCommandEncoder */ @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(cloneKey > 0 ? String.valueOf(cloneKey) : "", ';'); return ID + se.append(deleteKey > 0 ? String.valueOf(deleteKey) : "") .append(imageName) .append(commonName).getValue(); } /** @param map Each GamePiece belongs to a single {@link Map} */ @Override public void setMap(Map map) { if (map != this.map) { commands = null; this.map = map; } } /** @return Each GamePiece belongs to a single {@link Map} */ @Override public Map getMap() { return getParent() == null ? map : getParent().getMap(); } /** * Properties can be associated with a piece -- many may be game-specific, but others * are standard, such as the LocationName property exposed by BasicPiece -- and can * be read through this interface. The properties may or may not need to be encoded in * the piece's {@link #getState} method. * * A request to getProperty() that reaches the BasicPiece will have already checked for * such a property key being available from any outer Decorator/Trait in the stack. Upon * reaching BasicPiece, the search hierarchy for a matching property now becomes: * * (1) Specific named properties supported by BasicPiece. These include BASIC_NAME, * PIECE_NAME, LOCATION_NAME, CURRENT_MAP, CURRENT_BOARD, CURRENT_ZONE, CURRENT_X, * CURRENT_Y. * (2) "Scratchpad" properties - see {@link #setProperty} for full details, but these are * highly temporary properties intended to remain valid only during the execution of a * single key command. * (3) Persistent properties - see {@link #setPersistentProperty} for full details, but * they are stored in the piece and "game state robust" - saved during save/load, and * propagated to other players' clients in a multiplayer game. * (4) The values of any visible "Global Property" in a Vassal module, checking the Zone * level first, then the map level, and finally the module level. * * <br><br>Thus, when using this interface a piece's own properties are preferred to those of * "Global Properties", and those in turn are searched Zone-first then Map, then Module. * @param key String key of property to be returned * @return Object containing new value of the specified property */ @Override public Object getProperty(Object key) { if (BASIC_NAME.equals(key)) { return getName(); } else return getPublicProperty(key); } /** * Properties (see {@link #getProperty}) visible in a masked (see {@link Obscurable}) piece, even when the piece is masked. * @param key String key of property to be returned. */ public Object getPublicProperty(Object key) { if (Properties.KEY_COMMANDS.equals(key)) { return getKeyCommands(); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().locationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getConfigureName(); } else if (DECK_NAME.equals(key)) { return getParent() instanceof Deck ? ((Deck) getParent()).getDeckName() : ""; } else if (DECK_POSITION.equals(key)) { if (getParent() instanceof Deck) { final Deck deck = (Deck) getParent(); final int size = deck.getPieceCount(); final int pos = deck.indexOf(Decorator.getOutermost(this)); return String.valueOf(size - pos + 1); } else { return "0"; } } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { final Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { final Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getName(); } } return ""; } else if (CURRENT_X.equals(key)) { return String.valueOf(getPosition().x); } else if (CURRENT_Y.equals(key)) { return String.valueOf(getPosition().y); } else if (Properties.VISIBLE_STATE.equals(key)) { return ""; } // Check for a property in the scratch-pad properties Object prop = props == null ? null : props.get(key); // Check for a persistent property if (prop == null && persistentProps != null) { prop = persistentProps.get(key); } // Check for higher level properties. Each level if it exists will check the higher level if required. if (prop == null) { final Map map = getMap(); final Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getProperty(key); } else if (map != null) { prop = map.getProperty(key); } else { prop = GameModule.getGameModule().getProperty(key); } } return prop; } /** * Returns the localized text for a specified property if a translation is available, otherwise the non-localized version. * Searches the same hierarchy of properties as {@link #getProperty}. * @param key String key of property to be returned * @return localized text of property, if available, otherwise non-localized value */ @Override public Object getLocalizedProperty(Object key) { if (BASIC_NAME.equals(key)) { return getLocalizedName(); } else { return getLocalizedPublicProperty(key); } } /** * Returns the localized text for a specified property if a translation is available, otherwise the non-localized version, * but in both cases accounting for the unit's visibility (i.e. Mask/{@link Obscurable} Traits). * Searches the same hierarchy of properties as {@link #getProperty}. * @param key String key of property to be returned * @return Returns localized text of property, if available, otherwise non-localized value, accounting for Mask status. */ public Object getLocalizedPublicProperty(Object key) { if (List.of( Properties.KEY_COMMANDS, DECK_NAME, CURRENT_X, CURRENT_Y, Properties.VISIBLE_STATE ).contains(key)) { return getProperty(key); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().localizedLocationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (BASIC_NAME.equals(key)) { return getLocalizedName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getLocalizedConfigureName(); } else if (DECK_POSITION.equals(key)) { if (getParent() instanceof Deck) { final Deck deck = (Deck) getParent(); final int size = deck.getPieceCount(); final int pos = deck.indexOf(Decorator.getOutermost(this)); return String.valueOf(size - pos); } else { return "0"; } } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { final Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getLocalizedName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { final Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getLocalizedName(); } } return ""; } // Check for a property in the scratch-pad properties Object prop = props == null ? null : props.get(key); // Check for a persistent property if (prop == null && persistentProps != null) { prop = persistentProps.get(key); } // Check for higher level properties. Each level if it exists will check the higher level if required. if (prop == null) { final Map map = getMap(); final Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getLocalizedProperty(key); } else if (map != null) { prop = map.getLocalizedProperty(key); } else { prop = GameModule.getGameModule().getLocalizedProperty(key); } } return prop; } /** * Properties can be associated with a piece -- many may be game-specific, but others * are standard, such as the LocationName property exposed by BasicPiece -- and can * be set through this interface. The properties may or may not need to be encoded in * the piece's {@link #getState} method. * * A setProperty() call which reaches BasicPiece will already have passed through all of the outer * Decorator/Traits on the way in without finding one able to match the property. * * <br><br><b>NOTE:</b> Properties outside the piece CANNOT be set by this method (e.g. Global * Properties), even though they can be read by {@link #getProperty} -- in this the two methods are * not perfect mirrors. This method ALSO does not set persistent properties (they can only be set * by an explicit call to {@link #setPersistentProperty}). * * <br><br>BasicPiece <i>does</i>, however contain a "scratchpad" for temporary properties, and for * any call to this method that does not match a known property (which is, currently, ANY call which * reaches this method here in BasicPiece), a scratchpad property will be set. Scratchpad properties * are NOT saved when the game is saved, and NO arrangement is made to pass their values to other * players' machines. Thus they should only be used internally for highly temporary values during the * execution of a single key command. Their one other use is to store the piece's Unique ID -- and * although this value is obviously used over periods of time much longer than a single key command, * this is possible because the value is immutable and is refreshed to the same value whenever the * piece is re-created e.g. when loading a save. * * @param key String key of property to be changed * @param val Object containing new value of the property */ @Override public void setProperty(Object key, Object val) { if (props == null) { props = new HashMap<>(); } if (val == null) { props.remove(key); } else { props.put(key, val); } } /** * Setting a persistent property writes a property value into the piece (creating a new entry in the piece's persistent * property table if the specified key does not yet exist in it). Persistent properties are game-state-robust: they are * saved/restored with saved games, and are passed via {@link Command} to other players' clients in a multiplayer game. * The persistent property value can then be read from the piece via e.g. {@link #getProperty}. When reading back properties * out of a piece, the piece's built-in properties are checked first, then scratchpad properties (see {@link #setProperty}), * then external properties such as Global Properties. If <i>only</i> persistentProperties are to be searched, use * {@link #getPersistentProperty} instead. * * <br><br>In practical terms, setPersistentProperty is used mainly to implement the "Old" properties of BasicPiece (e.g. * "OldLocationName", "OldZone", "OldMap", "OldBoard", "OldX", "OldY"). A Persistent Property is indeed nearly identical * with {@link DynamicProperty} in storage/retrieval characteristics, and simply lacks the in-module interface for setting * values, etc. Module Designers are thus recommended to stick with Dynamic Property traits for these functions. * * @param key String key naming the persistent property to be set. If a corresponding persistent property does not exist it will be created. * @param newValue New value for the persistent property * @return a {@link Command} object which, when passed to another player's client via logfile, server, or saved game, will allow the * result of the "set" operation to be replicated. */ @Override public Command setPersistentProperty(Object key, Object newValue) { if (persistentProps == null) { persistentProps = new HashMap<>(); } final Object oldValue = newValue == null ? persistentProps.remove(key) : persistentProps.put(key, newValue); return Objects.equals(oldValue, newValue) ? null : new SetPersistentPropertyCommand(getId(), key, oldValue, newValue); } /** * @param key String key naming the persistent property whose value is to be returned. * @return the current value of a persistent property, or null if it doesn't exist. */ @Override public Object getPersistentProperty(Object key) { return persistentProps == null ? null : persistentProps.get(key); } /** * @param s Name of a module preference to be read * @return Value of the preference */ protected Object prefsValue(String s) { return GameModule.getGameModule().getPrefs().getValue(s); } /** * Draws the BasicPiece's image, if it has been set * @param g target Graphics object * @param x x-location of the center of the piece * @param y y-location of the center of the piece * @param obs the Component on which this piece is being drawn * @param zoom the scaling factor. */ @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { if (imageBounds == null) { imageBounds = boundingBox(); } imagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs); } /** * @return the set of key commands that will populate the a BasicPiece's right-click menu. * This will normally be an empty array in the present age of the world, but the ability to contain a * clone and delete command is retained for compatibility with Modules Of Ancient Times. * In the case of BasicPiece, this method also keeps track of whether move up/down/to-top/to-bottom commands are enabled. * * This method is chained from "outer" Decorator components of a larger logical game piece, in the process of generating * the complete list of key commands to build the right-click menu -- this process is originated by calling <code>getKeyCommands()</code> * on the piece's outermost Decorator/Trait. */ protected KeyCommand[] getKeyCommands() { if (commands == null) { final ArrayList<KeyCommand> l = new ArrayList<>(); final GamePiece target = Decorator.getOutermost(this); if (cloneKey > 0) { l.add(new KeyCommand(Resources.getString("Editor.Clone.clone"), KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK), target)); } if (deleteKey > 0) { l.add(new KeyCommand(Resources.getString("Editor.Delete.delete"), KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK), target)); } commands = l.toArray(new KeyCommand[0]); } final GamePiece outer = Decorator.getOutermost(this); // This code has no function that I can see? There is no way to add these Commands. // boolean canAdjustPosition = outer.getMap() != null && outer.getParent() != null && outer.getParent().topPiece() != getParent().bottomPiece(); // enableCommand("Move up", canAdjustPosition); // enableCommand("Move down", canAdjustPosition); // enableCommand("Move to top", canAdjustPosition); // enableCommand("Move to bottom", canAdjustPosition); enableCommand(Resources.getString("Editor.Clone.clone"), outer.getMap() != null); enableCommand(Resources.getString("Editor.Delete.delete"), outer.getMap() != null); return commands; } /** * @param name Name of internal-to-BasicPiece key command whose enabled status it to be set * @param enable true to enable, false to disable. */ private void enableCommand(String name, boolean enable) { for (final KeyCommand command : commands) { if (name.equals(command.getName())) { command.setEnabled(enable); } } } /** * @param stroke KeyStroke to query if corresponding internal-to-BasicPiece command is enabled * @return false if no Keystroke, true if not an internal-to-BasicPiece key command, and enabled status of key command otherwise. */ private boolean isEnabled(KeyStroke stroke) { if (stroke == null) { return false; } for (final KeyCommand command : commands) { if (stroke.equals(command.getKeyStroke())) { return command.isEnabled(); } } return true; } /** * @return piece's position on its map. */ @Override public Point getPosition() { return getParent() == null ? new Point(pos) : getParent().getPosition(); } /** * @param p Sets the location of this piece on its {@link Map} */ @Override public void setPosition(Point p) { if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } pos = p; if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } } /** * @return the parent {@link Stack} of which this piece is a member, or null if not a member of any Stack */ @Override public Stack getParent() { return parent; } /** * @param s sets the {@link Stack} to which this piece belongs. */ @Override public void setParent(Stack s) { parent = s; } /** * @return bounding box rectangle for BasicPiece's image, if an image has been specified. */ @Override public Rectangle boundingBox() { if (imageBounds == null) { imageBounds = ImageUtils.getBounds(imagePainter.getImageSize()); } return new Rectangle(imageBounds); } /** * @return the Shape of this piece, for purposes of selecting it by clicking on it with the mouse. In the case * of BasicPiece, this is equivalent to the boundingBox of the BasicPiece image, if one exists. Note that the * shape should be defined in reference to the piece's location, which is ordinarily the center of the basic * image. * * <br><br>For pieces that need a non-rectangular click volume, add a {@link NonRectangular} trait. */ @Override public Shape getShape() { return boundingBox(); } /** * @param c GamePiece to check if equal to this one * @return Equality check with specified game piece */ public boolean equals(GamePiece c) { return c == this; } /** * @return the name of this GamePiece. This is the name typed by the module designer in the configuration box * for the BasicPiece. */ @Override public String getName() { return commonName; } /** * @return the localized name of this GamePiece. This is the translated version of the name typed by the module designer * in the configuration box for the BasicPiece. It is used to fill the "BasicName" property. */ @Override public String getLocalizedName() { final String key = TranslatablePiece.PREFIX + getName(); return Localization.getInstance().translate(key, getName()); } /** * The primary way for the piece or trait to receive events. {@link KeyStroke} events are forward * to this method if they are received while the piece is selected (or as the result of e.g. a Global * Key Command being sent to the piece). The class implementing GamePiece can respond in any way it * likes. Actual key presses by the player, selected items from the right-click Context Menu, keystrokes * "applied on move" by a Map that the piece has just moved on, and Global Key Commands all send KeyStrokes * (and NamedKeyStrokes) which are passed to pieces and traits through this interface. * * <br><br>In the case of BasicPiece, if a key command gets here, that means it has already been seen by any and all of * its Traits ({@link Decorator}s), as BasicPiece is the innermost member of the Decorator stack. The key events * processed here by BasicPiece include the "move up"/"move down"/"move-to-top"/"move-to-bottom" stack-adjustment * commands, along with legacy support for cloning and deleting. * * @return a {@link Command} that, when executed, will make all changes to the game state (maps, pieces, other * pieces, etc) to duplicate what the piece did in response to this event on another machine. Often a * {@link ChangePiece} command, but for example if this keystroke caused the piece/trait to decide to fire * off a Global Key Command, then the Command returned would include the <i>entire</i> results of that, appended * as subcommands. * * @see VASSAL.build.module.map.ForwardToKeyBuffer */ @Override public Command keyEvent(KeyStroke stroke) { getKeyCommands(); if (!isEnabled(stroke)) { return null; } Command comm = null; final GamePiece outer = Decorator.getOutermost(this); if (cloneKey != 0 && KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) { final GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode(GameModule.getGameModule().encode(new AddPiece(outer)))).getTarget(); newPiece.setId(null); GameModule.getGameModule().getGameState().addPiece(newPiece); newPiece.setState(outer.getState()); comm = new AddPiece(newPiece); if (getMap() != null) { comm.append(getMap().placeOrMerge(newPiece, getPosition())); KeyBuffer.getBuffer().remove(outer); KeyBuffer.getBuffer().add(newPiece); if (GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) { final String name = outer.getLocalizedName(); final String loc = getMap().locationName(outer.getPosition()); final String s; if (loc != null) { s = Resources.getString("BasicPiece.clone_report_1", name, loc); } else { s = Resources.getString("BasicPiece.clone_report_2", name); } final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); report.execute(); comm = comm.append(report); } } } else if (deleteKey != 0 && KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) { comm = new RemovePiece(outer); if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) { final String name = outer.getLocalizedName(); final String loc = getMap().locationName(outer.getPosition()); final String s; if (loc != null) { s = Resources.getString("BasicPiece.delete_report_1", name, loc); } else { s = Resources.getString("BasicPiece.delete_report_2", name); } final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); comm = comm.append(report); } comm.execute(); } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) { if (parent != null) { final String oldState = parent.getState(); final int index = parent.indexOf(outer); if (index < parent.getPieceCount() - 1) { parent.insert(outer, index + 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) { if (parent != null) { final String oldState = parent.getState(); final int index = parent.indexOf(outer); if (index > 0) { parent.insert(outer, index - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) { parent = outer.getParent(); if (parent != null) { final String oldState = parent.getState(); if (parent.indexOf(outer) < parent.getPieceCount() - 1) { parent.insert(outer, parent.getPieceCount() - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) { parent = getParent(); if (parent != null) { final String oldState = parent.getState(); if (parent.indexOf(outer) > 0) { parent.insert(outer, 0); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } return comm; } /** * @return The "state information" is information that can change during * the course of a game. State information is saved when the game * is saved and is transferred between players on the server. For * example, the relative order of pieces in a stack is state * information, but whether the stack is expanded is not. * * <br><br>In the case of BasicPiece, the state information includes the current * map, x/y position, the unique Game Piece ID, and the keys and values * of any persistent properties (see {@link #setPersistentProperty}) */ @Override public String getState() { final SequenceEncoder se = new SequenceEncoder(';'); final String mapName = map == null ? "null" : map.getIdentifier(); // NON-NLS se.append(mapName); final Point p = getPosition(); se.append(p.x).append(p.y); se.append(getGpId()); se.append(persistentProps == null ? 0 : persistentProps.size()); // Persistent Property values will always be String (for now). if (persistentProps != null) { persistentProps.forEach((key, val) -> { se.append(key == null ? "" : key.toString()); se.append(val == null ? "" : val.toString()); }); } return se.getValue(); } /** * @param s New state information serialized in string form, ready * to be passed to a SequenceEncoder#decode. The "state information" is * information that can change during the course of a game. State information * is saved when the game is saved and is transferred between players on the * server. For example, the relative order of pieces in a stack is state * information, but whether the stack is expanded is not. * * <br><br>In the case of BasicPiece, the state information includes the current * map, x/y position, the unique Game Piece ID, and the keys and values * of any persistent properties (see {@link #setPersistentProperty}) */ @Override public void setState(String s) { final GamePiece outer = Decorator.getOutermost(this); final Map oldMap = getMap(); final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, ';'); final String mapId = st.nextToken(); Map newMap = null; if (!"null".equals(mapId)) { // NON-NLS newMap = Map.getMapById(mapId); if (newMap == null) { Decorator.reportDataError(this, Resources.getString("Error.not_found", "Map"), "mapId=" + mapId); // NON-NLS } } final Point newPos = new Point(st.nextInt(0), st.nextInt(0)); setPosition(newPos); if (newMap != oldMap) { if (newMap != null) { // This will remove from oldMap // and set the map to newMap newMap.addPiece(outer); } else { // oldMap can't possibly be null if we get to here oldMap.removePiece(outer); setMap(null); } } setGpId(st.nextToken("")); // Persistent Property values will always be String (for now). // Create the HashMap as lazily as possible, no point in creating it for pieces that never move if (persistentProps != null) { persistentProps.clear(); } final int propCount = st.nextInt(0); for (int i = 0; i < propCount; i++) { if (persistentProps == null) { persistentProps = new HashMap<>(); } final String key = st.nextToken(""); final String val = st.nextToken(""); persistentProps.put(key, val); } } /** * For BasicPiece, the "merge" of a new state simply involves copying in the * new one in its entirety -- if any difference is detected. * @param newState new serialized game state string * @param oldState old serialized game state string */ @Override public void mergeState(String newState, String oldState) { if (!newState.equals(oldState)) { setState(newState); } } /** * Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never * be changed by custom code. * @return unique ID for this piece * @see GameState#getNewPieceId */ @Override public String getId() { return id; } /** * Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never * be changed by custom code. * @param id sets unique ID for this piece * @see GameState#getNewPieceId */ @Override public void setId(String id) { this.id = id; } /** * @return the Highlighter instance for drawing selected pieces. Note that since this is a static method, all pieces in a * module will always use the same Highlighter */ public static Highlighter getHighlighter() { if (highlighter == null) { highlighter = new ColoredBorder(); } return highlighter; } /** * @param h Set the Highlighter for all pieces */ public static void setHighlighter(Highlighter h) { highlighter = h; } /** * @return Description of what this kind of piece is. Appears in PieceDefiner list of traits. */ @Override public String getDescription() { return Resources.getString("Editor.BasicPiece.trait_description"); } /** * @return the unique gamepiece ID for this piece, as stored in the Property "scratchpad" */ public String getGpId() { final String id = (String) getProperty(Properties.PIECE_ID); return id == null ? "" : id; } /** * @param id stores the unique gamepiece ID for this piece into the Property "scratchpad" */ public void setGpId(String id) { setProperty(Properties.PIECE_ID, id == null ? "" : id); } /** * @return the help file page for this type of piece. */ @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("BasicPiece.html"); // NON-NLS } /** * @return The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the * BasicPiece's type information in the Editor window. */ @Override public PieceEditor getEditor() { return new Ed(this); } /** * Test if this BasicPiece's Type and State are equal to another * This method is intended to be used by Unit Tests to verify that a trait * is unchanged after going through a process such as serialization/deserialization. * * @param o Object to compare this Decorator to * @return true if the Class, type and state all match */ public boolean testEquals(Object o) { // Check Class type if (! (o instanceof BasicPiece)) return false; final BasicPiece bp = (BasicPiece) o; // Check Type if (! Objects.equals(cloneKey, bp.cloneKey)) return false; if (! Objects.equals(deleteKey, bp.deleteKey)) return false; if (! Objects.equals(imageName, bp.imageName)) return false; if (! Objects.equals(commonName, bp.commonName)) return false; // Check State final String mapName1 = this.map == null ? "null" : this.map.getIdentifier(); // NON-NLS final String mapName2 = bp.map == null ? "null" : bp.map.getIdentifier(); // NON-NLS if (! Objects.equals(mapName1, mapName2)) return false; if (! Objects.equals(getPosition(), bp.getPosition())) return false; if (! Objects.equals(getGpId(), bp.getGpId())) return false; final int pp1 = persistentProps == null ? 0 : persistentProps.size(); final int pp2 = bp.persistentProps == null ? 0 : bp.persistentProps.size(); if (! Objects.equals(pp1, pp2)) return false; if (persistentProps != null && bp.persistentProps != null) { for (final Object key : persistentProps.keySet()) { if (!Objects.equals(persistentProps.get(key), bp.persistentProps.get(key))) return false; } } return true; } /** * The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the * BasicPiece's type information in the Editor window. */ private static class Ed implements PieceEditor { private TraitConfigPanel panel; private KeySpecifier cloneKeyInput; private KeySpecifier deleteKeyInput; private StringConfigurer pieceName; private ImageSelector picker; private final String state; /** * @param p to create PieceEditor for */ private Ed(BasicPiece p) { state = p.getState(); initComponents(p); } /** * @param p initializes the editor dialog for the specified BasicPiece */ private void initComponents(BasicPiece p) { panel = new TraitConfigPanel(); pieceName = new StringConfigurer(p.commonName); panel.add("Editor.name_label", pieceName); cloneKeyInput = new KeySpecifier(p.cloneKey); if (p.cloneKey != 0) { panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_clone"))); panel.add(cloneKeyInput); } deleteKeyInput = new KeySpecifier(p.deleteKey); if (p.deleteKey != 0) { panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_delete"))); panel.add(deleteKeyInput); } picker = new ImageSelector(p.imageName); panel.add("Editor.image_label", picker); } /** * @param p BasicPiece */ public void reset(BasicPiece p) { } /** * @return the Component for the BasicPiece configurer */ @Override public Component getControls() { return panel; } /** * @return the current state string for the BasicPiece */ @Override public String getState() { return state; } /** * @return the type information string for the BasicPiece based on the current values of the configurer fields */ @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(cloneKeyInput.getKey(), ';'); final String type = se.append(deleteKeyInput.getKey()).append(picker.getValueString()).append(pieceName.getValueString()).getValue(); return BasicPiece.ID + type; } } /** * @return String enumeration of type and state information. */ @Override public String toString() { return super.toString() + "[name=" + getName() + ",type=" + getType() + ",state=" + getState() + "]"; // NON-NLS } /** * @return Object encapsulating the internationalization data for the BasicPiece */ @Override public PieceI18nData getI18nData() { final PieceI18nData data = new PieceI18nData(this); data.add(commonName, Resources.getString("Editor.BasicPiece.basic_piece_name_description")); return data; } /** * @return Property names exposed by the Trait or Piece. In the case of BasicPiece, there are quite a few, mainly * dealing with past and present location. */ @Override public List<String> getPropertyNames() { final ArrayList<String> l = new ArrayList<>(); l.add(LOCATION_NAME); l.add(CURRENT_MAP); l.add(CURRENT_BOARD); l.add(CURRENT_ZONE); l.add(CURRENT_X); l.add(CURRENT_Y); l.add(OLD_LOCATION_NAME); l.add(OLD_MAP); l.add(OLD_BOARD); l.add(OLD_ZONE); l.add(OLD_X); l.add(OLD_Y); l.add(BASIC_NAME); l.add(PIECE_NAME); l.add(DECK_NAME); l.add(CLICKED_X); l.add(CLICKED_Y); return l; } /** * See {@link AbstractImageFinder} * Adds our image (if any) to the list of images * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { if (imageName != null) s.add(imageName); } }
Localized Piece Names exposed to Beanshell for creating display strings
vassal-app/src/main/java/VASSAL/counters/BasicPiece.java
Localized Piece Names exposed to Beanshell for creating display strings
Java
lgpl-2.1
0c1adfb926ae3c633393501b9eefb25ad0fa0c12
0
jfree/jfreechart,jfree/jfreechart,jfree/jfreechart,jfree/jfreechart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2017, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * */ package org.jfree.chart.text; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.text.AttributedString; import java.text.BreakIterator; import org.jfree.chart.ui.TextAnchor; /** * Some utility methods for working with text in Java2D. */ public class TextUtils { /** * When this flag is set to {@code true}, strings will be drawn * as attributed strings with the attributes taken from the current font. * This allows for underlining, strike-out etc, but it means that * TextLayout will be used to render the text: * * http://www.jfree.org/phpBB2/viewtopic.php?p=45459&highlight=#45459 */ private static boolean drawStringsWithFontAttributes = false; /** * A flag that controls whether or not the rotated string workaround is * used. */ private static boolean useDrawRotatedStringWorkaround = true; /** * A flag that controls whether the FontMetrics.getStringBounds() method * is used or a workaround is applied. */ private static boolean useFontMetricsGetStringBounds = false; /** * Private constructor prevents object creation. */ private TextUtils() { // prevent instantiation } /** * Creates a {@link TextBlock} from a {@code String}. Line breaks * are added where the {@code String} contains '\n' characters. * * @param text the text. * @param font the font. * @param paint the paint. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } TextBlock result = new TextBlock(); String input = text; boolean moreInputToProcess = (text.length() > 0); int start = 0; while (moreInputToProcess) { int index = input.indexOf("\n"); if (index > start) { String line = input.substring(start, index); if (index < input.length() - 1) { result.addLine(line, font, paint); input = input.substring(index + 1); } else { moreInputToProcess = false; } } else if (index == start) { if (index < input.length() - 1) { input = input.substring(index + 1); } else { moreInputToProcess = false; } } else { result.addLine(input, font, paint); moreInputToProcess = false; } } return result; } /** * Creates a new text block from the given string, breaking the * text into lines so that the {@code maxWidth} value is respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, TextMeasurer measurer) { return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE, measurer); } /** * Creates a new text block from the given string, breaking the * text into lines so that the {@code maxWidth} value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param maxLines the maximum number of lines. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) { TextBlock result = new TextBlock(); BreakIterator iterator = BreakIterator.getLineInstance(); iterator.setText(text); int current = 0; int lines = 0; int length = text.length(); while (current < length && lines < maxLines) { int next = nextLineBreak(text, current, maxWidth, iterator, measurer); if (next == BreakIterator.DONE) { result.addLine(text.substring(current), font, paint); return result; } else if (next == current) { next++; // we must take one more character or we'll loop forever } result.addLine(text.substring(current, next), font, paint); lines++; current = next; while (current < text.length()&& text.charAt(current) == '\n') { current++; } } if (current < length) { TextLine lastLine = result.getLastLine(); TextFragment lastFragment = lastLine.getLastTextFragment(); String oldStr = lastFragment.getText(); String newStr = "..."; if (oldStr.length() > 3) { newStr = oldStr.substring(0, oldStr.length() - 3) + "..."; } lastLine.removeFragment(lastFragment); TextFragment newFragment = new TextFragment(newStr, lastFragment.getFont(), lastFragment.getPaint()); lastLine.addFragment(newFragment); } return result; } /** * Returns the character index of the next line break. If the next * character is wider than {@code width]} this method will return * {@code start} - the caller should check for this case. * * @param text the text ({@code null} not permitted). * @param start the start index. * @param width the target display width. * @param iterator the word break iterator. * @param measurer the text measurer. * * @return The index of the next line break. */ private static int nextLineBreak(String text, int start, float width, BreakIterator iterator, TextMeasurer measurer) { // this method is (loosely) based on code in JFreeReport's // TextParagraph class int current = start; int end; float x = 0.0f; boolean firstWord = true; int newline = text.indexOf('\n', start); if (newline < 0) { newline = Integer.MAX_VALUE; } while (((end = iterator.following(current)) != BreakIterator.DONE)) { x += measurer.getStringWidth(text, current, end); if (x > width) { if (firstWord) { while (measurer.getStringWidth(text, start, end) > width) { end--; if (end <= start) { return end; } } return end; } else { end = iterator.previous(); return end; } } else { if (end > newline) { return newline; } } // we found at least one word that fits ... firstWord = false; current = end; } return BreakIterator.DONE; } /** * Returns the bounds for the specified text. * * @param text the text ({@code null} permitted). * @param g2 the graphics context (not {@code null}). * @param fm the font metrics (not {@code null}). * * @return The text bounds ({@code null} if the {@code text} * argument is {@code null}). */ public static Rectangle2D getTextBounds(String text, Graphics2D g2, FontMetrics fm) { Rectangle2D bounds; if (TextUtils.useFontMetricsGetStringBounds) { bounds = fm.getStringBounds(text, g2); // getStringBounds() can return incorrect height for some Unicode // characters...see bug parade 6183356, let's replace it with // something correct LineMetrics lm = fm.getFont().getLineMetrics(text, g2.getFontRenderContext()); bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(), lm.getHeight()); } else { double width = fm.stringWidth(text); double height = fm.getHeight(); bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width, height); } return bounds; } /** * Returns the bounds of an aligned string. * * @param text the string ({@code null} not permitted). * @param g2 the graphics target ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * @param anchor the anchor point that will be aligned to * {@code (x, y)} ({@code null} not permitted). * * @return The text bounds (never {@code null}). * * @since 1.3 */ public static Rectangle2D calcAlignedStringBounds(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); return textBounds; } /** * Draws a string such that the specified anchor point is aligned to the * given (x, y) location. * * @param text the text. * @param g2 the graphics device. * @param x the x coordinate (Java 2D). * @param y the y coordinate (Java 2D). * @param anchor the anchor location. * * @return The text bounds (adjusted for the text position). */ public static Rectangle2D drawAlignedString(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); if (!drawStringsWithFontAttributes) { g2.drawString(text, x + adjust[0], y + adjust[1]); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]); } return textBounds; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not {@code null}). * @param text the text. * @param anchor the anchor point. * @param textBounds the text bounds (if not {@code null}, this * object will be updated by this method to match the * string bounds). * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor, Rectangle2D textBounds) { float[] result = new float[3]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); result[2] = -ascent; float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } if (textBounds != null) { textBounds.setRect(bounds); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param angle the angle of the (clockwise) rotation (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ public static void drawRotatedString(String text, Graphics2D g2, double angle, float x, float y) { drawRotatedString(text, g2, x, y, angle, x, y); } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param textX the x-coordinate for the text (before rotation). * @param textY the y-coordinate for the text (before rotation). * @param angle the angle of the (clockwise) rotation (in radians). * @param rotateX the point about which the text is rotated. * @param rotateY the point about which the text is rotated. */ public static void drawRotatedString(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return; } if (angle == 0.0) { drawAlignedString(text, g2, textX, textY, TextAnchor.BASELINE_LEFT); return; } AffineTransform saved = g2.getTransform(); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); g2.transform(rotate); if (useDrawRotatedStringWorkaround) { // workaround for JDC bug ID 4312117 and others... TextLayout tl = new TextLayout(text, g2.getFont(), g2.getFontRenderContext()); tl.draw(g2, textX, textY); } else { if (!drawStringsWithFontAttributes) { g2.drawString(text, textX, textY); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), textX, textY); } } g2.setTransform(saved); } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle. * @param rotationX the x-coordinate for the rotation anchor point. * @param rotationY the y-coordinate for the rotation anchor point. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, float rotationX, float rotationY) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, rotationX, rotationY); } } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle (in radians). * @param rotationAnchor the rotation anchor. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); } } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text ({@code null} permitted). * @param g2 the graphics device. * @param x the x coordinate for the anchor point. * @param y the y coordinate for the anchor point. * @param textAnchor the text anchor. * @param angle the angle. * @param rotationAnchor the rotation anchor. * * @return The bounds (possibly {@code null}). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return null; } float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); Shape result = calculateRotatedStringBounds(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); return result; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not {@code null}). * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method that calculates the rotation anchor offsets for a * string. These offsets are relative to the text starting coordinate * ({@code BASELINE_LEFT}). * * @param g2 the graphics device. * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveRotationAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); LineMetrics metrics = g2.getFont().getLineMetrics(text, frc); FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isLeft()) { xAdj = 0.0f; } else if (anchor.isHorizontalCenter()) { xAdj = (float) bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) bounds.getWidth(); } if (anchor.isTop()) { yAdj = descent + leading - (float) bounds.getHeight(); } else if (anchor.isVerticalCenter()) { yAdj = descent + leading - (float) (bounds.getHeight() / 2.0); } else if (anchor.isHalfAscent()) { yAdj = -halfAscent; } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = metrics.getDescent() + metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text ({@code null} permitted). * @param g2 the graphics device. * @param textX the x coordinate for the text. * @param textY the y coordinate for the text. * @param angle the angle. * @param rotateX the x coordinate for the rotation point. * @param rotateY the y coordinate for the rotation point. * * @return The bounds ({@code null} if {@code text} is * {@code null} or has zero length). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return null; } FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); AffineTransform translate = AffineTransform.getTranslateInstance( textX, textY); Shape translatedBounds = translate.createTransformedShape(bounds); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); Shape result = rotate.createTransformedShape(translatedBounds); return result; } /** * Returns the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @return A boolean. */ public static boolean getUseFontMetricsGetStringBounds() { return useFontMetricsGetStringBounds; } /** * Sets the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @param use the flag. */ public static void setUseFontMetricsGetStringBounds(boolean use) { useFontMetricsGetStringBounds = use; } /** * Returns the flag that controls whether or not a workaround is used for * drawing rotated strings. * * @return A boolean. */ public static boolean isUseDrawRotatedStringWorkaround() { return useDrawRotatedStringWorkaround; } /** * Sets the flag that controls whether or not a workaround is used for * drawing rotated strings. The related bug is on Sun's bug parade * (id 4312117) and the workaround involves using a {@code TextLayout} * instance to draw the text instead of calling the * {@code drawString()} method in the {@code Graphics2D} class. * * @param use the new flag value. */ public static void setUseDrawRotatedStringWorkaround(boolean use) { TextUtils.useDrawRotatedStringWorkaround = use; } /** * Returns the flag that controls whether or not strings are drawn using * the current font attributes (such as underlining, strikethrough etc). * The default value is {@code false}. * * @return A boolean. * * @since 1.0.21 */ public static boolean getDrawStringsWithFontAttributes() { return TextUtils.drawStringsWithFontAttributes; } /** * Sets the flag that controls whether or not strings are drawn using the * current font attributes. This is a hack to allow underlining of titles * without big changes to the API. See: * http://www.jfree.org/phpBB2/viewtopic.php?p=45459&amp;highlight=#45459 * * @param b the new flag value. * * @since 1.0.21 */ public static void setDrawStringsWithFontAttributes(boolean b) { TextUtils.drawStringsWithFontAttributes = b; } }
src/main/java/org/jfree/chart/text/TextUtils.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2017, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * */ package org.jfree.chart.text; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.text.AttributedString; import java.text.BreakIterator; import org.jfree.chart.ui.TextAnchor; /** * Some utility methods for working with text in Java2D. */ public class TextUtils { /** * When this flag is set to {@code true}, strings will be drawn * as attributed strings with the attributes taken from the current font. * This allows for underlining, strike-out etc, but it means that * TextLayout will be used to render the text: * * http://www.jfree.org/phpBB2/viewtopic.php?p=45459&highlight=#45459 */ private static boolean drawStringsWithFontAttributes = false; /** * A flag that controls whether or not the rotated string workaround is * used. */ private static boolean useDrawRotatedStringWorkaround = true; /** * A flag that controls whether the FontMetrics.getStringBounds() method * is used or a workaround is applied. */ private static boolean useFontMetricsGetStringBounds = false; /** * Private constructor prevents object creation. */ private TextUtils() { // prevent instantiation } /** * Creates a {@link TextBlock} from a {@code String}. Line breaks * are added where the {@code String} contains '\n' characters. * * @param text the text. * @param font the font. * @param paint the paint. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } TextBlock result = new TextBlock(); String input = text; boolean moreInputToProcess = (text.length() > 0); int start = 0; while (moreInputToProcess) { int index = input.indexOf("\n"); if (index > start) { String line = input.substring(start, index); if (index < input.length() - 1) { result.addLine(line, font, paint); input = input.substring(index + 1); } else { moreInputToProcess = false; } } else if (index == start) { if (index < input.length() - 1) { input = input.substring(index + 1); } else { moreInputToProcess = false; } } else { result.addLine(input, font, paint); moreInputToProcess = false; } } return result; } /** * Creates a new text block from the given string, breaking the * text into lines so that the {@code maxWidth} value is respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, TextMeasurer measurer) { return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE, measurer); } /** * Creates a new text block from the given string, breaking the * text into lines so that the <code>maxWidth</code> value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param maxLines the maximum number of lines. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(String text, Font font, Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) { TextBlock result = new TextBlock(); BreakIterator iterator = BreakIterator.getLineInstance(); iterator.setText(text); int current = 0; int lines = 0; int length = text.length(); while (current < length && lines < maxLines) { int next = nextLineBreak(text, current, maxWidth, iterator, measurer); if (next == BreakIterator.DONE) { result.addLine(text.substring(current), font, paint); return result; } else if (next == current) { next++; // we must take one more character or we'll loop forever } result.addLine(text.substring(current, next), font, paint); lines++; current = next; while (current < text.length()&& text.charAt(current) == '\n') { current++; } } if (current < length) { TextLine lastLine = result.getLastLine(); TextFragment lastFragment = lastLine.getLastTextFragment(); String oldStr = lastFragment.getText(); String newStr = "..."; if (oldStr.length() > 3) { newStr = oldStr.substring(0, oldStr.length() - 3) + "..."; } lastLine.removeFragment(lastFragment); TextFragment newFragment = new TextFragment(newStr, lastFragment.getFont(), lastFragment.getPaint()); lastLine.addFragment(newFragment); } return result; } /** * Returns the character index of the next line break. If the next * character is wider than <code>width</code> this method will return * <code>start</code> - the caller should check for this case. * * @param text the text (<code>null</code> not permitted). * @param start the start index. * @param width the target display width. * @param iterator the word break iterator. * @param measurer the text measurer. * * @return The index of the next line break. */ private static int nextLineBreak(String text, int start, float width, BreakIterator iterator, TextMeasurer measurer) { // this method is (loosely) based on code in JFreeReport's // TextParagraph class int current = start; int end; float x = 0.0f; boolean firstWord = true; int newline = text.indexOf('\n', start); if (newline < 0) { newline = Integer.MAX_VALUE; } while (((end = iterator.following(current)) != BreakIterator.DONE)) { x += measurer.getStringWidth(text, current, end); if (x > width) { if (firstWord) { while (measurer.getStringWidth(text, start, end) > width) { end--; if (end <= start) { return end; } } return end; } else { end = iterator.previous(); return end; } } else { if (end > newline) { return newline; } } // we found at least one word that fits ... firstWord = false; current = end; } return BreakIterator.DONE; } /** * Returns the bounds for the specified text. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics context (not <code>null</code>). * @param fm the font metrics (not <code>null</code>). * * @return The text bounds (<code>null</code> if the <code>text</code> * argument is <code>null</code>). */ public static Rectangle2D getTextBounds(String text, Graphics2D g2, FontMetrics fm) { Rectangle2D bounds; if (TextUtils.useFontMetricsGetStringBounds) { bounds = fm.getStringBounds(text, g2); // getStringBounds() can return incorrect height for some Unicode // characters...see bug parade 6183356, let's replace it with // something correct LineMetrics lm = fm.getFont().getLineMetrics(text, g2.getFontRenderContext()); bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(), lm.getHeight()); } else { double width = fm.stringWidth(text); double height = fm.getHeight(); bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width, height); } return bounds; } /** * Returns the bounds of an aligned string. * * @param text the string ({@code null} not permitted). * @param g2 the graphics target ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * @param anchor the anchor point that will be aligned to * {@code (x, y)} ({@code null} not permitted). * * @return The text bounds (never {@code null}). * * @since 1.3 */ public static Rectangle2D calcAlignedStringBounds(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); return textBounds; } /** * Draws a string such that the specified anchor point is aligned to the * given (x, y) location. * * @param text the text. * @param g2 the graphics device. * @param x the x coordinate (Java 2D). * @param y the y coordinate (Java 2D). * @param anchor the anchor location. * * @return The text bounds (adjusted for the text position). */ public static Rectangle2D drawAlignedString(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); if (!drawStringsWithFontAttributes) { g2.drawString(text, x + adjust[0], y + adjust[1]); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]); } return textBounds; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not <code>null</code>). * @param text the text. * @param anchor the anchor point. * @param textBounds the text bounds (if not <code>null</code>, this * object will be updated by this method to match the * string bounds). * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor, Rectangle2D textBounds) { float[] result = new float[3]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); result[2] = -ascent; float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } if (textBounds != null) { textBounds.setRect(bounds); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param angle the angle of the (clockwise) rotation (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ public static void drawRotatedString(String text, Graphics2D g2, double angle, float x, float y) { drawRotatedString(text, g2, x, y, angle, x, y); } /** * A utility method for drawing rotated text. * <P> * A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param textX the x-coordinate for the text (before rotation). * @param textY the y-coordinate for the text (before rotation). * @param angle the angle of the (clockwise) rotation (in radians). * @param rotateX the point about which the text is rotated. * @param rotateY the point about which the text is rotated. */ public static void drawRotatedString(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return; } if (angle == 0.0) { drawAlignedString(text, g2, textX, textY, TextAnchor.BASELINE_LEFT); return; } AffineTransform saved = g2.getTransform(); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); g2.transform(rotate); if (useDrawRotatedStringWorkaround) { // workaround for JDC bug ID 4312117 and others... TextLayout tl = new TextLayout(text, g2.getFont(), g2.getFontRenderContext()); tl.draw(g2, textX, textY); } else { if (!drawStringsWithFontAttributes) { g2.drawString(text, textX, textY); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), textX, textY); } } g2.setTransform(saved); } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle. * @param rotationX the x-coordinate for the rotation anchor point. * @param rotationY the y-coordinate for the rotation anchor point. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, float rotationX, float rotationY) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, rotationX, rotationY); } } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle (in radians). * @param rotationAnchor the rotation anchor. */ public static void drawRotatedString(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return; } if (angle == 0.0) { drawAlignedString(text, g2, x, y, textAnchor); } else { float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); } } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics device. * @param x the x coordinate for the anchor point. * @param y the y coordinate for the anchor point. * @param textAnchor the text anchor. * @param angle the angle. * @param rotationAnchor the rotation anchor. * * @return The bounds (possibly <code>null</code>). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float x, float y, TextAnchor textAnchor, double angle, TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return null; } float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); Shape result = calculateRotatedStringBounds(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); return result; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not <code>null</code>). * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); Font f = g2.getFont(); FontMetrics fm = g2.getFontMetrics(f); Rectangle2D bounds = getTextBounds(text, g2, fm); LineMetrics metrics = f.getLineMetrics(text, frc); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isHorizontalCenter()) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) -bounds.getWidth(); } if (anchor.isTop()) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor.isHalfAscent()) { yAdj = halfAscent; } else if (anchor.isVerticalCenter()) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = -metrics.getDescent() - metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method that calculates the rotation anchor offsets for a * string. These offsets are relative to the text starting coordinate * (<code>BASELINE_LEFT</code>). * * @param g2 the graphics device. * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveRotationAnchorOffsets(Graphics2D g2, String text, TextAnchor anchor) { float[] result = new float[2]; FontRenderContext frc = g2.getFontRenderContext(); LineMetrics metrics = g2.getFont().getLineMetrics(text, frc); FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); float ascent = metrics.getAscent(); float halfAscent = ascent / 2.0f; float descent = metrics.getDescent(); float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor.isLeft()) { xAdj = 0.0f; } else if (anchor.isHorizontalCenter()) { xAdj = (float) bounds.getWidth() / 2.0f; } else if (anchor.isRight()) { xAdj = (float) bounds.getWidth(); } if (anchor.isTop()) { yAdj = descent + leading - (float) bounds.getHeight(); } else if (anchor.isVerticalCenter()) { yAdj = descent + leading - (float) (bounds.getHeight() / 2.0); } else if (anchor.isHalfAscent()) { yAdj = -halfAscent; } else if (anchor.isBaseline()) { yAdj = 0.0f; } else if (anchor.isBottom()) { yAdj = metrics.getDescent() + metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (<code>null</code> permitted). * @param g2 the graphics device. * @param textX the x coordinate for the text. * @param textY the y coordinate for the text. * @param angle the angle. * @param rotateX the x coordinate for the rotation point. * @param rotateY the y coordinate for the rotation point. * * @return The bounds (<code>null</code> if <code>text</code> is * <code>null</code> or has zero length). */ public static Shape calculateRotatedStringBounds(String text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { if ((text == null) || (text.equals(""))) { return null; } FontMetrics fm = g2.getFontMetrics(); Rectangle2D bounds = TextUtils.getTextBounds(text, g2, fm); AffineTransform translate = AffineTransform.getTranslateInstance( textX, textY); Shape translatedBounds = translate.createTransformedShape(bounds); AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); Shape result = rotate.createTransformedShape(translatedBounds); return result; } /** * Returns the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @return A boolean. */ public static boolean getUseFontMetricsGetStringBounds() { return useFontMetricsGetStringBounds; } /** * Sets the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @param use the flag. */ public static void setUseFontMetricsGetStringBounds(boolean use) { useFontMetricsGetStringBounds = use; } /** * Returns the flag that controls whether or not a workaround is used for * drawing rotated strings. * * @return A boolean. */ public static boolean isUseDrawRotatedStringWorkaround() { return useDrawRotatedStringWorkaround; } /** * Sets the flag that controls whether or not a workaround is used for * drawing rotated strings. The related bug is on Sun's bug parade * (id 4312117) and the workaround involves using a <code>TextLayout</code> * instance to draw the text instead of calling the * <code>drawString()</code> method in the <code>Graphics2D</code> class. * * @param use the new flag value. */ public static void setUseDrawRotatedStringWorkaround(boolean use) { TextUtils.useDrawRotatedStringWorkaround = use; } /** * Returns the flag that controls whether or not strings are drawn using * the current font attributes (such as underlining, strikethrough etc). * The default value is <code>false</code>. * * @return A boolean. * * @since 1.0.21 */ public static boolean getDrawStringsWithFontAttributes() { return TextUtils.drawStringsWithFontAttributes; } /** * Sets the flag that controls whether or not strings are drawn using the * current font attributes. This is a hack to allow underlining of titles * without big changes to the API. See: * http://www.jfree.org/phpBB2/viewtopic.php?p=45459&amp;highlight=#45459 * * @param b the new flag value. * * @since 1.0.21 */ public static void setDrawStringsWithFontAttributes(boolean b) { TextUtils.drawStringsWithFontAttributes = b; } }
Javadoc tags.
src/main/java/org/jfree/chart/text/TextUtils.java
Javadoc tags.
Java
unlicense
35ed83ae386c15599380d68c8a215f7a910c8553
0
TheGoodlike13/goodlike-utils
package eu.goodlike.time; import com.google.common.base.MoreObjects; import eu.goodlike.time.impl.TimeHandler; import java.time.LocalDate; import java.time.ZoneId; import java.util.Objects; /** * <pre> * Resolves epoch milliseconds from various formats * * Intended to reduce code duplication when checking for variables, etc * </pre> */ public final class TimeResolver { /** * @return epoch milliseconds of the starting time */ public long getStartTime() { return startTime; } /** * @return epoch milliseconds of the ending time */ public long getEndTime() { return endTime; } // CONSTRUCTORS /** * <pre> * Resolves the time using the following logic: * * 1) if start and end are set, use those; * 2) if at least one of them is not set, resolve the time from remaining parameters, then use that time * to set start, end or both and use those; * </pre> */ public static TimeResolver from(String timezone, String startDate, String endDate, Long start, Long end) { if (start == null || end == null) { TimeResolver step = TimeResolver.from(timezone, startDate, endDate); if (start == null) start = step.startTime; if (end == null) end = step.endTime; } return from(start, end); } /** * <pre> * Resolves the time using the following logic: * * 1) if timeZone is set, parse it, otherwise use default (UTC) * 2) if startDate is set, parse it to LocalDate using the timezone, otherwise set to current date using the timezone; * 3) if endDate is set, parse it to LocalDate using the timezone, otherwise set to startDate * 4) Resolve time from resulting ZoneId, start and end LocalDates * </pre> */ public static TimeResolver from(String timezone, String startDate, String endDate) { ZoneId zoneId = timezone == null ? Time.UTC() : ZoneId.of(timezone); LocalDate localStartDate = startDate == null ? LocalDate.now(zoneId) : LocalDate.parse(startDate); LocalDate localEndDate = endDate == null ? localStartDate : LocalDate.parse(endDate); return from(zoneId, localStartDate, localEndDate); } /** * Resolves the time using TimeHandler for given zoneId and given LocalDates */ public static TimeResolver from(ZoneId zoneId, LocalDate localStartDate, LocalDate localEndDate) { return from(Time.at(zoneId), localStartDate, localEndDate); } /** * <pre> * Resolves the time using the following logic: * * 1) get start epoch milliseconds from localStartDate; * 2) get end epoch milliseconds from localEndDate + 1 day (so it is inclusive); * 3) use start and end to resolve time * </pre> */ public static TimeResolver from(TimeHandler handler, LocalDate localStartDate, LocalDate localEndDate) { long start = handler.from(localStartDate).toEpochMilli(); long end = handler.from(localEndDate.plusDays(1)).toEpochMilli(); return from(start, end); } /** * @return TimeResolver for already known start/end epoch millisecond values; fairly pointless, exists for * compatibility only */ public static TimeResolver from(long start, long end) { return new TimeResolver(start, end); } public TimeResolver(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } // PRIVATE private final long startTime; private final long endTime; // OBJECT OVERRIDES @Override public String toString() { return MoreObjects.toStringHelper(this) .add("startTime", startTime) .add("endTime", endTime) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TimeResolver)) return false; TimeResolver that = (TimeResolver) o; return Objects.equals(startTime, that.startTime) && Objects.equals(endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(startTime, endTime); } }
src/main/java/eu/goodlike/time/TimeResolver.java
package eu.goodlike.time; import com.google.common.base.MoreObjects; import eu.goodlike.time.impl.TimeHandler; import java.time.LocalDate; import java.time.ZoneId; import java.util.Objects; /** * <pre> * Resolves epoch milliseconds from various formats * * Intended to reduce code duplication when checking for variables, etc * </pre> */ public final class TimeResolver { /** * @return epoch milliseconds of the starting time */ public long getStartTime() { return startTime; } /** * @return epoch milliseconds of the ending time */ public long getEndTime() { return endTime; } // CONSTRUCTORS /** * <pre> * Resolves the time using the following logic: * * 1) if start and end are set, use those; * 2) if at least one of them is not set, resolve the time from remaining parameters, then use that time * to set start, end or both and use those; * </pre> */ public static TimeResolver from(String timezone, String startDate, String endDate, Long start, Long end) { if (start == null || end == null) { TimeResolver step = TimeResolver.from(timezone, startDate, endDate); if (start == null) start = step.startTime; if (end == null) end = step.endTime; } return from(start, end); } /** * <pre> * Resolves the time using the following logic: * * 1) if timeZone is set, parse it, otherwise use default (UTC) * 2) if startDate is set, parse it to LocalDate using the timezone, otherwise set to current date using the timezone; * 3) if endDate is set, parse it to LocalDate using the timezone, otherwise set to startDate * 4) Resolve time from resulting ZoneId, start and end LocalDates * </pre> */ public static TimeResolver from(String timezone, String startDate, String endDate) { ZoneId zoneId = timezone == null ? Time.UTC() : ZoneId.of(timezone); LocalDate localStartDate = startDate == null ? LocalDate.now(zoneId) : LocalDate.parse(startDate); LocalDate localEndDate = endDate == null ? localStartDate : LocalDate.parse(endDate); return from(zoneId, localStartDate, localEndDate); } /** * Resolves the time using JodaTimeZoneHandler for given zoneId and given LocalDates */ public static TimeResolver from(ZoneId zoneId, LocalDate localStartDate, LocalDate localEndDate) { return from(Time.at(zoneId), localStartDate, localEndDate); } /** * <pre> * Resolves the time using the following logic: * * 1) get start epoch milliseconds from localStartDate; * 2) get end epoch milliseconds from localEndDate + 1 day (so it is inclusive); * 3) use start and end to resolve time * </pre> */ public static TimeResolver from(TimeHandler handler, LocalDate localStartDate, LocalDate localEndDate) { long start = handler.from(localStartDate).toEpochMilli(); long end = handler.from(localEndDate.plusDays(1)).toEpochMilli(); return from(start, end); } /** * @return TimeResolver for already known start/end epoch millisecond values; fairly pointless, exists for * compatibility only */ public static TimeResolver from(long start, long end) { return new TimeResolver(start, end); } public TimeResolver(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } // PRIVATE private final long startTime; private final long endTime; // OBJECT OVERRIDES @Override public String toString() { return MoreObjects.toStringHelper(this) .add("startTime", startTime) .add("endTime", endTime) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TimeResolver)) return false; TimeResolver that = (TimeResolver) o; return Objects.equals(startTime, that.startTime) && Objects.equals(endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(startTime, endTime); } }
Small doc fix
src/main/java/eu/goodlike/time/TimeResolver.java
Small doc fix
Java
apache-2.0
3b8eba2deac218b66624e4b9bb0c789c6a03489d
0
androidx/media,google/ExoPlayer,amzn/exoplayer-amazon-port,ened/ExoPlayer,google/ExoPlayer,ened/ExoPlayer,androidx/media,androidx/media,ened/ExoPlayer,amzn/exoplayer-amazon-port,google/ExoPlayer,amzn/exoplayer-amazon-port
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ui; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_BACK; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_FORWARD; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS; import static com.google.android.exoplayer2.Player.EVENT_AVAILABLE_COMMANDS_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_IS_PLAYING_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAYBACK_PARAMETERS_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAYBACK_STATE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAY_WHEN_READY_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_POSITION_DISCONTINUITY; import static com.google.android.exoplayer2.Player.EVENT_REPEAT_MODE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SEEK_BACK_INCREMENT_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SEEK_FORWARD_INCREMENT_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_TIMELINE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_TRACKS_CHANGED; import static com.google.android.exoplayer2.trackselection.TrackSelectionUtil.clearTrackSelectionOverridesForType; import static com.google.android.exoplayer2.trackselection.TrackSelectionUtil.forceTrackSelection; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Looper; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ControlDispatcher; import com.google.android.exoplayer2.DefaultControlDispatcher; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.ForwardingPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.Events; import com.google.android.exoplayer2.Player.State; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.TracksInfo; import com.google.android.exoplayer2.TracksInfo.TrackGroupInfo; import com.google.android.exoplayer2.source.TrackGroup; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters.TrackSelectionOverride; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.RepeatModeUtil; import com.google.android.exoplayer2.util.Util; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * A view for controlling {@link Player} instances. * * <p>A StyledPlayerControlView can be customized by setting attributes (or calling corresponding * methods), overriding drawables, overriding the view's layout file, or by specifying a custom view * layout file. * * <h2>Attributes</h2> * * The following attributes can be set on a StyledPlayerControlView when used in a layout XML file: * * <ul> * <li><b>{@code show_timeout}</b> - The time between the last user interaction and the controls * being automatically hidden, in milliseconds. Use zero if the controls should not * automatically timeout. * <ul> * <li>Corresponding method: {@link #setShowTimeoutMs(int)} * <li>Default: {@link #DEFAULT_SHOW_TIMEOUT_MS} * </ul> * <li><b>{@code show_rewind_button}</b> - Whether the rewind button is shown. * <ul> * <li>Corresponding method: {@link #setShowRewindButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_fastforward_button}</b> - Whether the fast forward button is shown. * <ul> * <li>Corresponding method: {@link #setShowFastForwardButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_previous_button}</b> - Whether the previous button is shown. * <ul> * <li>Corresponding method: {@link #setShowPreviousButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_next_button}</b> - Whether the next button is shown. * <ul> * <li>Corresponding method: {@link #setShowNextButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code repeat_toggle_modes}</b> - A flagged enumeration value specifying which repeat * mode toggle options are enabled. Valid values are: {@code none}, {@code one}, {@code all}, * or {@code one|all}. * <ul> * <li>Corresponding method: {@link #setRepeatToggleModes(int)} * <li>Default: {@link #DEFAULT_REPEAT_TOGGLE_MODES} * </ul> * <li><b>{@code show_shuffle_button}</b> - Whether the shuffle button is shown. * <ul> * <li>Corresponding method: {@link #setShowShuffleButton(boolean)} * <li>Default: false * </ul> * <li><b>{@code show_subtitle_button}</b> - Whether the subtitle button is shown. * <ul> * <li>Corresponding method: {@link #setShowSubtitleButton(boolean)} * <li>Default: false * </ul> * <li><b>{@code animation_enabled}</b> - Whether an animation is used to show and hide the * playback controls. * <ul> * <li>Corresponding method: {@link #setAnimationEnabled(boolean)} * <li>Default: true * </ul> * <li><b>{@code time_bar_min_update_interval}</b> - Specifies the minimum interval between time * bar position updates. * <ul> * <li>Corresponding method: {@link #setTimeBarMinUpdateInterval(int)} * <li>Default: {@link #DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS} * </ul> * <li><b>{@code controller_layout_id}</b> - Specifies the id of the layout to be inflated. See * below for more details. * <ul> * <li>Corresponding method: None * <li>Default: {@code R.layout.exo_styled_player_control_view} * </ul> * <li>All attributes that can be set on {@link DefaultTimeBar} can also be set on a * StyledPlayerControlView, and will be propagated to the inflated {@link DefaultTimeBar} * unless the layout is overridden to specify a custom {@code exo_progress} (see below). * </ul> * * <h2>Overriding drawables</h2> * * The drawables used by StyledPlayerControlView (with its default layout file) can be overridden by * drawables with the same names defined in your application. The drawables that can be overridden * are: * * <ul> * <li><b>{@code exo_styled_controls_play}</b> - The play icon. * <li><b>{@code exo_styled_controls_pause}</b> - The pause icon. * <li><b>{@code exo_styled_controls_rewind}</b> - The background of rewind icon. * <li><b>{@code exo_styled_controls_fastforward}</b> - The background of fast forward icon. * <li><b>{@code exo_styled_controls_previous}</b> - The previous icon. * <li><b>{@code exo_styled_controls_next}</b> - The next icon. * <li><b>{@code exo_styled_controls_repeat_off}</b> - The repeat icon for {@link * Player#REPEAT_MODE_OFF}. * <li><b>{@code exo_styled_controls_repeat_one}</b> - The repeat icon for {@link * Player#REPEAT_MODE_ONE}. * <li><b>{@code exo_styled_controls_repeat_all}</b> - The repeat icon for {@link * Player#REPEAT_MODE_ALL}. * <li><b>{@code exo_styled_controls_shuffle_off}</b> - The shuffle icon when shuffling is * disabled. * <li><b>{@code exo_styled_controls_shuffle_on}</b> - The shuffle icon when shuffling is enabled. * <li><b>{@code exo_styled_controls_vr}</b> - The VR icon. * </ul> * * <h2>Overriding the layout file</h2> * * To customize the layout of StyledPlayerControlView throughout your app, or just for certain * configurations, you can define {@code exo_styled_player_control_view.xml} layout files in your * application {@code res/layout*} directories. But, in this case, you need to be careful since the * default animation implementation expects certain relative positions between children. See also <a * href="CustomLayout">Specifying a custom layout file</a>. * * <p>The layout files in your {@code res/layout*} will override the one provided by the library, * and will be inflated for use by StyledPlayerControlView. The view identifies and binds its * children by looking for the following ids: * * <ul> * <li><b>{@code exo_play_pause}</b> - The play and pause button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_rew}</b> - The rewind button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_rew_with_amount}</b> - The rewind button with rewind amount. * <ul> * <li>Type: {@link TextView} * <li>Note: StyledPlayerControlView will programmatically set the text with the rewind * amount in seconds. Ignored if an {@code exo_rew} exists. Otherwise, it works as the * rewind button. * </ul> * <li><b>{@code exo_ffwd}</b> - The fast forward button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_ffwd_with_amount}</b> - The fast forward button with fast forward amount. * <ul> * <li>Type: {@link TextView} * <li>Note: StyledPlayerControlView will programmatically set the text with the fast * forward amount in seconds. Ignored if an {@code exo_ffwd} exists. Otherwise, it works * as the fast forward button. * </ul> * <li><b>{@code exo_prev}</b> - The previous button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_next}</b> - The next button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_repeat_toggle}</b> - The repeat toggle button. * <ul> * <li>Type: {@link ImageView} * <li>Note: StyledPlayerControlView will programmatically set the drawable on the repeat * toggle button according to the player's current repeat mode. The drawables used are * {@code exo_controls_repeat_off}, {@code exo_controls_repeat_one} and {@code * exo_controls_repeat_all}. See the section above for information on overriding these * drawables. * </ul> * <li><b>{@code exo_shuffle}</b> - The shuffle button. * <ul> * <li>Type: {@link ImageView} * <li>Note: StyledPlayerControlView will programmatically set the drawable on the shuffle * button according to the player's current repeat mode. The drawables used are {@code * exo_controls_shuffle_off} and {@code exo_controls_shuffle_on}. See the section above * for information on overriding these drawables. * </ul> * <li><b>{@code exo_vr}</b> - The VR mode button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_subtitle}</b> - The subtitle button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_fullscreen}</b> - The fullscreen button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_minimal_fullscreen}</b> - The fullscreen button in minimal mode. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_position}</b> - Text view displaying the current playback position. * <ul> * <li>Type: {@link TextView} * </ul> * <li><b>{@code exo_duration}</b> - Text view displaying the current media duration. * <ul> * <li>Type: {@link TextView} * </ul> * <li><b>{@code exo_progress_placeholder}</b> - A placeholder that's replaced with the inflated * {@link DefaultTimeBar}. Ignored if an {@code exo_progress} view exists. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_progress}</b> - Time bar that's updated during playback and allows seeking. * {@link DefaultTimeBar} attributes set on the StyledPlayerControlView will not be * automatically propagated through to this instance. If a view exists with this id, any * {@code exo_progress_placeholder} view will be ignored. * <ul> * <li>Type: {@link TimeBar} * </ul> * </ul> * * <p>All child views are optional and so can be omitted if not required, however where defined they * must be of the expected type. * * <h2 id="CustomLayout">Specifying a custom layout file</h2> * * Defining your own {@code exo_styled_player_control_view.xml} is useful to customize the layout of * StyledPlayerControlView throughout your application. It's also possible to customize the layout * for a single instance in a layout file. This is achieved by setting the {@code * controller_layout_id} attribute on a StyledPlayerControlView. This will cause the specified * layout to be inflated instead of {@code exo_styled_player_control_view.xml} for only the instance * on which the attribute is set. * * <p>You need to be careful when you set the {@code controller_layout_id}, because the default * animation implementation expects certain relative positions between children. */ public class StyledPlayerControlView extends FrameLayout { static { ExoPlayerLibraryInfo.registerModule("goog.exo.ui"); } /** Listener to be notified about changes of the visibility of the UI control. */ public interface VisibilityListener { /** * Called when the visibility changes. * * @param visibility The new visibility. Either {@link View#VISIBLE} or {@link View#GONE}. */ void onVisibilityChange(int visibility); } /** Listener to be notified when progress has been updated. */ public interface ProgressUpdateListener { /** * Called when progress needs to be updated. * * @param position The current position. * @param bufferedPosition The current buffered position. */ void onProgressUpdate(long position, long bufferedPosition); } /** * Listener to be invoked to inform the fullscreen mode is changed. Application should handle the * fullscreen mode accordingly. */ public interface OnFullScreenModeChangedListener { /** * Called to indicate a fullscreen mode change. * * @param isFullScreen {@code true} if the video rendering surface should be fullscreen {@code * false} otherwise. */ void onFullScreenModeChanged(boolean isFullScreen); } /** The default show timeout, in milliseconds. */ public static final int DEFAULT_SHOW_TIMEOUT_MS = 5_000; /** The default repeat toggle modes. */ public static final @RepeatModeUtil.RepeatToggleModes int DEFAULT_REPEAT_TOGGLE_MODES = RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE; /** The default minimum interval between time bar position updates. */ public static final int DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS = 200; /** The maximum number of windows that can be shown in a multi-window time bar. */ public static final int MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR = 100; /** The maximum interval between time bar position updates. */ private static final int MAX_UPDATE_INTERVAL_MS = 1_000; private static final int SETTINGS_PLAYBACK_SPEED_POSITION = 0; private static final int SETTINGS_AUDIO_TRACK_SELECTION_POSITION = 1; private final ComponentListener componentListener; private final CopyOnWriteArrayList<VisibilityListener> visibilityListeners; @Nullable private final View previousButton; @Nullable private final View nextButton; @Nullable private final View playPauseButton; @Nullable private final View fastForwardButton; @Nullable private final View rewindButton; @Nullable private final TextView fastForwardButtonTextView; @Nullable private final TextView rewindButtonTextView; @Nullable private final ImageView repeatToggleButton; @Nullable private final ImageView shuffleButton; @Nullable private final View vrButton; @Nullable private final TextView durationView; @Nullable private final TextView positionView; @Nullable private final TimeBar timeBar; private final StringBuilder formatBuilder; private final Formatter formatter; private final Timeline.Period period; private final Timeline.Window window; private final Runnable updateProgressAction; private final Drawable repeatOffButtonDrawable; private final Drawable repeatOneButtonDrawable; private final Drawable repeatAllButtonDrawable; private final String repeatOffButtonContentDescription; private final String repeatOneButtonContentDescription; private final String repeatAllButtonContentDescription; private final Drawable shuffleOnButtonDrawable; private final Drawable shuffleOffButtonDrawable; private final float buttonAlphaEnabled; private final float buttonAlphaDisabled; private final String shuffleOnContentDescription; private final String shuffleOffContentDescription; private final Drawable subtitleOnButtonDrawable; private final Drawable subtitleOffButtonDrawable; private final String subtitleOnContentDescription; private final String subtitleOffContentDescription; private final Drawable fullScreenExitDrawable; private final Drawable fullScreenEnterDrawable; private final String fullScreenExitContentDescription; private final String fullScreenEnterContentDescription; @Nullable private Player player; private ControlDispatcher controlDispatcher; @Nullable private ProgressUpdateListener progressUpdateListener; @Nullable private OnFullScreenModeChangedListener onFullScreenModeChangedListener; private boolean isFullScreen; private boolean isAttachedToWindow; private boolean showMultiWindowTimeBar; private boolean multiWindowTimeBar; private boolean scrubbing; private int showTimeoutMs; private int timeBarMinUpdateIntervalMs; private @RepeatModeUtil.RepeatToggleModes int repeatToggleModes; private long[] adGroupTimesMs; private boolean[] playedAdGroups; private long[] extraAdGroupTimesMs; private boolean[] extraPlayedAdGroups; private long currentWindowOffset; private StyledPlayerControlViewLayoutManager controlViewLayoutManager; private Resources resources; private RecyclerView settingsView; private SettingsAdapter settingsAdapter; private PlaybackSpeedAdapter playbackSpeedAdapter; private PopupWindow settingsWindow; private boolean needToHideBars; private int settingsWindowMargin; private TextTrackSelectionAdapter textTrackSelectionAdapter; private AudioTrackSelectionAdapter audioTrackSelectionAdapter; // TODO(insun): Add setTrackNameProvider to use customized track name provider. private TrackNameProvider trackNameProvider; @Nullable private ImageView subtitleButton; @Nullable private ImageView fullScreenButton; @Nullable private ImageView minimalFullScreenButton; @Nullable private View settingsButton; @Nullable private View playbackSpeedButton; @Nullable private View audioTrackButton; public StyledPlayerControlView(Context context) { this(context, /* attrs= */ null); } public StyledPlayerControlView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, /* defStyleAttr= */ 0); } public StyledPlayerControlView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, attrs); } @SuppressWarnings({ "nullness:argument", "nullness:assignment", "nullness:method.invocation", "nullness:methodref.receiver.bound" }) public StyledPlayerControlView( Context context, @Nullable AttributeSet attrs, int defStyleAttr, @Nullable AttributeSet playbackAttrs) { super(context, attrs, defStyleAttr); int controllerLayoutId = R.layout.exo_styled_player_control_view; showTimeoutMs = DEFAULT_SHOW_TIMEOUT_MS; repeatToggleModes = DEFAULT_REPEAT_TOGGLE_MODES; timeBarMinUpdateIntervalMs = DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS; boolean showRewindButton = true; boolean showFastForwardButton = true; boolean showPreviousButton = true; boolean showNextButton = true; boolean showShuffleButton = false; boolean showSubtitleButton = false; boolean animationEnabled = true; boolean showVrButton = false; if (playbackAttrs != null) { TypedArray a = context .getTheme() .obtainStyledAttributes( playbackAttrs, R.styleable.StyledPlayerControlView, defStyleAttr, /* defStyleRes= */ 0); try { controllerLayoutId = a.getResourceId( R.styleable.StyledPlayerControlView_controller_layout_id, controllerLayoutId); showTimeoutMs = a.getInt(R.styleable.StyledPlayerControlView_show_timeout, showTimeoutMs); repeatToggleModes = getRepeatToggleModes(a, repeatToggleModes); showRewindButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_rewind_button, showRewindButton); showFastForwardButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_fastforward_button, showFastForwardButton); showPreviousButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_previous_button, showPreviousButton); showNextButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_next_button, showNextButton); showShuffleButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_shuffle_button, showShuffleButton); showSubtitleButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_subtitle_button, showSubtitleButton); showVrButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_vr_button, showVrButton); setTimeBarMinUpdateInterval( a.getInt( R.styleable.StyledPlayerControlView_time_bar_min_update_interval, timeBarMinUpdateIntervalMs)); animationEnabled = a.getBoolean(R.styleable.StyledPlayerControlView_animation_enabled, animationEnabled); } finally { a.recycle(); } } LayoutInflater.from(context).inflate(controllerLayoutId, /* root= */ this); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); componentListener = new ComponentListener(); visibilityListeners = new CopyOnWriteArrayList<>(); period = new Timeline.Period(); window = new Timeline.Window(); formatBuilder = new StringBuilder(); formatter = new Formatter(formatBuilder, Locale.getDefault()); adGroupTimesMs = new long[0]; playedAdGroups = new boolean[0]; extraAdGroupTimesMs = new long[0]; extraPlayedAdGroups = new boolean[0]; controlDispatcher = new DefaultControlDispatcher(); updateProgressAction = this::updateProgress; durationView = findViewById(R.id.exo_duration); positionView = findViewById(R.id.exo_position); subtitleButton = findViewById(R.id.exo_subtitle); if (subtitleButton != null) { subtitleButton.setOnClickListener(componentListener); } fullScreenButton = findViewById(R.id.exo_fullscreen); initializeFullScreenButton(fullScreenButton, this::onFullScreenButtonClicked); minimalFullScreenButton = findViewById(R.id.exo_minimal_fullscreen); initializeFullScreenButton(minimalFullScreenButton, this::onFullScreenButtonClicked); settingsButton = findViewById(R.id.exo_settings); if (settingsButton != null) { settingsButton.setOnClickListener(componentListener); } playbackSpeedButton = findViewById(R.id.exo_playback_speed); if (playbackSpeedButton != null) { playbackSpeedButton.setOnClickListener(componentListener); } audioTrackButton = findViewById(R.id.exo_audio_track); if (audioTrackButton != null) { audioTrackButton.setOnClickListener(componentListener); } TimeBar customTimeBar = findViewById(R.id.exo_progress); View timeBarPlaceholder = findViewById(R.id.exo_progress_placeholder); if (customTimeBar != null) { timeBar = customTimeBar; } else if (timeBarPlaceholder != null) { // Propagate playbackAttrs as timebarAttrs so that DefaultTimeBar's custom attributes are // transferred, but standard attributes (e.g. background) are not. DefaultTimeBar defaultTimeBar = new DefaultTimeBar(context, null, 0, playbackAttrs, R.style.ExoStyledControls_TimeBar); defaultTimeBar.setId(R.id.exo_progress); defaultTimeBar.setLayoutParams(timeBarPlaceholder.getLayoutParams()); ViewGroup parent = ((ViewGroup) timeBarPlaceholder.getParent()); int timeBarIndex = parent.indexOfChild(timeBarPlaceholder); parent.removeView(timeBarPlaceholder); parent.addView(defaultTimeBar, timeBarIndex); timeBar = defaultTimeBar; } else { timeBar = null; } if (timeBar != null) { timeBar.addListener(componentListener); } playPauseButton = findViewById(R.id.exo_play_pause); if (playPauseButton != null) { playPauseButton.setOnClickListener(componentListener); } previousButton = findViewById(R.id.exo_prev); if (previousButton != null) { previousButton.setOnClickListener(componentListener); } nextButton = findViewById(R.id.exo_next); if (nextButton != null) { nextButton.setOnClickListener(componentListener); } Typeface typeface = ResourcesCompat.getFont(context, R.font.roboto_medium_numbers); View rewButton = findViewById(R.id.exo_rew); rewindButtonTextView = rewButton == null ? findViewById(R.id.exo_rew_with_amount) : null; if (rewindButtonTextView != null) { rewindButtonTextView.setTypeface(typeface); } rewindButton = rewButton == null ? rewindButtonTextView : rewButton; if (rewindButton != null) { rewindButton.setOnClickListener(componentListener); } View ffwdButton = findViewById(R.id.exo_ffwd); fastForwardButtonTextView = ffwdButton == null ? findViewById(R.id.exo_ffwd_with_amount) : null; if (fastForwardButtonTextView != null) { fastForwardButtonTextView.setTypeface(typeface); } fastForwardButton = ffwdButton == null ? fastForwardButtonTextView : ffwdButton; if (fastForwardButton != null) { fastForwardButton.setOnClickListener(componentListener); } repeatToggleButton = findViewById(R.id.exo_repeat_toggle); if (repeatToggleButton != null) { repeatToggleButton.setOnClickListener(componentListener); } shuffleButton = findViewById(R.id.exo_shuffle); if (shuffleButton != null) { shuffleButton.setOnClickListener(componentListener); } resources = context.getResources(); buttonAlphaEnabled = (float) resources.getInteger(R.integer.exo_media_button_opacity_percentage_enabled) / 100; buttonAlphaDisabled = (float) resources.getInteger(R.integer.exo_media_button_opacity_percentage_disabled) / 100; vrButton = findViewById(R.id.exo_vr); if (vrButton != null) { updateButton(/* enabled= */ false, vrButton); } controlViewLayoutManager = new StyledPlayerControlViewLayoutManager(this); controlViewLayoutManager.setAnimationEnabled(animationEnabled); String[] settingTexts = new String[2]; Drawable[] settingIcons = new Drawable[2]; settingTexts[SETTINGS_PLAYBACK_SPEED_POSITION] = resources.getString(R.string.exo_controls_playback_speed); settingIcons[SETTINGS_PLAYBACK_SPEED_POSITION] = resources.getDrawable(R.drawable.exo_styled_controls_speed); settingTexts[SETTINGS_AUDIO_TRACK_SELECTION_POSITION] = resources.getString(R.string.exo_track_selection_title_audio); settingIcons[SETTINGS_AUDIO_TRACK_SELECTION_POSITION] = resources.getDrawable(R.drawable.exo_styled_controls_audiotrack); settingsAdapter = new SettingsAdapter(settingTexts, settingIcons); settingsWindowMargin = resources.getDimensionPixelSize(R.dimen.exo_settings_offset); settingsView = (RecyclerView) LayoutInflater.from(context) .inflate(R.layout.exo_styled_settings_list, /* root= */ null); settingsView.setAdapter(settingsAdapter); settingsView.setLayoutManager(new LinearLayoutManager(getContext())); settingsWindow = new PopupWindow(settingsView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true); if (Util.SDK_INT < 23) { // Work around issue where tapping outside of the menu area or pressing the back button // doesn't dismiss the menu as expected. See: https://github.com/google/ExoPlayer/issues/8272. settingsWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } settingsWindow.setOnDismissListener(componentListener); needToHideBars = true; trackNameProvider = new DefaultTrackNameProvider(getResources()); subtitleOnButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_subtitle_on); subtitleOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_subtitle_off); subtitleOnContentDescription = resources.getString(R.string.exo_controls_cc_enabled_description); subtitleOffContentDescription = resources.getString(R.string.exo_controls_cc_disabled_description); textTrackSelectionAdapter = new TextTrackSelectionAdapter(); audioTrackSelectionAdapter = new AudioTrackSelectionAdapter(); playbackSpeedAdapter = new PlaybackSpeedAdapter( resources.getStringArray(R.array.exo_playback_speeds), resources.getIntArray(R.array.exo_speed_multiplied_by_100)); fullScreenExitDrawable = resources.getDrawable(R.drawable.exo_styled_controls_fullscreen_exit); fullScreenEnterDrawable = resources.getDrawable(R.drawable.exo_styled_controls_fullscreen_enter); repeatOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_off); repeatOneButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_one); repeatAllButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_all); shuffleOnButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_shuffle_on); shuffleOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_shuffle_off); fullScreenExitContentDescription = resources.getString(R.string.exo_controls_fullscreen_exit_description); fullScreenEnterContentDescription = resources.getString(R.string.exo_controls_fullscreen_enter_description); repeatOffButtonContentDescription = resources.getString(R.string.exo_controls_repeat_off_description); repeatOneButtonContentDescription = resources.getString(R.string.exo_controls_repeat_one_description); repeatAllButtonContentDescription = resources.getString(R.string.exo_controls_repeat_all_description); shuffleOnContentDescription = resources.getString(R.string.exo_controls_shuffle_on_description); shuffleOffContentDescription = resources.getString(R.string.exo_controls_shuffle_off_description); // TODO(insun) : Make showing bottomBar configurable. (ex. show_bottom_bar attribute). ViewGroup bottomBar = findViewById(R.id.exo_bottom_bar); controlViewLayoutManager.setShowButton(bottomBar, true); controlViewLayoutManager.setShowButton(fastForwardButton, showFastForwardButton); controlViewLayoutManager.setShowButton(rewindButton, showRewindButton); controlViewLayoutManager.setShowButton(previousButton, showPreviousButton); controlViewLayoutManager.setShowButton(nextButton, showNextButton); controlViewLayoutManager.setShowButton(shuffleButton, showShuffleButton); controlViewLayoutManager.setShowButton(subtitleButton, showSubtitleButton); controlViewLayoutManager.setShowButton(vrButton, showVrButton); controlViewLayoutManager.setShowButton( repeatToggleButton, repeatToggleModes != RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE); addOnLayoutChangeListener(this::onLayoutChange); } /** * Returns the {@link Player} currently being controlled by this view, or null if no player is * set. */ @Nullable public Player getPlayer() { return player; } /** * Sets the {@link Player} to control. * * @param player The {@link Player} to control, or {@code null} to detach the current player. Only * players which are accessed on the main thread are supported ({@code * player.getApplicationLooper() == Looper.getMainLooper()}). */ public void setPlayer(@Nullable Player player) { Assertions.checkState(Looper.myLooper() == Looper.getMainLooper()); Assertions.checkArgument( player == null || player.getApplicationLooper() == Looper.getMainLooper()); if (this.player == player) { return; } if (this.player != null) { this.player.removeListener(componentListener); } this.player = player; if (player != null) { player.addListener(componentListener); } if (player instanceof ForwardingPlayer) { player = ((ForwardingPlayer) player).getWrappedPlayer(); } updateAll(); } /** * Sets whether the time bar should show all windows, as opposed to just the current one. If the * timeline has a period with unknown duration or more than {@link * #MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR} windows the time bar will fall back to showing a single * window. * * @param showMultiWindowTimeBar Whether the time bar should show all windows. */ public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) { this.showMultiWindowTimeBar = showMultiWindowTimeBar; updateTimeline(); } /** * Sets the millisecond positions of extra ad markers relative to the start of the window (or * timeline, if in multi-window mode) and whether each extra ad has been played or not. The * markers are shown in addition to any ad markers for ads in the player's timeline. * * @param extraAdGroupTimesMs The millisecond timestamps of the extra ad markers to show, or * {@code null} to show no extra ad markers. * @param extraPlayedAdGroups Whether each ad has been played. Must be the same length as {@code * extraAdGroupTimesMs}, or {@code null} if {@code extraAdGroupTimesMs} is {@code null}. */ public void setExtraAdGroupMarkers( @Nullable long[] extraAdGroupTimesMs, @Nullable boolean[] extraPlayedAdGroups) { if (extraAdGroupTimesMs == null) { this.extraAdGroupTimesMs = new long[0]; this.extraPlayedAdGroups = new boolean[0]; } else { extraPlayedAdGroups = checkNotNull(extraPlayedAdGroups); Assertions.checkArgument(extraAdGroupTimesMs.length == extraPlayedAdGroups.length); this.extraAdGroupTimesMs = extraAdGroupTimesMs; this.extraPlayedAdGroups = extraPlayedAdGroups; } updateTimeline(); } /** * Adds a {@link VisibilityListener}. * * @param listener The listener to be notified about visibility changes. */ public void addVisibilityListener(VisibilityListener listener) { checkNotNull(listener); visibilityListeners.add(listener); } /** * Removes a {@link VisibilityListener}. * * @param listener The listener to be removed. */ public void removeVisibilityListener(VisibilityListener listener) { visibilityListeners.remove(listener); } /** * Sets the {@link ProgressUpdateListener}. * * @param listener The listener to be notified about when progress is updated. */ public void setProgressUpdateListener(@Nullable ProgressUpdateListener listener) { this.progressUpdateListener = listener; } /** * @deprecated Use a {@link ForwardingPlayer} and pass it to {@link #setPlayer(Player)} instead. * You can also customize some operations when configuring the player (for example by using * {@code ExoPlayer.Builder.setSeekBackIncrementMs(long)}). */ @Deprecated public void setControlDispatcher(ControlDispatcher controlDispatcher) { if (this.controlDispatcher != controlDispatcher) { this.controlDispatcher = controlDispatcher; updateNavigation(); } } /** * Sets whether the rewind button is shown. * * @param showRewindButton Whether the rewind button is shown. */ public void setShowRewindButton(boolean showRewindButton) { controlViewLayoutManager.setShowButton(rewindButton, showRewindButton); updateNavigation(); } /** * Sets whether the fast forward button is shown. * * @param showFastForwardButton Whether the fast forward button is shown. */ public void setShowFastForwardButton(boolean showFastForwardButton) { controlViewLayoutManager.setShowButton(fastForwardButton, showFastForwardButton); updateNavigation(); } /** * Sets whether the previous button is shown. * * @param showPreviousButton Whether the previous button is shown. */ public void setShowPreviousButton(boolean showPreviousButton) { controlViewLayoutManager.setShowButton(previousButton, showPreviousButton); updateNavigation(); } /** * Sets whether the next button is shown. * * @param showNextButton Whether the next button is shown. */ public void setShowNextButton(boolean showNextButton) { controlViewLayoutManager.setShowButton(nextButton, showNextButton); updateNavigation(); } /** * Returns the playback controls timeout. The playback controls are automatically hidden after * this duration of time has elapsed without user input. * * @return The duration in milliseconds. A non-positive value indicates that the controls will * remain visible indefinitely. */ public int getShowTimeoutMs() { return showTimeoutMs; } /** * Sets the playback controls timeout. The playback controls are automatically hidden after this * duration of time has elapsed without user input. * * @param showTimeoutMs The duration in milliseconds. A non-positive value will cause the controls * to remain visible indefinitely. */ public void setShowTimeoutMs(int showTimeoutMs) { this.showTimeoutMs = showTimeoutMs; if (isFullyVisible()) { controlViewLayoutManager.resetHideCallbacks(); } } /** * Returns which repeat toggle modes are enabled. * * @return The currently enabled {@link RepeatModeUtil.RepeatToggleModes}. */ public @RepeatModeUtil.RepeatToggleModes int getRepeatToggleModes() { return repeatToggleModes; } /** * Sets which repeat toggle modes are enabled. * * @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}. */ public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) { this.repeatToggleModes = repeatToggleModes; if (player != null) { @Player.RepeatMode int currentMode = player.getRepeatMode(); if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE && currentMode != Player.REPEAT_MODE_OFF) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_OFF); } else if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_ONE && currentMode == Player.REPEAT_MODE_ALL) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_ONE); } else if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_ALL && currentMode == Player.REPEAT_MODE_ONE) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_ALL); } } controlViewLayoutManager.setShowButton( repeatToggleButton, repeatToggleModes != RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE); updateRepeatModeButton(); } /** Returns whether the shuffle button is shown. */ public boolean getShowShuffleButton() { return controlViewLayoutManager.getShowButton(shuffleButton); } /** * Sets whether the shuffle button is shown. * * @param showShuffleButton Whether the shuffle button is shown. */ public void setShowShuffleButton(boolean showShuffleButton) { controlViewLayoutManager.setShowButton(shuffleButton, showShuffleButton); updateShuffleButton(); } /** Returns whether the subtitle button is shown. */ public boolean getShowSubtitleButton() { return controlViewLayoutManager.getShowButton(subtitleButton); } /** * Sets whether the subtitle button is shown. * * @param showSubtitleButton Whether the subtitle button is shown. */ public void setShowSubtitleButton(boolean showSubtitleButton) { controlViewLayoutManager.setShowButton(subtitleButton, showSubtitleButton); } /** Returns whether the VR button is shown. */ public boolean getShowVrButton() { return controlViewLayoutManager.getShowButton(vrButton); } /** * Sets whether the VR button is shown. * * @param showVrButton Whether the VR button is shown. */ public void setShowVrButton(boolean showVrButton) { controlViewLayoutManager.setShowButton(vrButton, showVrButton); } /** * Sets listener for the VR button. * * @param onClickListener Listener for the VR button, or null to clear the listener. */ public void setVrButtonListener(@Nullable OnClickListener onClickListener) { if (vrButton != null) { vrButton.setOnClickListener(onClickListener); updateButton(onClickListener != null, vrButton); } } /** * Sets whether an animation is used to show and hide the playback controls. * * @param animationEnabled Whether an animation is applied to show and hide playback controls. */ public void setAnimationEnabled(boolean animationEnabled) { controlViewLayoutManager.setAnimationEnabled(animationEnabled); } /** Returns whether an animation is used to show and hide the playback controls. */ public boolean isAnimationEnabled() { return controlViewLayoutManager.isAnimationEnabled(); } /** * Sets the minimum interval between time bar position updates. * * <p>Note that smaller intervals, e.g. 33ms, will result in a smooth movement but will use more * CPU resources while the time bar is visible, whereas larger intervals, e.g. 200ms, will result * in a step-wise update with less CPU usage. * * @param minUpdateIntervalMs The minimum interval between time bar position updates, in * milliseconds. */ public void setTimeBarMinUpdateInterval(int minUpdateIntervalMs) { // Do not accept values below 16ms (60fps) and larger than the maximum update interval. timeBarMinUpdateIntervalMs = Util.constrainValue(minUpdateIntervalMs, 16, MAX_UPDATE_INTERVAL_MS); } /** * Sets a listener to be called when the fullscreen mode should be changed. A non-null listener * needs to be set in order to display the fullscreen button. * * @param listener The listener to be called. A value of <code>null</code> removes any existing * listener and hides the fullscreen button. */ public void setOnFullScreenModeChangedListener( @Nullable OnFullScreenModeChangedListener listener) { onFullScreenModeChangedListener = listener; updateFullScreenButtonVisibility(fullScreenButton, listener != null); updateFullScreenButtonVisibility(minimalFullScreenButton, listener != null); } /** * Shows the playback controls. If {@link #getShowTimeoutMs()} is positive then the controls will * be automatically hidden after this duration of time has elapsed without user input. */ public void show() { controlViewLayoutManager.show(); } /** Hides the controller. */ public void hide() { controlViewLayoutManager.hide(); } /** Hides the controller without any animation. */ public void hideImmediately() { controlViewLayoutManager.hideImmediately(); } /** Returns whether the controller is fully visible, which means all UI controls are visible. */ public boolean isFullyVisible() { return controlViewLayoutManager.isFullyVisible(); } /** Returns whether the controller is currently visible. */ public boolean isVisible() { return getVisibility() == VISIBLE; } /* package */ void notifyOnVisibilityChange() { for (VisibilityListener visibilityListener : visibilityListeners) { visibilityListener.onVisibilityChange(getVisibility()); } } /* package */ void updateAll() { updatePlayPauseButton(); updateNavigation(); updateRepeatModeButton(); updateShuffleButton(); updateTrackLists(); updatePlaybackSpeedList(); updateTimeline(); } private void updatePlayPauseButton() { if (!isVisible() || !isAttachedToWindow) { return; } if (playPauseButton != null) { if (shouldShowPauseButton()) { ((ImageView) playPauseButton) .setImageDrawable(resources.getDrawable(R.drawable.exo_styled_controls_pause)); playPauseButton.setContentDescription( resources.getString(R.string.exo_controls_pause_description)); } else { ((ImageView) playPauseButton) .setImageDrawable(resources.getDrawable(R.drawable.exo_styled_controls_play)); playPauseButton.setContentDescription( resources.getString(R.string.exo_controls_play_description)); } } } private void updateNavigation() { if (!isVisible() || !isAttachedToWindow) { return; } @Nullable Player player = this.player; boolean enableSeeking = false; boolean enablePrevious = false; boolean enableRewind = false; boolean enableFastForward = false; boolean enableNext = false; if (player != null) { enableSeeking = player.isCommandAvailable(COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM); enablePrevious = player.isCommandAvailable(COMMAND_SEEK_TO_PREVIOUS); enableRewind = player.isCommandAvailable(COMMAND_SEEK_BACK) && controlDispatcher.isRewindEnabled(); enableFastForward = player.isCommandAvailable(COMMAND_SEEK_FORWARD) && controlDispatcher.isFastForwardEnabled(); enableNext = player.isCommandAvailable(COMMAND_SEEK_TO_NEXT); } if (enableRewind) { updateRewindButton(); } if (enableFastForward) { updateFastForwardButton(); } updateButton(enablePrevious, previousButton); updateButton(enableRewind, rewindButton); updateButton(enableFastForward, fastForwardButton); updateButton(enableNext, nextButton); if (timeBar != null) { timeBar.setEnabled(enableSeeking); } } private void updateRewindButton() { long rewindMs = controlDispatcher instanceof DefaultControlDispatcher && player != null ? ((DefaultControlDispatcher) controlDispatcher).getRewindIncrementMs(player) : C.DEFAULT_SEEK_BACK_INCREMENT_MS; int rewindSec = (int) (rewindMs / 1_000); if (rewindButtonTextView != null) { rewindButtonTextView.setText(String.valueOf(rewindSec)); } if (rewindButton != null) { rewindButton.setContentDescription( resources.getQuantityString( R.plurals.exo_controls_rewind_by_amount_description, rewindSec, rewindSec)); } } private void updateFastForwardButton() { long fastForwardMs = controlDispatcher instanceof DefaultControlDispatcher && player != null ? ((DefaultControlDispatcher) controlDispatcher).getFastForwardIncrementMs(player) : C.DEFAULT_SEEK_FORWARD_INCREMENT_MS; int fastForwardSec = (int) (fastForwardMs / 1_000); if (fastForwardButtonTextView != null) { fastForwardButtonTextView.setText(String.valueOf(fastForwardSec)); } if (fastForwardButton != null) { fastForwardButton.setContentDescription( resources.getQuantityString( R.plurals.exo_controls_fastforward_by_amount_description, fastForwardSec, fastForwardSec)); } } private void updateRepeatModeButton() { if (!isVisible() || !isAttachedToWindow || repeatToggleButton == null) { return; } if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE) { updateButton(/* enabled= */ false, repeatToggleButton); return; } @Nullable Player player = this.player; if (player == null) { updateButton(/* enabled= */ false, repeatToggleButton); repeatToggleButton.setImageDrawable(repeatOffButtonDrawable); repeatToggleButton.setContentDescription(repeatOffButtonContentDescription); return; } updateButton(/* enabled= */ true, repeatToggleButton); switch (player.getRepeatMode()) { case Player.REPEAT_MODE_OFF: repeatToggleButton.setImageDrawable(repeatOffButtonDrawable); repeatToggleButton.setContentDescription(repeatOffButtonContentDescription); break; case Player.REPEAT_MODE_ONE: repeatToggleButton.setImageDrawable(repeatOneButtonDrawable); repeatToggleButton.setContentDescription(repeatOneButtonContentDescription); break; case Player.REPEAT_MODE_ALL: repeatToggleButton.setImageDrawable(repeatAllButtonDrawable); repeatToggleButton.setContentDescription(repeatAllButtonContentDescription); break; default: // Never happens. } } private void updateShuffleButton() { if (!isVisible() || !isAttachedToWindow || shuffleButton == null) { return; } @Nullable Player player = this.player; if (!controlViewLayoutManager.getShowButton(shuffleButton)) { updateButton(/* enabled= */ false, shuffleButton); } else if (player == null) { updateButton(/* enabled= */ false, shuffleButton); shuffleButton.setImageDrawable(shuffleOffButtonDrawable); shuffleButton.setContentDescription(shuffleOffContentDescription); } else { updateButton(/* enabled= */ true, shuffleButton); shuffleButton.setImageDrawable( player.getShuffleModeEnabled() ? shuffleOnButtonDrawable : shuffleOffButtonDrawable); shuffleButton.setContentDescription( player.getShuffleModeEnabled() ? shuffleOnContentDescription : shuffleOffContentDescription); } } private void updateTrackLists() { initTrackSelectionAdapter(); updateButton(textTrackSelectionAdapter.getItemCount() > 0, subtitleButton); } private void initTrackSelectionAdapter() { textTrackSelectionAdapter.clear(); audioTrackSelectionAdapter.clear(); if (player == null || !player.isCommandAvailable(Player.COMMAND_GET_TRACK_INFOS) || !player.isCommandAvailable(Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS)) { return; } TracksInfo tracksInfo = player.getCurrentTracksInfo(); audioTrackSelectionAdapter.init( gatherSupportedTrackInfosOfType(tracksInfo, C.TRACK_TYPE_AUDIO)); if (controlViewLayoutManager.getShowButton(subtitleButton)) { textTrackSelectionAdapter.init( gatherSupportedTrackInfosOfType(tracksInfo, C.TRACK_TYPE_TEXT)); } else { textTrackSelectionAdapter.init(ImmutableList.of()); } } private ImmutableList<TrackInformation> gatherSupportedTrackInfosOfType( TracksInfo tracksInfo, @C.TrackType int trackType) { ImmutableList.Builder<TrackInformation> tracks = new ImmutableList.Builder<>(); List<TrackGroupInfo> trackGroupInfos = tracksInfo.getTrackGroupInfos(); for (int trackGroupIndex = 0; trackGroupIndex < trackGroupInfos.size(); trackGroupIndex++) { TrackGroupInfo trackGroupInfo = trackGroupInfos.get(trackGroupIndex); if (trackGroupInfo.getTrackType() != trackType) { continue; } TrackGroup trackGroup = trackGroupInfo.getTrackGroup(); for (int trackIndex = 0; trackIndex < trackGroup.length; trackIndex++) { if (!trackGroupInfo.isTrackSupported(trackIndex)) { continue; } String trackName = trackNameProvider.getTrackName(trackGroup.getFormat(trackIndex)); tracks.add(new TrackInformation(tracksInfo, trackGroupIndex, trackIndex, trackName)); } } return tracks.build(); } private void updateTimeline() { @Nullable Player player = this.player; if (player == null) { return; } multiWindowTimeBar = showMultiWindowTimeBar && canShowMultiWindowTimeBar(player.getCurrentTimeline(), window); currentWindowOffset = 0; long durationUs = 0; int adGroupCount = 0; Timeline timeline = player.getCurrentTimeline(); if (!timeline.isEmpty()) { int currentWindowIndex = player.getCurrentWindowIndex(); int firstWindowIndex = multiWindowTimeBar ? 0 : currentWindowIndex; int lastWindowIndex = multiWindowTimeBar ? timeline.getWindowCount() - 1 : currentWindowIndex; for (int i = firstWindowIndex; i <= lastWindowIndex; i++) { if (i == currentWindowIndex) { currentWindowOffset = C.usToMs(durationUs); } timeline.getWindow(i, window); if (window.durationUs == C.TIME_UNSET) { Assertions.checkState(!multiWindowTimeBar); break; } for (int j = window.firstPeriodIndex; j <= window.lastPeriodIndex; j++) { timeline.getPeriod(j, period); int removedGroups = period.getRemovedAdGroupCount(); int totalGroups = period.getAdGroupCount(); for (int adGroupIndex = removedGroups; adGroupIndex < totalGroups; adGroupIndex++) { long adGroupTimeInPeriodUs = period.getAdGroupTimeUs(adGroupIndex); if (adGroupTimeInPeriodUs == C.TIME_END_OF_SOURCE) { if (period.durationUs == C.TIME_UNSET) { // Don't show ad markers for postrolls in periods with unknown duration. continue; } adGroupTimeInPeriodUs = period.durationUs; } long adGroupTimeInWindowUs = adGroupTimeInPeriodUs + period.getPositionInWindowUs(); if (adGroupTimeInWindowUs >= 0) { if (adGroupCount == adGroupTimesMs.length) { int newLength = adGroupTimesMs.length == 0 ? 1 : adGroupTimesMs.length * 2; adGroupTimesMs = Arrays.copyOf(adGroupTimesMs, newLength); playedAdGroups = Arrays.copyOf(playedAdGroups, newLength); } adGroupTimesMs[adGroupCount] = C.usToMs(durationUs + adGroupTimeInWindowUs); playedAdGroups[adGroupCount] = period.hasPlayedAdGroup(adGroupIndex); adGroupCount++; } } } durationUs += window.durationUs; } } long durationMs = C.usToMs(durationUs); if (durationView != null) { durationView.setText(Util.getStringForTime(formatBuilder, formatter, durationMs)); } if (timeBar != null) { timeBar.setDuration(durationMs); int extraAdGroupCount = extraAdGroupTimesMs.length; int totalAdGroupCount = adGroupCount + extraAdGroupCount; if (totalAdGroupCount > adGroupTimesMs.length) { adGroupTimesMs = Arrays.copyOf(adGroupTimesMs, totalAdGroupCount); playedAdGroups = Arrays.copyOf(playedAdGroups, totalAdGroupCount); } System.arraycopy(extraAdGroupTimesMs, 0, adGroupTimesMs, adGroupCount, extraAdGroupCount); System.arraycopy(extraPlayedAdGroups, 0, playedAdGroups, adGroupCount, extraAdGroupCount); timeBar.setAdGroupTimesMs(adGroupTimesMs, playedAdGroups, totalAdGroupCount); } updateProgress(); } private void updateProgress() { if (!isVisible() || !isAttachedToWindow) { return; } @Nullable Player player = this.player; long position = 0; long bufferedPosition = 0; if (player != null) { position = currentWindowOffset + player.getContentPosition(); bufferedPosition = currentWindowOffset + player.getContentBufferedPosition(); } if (positionView != null && !scrubbing) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } if (timeBar != null) { timeBar.setPosition(position); timeBar.setBufferedPosition(bufferedPosition); } if (progressUpdateListener != null) { progressUpdateListener.onProgressUpdate(position, bufferedPosition); } // Cancel any pending updates and schedule a new one if necessary. removeCallbacks(updateProgressAction); int playbackState = player == null ? Player.STATE_IDLE : player.getPlaybackState(); if (player != null && player.isPlaying()) { long mediaTimeDelayMs = timeBar != null ? timeBar.getPreferredUpdateDelay() : MAX_UPDATE_INTERVAL_MS; // Limit delay to the start of the next full second to ensure position display is smooth. long mediaTimeUntilNextFullSecondMs = 1000 - position % 1000; mediaTimeDelayMs = Math.min(mediaTimeDelayMs, mediaTimeUntilNextFullSecondMs); // Calculate the delay until the next update in real time, taking playback speed into account. float playbackSpeed = player.getPlaybackParameters().speed; long delayMs = playbackSpeed > 0 ? (long) (mediaTimeDelayMs / playbackSpeed) : MAX_UPDATE_INTERVAL_MS; // Constrain the delay to avoid too frequent / infrequent updates. delayMs = Util.constrainValue(delayMs, timeBarMinUpdateIntervalMs, MAX_UPDATE_INTERVAL_MS); postDelayed(updateProgressAction, delayMs); } else if (playbackState != Player.STATE_ENDED && playbackState != Player.STATE_IDLE) { postDelayed(updateProgressAction, MAX_UPDATE_INTERVAL_MS); } } private void updatePlaybackSpeedList() { if (player == null) { return; } playbackSpeedAdapter.updateSelectedIndex(player.getPlaybackParameters().speed); settingsAdapter.setSubTextAtPosition( SETTINGS_PLAYBACK_SPEED_POSITION, playbackSpeedAdapter.getSelectedText()); } private void updateSettingsWindowSize() { settingsView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int maxWidth = getWidth() - settingsWindowMargin * 2; int itemWidth = settingsView.getMeasuredWidth(); int width = Math.min(itemWidth, maxWidth); settingsWindow.setWidth(width); int maxHeight = getHeight() - settingsWindowMargin * 2; int totalHeight = settingsView.getMeasuredHeight(); int height = Math.min(maxHeight, totalHeight); settingsWindow.setHeight(height); } private void displaySettingsWindow(RecyclerView.Adapter<?> adapter) { settingsView.setAdapter(adapter); updateSettingsWindowSize(); needToHideBars = false; settingsWindow.dismiss(); needToHideBars = true; int xoff = getWidth() - settingsWindow.getWidth() - settingsWindowMargin; int yoff = -settingsWindow.getHeight() - settingsWindowMargin; settingsWindow.showAsDropDown(this, xoff, yoff); } private void setPlaybackSpeed(float speed) { if (player == null) { return; } controlDispatcher.dispatchSetPlaybackParameters( player, player.getPlaybackParameters().withSpeed(speed)); } /* package */ void requestPlayPauseFocus() { if (playPauseButton != null) { playPauseButton.requestFocus(); } } private void updateButton(boolean enabled, @Nullable View view) { if (view == null) { return; } view.setEnabled(enabled); view.setAlpha(enabled ? buttonAlphaEnabled : buttonAlphaDisabled); } private void seekToTimeBarPosition(Player player, long positionMs) { int windowIndex; Timeline timeline = player.getCurrentTimeline(); if (multiWindowTimeBar && !timeline.isEmpty()) { int windowCount = timeline.getWindowCount(); windowIndex = 0; while (true) { long windowDurationMs = timeline.getWindow(windowIndex, window).getDurationMs(); if (positionMs < windowDurationMs) { break; } else if (windowIndex == windowCount - 1) { // Seeking past the end of the last window should seek to the end of the timeline. positionMs = windowDurationMs; break; } positionMs -= windowDurationMs; windowIndex++; } } else { windowIndex = player.getCurrentWindowIndex(); } seekTo(player, windowIndex, positionMs); updateProgress(); } private boolean seekTo(Player player, int windowIndex, long positionMs) { return controlDispatcher.dispatchSeekTo(player, windowIndex, positionMs); } private void onFullScreenButtonClicked(View v) { if (onFullScreenModeChangedListener == null) { return; } isFullScreen = !isFullScreen; updateFullScreenButtonForState(fullScreenButton, isFullScreen); updateFullScreenButtonForState(minimalFullScreenButton, isFullScreen); if (onFullScreenModeChangedListener != null) { onFullScreenModeChangedListener.onFullScreenModeChanged(isFullScreen); } } private void updateFullScreenButtonForState( @Nullable ImageView fullScreenButton, boolean isFullScreen) { if (fullScreenButton == null) { return; } if (isFullScreen) { fullScreenButton.setImageDrawable(fullScreenExitDrawable); fullScreenButton.setContentDescription(fullScreenExitContentDescription); } else { fullScreenButton.setImageDrawable(fullScreenEnterDrawable); fullScreenButton.setContentDescription(fullScreenEnterContentDescription); } } private void onSettingViewClicked(int position) { if (position == SETTINGS_PLAYBACK_SPEED_POSITION) { displaySettingsWindow(playbackSpeedAdapter); } else if (position == SETTINGS_AUDIO_TRACK_SELECTION_POSITION) { displaySettingsWindow(audioTrackSelectionAdapter); } else { settingsWindow.dismiss(); } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); controlViewLayoutManager.onAttachedToWindow(); isAttachedToWindow = true; if (isFullyVisible()) { controlViewLayoutManager.resetHideCallbacks(); } updateAll(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); controlViewLayoutManager.onDetachedFromWindow(); isAttachedToWindow = false; removeCallbacks(updateProgressAction); controlViewLayoutManager.removeHideCallbacks(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { return dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event); } /** * Called to process media key events. Any {@link KeyEvent} can be passed but only media key * events will be handled. * * @param event A key event. * @return Whether the key event was handled. */ public boolean dispatchMediaKeyEvent(KeyEvent event) { int keyCode = event.getKeyCode(); @Nullable Player player = this.player; if (player == null || !isHandledMediaKey(keyCode)) { return false; } if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { if (player.getPlaybackState() != Player.STATE_ENDED) { controlDispatcher.dispatchFastForward(player); } } else if (keyCode == KeyEvent.KEYCODE_MEDIA_REWIND) { controlDispatcher.dispatchRewind(player); } else if (event.getRepeatCount() == 0) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_HEADSETHOOK: dispatchPlayPause(player); break; case KeyEvent.KEYCODE_MEDIA_PLAY: dispatchPlay(player); break; case KeyEvent.KEYCODE_MEDIA_PAUSE: dispatchPause(player); break; case KeyEvent.KEYCODE_MEDIA_NEXT: controlDispatcher.dispatchNext(player); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: controlDispatcher.dispatchPrevious(player); break; default: break; } } } return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); controlViewLayoutManager.onLayout(changed, left, top, right, bottom); } private void onLayoutChange( View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int width = right - left; int height = bottom - top; int oldWidth = oldRight - oldLeft; int oldHeight = oldBottom - oldTop; if ((width != oldWidth || height != oldHeight) && settingsWindow.isShowing()) { updateSettingsWindowSize(); int xOffset = getWidth() - settingsWindow.getWidth() - settingsWindowMargin; int yOffset = -settingsWindow.getHeight() - settingsWindowMargin; settingsWindow.update(v, xOffset, yOffset, -1, -1); } } private boolean shouldShowPauseButton() { return player != null && player.getPlaybackState() != Player.STATE_ENDED && player.getPlaybackState() != Player.STATE_IDLE && player.getPlayWhenReady(); } private void dispatchPlayPause(Player player) { @State int state = player.getPlaybackState(); if (state == Player.STATE_IDLE || state == Player.STATE_ENDED || !player.getPlayWhenReady()) { dispatchPlay(player); } else { dispatchPause(player); } } @SuppressWarnings("deprecation") private void dispatchPlay(Player player) { @State int state = player.getPlaybackState(); if (state == Player.STATE_IDLE) { controlDispatcher.dispatchPrepare(player); } else if (state == Player.STATE_ENDED) { seekTo(player, player.getCurrentWindowIndex(), C.TIME_UNSET); } controlDispatcher.dispatchSetPlayWhenReady(player, /* playWhenReady= */ true); } private void dispatchPause(Player player) { controlDispatcher.dispatchSetPlayWhenReady(player, /* playWhenReady= */ false); } @SuppressLint("InlinedApi") private static boolean isHandledMediaKey(int keyCode) { return keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD || keyCode == KeyEvent.KEYCODE_MEDIA_REWIND || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE || keyCode == KeyEvent.KEYCODE_MEDIA_NEXT || keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS; } /** * Returns whether the specified {@code timeline} can be shown on a multi-window time bar. * * @param timeline The {@link Timeline} to check. * @param window A scratch {@link Timeline.Window} instance. * @return Whether the specified timeline can be shown on a multi-window time bar. */ private static boolean canShowMultiWindowTimeBar(Timeline timeline, Timeline.Window window) { if (timeline.getWindowCount() > MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR) { return false; } int windowCount = timeline.getWindowCount(); for (int i = 0; i < windowCount; i++) { if (timeline.getWindow(i, window).durationUs == C.TIME_UNSET) { return false; } } return true; } private static void initializeFullScreenButton(View fullScreenButton, OnClickListener listener) { if (fullScreenButton == null) { return; } fullScreenButton.setVisibility(GONE); fullScreenButton.setOnClickListener(listener); } private static void updateFullScreenButtonVisibility( @Nullable View fullScreenButton, boolean visible) { if (fullScreenButton == null) { return; } if (visible) { fullScreenButton.setVisibility(VISIBLE); } else { fullScreenButton.setVisibility(GONE); } } @SuppressWarnings("ResourceType") private static @RepeatModeUtil.RepeatToggleModes int getRepeatToggleModes( TypedArray a, @RepeatModeUtil.RepeatToggleModes int defaultValue) { return a.getInt(R.styleable.StyledPlayerControlView_repeat_toggle_modes, defaultValue); } private final class ComponentListener implements Player.Listener, TimeBar.OnScrubListener, OnClickListener, PopupWindow.OnDismissListener { @Override public void onEvents(Player player, Events events) { if (events.containsAny(EVENT_PLAYBACK_STATE_CHANGED, EVENT_PLAY_WHEN_READY_CHANGED)) { updatePlayPauseButton(); } if (events.containsAny( EVENT_PLAYBACK_STATE_CHANGED, EVENT_PLAY_WHEN_READY_CHANGED, EVENT_IS_PLAYING_CHANGED)) { updateProgress(); } if (events.contains(EVENT_REPEAT_MODE_CHANGED)) { updateRepeatModeButton(); } if (events.contains(EVENT_SHUFFLE_MODE_ENABLED_CHANGED)) { updateShuffleButton(); } if (events.containsAny( EVENT_REPEAT_MODE_CHANGED, EVENT_SHUFFLE_MODE_ENABLED_CHANGED, EVENT_POSITION_DISCONTINUITY, EVENT_TIMELINE_CHANGED, EVENT_SEEK_BACK_INCREMENT_CHANGED, EVENT_SEEK_FORWARD_INCREMENT_CHANGED, EVENT_AVAILABLE_COMMANDS_CHANGED)) { updateNavigation(); } if (events.containsAny(EVENT_POSITION_DISCONTINUITY, EVENT_TIMELINE_CHANGED)) { updateTimeline(); } if (events.contains(EVENT_PLAYBACK_PARAMETERS_CHANGED)) { updatePlaybackSpeedList(); } if (events.contains(EVENT_TRACKS_CHANGED)) { updateTrackLists(); } } @Override public void onScrubStart(TimeBar timeBar, long position) { scrubbing = true; if (positionView != null) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } controlViewLayoutManager.removeHideCallbacks(); } @Override public void onScrubMove(TimeBar timeBar, long position) { if (positionView != null) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } } @Override public void onScrubStop(TimeBar timeBar, long position, boolean canceled) { scrubbing = false; if (!canceled && player != null) { seekToTimeBarPosition(player, position); } controlViewLayoutManager.resetHideCallbacks(); } @Override public void onDismiss() { if (needToHideBars) { controlViewLayoutManager.resetHideCallbacks(); } } @Override public void onClick(View view) { @Nullable Player player = StyledPlayerControlView.this.player; if (player == null) { return; } controlViewLayoutManager.resetHideCallbacks(); if (nextButton == view) { controlDispatcher.dispatchNext(player); } else if (previousButton == view) { controlDispatcher.dispatchPrevious(player); } else if (fastForwardButton == view) { if (player.getPlaybackState() != Player.STATE_ENDED) { controlDispatcher.dispatchFastForward(player); } } else if (rewindButton == view) { controlDispatcher.dispatchRewind(player); } else if (playPauseButton == view) { dispatchPlayPause(player); } else if (repeatToggleButton == view) { controlDispatcher.dispatchSetRepeatMode( player, RepeatModeUtil.getNextRepeatMode(player.getRepeatMode(), repeatToggleModes)); } else if (shuffleButton == view) { controlDispatcher.dispatchSetShuffleModeEnabled(player, !player.getShuffleModeEnabled()); } else if (settingsButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(settingsAdapter); } else if (playbackSpeedButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(playbackSpeedAdapter); } else if (audioTrackButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(audioTrackSelectionAdapter); } else if (subtitleButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(textTrackSelectionAdapter); } } } private class SettingsAdapter extends RecyclerView.Adapter<SettingViewHolder> { private final String[] mainTexts; private final String[] subTexts; private final Drawable[] iconIds; public SettingsAdapter(String[] mainTexts, Drawable[] iconIds) { this.mainTexts = mainTexts; this.subTexts = new String[mainTexts.length]; this.iconIds = iconIds; } @Override public SettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate(R.layout.exo_styled_settings_list_item, parent, /* attachToRoot= */ false); return new SettingViewHolder(v); } @Override public void onBindViewHolder(SettingViewHolder holder, int position) { holder.mainTextView.setText(mainTexts[position]); if (subTexts[position] == null) { holder.subTextView.setVisibility(GONE); } else { holder.subTextView.setText(subTexts[position]); } if (iconIds[position] == null) { holder.iconView.setVisibility(GONE); } else { holder.iconView.setImageDrawable(iconIds[position]); } } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return mainTexts.length; } public void setSubTextAtPosition(int position, String subText) { this.subTexts[position] = subText; } } private final class SettingViewHolder extends RecyclerView.ViewHolder { private final TextView mainTextView; private final TextView subTextView; private final ImageView iconView; public SettingViewHolder(View itemView) { super(itemView); if (Util.SDK_INT < 26) { // Workaround for https://github.com/google/ExoPlayer/issues/9061. itemView.setFocusable(true); } mainTextView = itemView.findViewById(R.id.exo_main_text); subTextView = itemView.findViewById(R.id.exo_sub_text); iconView = itemView.findViewById(R.id.exo_icon); itemView.setOnClickListener(v -> onSettingViewClicked(getAdapterPosition())); } } private final class PlaybackSpeedAdapter extends RecyclerView.Adapter<SubSettingViewHolder> { private final String[] playbackSpeedTexts; private final int[] playbackSpeedsMultBy100; private int selectedIndex; public PlaybackSpeedAdapter(String[] playbackSpeedTexts, int[] playbackSpeedsMultBy100) { this.playbackSpeedTexts = playbackSpeedTexts; this.playbackSpeedsMultBy100 = playbackSpeedsMultBy100; } public void updateSelectedIndex(float playbackSpeed) { int currentSpeedMultBy100 = Math.round(playbackSpeed * 100); int closestMatchIndex = 0; int closestMatchDifference = Integer.MAX_VALUE; for (int i = 0; i < playbackSpeedsMultBy100.length; i++) { int difference = Math.abs(currentSpeedMultBy100 - playbackSpeedsMultBy100[i]); if (difference < closestMatchDifference) { closestMatchIndex = i; closestMatchDifference = difference; } } selectedIndex = closestMatchIndex; } public String getSelectedText() { return playbackSpeedTexts[selectedIndex]; } @Override public SubSettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate( R.layout.exo_styled_sub_settings_list_item, parent, /* attachToRoot= */ false); return new SubSettingViewHolder(v); } @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { if (position < playbackSpeedTexts.length) { holder.textView.setText(playbackSpeedTexts[position]); } holder.checkView.setVisibility(position == selectedIndex ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (position != selectedIndex) { float speed = playbackSpeedsMultBy100[position] / 100.0f; setPlaybackSpeed(speed); } settingsWindow.dismiss(); }); } @Override public int getItemCount() { return playbackSpeedTexts.length; } } private static final class TrackInformation { private TracksInfo tracksInfo; private int trackGroupIndex; public final TrackGroupInfo trackGroupInfo; public final TrackGroup trackGroup; public final int trackIndex; public final String trackName; public TrackInformation( TracksInfo tracksInfo, int trackGroupIndex, int trackIndex, String trackName) { this.tracksInfo = tracksInfo; this.trackGroupIndex = trackGroupIndex; this.trackGroupInfo = tracksInfo.getTrackGroupInfos().get(trackGroupIndex); this.trackGroup = trackGroupInfo.getTrackGroup(); this.trackIndex = trackIndex; this.trackName = trackName; } public boolean isSelected() { return trackGroupInfo.isTrackSelected(trackIndex); } } private final class TextTrackSelectionAdapter extends TrackSelectionAdapter { @Override public void init(List<TrackInformation> trackInformations) { boolean subtitleIsOn = false; for (int i = 0; i < trackInformations.size(); i++) { if (trackInformations.get(i).isSelected()) { subtitleIsOn = true; break; } } if (subtitleButton != null) { subtitleButton.setImageDrawable( subtitleIsOn ? subtitleOnButtonDrawable : subtitleOffButtonDrawable); subtitleButton.setContentDescription( subtitleIsOn ? subtitleOnContentDescription : subtitleOffContentDescription); } this.tracks = trackInformations; } @Override public void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder) { // CC options include "Off" at the first position, which disables text rendering. holder.textView.setText(R.string.exo_track_selection_none); boolean isTrackSelectionOff = true; for (int i = 0; i < tracks.size(); i++) { if (tracks.get(i).isSelected()) { isTrackSelectionOff = false; break; } } holder.checkView.setVisibility(isTrackSelectionOff ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (player != null) { TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); player.setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setDisabledTrackTypes( new ImmutableSet.Builder<@C.TrackType Integer>() .addAll(trackSelectionParameters.disabledTrackTypes) .add(C.TRACK_TYPE_TEXT) .build()) .build()); settingsWindow.dismiss(); } }); } @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { super.onBindViewHolder(holder, position); if (position > 0) { TrackInformation track = tracks.get(position - 1); holder.checkView.setVisibility(track.isSelected() ? VISIBLE : INVISIBLE); } } @Override public void onTrackSelection(String subtext) { // No-op } } private final class AudioTrackSelectionAdapter extends TrackSelectionAdapter { @Override public void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder) { // Audio track selection option includes "Auto" at the top. holder.textView.setText(R.string.exo_track_selection_auto); // hasSelectionOverride is true means there is an explicit track selection, not "Auto". boolean hasSelectionOverride = false; TrackSelectionParameters parameters = checkNotNull(player).getTrackSelectionParameters(); for (int i = 0; i < tracks.size(); i++) { if (parameters.trackSelectionOverrides.containsKey(tracks.get(i).trackGroup)) { hasSelectionOverride = true; break; } } holder.checkView.setVisibility(hasSelectionOverride ? INVISIBLE : VISIBLE); holder.itemView.setOnClickListener( v -> { if (player == null) { return; } TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); // Remove all audio overrides. ImmutableMap<TrackGroup, TrackSelectionOverride> trackSelectionOverrides = clearTrackSelectionOverridesForType( C.TRACK_TYPE_AUDIO, trackSelectionParameters.trackSelectionOverrides); player.setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setTrackSelectionOverrides(trackSelectionOverrides) .build()); settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_auto)); settingsWindow.dismiss(); }); } @Override public void onTrackSelection(String subtext) { settingsAdapter.setSubTextAtPosition(SETTINGS_AUDIO_TRACK_SELECTION_POSITION, subtext); } @Override public void init(List<TrackInformation> trackInformations) { // Update subtext in settings menu with current audio track selection. boolean hasSelectionOverride = false; for (int i = 0; i < trackInformations.size(); i++) { if (checkNotNull(player) .getTrackSelectionParameters() .trackSelectionOverrides .containsKey(trackInformations.get(i).trackGroup)) { hasSelectionOverride = true; break; } } if (trackInformations.isEmpty()) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_none)); // TODO(insun) : Make the audio item in main settings (settingsAdapater) // to be non-clickable. } else if (!hasSelectionOverride) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_auto)); } else { for (int i = 0; i < trackInformations.size(); i++) { TrackInformation track = trackInformations.get(i); if (track.isSelected()) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, track.trackName); break; } } } this.tracks = trackInformations; } } private abstract class TrackSelectionAdapter extends RecyclerView.Adapter<SubSettingViewHolder> { protected List<TrackInformation> tracks; protected TrackSelectionAdapter() { this.tracks = new ArrayList<>(); } public abstract void init(List<TrackInformation> trackInformations); @Override public SubSettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate( R.layout.exo_styled_sub_settings_list_item, parent, /* attachToRoot= */ false); return new SubSettingViewHolder(v); } protected abstract void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder); protected abstract void onTrackSelection(String subtext); @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { if (player == null) { return; } if (position == 0) { onBindViewHolderAtZeroPosition(holder); } else { TrackInformation track = tracks.get(position - 1); boolean explicitlySelected = checkNotNull(player) .getTrackSelectionParameters() .trackSelectionOverrides .containsKey(track.trackGroup) && track.isSelected(); holder.textView.setText(track.trackName); holder.checkView.setVisibility(explicitlySelected ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (player == null) { return; } TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); Map<TrackGroup, TrackSelectionOverride> overrides = forceTrackSelection( trackSelectionParameters.trackSelectionOverrides, track.tracksInfo, track.trackGroupIndex, new TrackSelectionOverride(ImmutableSet.of(track.trackIndex))); checkNotNull(player) .setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setTrackSelectionOverrides(overrides) .build()); onTrackSelection(track.trackName); settingsWindow.dismiss(); }); } } @Override public int getItemCount() { return tracks.isEmpty() ? 0 : tracks.size() + 1; } protected void clear() { tracks = Collections.emptyList(); } } private static class SubSettingViewHolder extends RecyclerView.ViewHolder { public final TextView textView; public final View checkView; public SubSettingViewHolder(View itemView) { super(itemView); if (Util.SDK_INT < 26) { // Workaround for https://github.com/google/ExoPlayer/issues/9061. itemView.setFocusable(true); } textView = itemView.findViewById(R.id.exo_text); checkView = itemView.findViewById(R.id.exo_check); } } }
library/ui/src/main/java/com/google/android/exoplayer2/ui/StyledPlayerControlView.java
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ui; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_BACK; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_FORWARD; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_NEXT; import static com.google.android.exoplayer2.Player.COMMAND_SEEK_TO_PREVIOUS; import static com.google.android.exoplayer2.Player.EVENT_AVAILABLE_COMMANDS_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_IS_PLAYING_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAYBACK_PARAMETERS_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAYBACK_STATE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_PLAY_WHEN_READY_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_POSITION_DISCONTINUITY; import static com.google.android.exoplayer2.Player.EVENT_REPEAT_MODE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SEEK_BACK_INCREMENT_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SEEK_FORWARD_INCREMENT_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_TIMELINE_CHANGED; import static com.google.android.exoplayer2.Player.EVENT_TRACKS_CHANGED; import static com.google.android.exoplayer2.trackselection.TrackSelectionUtil.clearTrackSelectionOverridesForType; import static com.google.android.exoplayer2.trackselection.TrackSelectionUtil.forceTrackSelection; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Looper; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.core.content.res.ResourcesCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ControlDispatcher; import com.google.android.exoplayer2.DefaultControlDispatcher; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.ForwardingPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.Events; import com.google.android.exoplayer2.Player.State; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.TracksInfo; import com.google.android.exoplayer2.TracksInfo.TrackGroupInfo; import com.google.android.exoplayer2.source.TrackGroup; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters.TrackSelectionOverride; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.RepeatModeUtil; import com.google.android.exoplayer2.util.Util; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * A view for controlling {@link Player} instances. * * <p>A StyledPlayerControlView can be customized by setting attributes (or calling corresponding * methods), overriding drawables, overriding the view's layout file, or by specifying a custom view * layout file. * * <h2>Attributes</h2> * * The following attributes can be set on a StyledPlayerControlView when used in a layout XML file: * * <ul> * <li><b>{@code show_timeout}</b> - The time between the last user interaction and the controls * being automatically hidden, in milliseconds. Use zero if the controls should not * automatically timeout. * <ul> * <li>Corresponding method: {@link #setShowTimeoutMs(int)} * <li>Default: {@link #DEFAULT_SHOW_TIMEOUT_MS} * </ul> * <li><b>{@code show_rewind_button}</b> - Whether the rewind button is shown. * <ul> * <li>Corresponding method: {@link #setShowRewindButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_fastforward_button}</b> - Whether the fast forward button is shown. * <ul> * <li>Corresponding method: {@link #setShowFastForwardButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_previous_button}</b> - Whether the previous button is shown. * <ul> * <li>Corresponding method: {@link #setShowPreviousButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code show_next_button}</b> - Whether the next button is shown. * <ul> * <li>Corresponding method: {@link #setShowNextButton(boolean)} * <li>Default: true * </ul> * <li><b>{@code repeat_toggle_modes}</b> - A flagged enumeration value specifying which repeat * mode toggle options are enabled. Valid values are: {@code none}, {@code one}, {@code all}, * or {@code one|all}. * <ul> * <li>Corresponding method: {@link #setRepeatToggleModes(int)} * <li>Default: {@link #DEFAULT_REPEAT_TOGGLE_MODES} * </ul> * <li><b>{@code show_shuffle_button}</b> - Whether the shuffle button is shown. * <ul> * <li>Corresponding method: {@link #setShowShuffleButton(boolean)} * <li>Default: false * </ul> * <li><b>{@code show_subtitle_button}</b> - Whether the subtitle button is shown. * <ul> * <li>Corresponding method: {@link #setShowSubtitleButton(boolean)} * <li>Default: false * </ul> * <li><b>{@code animation_enabled}</b> - Whether an animation is used to show and hide the * playback controls. * <ul> * <li>Corresponding method: {@link #setAnimationEnabled(boolean)} * <li>Default: true * </ul> * <li><b>{@code time_bar_min_update_interval}</b> - Specifies the minimum interval between time * bar position updates. * <ul> * <li>Corresponding method: {@link #setTimeBarMinUpdateInterval(int)} * <li>Default: {@link #DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS} * </ul> * <li><b>{@code controller_layout_id}</b> - Specifies the id of the layout to be inflated. See * below for more details. * <ul> * <li>Corresponding method: None * <li>Default: {@code R.layout.exo_styled_player_control_view} * </ul> * <li>All attributes that can be set on {@link DefaultTimeBar} can also be set on a * StyledPlayerControlView, and will be propagated to the inflated {@link DefaultTimeBar} * unless the layout is overridden to specify a custom {@code exo_progress} (see below). * </ul> * * <h2>Overriding drawables</h2> * * The drawables used by StyledPlayerControlView (with its default layout file) can be overridden by * drawables with the same names defined in your application. The drawables that can be overridden * are: * * <ul> * <li><b>{@code exo_styled_controls_play}</b> - The play icon. * <li><b>{@code exo_styled_controls_pause}</b> - The pause icon. * <li><b>{@code exo_styled_controls_rewind}</b> - The background of rewind icon. * <li><b>{@code exo_styled_controls_fastforward}</b> - The background of fast forward icon. * <li><b>{@code exo_styled_controls_previous}</b> - The previous icon. * <li><b>{@code exo_styled_controls_next}</b> - The next icon. * <li><b>{@code exo_styled_controls_repeat_off}</b> - The repeat icon for {@link * Player#REPEAT_MODE_OFF}. * <li><b>{@code exo_styled_controls_repeat_one}</b> - The repeat icon for {@link * Player#REPEAT_MODE_ONE}. * <li><b>{@code exo_styled_controls_repeat_all}</b> - The repeat icon for {@link * Player#REPEAT_MODE_ALL}. * <li><b>{@code exo_styled_controls_shuffle_off}</b> - The shuffle icon when shuffling is * disabled. * <li><b>{@code exo_styled_controls_shuffle_on}</b> - The shuffle icon when shuffling is enabled. * <li><b>{@code exo_styled_controls_vr}</b> - The VR icon. * </ul> * * <h2>Overriding the layout file</h2> * * To customize the layout of StyledPlayerControlView throughout your app, or just for certain * configurations, you can define {@code exo_styled_player_control_view.xml} layout files in your * application {@code res/layout*} directories. But, in this case, you need to be careful since the * default animation implementation expects certain relative positions between children. See also <a * href="CustomLayout">Specifying a custom layout file</a>. * * <p>The layout files in your {@code res/layout*} will override the one provided by the library, * and will be inflated for use by StyledPlayerControlView. The view identifies and binds its * children by looking for the following ids: * * <ul> * <li><b>{@code exo_play_pause}</b> - The play and pause button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_rew}</b> - The rewind button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_rew_with_amount}</b> - The rewind button with rewind amount. * <ul> * <li>Type: {@link TextView} * <li>Note: StyledPlayerControlView will programmatically set the text with the rewind * amount in seconds. Ignored if an {@code exo_rew} exists. Otherwise, it works as the * rewind button. * </ul> * <li><b>{@code exo_ffwd}</b> - The fast forward button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_ffwd_with_amount}</b> - The fast forward button with fast forward amount. * <ul> * <li>Type: {@link TextView} * <li>Note: StyledPlayerControlView will programmatically set the text with the fast * forward amount in seconds. Ignored if an {@code exo_ffwd} exists. Otherwise, it works * as the fast forward button. * </ul> * <li><b>{@code exo_prev}</b> - The previous button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_next}</b> - The next button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_repeat_toggle}</b> - The repeat toggle button. * <ul> * <li>Type: {@link ImageView} * <li>Note: StyledPlayerControlView will programmatically set the drawable on the repeat * toggle button according to the player's current repeat mode. The drawables used are * {@code exo_controls_repeat_off}, {@code exo_controls_repeat_one} and {@code * exo_controls_repeat_all}. See the section above for information on overriding these * drawables. * </ul> * <li><b>{@code exo_shuffle}</b> - The shuffle button. * <ul> * <li>Type: {@link ImageView} * <li>Note: StyledPlayerControlView will programmatically set the drawable on the shuffle * button according to the player's current repeat mode. The drawables used are {@code * exo_controls_shuffle_off} and {@code exo_controls_shuffle_on}. See the section above * for information on overriding these drawables. * </ul> * <li><b>{@code exo_vr}</b> - The VR mode button. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_subtitle}</b> - The subtitle button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_fullscreen}</b> - The fullscreen button. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_minimal_fullscreen}</b> - The fullscreen button in minimal mode. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_position}</b> - Text view displaying the current playback position. * <ul> * <li>Type: {@link TextView} * </ul> * <li><b>{@code exo_duration}</b> - Text view displaying the current media duration. * <ul> * <li>Type: {@link TextView} * </ul> * <li><b>{@code exo_progress_placeholder}</b> - A placeholder that's replaced with the inflated * {@link DefaultTimeBar}. Ignored if an {@code exo_progress} view exists. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_progress}</b> - Time bar that's updated during playback and allows seeking. * {@link DefaultTimeBar} attributes set on the StyledPlayerControlView will not be * automatically propagated through to this instance. If a view exists with this id, any * {@code exo_progress_placeholder} view will be ignored. * <ul> * <li>Type: {@link TimeBar} * </ul> * </ul> * * <p>All child views are optional and so can be omitted if not required, however where defined they * must be of the expected type. * * <h2 id="CustomLayout">Specifying a custom layout file</h2> * * Defining your own {@code exo_styled_player_control_view.xml} is useful to customize the layout of * StyledPlayerControlView throughout your application. It's also possible to customize the layout * for a single instance in a layout file. This is achieved by setting the {@code * controller_layout_id} attribute on a StyledPlayerControlView. This will cause the specified * layout to be inflated instead of {@code exo_styled_player_control_view.xml} for only the instance * on which the attribute is set. * * <p>You need to be careful when you set the {@code controller_layout_id}, because the default * animation implementation expects certain relative positions between children. */ public class StyledPlayerControlView extends FrameLayout { static { ExoPlayerLibraryInfo.registerModule("goog.exo.ui"); } /** Listener to be notified about changes of the visibility of the UI control. */ public interface VisibilityListener { /** * Called when the visibility changes. * * @param visibility The new visibility. Either {@link View#VISIBLE} or {@link View#GONE}. */ void onVisibilityChange(int visibility); } /** Listener to be notified when progress has been updated. */ public interface ProgressUpdateListener { /** * Called when progress needs to be updated. * * @param position The current position. * @param bufferedPosition The current buffered position. */ void onProgressUpdate(long position, long bufferedPosition); } /** * Listener to be invoked to inform the fullscreen mode is changed. Application should handle the * fullscreen mode accordingly. */ public interface OnFullScreenModeChangedListener { /** * Called to indicate a fullscreen mode change. * * @param isFullScreen {@code true} if the video rendering surface should be fullscreen {@code * false} otherwise. */ void onFullScreenModeChanged(boolean isFullScreen); } /** The default show timeout, in milliseconds. */ public static final int DEFAULT_SHOW_TIMEOUT_MS = 5_000; /** The default repeat toggle modes. */ public static final @RepeatModeUtil.RepeatToggleModes int DEFAULT_REPEAT_TOGGLE_MODES = RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE; /** The default minimum interval between time bar position updates. */ public static final int DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS = 200; /** The maximum number of windows that can be shown in a multi-window time bar. */ public static final int MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR = 100; /** The maximum interval between time bar position updates. */ private static final int MAX_UPDATE_INTERVAL_MS = 1_000; private static final int SETTINGS_PLAYBACK_SPEED_POSITION = 0; private static final int SETTINGS_AUDIO_TRACK_SELECTION_POSITION = 1; private final ComponentListener componentListener; private final CopyOnWriteArrayList<VisibilityListener> visibilityListeners; @Nullable private final View previousButton; @Nullable private final View nextButton; @Nullable private final View playPauseButton; @Nullable private final View fastForwardButton; @Nullable private final View rewindButton; @Nullable private final TextView fastForwardButtonTextView; @Nullable private final TextView rewindButtonTextView; @Nullable private final ImageView repeatToggleButton; @Nullable private final ImageView shuffleButton; @Nullable private final View vrButton; @Nullable private final TextView durationView; @Nullable private final TextView positionView; @Nullable private final TimeBar timeBar; private final StringBuilder formatBuilder; private final Formatter formatter; private final Timeline.Period period; private final Timeline.Window window; private final Runnable updateProgressAction; private final Drawable repeatOffButtonDrawable; private final Drawable repeatOneButtonDrawable; private final Drawable repeatAllButtonDrawable; private final String repeatOffButtonContentDescription; private final String repeatOneButtonContentDescription; private final String repeatAllButtonContentDescription; private final Drawable shuffleOnButtonDrawable; private final Drawable shuffleOffButtonDrawable; private final float buttonAlphaEnabled; private final float buttonAlphaDisabled; private final String shuffleOnContentDescription; private final String shuffleOffContentDescription; private final Drawable subtitleOnButtonDrawable; private final Drawable subtitleOffButtonDrawable; private final String subtitleOnContentDescription; private final String subtitleOffContentDescription; private final Drawable fullScreenExitDrawable; private final Drawable fullScreenEnterDrawable; private final String fullScreenExitContentDescription; private final String fullScreenEnterContentDescription; @Nullable private Player player; private ControlDispatcher controlDispatcher; @Nullable private ProgressUpdateListener progressUpdateListener; @Nullable private OnFullScreenModeChangedListener onFullScreenModeChangedListener; private boolean isFullScreen; private boolean isAttachedToWindow; private boolean showMultiWindowTimeBar; private boolean multiWindowTimeBar; private boolean scrubbing; private int showTimeoutMs; private int timeBarMinUpdateIntervalMs; private @RepeatModeUtil.RepeatToggleModes int repeatToggleModes; private long[] adGroupTimesMs; private boolean[] playedAdGroups; private long[] extraAdGroupTimesMs; private boolean[] extraPlayedAdGroups; private long currentWindowOffset; private StyledPlayerControlViewLayoutManager controlViewLayoutManager; private Resources resources; private RecyclerView settingsView; private SettingsAdapter settingsAdapter; private PlaybackSpeedAdapter playbackSpeedAdapter; private PopupWindow settingsWindow; private boolean needToHideBars; private int settingsWindowMargin; private TextTrackSelectionAdapter textTrackSelectionAdapter; private AudioTrackSelectionAdapter audioTrackSelectionAdapter; // TODO(insun): Add setTrackNameProvider to use customized track name provider. private TrackNameProvider trackNameProvider; @Nullable private ImageView subtitleButton; @Nullable private ImageView fullScreenButton; @Nullable private ImageView minimalFullScreenButton; @Nullable private View settingsButton; @Nullable private View playbackSpeedButton; @Nullable private View audioTrackButton; public StyledPlayerControlView(Context context) { this(context, /* attrs= */ null); } public StyledPlayerControlView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, /* defStyleAttr= */ 0); } public StyledPlayerControlView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, attrs); } @SuppressWarnings({ "nullness:argument", "nullness:assignment", "nullness:method.invocation", "nullness:methodref.receiver.bound" }) public StyledPlayerControlView( Context context, @Nullable AttributeSet attrs, int defStyleAttr, @Nullable AttributeSet playbackAttrs) { super(context, attrs, defStyleAttr); int controllerLayoutId = R.layout.exo_styled_player_control_view; showTimeoutMs = DEFAULT_SHOW_TIMEOUT_MS; repeatToggleModes = DEFAULT_REPEAT_TOGGLE_MODES; timeBarMinUpdateIntervalMs = DEFAULT_TIME_BAR_MIN_UPDATE_INTERVAL_MS; boolean showRewindButton = true; boolean showFastForwardButton = true; boolean showPreviousButton = true; boolean showNextButton = true; boolean showShuffleButton = false; boolean showSubtitleButton = false; boolean animationEnabled = true; boolean showVrButton = false; if (playbackAttrs != null) { TypedArray a = context .getTheme() .obtainStyledAttributes( playbackAttrs, R.styleable.StyledPlayerControlView, defStyleAttr, /* defStyleRes= */ 0); try { controllerLayoutId = a.getResourceId( R.styleable.StyledPlayerControlView_controller_layout_id, controllerLayoutId); showTimeoutMs = a.getInt(R.styleable.StyledPlayerControlView_show_timeout, showTimeoutMs); repeatToggleModes = getRepeatToggleModes(a, repeatToggleModes); showRewindButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_rewind_button, showRewindButton); showFastForwardButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_fastforward_button, showFastForwardButton); showPreviousButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_previous_button, showPreviousButton); showNextButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_next_button, showNextButton); showShuffleButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_shuffle_button, showShuffleButton); showSubtitleButton = a.getBoolean( R.styleable.StyledPlayerControlView_show_subtitle_button, showSubtitleButton); showVrButton = a.getBoolean(R.styleable.StyledPlayerControlView_show_vr_button, showVrButton); setTimeBarMinUpdateInterval( a.getInt( R.styleable.StyledPlayerControlView_time_bar_min_update_interval, timeBarMinUpdateIntervalMs)); animationEnabled = a.getBoolean(R.styleable.StyledPlayerControlView_animation_enabled, animationEnabled); } finally { a.recycle(); } } LayoutInflater.from(context).inflate(controllerLayoutId, /* root= */ this); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); componentListener = new ComponentListener(); visibilityListeners = new CopyOnWriteArrayList<>(); period = new Timeline.Period(); window = new Timeline.Window(); formatBuilder = new StringBuilder(); formatter = new Formatter(formatBuilder, Locale.getDefault()); adGroupTimesMs = new long[0]; playedAdGroups = new boolean[0]; extraAdGroupTimesMs = new long[0]; extraPlayedAdGroups = new boolean[0]; controlDispatcher = new DefaultControlDispatcher(); updateProgressAction = this::updateProgress; durationView = findViewById(R.id.exo_duration); positionView = findViewById(R.id.exo_position); subtitleButton = findViewById(R.id.exo_subtitle); if (subtitleButton != null) { subtitleButton.setOnClickListener(componentListener); } fullScreenButton = findViewById(R.id.exo_fullscreen); initializeFullScreenButton(fullScreenButton, this::onFullScreenButtonClicked); minimalFullScreenButton = findViewById(R.id.exo_minimal_fullscreen); initializeFullScreenButton(minimalFullScreenButton, this::onFullScreenButtonClicked); settingsButton = findViewById(R.id.exo_settings); if (settingsButton != null) { settingsButton.setOnClickListener(componentListener); } playbackSpeedButton = findViewById(R.id.exo_playback_speed); if (playbackSpeedButton != null) { playbackSpeedButton.setOnClickListener(componentListener); } audioTrackButton = findViewById(R.id.exo_audio_track); if (audioTrackButton != null) { audioTrackButton.setOnClickListener(componentListener); } TimeBar customTimeBar = findViewById(R.id.exo_progress); View timeBarPlaceholder = findViewById(R.id.exo_progress_placeholder); if (customTimeBar != null) { timeBar = customTimeBar; } else if (timeBarPlaceholder != null) { // Propagate playbackAttrs as timebarAttrs so that DefaultTimeBar's custom attributes are // transferred, but standard attributes (e.g. background) are not. DefaultTimeBar defaultTimeBar = new DefaultTimeBar(context, null, 0, playbackAttrs, R.style.ExoStyledControls_TimeBar); defaultTimeBar.setId(R.id.exo_progress); defaultTimeBar.setLayoutParams(timeBarPlaceholder.getLayoutParams()); ViewGroup parent = ((ViewGroup) timeBarPlaceholder.getParent()); int timeBarIndex = parent.indexOfChild(timeBarPlaceholder); parent.removeView(timeBarPlaceholder); parent.addView(defaultTimeBar, timeBarIndex); timeBar = defaultTimeBar; } else { timeBar = null; } if (timeBar != null) { timeBar.addListener(componentListener); } playPauseButton = findViewById(R.id.exo_play_pause); if (playPauseButton != null) { playPauseButton.setOnClickListener(componentListener); } previousButton = findViewById(R.id.exo_prev); if (previousButton != null) { previousButton.setOnClickListener(componentListener); } nextButton = findViewById(R.id.exo_next); if (nextButton != null) { nextButton.setOnClickListener(componentListener); } Typeface typeface = ResourcesCompat.getFont(context, R.font.roboto_medium_numbers); View rewButton = findViewById(R.id.exo_rew); rewindButtonTextView = rewButton == null ? findViewById(R.id.exo_rew_with_amount) : null; if (rewindButtonTextView != null) { rewindButtonTextView.setTypeface(typeface); } rewindButton = rewButton == null ? rewindButtonTextView : rewButton; if (rewindButton != null) { rewindButton.setOnClickListener(componentListener); } View ffwdButton = findViewById(R.id.exo_ffwd); fastForwardButtonTextView = ffwdButton == null ? findViewById(R.id.exo_ffwd_with_amount) : null; if (fastForwardButtonTextView != null) { fastForwardButtonTextView.setTypeface(typeface); } fastForwardButton = ffwdButton == null ? fastForwardButtonTextView : ffwdButton; if (fastForwardButton != null) { fastForwardButton.setOnClickListener(componentListener); } repeatToggleButton = findViewById(R.id.exo_repeat_toggle); if (repeatToggleButton != null) { repeatToggleButton.setOnClickListener(componentListener); } shuffleButton = findViewById(R.id.exo_shuffle); if (shuffleButton != null) { shuffleButton.setOnClickListener(componentListener); } resources = context.getResources(); buttonAlphaEnabled = (float) resources.getInteger(R.integer.exo_media_button_opacity_percentage_enabled) / 100; buttonAlphaDisabled = (float) resources.getInteger(R.integer.exo_media_button_opacity_percentage_disabled) / 100; vrButton = findViewById(R.id.exo_vr); if (vrButton != null) { updateButton(/* enabled= */ false, vrButton); } controlViewLayoutManager = new StyledPlayerControlViewLayoutManager(this); controlViewLayoutManager.setAnimationEnabled(animationEnabled); String[] settingTexts = new String[2]; Drawable[] settingIcons = new Drawable[2]; settingTexts[SETTINGS_PLAYBACK_SPEED_POSITION] = resources.getString(R.string.exo_controls_playback_speed); settingIcons[SETTINGS_PLAYBACK_SPEED_POSITION] = resources.getDrawable(R.drawable.exo_styled_controls_speed); settingTexts[SETTINGS_AUDIO_TRACK_SELECTION_POSITION] = resources.getString(R.string.exo_track_selection_title_audio); settingIcons[SETTINGS_AUDIO_TRACK_SELECTION_POSITION] = resources.getDrawable(R.drawable.exo_styled_controls_audiotrack); settingsAdapter = new SettingsAdapter(settingTexts, settingIcons); settingsWindowMargin = resources.getDimensionPixelSize(R.dimen.exo_settings_offset); settingsView = (RecyclerView) LayoutInflater.from(context) .inflate(R.layout.exo_styled_settings_list, /* root= */ null); settingsView.setAdapter(settingsAdapter); settingsView.setLayoutManager(new LinearLayoutManager(getContext())); settingsWindow = new PopupWindow(settingsView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true); if (Util.SDK_INT < 23) { // Work around issue where tapping outside of the menu area or pressing the back button // doesn't dismiss the menu as expected. See: https://github.com/google/ExoPlayer/issues/8272. settingsWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } settingsWindow.setOnDismissListener(componentListener); needToHideBars = true; trackNameProvider = new DefaultTrackNameProvider(getResources()); subtitleOnButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_subtitle_on); subtitleOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_subtitle_off); subtitleOnContentDescription = resources.getString(R.string.exo_controls_cc_enabled_description); subtitleOffContentDescription = resources.getString(R.string.exo_controls_cc_disabled_description); textTrackSelectionAdapter = new TextTrackSelectionAdapter(); audioTrackSelectionAdapter = new AudioTrackSelectionAdapter(); playbackSpeedAdapter = new PlaybackSpeedAdapter( resources.getStringArray(R.array.exo_playback_speeds), resources.getIntArray(R.array.exo_speed_multiplied_by_100)); fullScreenExitDrawable = resources.getDrawable(R.drawable.exo_styled_controls_fullscreen_exit); fullScreenEnterDrawable = resources.getDrawable(R.drawable.exo_styled_controls_fullscreen_enter); repeatOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_off); repeatOneButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_one); repeatAllButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_repeat_all); shuffleOnButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_shuffle_on); shuffleOffButtonDrawable = resources.getDrawable(R.drawable.exo_styled_controls_shuffle_off); fullScreenExitContentDescription = resources.getString(R.string.exo_controls_fullscreen_exit_description); fullScreenEnterContentDescription = resources.getString(R.string.exo_controls_fullscreen_enter_description); repeatOffButtonContentDescription = resources.getString(R.string.exo_controls_repeat_off_description); repeatOneButtonContentDescription = resources.getString(R.string.exo_controls_repeat_one_description); repeatAllButtonContentDescription = resources.getString(R.string.exo_controls_repeat_all_description); shuffleOnContentDescription = resources.getString(R.string.exo_controls_shuffle_on_description); shuffleOffContentDescription = resources.getString(R.string.exo_controls_shuffle_off_description); // TODO(insun) : Make showing bottomBar configurable. (ex. show_bottom_bar attribute). ViewGroup bottomBar = findViewById(R.id.exo_bottom_bar); controlViewLayoutManager.setShowButton(bottomBar, true); controlViewLayoutManager.setShowButton(fastForwardButton, showFastForwardButton); controlViewLayoutManager.setShowButton(rewindButton, showRewindButton); controlViewLayoutManager.setShowButton(previousButton, showPreviousButton); controlViewLayoutManager.setShowButton(nextButton, showNextButton); controlViewLayoutManager.setShowButton(shuffleButton, showShuffleButton); controlViewLayoutManager.setShowButton(subtitleButton, showSubtitleButton); controlViewLayoutManager.setShowButton(vrButton, showVrButton); controlViewLayoutManager.setShowButton( repeatToggleButton, repeatToggleModes != RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE); addOnLayoutChangeListener(this::onLayoutChange); } /** * Returns the {@link Player} currently being controlled by this view, or null if no player is * set. */ @Nullable public Player getPlayer() { return player; } /** * Sets the {@link Player} to control. * * @param player The {@link Player} to control, or {@code null} to detach the current player. Only * players which are accessed on the main thread are supported ({@code * player.getApplicationLooper() == Looper.getMainLooper()}). */ public void setPlayer(@Nullable Player player) { Assertions.checkState(Looper.myLooper() == Looper.getMainLooper()); Assertions.checkArgument( player == null || player.getApplicationLooper() == Looper.getMainLooper()); if (this.player == player) { return; } if (this.player != null) { this.player.removeListener(componentListener); } this.player = player; if (player != null) { player.addListener(componentListener); } if (player instanceof ForwardingPlayer) { player = ((ForwardingPlayer) player).getWrappedPlayer(); } updateAll(); } /** * Sets whether the time bar should show all windows, as opposed to just the current one. If the * timeline has a period with unknown duration or more than {@link * #MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR} windows the time bar will fall back to showing a single * window. * * @param showMultiWindowTimeBar Whether the time bar should show all windows. */ public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) { this.showMultiWindowTimeBar = showMultiWindowTimeBar; updateTimeline(); } /** * Sets the millisecond positions of extra ad markers relative to the start of the window (or * timeline, if in multi-window mode) and whether each extra ad has been played or not. The * markers are shown in addition to any ad markers for ads in the player's timeline. * * @param extraAdGroupTimesMs The millisecond timestamps of the extra ad markers to show, or * {@code null} to show no extra ad markers. * @param extraPlayedAdGroups Whether each ad has been played. Must be the same length as {@code * extraAdGroupTimesMs}, or {@code null} if {@code extraAdGroupTimesMs} is {@code null}. */ public void setExtraAdGroupMarkers( @Nullable long[] extraAdGroupTimesMs, @Nullable boolean[] extraPlayedAdGroups) { if (extraAdGroupTimesMs == null) { this.extraAdGroupTimesMs = new long[0]; this.extraPlayedAdGroups = new boolean[0]; } else { extraPlayedAdGroups = checkNotNull(extraPlayedAdGroups); Assertions.checkArgument(extraAdGroupTimesMs.length == extraPlayedAdGroups.length); this.extraAdGroupTimesMs = extraAdGroupTimesMs; this.extraPlayedAdGroups = extraPlayedAdGroups; } updateTimeline(); } /** * Adds a {@link VisibilityListener}. * * @param listener The listener to be notified about visibility changes. */ public void addVisibilityListener(VisibilityListener listener) { checkNotNull(listener); visibilityListeners.add(listener); } /** * Removes a {@link VisibilityListener}. * * @param listener The listener to be removed. */ public void removeVisibilityListener(VisibilityListener listener) { visibilityListeners.remove(listener); } /** * Sets the {@link ProgressUpdateListener}. * * @param listener The listener to be notified about when progress is updated. */ public void setProgressUpdateListener(@Nullable ProgressUpdateListener listener) { this.progressUpdateListener = listener; } /** * @deprecated Use a {@link ForwardingPlayer} and pass it to {@link #setPlayer(Player)} instead. * You can also customize some operations when configuring the player (for example by using * {@code ExoPlayer.Builder.setSeekBackIncrementMs(long)}). */ @Deprecated public void setControlDispatcher(ControlDispatcher controlDispatcher) { if (this.controlDispatcher != controlDispatcher) { this.controlDispatcher = controlDispatcher; updateNavigation(); } } /** * Sets whether the rewind button is shown. * * @param showRewindButton Whether the rewind button is shown. */ public void setShowRewindButton(boolean showRewindButton) { controlViewLayoutManager.setShowButton(rewindButton, showRewindButton); updateNavigation(); } /** * Sets whether the fast forward button is shown. * * @param showFastForwardButton Whether the fast forward button is shown. */ public void setShowFastForwardButton(boolean showFastForwardButton) { controlViewLayoutManager.setShowButton(fastForwardButton, showFastForwardButton); updateNavigation(); } /** * Sets whether the previous button is shown. * * @param showPreviousButton Whether the previous button is shown. */ public void setShowPreviousButton(boolean showPreviousButton) { controlViewLayoutManager.setShowButton(previousButton, showPreviousButton); updateNavigation(); } /** * Sets whether the next button is shown. * * @param showNextButton Whether the next button is shown. */ public void setShowNextButton(boolean showNextButton) { controlViewLayoutManager.setShowButton(nextButton, showNextButton); updateNavigation(); } /** * Returns the playback controls timeout. The playback controls are automatically hidden after * this duration of time has elapsed without user input. * * @return The duration in milliseconds. A non-positive value indicates that the controls will * remain visible indefinitely. */ public int getShowTimeoutMs() { return showTimeoutMs; } /** * Sets the playback controls timeout. The playback controls are automatically hidden after this * duration of time has elapsed without user input. * * @param showTimeoutMs The duration in milliseconds. A non-positive value will cause the controls * to remain visible indefinitely. */ public void setShowTimeoutMs(int showTimeoutMs) { this.showTimeoutMs = showTimeoutMs; if (isFullyVisible()) { controlViewLayoutManager.resetHideCallbacks(); } } /** * Returns which repeat toggle modes are enabled. * * @return The currently enabled {@link RepeatModeUtil.RepeatToggleModes}. */ public @RepeatModeUtil.RepeatToggleModes int getRepeatToggleModes() { return repeatToggleModes; } /** * Sets which repeat toggle modes are enabled. * * @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}. */ public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) { this.repeatToggleModes = repeatToggleModes; if (player != null) { @Player.RepeatMode int currentMode = player.getRepeatMode(); if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE && currentMode != Player.REPEAT_MODE_OFF) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_OFF); } else if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_ONE && currentMode == Player.REPEAT_MODE_ALL) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_ONE); } else if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_ALL && currentMode == Player.REPEAT_MODE_ONE) { controlDispatcher.dispatchSetRepeatMode(player, Player.REPEAT_MODE_ALL); } } controlViewLayoutManager.setShowButton( repeatToggleButton, repeatToggleModes != RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE); updateRepeatModeButton(); } /** Returns whether the shuffle button is shown. */ public boolean getShowShuffleButton() { return controlViewLayoutManager.getShowButton(shuffleButton); } /** * Sets whether the shuffle button is shown. * * @param showShuffleButton Whether the shuffle button is shown. */ public void setShowShuffleButton(boolean showShuffleButton) { controlViewLayoutManager.setShowButton(shuffleButton, showShuffleButton); updateShuffleButton(); } /** Returns whether the subtitle button is shown. */ public boolean getShowSubtitleButton() { return controlViewLayoutManager.getShowButton(subtitleButton); } /** * Sets whether the subtitle button is shown. * * @param showSubtitleButton Whether the subtitle button is shown. */ public void setShowSubtitleButton(boolean showSubtitleButton) { controlViewLayoutManager.setShowButton(subtitleButton, showSubtitleButton); } /** Returns whether the VR button is shown. */ public boolean getShowVrButton() { return controlViewLayoutManager.getShowButton(vrButton); } /** * Sets whether the VR button is shown. * * @param showVrButton Whether the VR button is shown. */ public void setShowVrButton(boolean showVrButton) { controlViewLayoutManager.setShowButton(vrButton, showVrButton); } /** * Sets listener for the VR button. * * @param onClickListener Listener for the VR button, or null to clear the listener. */ public void setVrButtonListener(@Nullable OnClickListener onClickListener) { if (vrButton != null) { vrButton.setOnClickListener(onClickListener); updateButton(onClickListener != null, vrButton); } } /** * Sets whether an animation is used to show and hide the playback controls. * * @param animationEnabled Whether an animation is applied to show and hide playback controls. */ public void setAnimationEnabled(boolean animationEnabled) { controlViewLayoutManager.setAnimationEnabled(animationEnabled); } /** Returns whether an animation is used to show and hide the playback controls. */ public boolean isAnimationEnabled() { return controlViewLayoutManager.isAnimationEnabled(); } /** * Sets the minimum interval between time bar position updates. * * <p>Note that smaller intervals, e.g. 33ms, will result in a smooth movement but will use more * CPU resources while the time bar is visible, whereas larger intervals, e.g. 200ms, will result * in a step-wise update with less CPU usage. * * @param minUpdateIntervalMs The minimum interval between time bar position updates, in * milliseconds. */ public void setTimeBarMinUpdateInterval(int minUpdateIntervalMs) { // Do not accept values below 16ms (60fps) and larger than the maximum update interval. timeBarMinUpdateIntervalMs = Util.constrainValue(minUpdateIntervalMs, 16, MAX_UPDATE_INTERVAL_MS); } /** * Sets a listener to be called when the fullscreen mode should be changed. A non-null listener * needs to be set in order to display the fullscreen button. * * @param listener The listener to be called. A value of <code>null</code> removes any existing * listener and hides the fullscreen button. */ public void setOnFullScreenModeChangedListener( @Nullable OnFullScreenModeChangedListener listener) { onFullScreenModeChangedListener = listener; updateFullScreenButtonVisibility(fullScreenButton, listener != null); updateFullScreenButtonVisibility(minimalFullScreenButton, listener != null); } /** * Shows the playback controls. If {@link #getShowTimeoutMs()} is positive then the controls will * be automatically hidden after this duration of time has elapsed without user input. */ public void show() { controlViewLayoutManager.show(); } /** Hides the controller. */ public void hide() { controlViewLayoutManager.hide(); } /** Hides the controller without any animation. */ public void hideImmediately() { controlViewLayoutManager.hideImmediately(); } /** Returns whether the controller is fully visible, which means all UI controls are visible. */ public boolean isFullyVisible() { return controlViewLayoutManager.isFullyVisible(); } /** Returns whether the controller is currently visible. */ public boolean isVisible() { return getVisibility() == VISIBLE; } /* package */ void notifyOnVisibilityChange() { for (VisibilityListener visibilityListener : visibilityListeners) { visibilityListener.onVisibilityChange(getVisibility()); } } /* package */ void updateAll() { updatePlayPauseButton(); updateNavigation(); updateRepeatModeButton(); updateShuffleButton(); updateTrackLists(); updatePlaybackSpeedList(); updateTimeline(); } private void updatePlayPauseButton() { if (!isVisible() || !isAttachedToWindow) { return; } if (playPauseButton != null) { if (shouldShowPauseButton()) { ((ImageView) playPauseButton) .setImageDrawable(resources.getDrawable(R.drawable.exo_styled_controls_pause)); playPauseButton.setContentDescription( resources.getString(R.string.exo_controls_pause_description)); } else { ((ImageView) playPauseButton) .setImageDrawable(resources.getDrawable(R.drawable.exo_styled_controls_play)); playPauseButton.setContentDescription( resources.getString(R.string.exo_controls_play_description)); } } } private void updateNavigation() { if (!isVisible() || !isAttachedToWindow) { return; } @Nullable Player player = this.player; boolean enableSeeking = false; boolean enablePrevious = false; boolean enableRewind = false; boolean enableFastForward = false; boolean enableNext = false; if (player != null) { enableSeeking = player.isCommandAvailable(COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM); enablePrevious = player.isCommandAvailable(COMMAND_SEEK_TO_PREVIOUS); enableRewind = player.isCommandAvailable(COMMAND_SEEK_BACK) && controlDispatcher.isRewindEnabled(); enableFastForward = player.isCommandAvailable(COMMAND_SEEK_FORWARD) && controlDispatcher.isFastForwardEnabled(); enableNext = player.isCommandAvailable(COMMAND_SEEK_TO_NEXT); } if (enableRewind) { updateRewindButton(); } if (enableFastForward) { updateFastForwardButton(); } updateButton(enablePrevious, previousButton); updateButton(enableRewind, rewindButton); updateButton(enableFastForward, fastForwardButton); updateButton(enableNext, nextButton); if (timeBar != null) { timeBar.setEnabled(enableSeeking); } } private void updateRewindButton() { long rewindMs = controlDispatcher instanceof DefaultControlDispatcher && player != null ? ((DefaultControlDispatcher) controlDispatcher).getRewindIncrementMs(player) : C.DEFAULT_SEEK_BACK_INCREMENT_MS; int rewindSec = (int) (rewindMs / 1_000); if (rewindButtonTextView != null) { rewindButtonTextView.setText(String.valueOf(rewindSec)); } if (rewindButton != null) { rewindButton.setContentDescription( resources.getQuantityString( R.plurals.exo_controls_rewind_by_amount_description, rewindSec, rewindSec)); } } private void updateFastForwardButton() { long fastForwardMs = controlDispatcher instanceof DefaultControlDispatcher && player != null ? ((DefaultControlDispatcher) controlDispatcher).getFastForwardIncrementMs(player) : C.DEFAULT_SEEK_FORWARD_INCREMENT_MS; int fastForwardSec = (int) (fastForwardMs / 1_000); if (fastForwardButtonTextView != null) { fastForwardButtonTextView.setText(String.valueOf(fastForwardSec)); } if (fastForwardButton != null) { fastForwardButton.setContentDescription( resources.getQuantityString( R.plurals.exo_controls_fastforward_by_amount_description, fastForwardSec, fastForwardSec)); } } private void updateRepeatModeButton() { if (!isVisible() || !isAttachedToWindow || repeatToggleButton == null) { return; } if (repeatToggleModes == RepeatModeUtil.REPEAT_TOGGLE_MODE_NONE) { updateButton(/* enabled= */ false, repeatToggleButton); return; } @Nullable Player player = this.player; if (player == null) { updateButton(/* enabled= */ false, repeatToggleButton); repeatToggleButton.setImageDrawable(repeatOffButtonDrawable); repeatToggleButton.setContentDescription(repeatOffButtonContentDescription); return; } updateButton(/* enabled= */ true, repeatToggleButton); switch (player.getRepeatMode()) { case Player.REPEAT_MODE_OFF: repeatToggleButton.setImageDrawable(repeatOffButtonDrawable); repeatToggleButton.setContentDescription(repeatOffButtonContentDescription); break; case Player.REPEAT_MODE_ONE: repeatToggleButton.setImageDrawable(repeatOneButtonDrawable); repeatToggleButton.setContentDescription(repeatOneButtonContentDescription); break; case Player.REPEAT_MODE_ALL: repeatToggleButton.setImageDrawable(repeatAllButtonDrawable); repeatToggleButton.setContentDescription(repeatAllButtonContentDescription); break; default: // Never happens. } } private void updateShuffleButton() { if (!isVisible() || !isAttachedToWindow || shuffleButton == null) { return; } @Nullable Player player = this.player; if (!controlViewLayoutManager.getShowButton(shuffleButton)) { updateButton(/* enabled= */ false, shuffleButton); } else if (player == null) { updateButton(/* enabled= */ false, shuffleButton); shuffleButton.setImageDrawable(shuffleOffButtonDrawable); shuffleButton.setContentDescription(shuffleOffContentDescription); } else { updateButton(/* enabled= */ true, shuffleButton); shuffleButton.setImageDrawable( player.getShuffleModeEnabled() ? shuffleOnButtonDrawable : shuffleOffButtonDrawable); shuffleButton.setContentDescription( player.getShuffleModeEnabled() ? shuffleOnContentDescription : shuffleOffContentDescription); } } private void updateTrackLists() { initTrackSelectionAdapter(); updateButton(textTrackSelectionAdapter.getItemCount() > 0, subtitleButton); } private void initTrackSelectionAdapter() { textTrackSelectionAdapter.clear(); audioTrackSelectionAdapter.clear(); if (player == null || !player.isCommandAvailable(Player.COMMAND_GET_TRACK_INFOS) || !player.isCommandAvailable(Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS)) { return; } TracksInfo tracksInfo = player.getCurrentTracksInfo(); List<TrackGroupInfo> trackGroupInfos = tracksInfo.getTrackGroupInfos(); if (trackGroupInfos.isEmpty()) { return; } List<TrackInformation> textTracks = new ArrayList<>(); List<TrackInformation> audioTracks = new ArrayList<>(); for (int trackGroupIndex = 0; trackGroupIndex < trackGroupInfos.size(); trackGroupIndex++) { TrackGroupInfo trackGroupInfo = trackGroupInfos.get(trackGroupIndex); if (!trackGroupInfo.isSupported()) { continue; } if (trackGroupInfo.getTrackType() == C.TRACK_TYPE_TEXT && controlViewLayoutManager.getShowButton(subtitleButton)) { // Get TrackSelection at the corresponding renderer index. gatherTrackInfosForAdapter(tracksInfo, trackGroupIndex, textTracks); } else if (trackGroupInfo.getTrackType() == C.TRACK_TYPE_AUDIO) { gatherTrackInfosForAdapter(tracksInfo, trackGroupIndex, audioTracks); } } textTrackSelectionAdapter.init(textTracks); audioTrackSelectionAdapter.init(audioTracks); } private void gatherTrackInfosForAdapter( TracksInfo tracksInfo, int trackGroupIndex, List<TrackInformation> tracks) { TrackGroupInfo trackGroupInfo = tracksInfo.getTrackGroupInfos().get(trackGroupIndex); TrackGroup trackGroup = trackGroupInfo.getTrackGroup(); for (int trackIndex = 0; trackIndex < trackGroup.length; trackIndex++) { Format format = trackGroup.getFormat(trackIndex); if (trackGroupInfo.isTrackSupported(trackIndex)) { tracks.add( new TrackInformation( tracksInfo, trackGroupIndex, trackIndex, trackNameProvider.getTrackName(format))); } } } private void updateTimeline() { @Nullable Player player = this.player; if (player == null) { return; } multiWindowTimeBar = showMultiWindowTimeBar && canShowMultiWindowTimeBar(player.getCurrentTimeline(), window); currentWindowOffset = 0; long durationUs = 0; int adGroupCount = 0; Timeline timeline = player.getCurrentTimeline(); if (!timeline.isEmpty()) { int currentWindowIndex = player.getCurrentWindowIndex(); int firstWindowIndex = multiWindowTimeBar ? 0 : currentWindowIndex; int lastWindowIndex = multiWindowTimeBar ? timeline.getWindowCount() - 1 : currentWindowIndex; for (int i = firstWindowIndex; i <= lastWindowIndex; i++) { if (i == currentWindowIndex) { currentWindowOffset = C.usToMs(durationUs); } timeline.getWindow(i, window); if (window.durationUs == C.TIME_UNSET) { Assertions.checkState(!multiWindowTimeBar); break; } for (int j = window.firstPeriodIndex; j <= window.lastPeriodIndex; j++) { timeline.getPeriod(j, period); int removedGroups = period.getRemovedAdGroupCount(); int totalGroups = period.getAdGroupCount(); for (int adGroupIndex = removedGroups; adGroupIndex < totalGroups; adGroupIndex++) { long adGroupTimeInPeriodUs = period.getAdGroupTimeUs(adGroupIndex); if (adGroupTimeInPeriodUs == C.TIME_END_OF_SOURCE) { if (period.durationUs == C.TIME_UNSET) { // Don't show ad markers for postrolls in periods with unknown duration. continue; } adGroupTimeInPeriodUs = period.durationUs; } long adGroupTimeInWindowUs = adGroupTimeInPeriodUs + period.getPositionInWindowUs(); if (adGroupTimeInWindowUs >= 0) { if (adGroupCount == adGroupTimesMs.length) { int newLength = adGroupTimesMs.length == 0 ? 1 : adGroupTimesMs.length * 2; adGroupTimesMs = Arrays.copyOf(adGroupTimesMs, newLength); playedAdGroups = Arrays.copyOf(playedAdGroups, newLength); } adGroupTimesMs[adGroupCount] = C.usToMs(durationUs + adGroupTimeInWindowUs); playedAdGroups[adGroupCount] = period.hasPlayedAdGroup(adGroupIndex); adGroupCount++; } } } durationUs += window.durationUs; } } long durationMs = C.usToMs(durationUs); if (durationView != null) { durationView.setText(Util.getStringForTime(formatBuilder, formatter, durationMs)); } if (timeBar != null) { timeBar.setDuration(durationMs); int extraAdGroupCount = extraAdGroupTimesMs.length; int totalAdGroupCount = adGroupCount + extraAdGroupCount; if (totalAdGroupCount > adGroupTimesMs.length) { adGroupTimesMs = Arrays.copyOf(adGroupTimesMs, totalAdGroupCount); playedAdGroups = Arrays.copyOf(playedAdGroups, totalAdGroupCount); } System.arraycopy(extraAdGroupTimesMs, 0, adGroupTimesMs, adGroupCount, extraAdGroupCount); System.arraycopy(extraPlayedAdGroups, 0, playedAdGroups, adGroupCount, extraAdGroupCount); timeBar.setAdGroupTimesMs(adGroupTimesMs, playedAdGroups, totalAdGroupCount); } updateProgress(); } private void updateProgress() { if (!isVisible() || !isAttachedToWindow) { return; } @Nullable Player player = this.player; long position = 0; long bufferedPosition = 0; if (player != null) { position = currentWindowOffset + player.getContentPosition(); bufferedPosition = currentWindowOffset + player.getContentBufferedPosition(); } if (positionView != null && !scrubbing) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } if (timeBar != null) { timeBar.setPosition(position); timeBar.setBufferedPosition(bufferedPosition); } if (progressUpdateListener != null) { progressUpdateListener.onProgressUpdate(position, bufferedPosition); } // Cancel any pending updates and schedule a new one if necessary. removeCallbacks(updateProgressAction); int playbackState = player == null ? Player.STATE_IDLE : player.getPlaybackState(); if (player != null && player.isPlaying()) { long mediaTimeDelayMs = timeBar != null ? timeBar.getPreferredUpdateDelay() : MAX_UPDATE_INTERVAL_MS; // Limit delay to the start of the next full second to ensure position display is smooth. long mediaTimeUntilNextFullSecondMs = 1000 - position % 1000; mediaTimeDelayMs = Math.min(mediaTimeDelayMs, mediaTimeUntilNextFullSecondMs); // Calculate the delay until the next update in real time, taking playback speed into account. float playbackSpeed = player.getPlaybackParameters().speed; long delayMs = playbackSpeed > 0 ? (long) (mediaTimeDelayMs / playbackSpeed) : MAX_UPDATE_INTERVAL_MS; // Constrain the delay to avoid too frequent / infrequent updates. delayMs = Util.constrainValue(delayMs, timeBarMinUpdateIntervalMs, MAX_UPDATE_INTERVAL_MS); postDelayed(updateProgressAction, delayMs); } else if (playbackState != Player.STATE_ENDED && playbackState != Player.STATE_IDLE) { postDelayed(updateProgressAction, MAX_UPDATE_INTERVAL_MS); } } private void updatePlaybackSpeedList() { if (player == null) { return; } playbackSpeedAdapter.updateSelectedIndex(player.getPlaybackParameters().speed); settingsAdapter.setSubTextAtPosition( SETTINGS_PLAYBACK_SPEED_POSITION, playbackSpeedAdapter.getSelectedText()); } private void updateSettingsWindowSize() { settingsView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int maxWidth = getWidth() - settingsWindowMargin * 2; int itemWidth = settingsView.getMeasuredWidth(); int width = Math.min(itemWidth, maxWidth); settingsWindow.setWidth(width); int maxHeight = getHeight() - settingsWindowMargin * 2; int totalHeight = settingsView.getMeasuredHeight(); int height = Math.min(maxHeight, totalHeight); settingsWindow.setHeight(height); } private void displaySettingsWindow(RecyclerView.Adapter<?> adapter) { settingsView.setAdapter(adapter); updateSettingsWindowSize(); needToHideBars = false; settingsWindow.dismiss(); needToHideBars = true; int xoff = getWidth() - settingsWindow.getWidth() - settingsWindowMargin; int yoff = -settingsWindow.getHeight() - settingsWindowMargin; settingsWindow.showAsDropDown(this, xoff, yoff); } private void setPlaybackSpeed(float speed) { if (player == null) { return; } controlDispatcher.dispatchSetPlaybackParameters( player, player.getPlaybackParameters().withSpeed(speed)); } /* package */ void requestPlayPauseFocus() { if (playPauseButton != null) { playPauseButton.requestFocus(); } } private void updateButton(boolean enabled, @Nullable View view) { if (view == null) { return; } view.setEnabled(enabled); view.setAlpha(enabled ? buttonAlphaEnabled : buttonAlphaDisabled); } private void seekToTimeBarPosition(Player player, long positionMs) { int windowIndex; Timeline timeline = player.getCurrentTimeline(); if (multiWindowTimeBar && !timeline.isEmpty()) { int windowCount = timeline.getWindowCount(); windowIndex = 0; while (true) { long windowDurationMs = timeline.getWindow(windowIndex, window).getDurationMs(); if (positionMs < windowDurationMs) { break; } else if (windowIndex == windowCount - 1) { // Seeking past the end of the last window should seek to the end of the timeline. positionMs = windowDurationMs; break; } positionMs -= windowDurationMs; windowIndex++; } } else { windowIndex = player.getCurrentWindowIndex(); } seekTo(player, windowIndex, positionMs); updateProgress(); } private boolean seekTo(Player player, int windowIndex, long positionMs) { return controlDispatcher.dispatchSeekTo(player, windowIndex, positionMs); } private void onFullScreenButtonClicked(View v) { if (onFullScreenModeChangedListener == null) { return; } isFullScreen = !isFullScreen; updateFullScreenButtonForState(fullScreenButton, isFullScreen); updateFullScreenButtonForState(minimalFullScreenButton, isFullScreen); if (onFullScreenModeChangedListener != null) { onFullScreenModeChangedListener.onFullScreenModeChanged(isFullScreen); } } private void updateFullScreenButtonForState( @Nullable ImageView fullScreenButton, boolean isFullScreen) { if (fullScreenButton == null) { return; } if (isFullScreen) { fullScreenButton.setImageDrawable(fullScreenExitDrawable); fullScreenButton.setContentDescription(fullScreenExitContentDescription); } else { fullScreenButton.setImageDrawable(fullScreenEnterDrawable); fullScreenButton.setContentDescription(fullScreenEnterContentDescription); } } private void onSettingViewClicked(int position) { if (position == SETTINGS_PLAYBACK_SPEED_POSITION) { displaySettingsWindow(playbackSpeedAdapter); } else if (position == SETTINGS_AUDIO_TRACK_SELECTION_POSITION) { displaySettingsWindow(audioTrackSelectionAdapter); } else { settingsWindow.dismiss(); } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); controlViewLayoutManager.onAttachedToWindow(); isAttachedToWindow = true; if (isFullyVisible()) { controlViewLayoutManager.resetHideCallbacks(); } updateAll(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); controlViewLayoutManager.onDetachedFromWindow(); isAttachedToWindow = false; removeCallbacks(updateProgressAction); controlViewLayoutManager.removeHideCallbacks(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { return dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event); } /** * Called to process media key events. Any {@link KeyEvent} can be passed but only media key * events will be handled. * * @param event A key event. * @return Whether the key event was handled. */ public boolean dispatchMediaKeyEvent(KeyEvent event) { int keyCode = event.getKeyCode(); @Nullable Player player = this.player; if (player == null || !isHandledMediaKey(keyCode)) { return false; } if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { if (player.getPlaybackState() != Player.STATE_ENDED) { controlDispatcher.dispatchFastForward(player); } } else if (keyCode == KeyEvent.KEYCODE_MEDIA_REWIND) { controlDispatcher.dispatchRewind(player); } else if (event.getRepeatCount() == 0) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_HEADSETHOOK: dispatchPlayPause(player); break; case KeyEvent.KEYCODE_MEDIA_PLAY: dispatchPlay(player); break; case KeyEvent.KEYCODE_MEDIA_PAUSE: dispatchPause(player); break; case KeyEvent.KEYCODE_MEDIA_NEXT: controlDispatcher.dispatchNext(player); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: controlDispatcher.dispatchPrevious(player); break; default: break; } } } return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); controlViewLayoutManager.onLayout(changed, left, top, right, bottom); } private void onLayoutChange( View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int width = right - left; int height = bottom - top; int oldWidth = oldRight - oldLeft; int oldHeight = oldBottom - oldTop; if ((width != oldWidth || height != oldHeight) && settingsWindow.isShowing()) { updateSettingsWindowSize(); int xOffset = getWidth() - settingsWindow.getWidth() - settingsWindowMargin; int yOffset = -settingsWindow.getHeight() - settingsWindowMargin; settingsWindow.update(v, xOffset, yOffset, -1, -1); } } private boolean shouldShowPauseButton() { return player != null && player.getPlaybackState() != Player.STATE_ENDED && player.getPlaybackState() != Player.STATE_IDLE && player.getPlayWhenReady(); } private void dispatchPlayPause(Player player) { @State int state = player.getPlaybackState(); if (state == Player.STATE_IDLE || state == Player.STATE_ENDED || !player.getPlayWhenReady()) { dispatchPlay(player); } else { dispatchPause(player); } } @SuppressWarnings("deprecation") private void dispatchPlay(Player player) { @State int state = player.getPlaybackState(); if (state == Player.STATE_IDLE) { controlDispatcher.dispatchPrepare(player); } else if (state == Player.STATE_ENDED) { seekTo(player, player.getCurrentWindowIndex(), C.TIME_UNSET); } controlDispatcher.dispatchSetPlayWhenReady(player, /* playWhenReady= */ true); } private void dispatchPause(Player player) { controlDispatcher.dispatchSetPlayWhenReady(player, /* playWhenReady= */ false); } @SuppressLint("InlinedApi") private static boolean isHandledMediaKey(int keyCode) { return keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD || keyCode == KeyEvent.KEYCODE_MEDIA_REWIND || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE || keyCode == KeyEvent.KEYCODE_MEDIA_NEXT || keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS; } /** * Returns whether the specified {@code timeline} can be shown on a multi-window time bar. * * @param timeline The {@link Timeline} to check. * @param window A scratch {@link Timeline.Window} instance. * @return Whether the specified timeline can be shown on a multi-window time bar. */ private static boolean canShowMultiWindowTimeBar(Timeline timeline, Timeline.Window window) { if (timeline.getWindowCount() > MAX_WINDOWS_FOR_MULTI_WINDOW_TIME_BAR) { return false; } int windowCount = timeline.getWindowCount(); for (int i = 0; i < windowCount; i++) { if (timeline.getWindow(i, window).durationUs == C.TIME_UNSET) { return false; } } return true; } private static void initializeFullScreenButton(View fullScreenButton, OnClickListener listener) { if (fullScreenButton == null) { return; } fullScreenButton.setVisibility(GONE); fullScreenButton.setOnClickListener(listener); } private static void updateFullScreenButtonVisibility( @Nullable View fullScreenButton, boolean visible) { if (fullScreenButton == null) { return; } if (visible) { fullScreenButton.setVisibility(VISIBLE); } else { fullScreenButton.setVisibility(GONE); } } @SuppressWarnings("ResourceType") private static @RepeatModeUtil.RepeatToggleModes int getRepeatToggleModes( TypedArray a, @RepeatModeUtil.RepeatToggleModes int defaultValue) { return a.getInt(R.styleable.StyledPlayerControlView_repeat_toggle_modes, defaultValue); } private final class ComponentListener implements Player.Listener, TimeBar.OnScrubListener, OnClickListener, PopupWindow.OnDismissListener { @Override public void onEvents(Player player, Events events) { if (events.containsAny(EVENT_PLAYBACK_STATE_CHANGED, EVENT_PLAY_WHEN_READY_CHANGED)) { updatePlayPauseButton(); } if (events.containsAny( EVENT_PLAYBACK_STATE_CHANGED, EVENT_PLAY_WHEN_READY_CHANGED, EVENT_IS_PLAYING_CHANGED)) { updateProgress(); } if (events.contains(EVENT_REPEAT_MODE_CHANGED)) { updateRepeatModeButton(); } if (events.contains(EVENT_SHUFFLE_MODE_ENABLED_CHANGED)) { updateShuffleButton(); } if (events.containsAny( EVENT_REPEAT_MODE_CHANGED, EVENT_SHUFFLE_MODE_ENABLED_CHANGED, EVENT_POSITION_DISCONTINUITY, EVENT_TIMELINE_CHANGED, EVENT_SEEK_BACK_INCREMENT_CHANGED, EVENT_SEEK_FORWARD_INCREMENT_CHANGED, EVENT_AVAILABLE_COMMANDS_CHANGED)) { updateNavigation(); } if (events.containsAny(EVENT_POSITION_DISCONTINUITY, EVENT_TIMELINE_CHANGED)) { updateTimeline(); } if (events.contains(EVENT_PLAYBACK_PARAMETERS_CHANGED)) { updatePlaybackSpeedList(); } if (events.contains(EVENT_TRACKS_CHANGED)) { updateTrackLists(); } } @Override public void onScrubStart(TimeBar timeBar, long position) { scrubbing = true; if (positionView != null) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } controlViewLayoutManager.removeHideCallbacks(); } @Override public void onScrubMove(TimeBar timeBar, long position) { if (positionView != null) { positionView.setText(Util.getStringForTime(formatBuilder, formatter, position)); } } @Override public void onScrubStop(TimeBar timeBar, long position, boolean canceled) { scrubbing = false; if (!canceled && player != null) { seekToTimeBarPosition(player, position); } controlViewLayoutManager.resetHideCallbacks(); } @Override public void onDismiss() { if (needToHideBars) { controlViewLayoutManager.resetHideCallbacks(); } } @Override public void onClick(View view) { @Nullable Player player = StyledPlayerControlView.this.player; if (player == null) { return; } controlViewLayoutManager.resetHideCallbacks(); if (nextButton == view) { controlDispatcher.dispatchNext(player); } else if (previousButton == view) { controlDispatcher.dispatchPrevious(player); } else if (fastForwardButton == view) { if (player.getPlaybackState() != Player.STATE_ENDED) { controlDispatcher.dispatchFastForward(player); } } else if (rewindButton == view) { controlDispatcher.dispatchRewind(player); } else if (playPauseButton == view) { dispatchPlayPause(player); } else if (repeatToggleButton == view) { controlDispatcher.dispatchSetRepeatMode( player, RepeatModeUtil.getNextRepeatMode(player.getRepeatMode(), repeatToggleModes)); } else if (shuffleButton == view) { controlDispatcher.dispatchSetShuffleModeEnabled(player, !player.getShuffleModeEnabled()); } else if (settingsButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(settingsAdapter); } else if (playbackSpeedButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(playbackSpeedAdapter); } else if (audioTrackButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(audioTrackSelectionAdapter); } else if (subtitleButton == view) { controlViewLayoutManager.removeHideCallbacks(); displaySettingsWindow(textTrackSelectionAdapter); } } } private class SettingsAdapter extends RecyclerView.Adapter<SettingViewHolder> { private final String[] mainTexts; private final String[] subTexts; private final Drawable[] iconIds; public SettingsAdapter(String[] mainTexts, Drawable[] iconIds) { this.mainTexts = mainTexts; this.subTexts = new String[mainTexts.length]; this.iconIds = iconIds; } @Override public SettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate(R.layout.exo_styled_settings_list_item, parent, /* attachToRoot= */ false); return new SettingViewHolder(v); } @Override public void onBindViewHolder(SettingViewHolder holder, int position) { holder.mainTextView.setText(mainTexts[position]); if (subTexts[position] == null) { holder.subTextView.setVisibility(GONE); } else { holder.subTextView.setText(subTexts[position]); } if (iconIds[position] == null) { holder.iconView.setVisibility(GONE); } else { holder.iconView.setImageDrawable(iconIds[position]); } } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return mainTexts.length; } public void setSubTextAtPosition(int position, String subText) { this.subTexts[position] = subText; } } private final class SettingViewHolder extends RecyclerView.ViewHolder { private final TextView mainTextView; private final TextView subTextView; private final ImageView iconView; public SettingViewHolder(View itemView) { super(itemView); if (Util.SDK_INT < 26) { // Workaround for https://github.com/google/ExoPlayer/issues/9061. itemView.setFocusable(true); } mainTextView = itemView.findViewById(R.id.exo_main_text); subTextView = itemView.findViewById(R.id.exo_sub_text); iconView = itemView.findViewById(R.id.exo_icon); itemView.setOnClickListener(v -> onSettingViewClicked(getAdapterPosition())); } } private final class PlaybackSpeedAdapter extends RecyclerView.Adapter<SubSettingViewHolder> { private final String[] playbackSpeedTexts; private final int[] playbackSpeedsMultBy100; private int selectedIndex; public PlaybackSpeedAdapter(String[] playbackSpeedTexts, int[] playbackSpeedsMultBy100) { this.playbackSpeedTexts = playbackSpeedTexts; this.playbackSpeedsMultBy100 = playbackSpeedsMultBy100; } public void updateSelectedIndex(float playbackSpeed) { int currentSpeedMultBy100 = Math.round(playbackSpeed * 100); int closestMatchIndex = 0; int closestMatchDifference = Integer.MAX_VALUE; for (int i = 0; i < playbackSpeedsMultBy100.length; i++) { int difference = Math.abs(currentSpeedMultBy100 - playbackSpeedsMultBy100[i]); if (difference < closestMatchDifference) { closestMatchIndex = i; closestMatchDifference = difference; } } selectedIndex = closestMatchIndex; } public String getSelectedText() { return playbackSpeedTexts[selectedIndex]; } @Override public SubSettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate( R.layout.exo_styled_sub_settings_list_item, parent, /* attachToRoot= */ false); return new SubSettingViewHolder(v); } @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { if (position < playbackSpeedTexts.length) { holder.textView.setText(playbackSpeedTexts[position]); } holder.checkView.setVisibility(position == selectedIndex ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (position != selectedIndex) { float speed = playbackSpeedsMultBy100[position] / 100.0f; setPlaybackSpeed(speed); } settingsWindow.dismiss(); }); } @Override public int getItemCount() { return playbackSpeedTexts.length; } } private static final class TrackInformation { private TracksInfo tracksInfo; private int trackGroupIndex; public final TrackGroupInfo trackGroupInfo; public final TrackGroup trackGroup; public final int trackIndex; public final String trackName; public TrackInformation( TracksInfo tracksInfo, int trackGroupIndex, int trackIndex, String trackName) { this.tracksInfo = tracksInfo; this.trackGroupIndex = trackGroupIndex; this.trackGroupInfo = tracksInfo.getTrackGroupInfos().get(trackGroupIndex); this.trackGroup = trackGroupInfo.getTrackGroup(); this.trackIndex = trackIndex; this.trackName = trackName; } public boolean isSelected() { return trackGroupInfo.isTrackSelected(trackIndex); } } private final class TextTrackSelectionAdapter extends TrackSelectionAdapter { @Override public void init(List<TrackInformation> trackInformations) { boolean subtitleIsOn = false; for (int i = 0; i < trackInformations.size(); i++) { if (trackInformations.get(i).isSelected()) { subtitleIsOn = true; break; } } if (subtitleButton != null) { subtitleButton.setImageDrawable( subtitleIsOn ? subtitleOnButtonDrawable : subtitleOffButtonDrawable); subtitleButton.setContentDescription( subtitleIsOn ? subtitleOnContentDescription : subtitleOffContentDescription); } this.tracks = trackInformations; } @Override public void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder) { // CC options include "Off" at the first position, which disables text rendering. holder.textView.setText(R.string.exo_track_selection_none); boolean isTrackSelectionOff = true; for (int i = 0; i < tracks.size(); i++) { if (tracks.get(i).isSelected()) { isTrackSelectionOff = false; break; } } holder.checkView.setVisibility(isTrackSelectionOff ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (player != null) { TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); player.setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setDisabledTrackTypes( new ImmutableSet.Builder<@C.TrackType Integer>() .addAll(trackSelectionParameters.disabledTrackTypes) .add(C.TRACK_TYPE_TEXT) .build()) .build()); settingsWindow.dismiss(); } }); } @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { super.onBindViewHolder(holder, position); if (position > 0) { TrackInformation track = tracks.get(position - 1); holder.checkView.setVisibility(track.isSelected() ? VISIBLE : INVISIBLE); } } @Override public void onTrackSelection(String subtext) { // No-op } } private final class AudioTrackSelectionAdapter extends TrackSelectionAdapter { @Override public void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder) { // Audio track selection option includes "Auto" at the top. holder.textView.setText(R.string.exo_track_selection_auto); // hasSelectionOverride is true means there is an explicit track selection, not "Auto". boolean hasSelectionOverride = false; TrackSelectionParameters parameters = checkNotNull(player).getTrackSelectionParameters(); for (int i = 0; i < tracks.size(); i++) { if (parameters.trackSelectionOverrides.containsKey(tracks.get(i).trackGroup)) { hasSelectionOverride = true; break; } } holder.checkView.setVisibility(hasSelectionOverride ? INVISIBLE : VISIBLE); holder.itemView.setOnClickListener( v -> { if (player == null) { return; } TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); // Remove all audio overrides. ImmutableMap<TrackGroup, TrackSelectionOverride> trackSelectionOverrides = clearTrackSelectionOverridesForType( C.TRACK_TYPE_AUDIO, trackSelectionParameters.trackSelectionOverrides); player.setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setTrackSelectionOverrides(trackSelectionOverrides) .build()); settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_auto)); settingsWindow.dismiss(); }); } @Override public void onTrackSelection(String subtext) { settingsAdapter.setSubTextAtPosition(SETTINGS_AUDIO_TRACK_SELECTION_POSITION, subtext); } @Override public void init(List<TrackInformation> trackInformations) { // Update subtext in settings menu with current audio track selection. boolean hasSelectionOverride = false; for (int i = 0; i < trackInformations.size(); i++) { if (checkNotNull(player) .getTrackSelectionParameters() .trackSelectionOverrides .containsKey(trackInformations.get(i).trackGroup)) { hasSelectionOverride = true; break; } } if (trackInformations.isEmpty()) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_none)); // TODO(insun) : Make the audio item in main settings (settingsAdapater) // to be non-clickable. } else if (!hasSelectionOverride) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, getResources().getString(R.string.exo_track_selection_auto)); } else { for (int i = 0; i < trackInformations.size(); i++) { TrackInformation track = trackInformations.get(i); if (track.isSelected()) { settingsAdapter.setSubTextAtPosition( SETTINGS_AUDIO_TRACK_SELECTION_POSITION, track.trackName); break; } } } this.tracks = trackInformations; } } private abstract class TrackSelectionAdapter extends RecyclerView.Adapter<SubSettingViewHolder> { protected List<TrackInformation> tracks; protected TrackSelectionAdapter() { this.tracks = new ArrayList<>(); } public abstract void init(List<TrackInformation> trackInformations); @Override public SubSettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(getContext()) .inflate( R.layout.exo_styled_sub_settings_list_item, parent, /* attachToRoot= */ false); return new SubSettingViewHolder(v); } protected abstract void onBindViewHolderAtZeroPosition(SubSettingViewHolder holder); protected abstract void onTrackSelection(String subtext); @Override public void onBindViewHolder(SubSettingViewHolder holder, int position) { if (player == null) { return; } if (position == 0) { onBindViewHolderAtZeroPosition(holder); } else { TrackInformation track = tracks.get(position - 1); boolean explicitlySelected = checkNotNull(player) .getTrackSelectionParameters() .trackSelectionOverrides .containsKey(track.trackGroup) && track.isSelected(); holder.textView.setText(track.trackName); holder.checkView.setVisibility(explicitlySelected ? VISIBLE : INVISIBLE); holder.itemView.setOnClickListener( v -> { if (player == null) { return; } TrackSelectionParameters trackSelectionParameters = player.getTrackSelectionParameters(); Map<TrackGroup, TrackSelectionOverride> overrides = forceTrackSelection( trackSelectionParameters.trackSelectionOverrides, track.tracksInfo, track.trackGroupIndex, new TrackSelectionOverride(ImmutableSet.of(track.trackIndex))); checkNotNull(player) .setTrackSelectionParameters( trackSelectionParameters .buildUpon() .setTrackSelectionOverrides(overrides) .build()); onTrackSelection(track.trackName); settingsWindow.dismiss(); }); } } @Override public int getItemCount() { return tracks.isEmpty() ? 0 : tracks.size() + 1; } protected void clear() { tracks = Collections.emptyList(); } } private static class SubSettingViewHolder extends RecyclerView.ViewHolder { public final TextView textView; public final View checkView; public SubSettingViewHolder(View itemView) { super(itemView); if (Util.SDK_INT < 26) { // Workaround for https://github.com/google/ExoPlayer/issues/9061. itemView.setFocusable(true); } textView = itemView.findViewById(R.id.exo_text); checkView = itemView.findViewById(R.id.exo_check); } } }
Refactor `initTrackSelectionAdapter` As suggested in parent change, return a list of `TrackType` instead of appending to it. This has the slight disadvantage of iterating twice over the (short) list, but clarifies the code. PiperOrigin-RevId: 402844458
library/ui/src/main/java/com/google/android/exoplayer2/ui/StyledPlayerControlView.java
Refactor `initTrackSelectionAdapter`
Java
apache-2.0
85a86e434a6aa4be083afe38130818865622d061
0
stari4ek/ExoPlayer,google/ExoPlayer,androidx/media,ened/ExoPlayer,stari4ek/ExoPlayer,amzn/exoplayer-amazon-port,superbderrick/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port,ened/ExoPlayer,stari4ek/ExoPlayer,androidx/media,superbderrick/ExoPlayer,superbderrick/ExoPlayer,google/ExoPlayer,ened/ExoPlayer,amzn/exoplayer-amazon-port,google/ExoPlayer
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.extractor.mp4; import static com.google.android.exoplayer2.util.MimeTypes.getMimeTypeFromMp4ObjectType; import androidx.annotation.Nullable; import android.util.Pair; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.ParserException; import com.google.android.exoplayer2.audio.Ac3Util; import com.google.android.exoplayer2.audio.Ac4Util; import com.google.android.exoplayer2.drm.DrmInitData; import com.google.android.exoplayer2.extractor.GaplessInfoHolder; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.CodecSpecificDataUtil; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.ParsableByteArray; import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.video.AvcConfig; import com.google.android.exoplayer2.video.DolbyVisionConfig; import com.google.android.exoplayer2.video.HevcConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** Utility methods for parsing MP4 format atom payloads according to ISO 14496-12. */ @SuppressWarnings({"ConstantField", "ConstantCaseForConstants"}) /* package */ final class AtomParsers { private static final String TAG = "AtomParsers"; private static final int TYPE_vide = Util.getIntegerCodeForString("vide"); private static final int TYPE_soun = Util.getIntegerCodeForString("soun"); private static final int TYPE_text = Util.getIntegerCodeForString("text"); private static final int TYPE_sbtl = Util.getIntegerCodeForString("sbtl"); private static final int TYPE_subt = Util.getIntegerCodeForString("subt"); private static final int TYPE_clcp = Util.getIntegerCodeForString("clcp"); private static final int TYPE_meta = Util.getIntegerCodeForString("meta"); private static final int TYPE_mdta = Util.getIntegerCodeForString("mdta"); /** * The threshold number of samples to trim from the start/end of an audio track when applying an * edit below which gapless info can be used (rather than removing samples from the sample table). */ private static final int MAX_GAPLESS_TRIM_SIZE_SAMPLES = 4; /** The magic signature for an Opus Identification header, as defined in RFC-7845. */ private static final byte[] opusMagic = Util.getUtf8Bytes("OpusHead"); /** * Parses a trak atom (defined in 14496-12). * * @param trak Atom to decode. * @param mvhd Movie header atom, used to get the timescale. * @param duration The duration in units of the timescale declared in the mvhd atom, or * {@link C#TIME_UNSET} if the duration should be parsed from the tkhd atom. * @param drmInitData {@link DrmInitData} to be included in the format. * @param ignoreEditLists Whether to ignore any edit lists in the trak box. * @param isQuickTime True for QuickTime media. False otherwise. * @return A {@link Track} instance, or {@code null} if the track's type isn't supported. */ public static Track parseTrak(Atom.ContainerAtom trak, Atom.LeafAtom mvhd, long duration, DrmInitData drmInitData, boolean ignoreEditLists, boolean isQuickTime) throws ParserException { Atom.ContainerAtom mdia = trak.getContainerAtomOfType(Atom.TYPE_mdia); int trackType = getTrackTypeForHdlr(parseHdlr(mdia.getLeafAtomOfType(Atom.TYPE_hdlr).data)); if (trackType == C.TRACK_TYPE_UNKNOWN) { return null; } TkhdData tkhdData = parseTkhd(trak.getLeafAtomOfType(Atom.TYPE_tkhd).data); if (duration == C.TIME_UNSET) { duration = tkhdData.duration; } long movieTimescale = parseMvhd(mvhd.data); long durationUs; if (duration == C.TIME_UNSET) { durationUs = C.TIME_UNSET; } else { durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, movieTimescale); } Atom.ContainerAtom stbl = mdia.getContainerAtomOfType(Atom.TYPE_minf) .getContainerAtomOfType(Atom.TYPE_stbl); Pair<Long, String> mdhdData = parseMdhd(mdia.getLeafAtomOfType(Atom.TYPE_mdhd).data); StsdData stsdData = parseStsd(stbl.getLeafAtomOfType(Atom.TYPE_stsd).data, tkhdData.id, tkhdData.rotationDegrees, mdhdData.second, drmInitData, isQuickTime); long[] editListDurations = null; long[] editListMediaTimes = null; if (!ignoreEditLists) { Pair<long[], long[]> edtsData = parseEdts(trak.getContainerAtomOfType(Atom.TYPE_edts)); editListDurations = edtsData.first; editListMediaTimes = edtsData.second; } return stsdData.format == null ? null : new Track(tkhdData.id, trackType, mdhdData.first, movieTimescale, durationUs, stsdData.format, stsdData.requiredSampleTransformation, stsdData.trackEncryptionBoxes, stsdData.nalUnitLengthFieldLength, editListDurations, editListMediaTimes); } /** * Parses an stbl atom (defined in 14496-12). * * @param track Track to which this sample table corresponds. * @param stblAtom stbl (sample table) atom to decode. * @param gaplessInfoHolder Holder to populate with gapless playback information. * @return Sample table described by the stbl atom. * @throws ParserException Thrown if the stbl atom can't be parsed. */ public static TrackSampleTable parseStbl( Track track, Atom.ContainerAtom stblAtom, GaplessInfoHolder gaplessInfoHolder) throws ParserException { SampleSizeBox sampleSizeBox; Atom.LeafAtom stszAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stsz); if (stszAtom != null) { sampleSizeBox = new StszSampleSizeBox(stszAtom); } else { Atom.LeafAtom stz2Atom = stblAtom.getLeafAtomOfType(Atom.TYPE_stz2); if (stz2Atom == null) { throw new ParserException("Track has no sample table size information"); } sampleSizeBox = new Stz2SampleSizeBox(stz2Atom); } int sampleCount = sampleSizeBox.getSampleCount(); if (sampleCount == 0) { return new TrackSampleTable( track, /* offsets= */ new long[0], /* sizes= */ new int[0], /* maximumSize= */ 0, /* timestampsUs= */ new long[0], /* flags= */ new int[0], /* durationUs= */ C.TIME_UNSET); } // Entries are byte offsets of chunks. boolean chunkOffsetsAreLongs = false; Atom.LeafAtom chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stco); if (chunkOffsetsAtom == null) { chunkOffsetsAreLongs = true; chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_co64); } ParsableByteArray chunkOffsets = chunkOffsetsAtom.data; // Entries are (chunk number, number of samples per chunk, sample description index). ParsableByteArray stsc = stblAtom.getLeafAtomOfType(Atom.TYPE_stsc).data; // Entries are (number of samples, timestamp delta between those samples). ParsableByteArray stts = stblAtom.getLeafAtomOfType(Atom.TYPE_stts).data; // Entries are the indices of samples that are synchronization samples. Atom.LeafAtom stssAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stss); ParsableByteArray stss = stssAtom != null ? stssAtom.data : null; // Entries are (number of samples, timestamp offset). Atom.LeafAtom cttsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_ctts); ParsableByteArray ctts = cttsAtom != null ? cttsAtom.data : null; // Prepare to read chunk information. ChunkIterator chunkIterator = new ChunkIterator(stsc, chunkOffsets, chunkOffsetsAreLongs); // Prepare to read sample timestamps. stts.setPosition(Atom.FULL_HEADER_SIZE); int remainingTimestampDeltaChanges = stts.readUnsignedIntToInt() - 1; int remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); int timestampDeltaInTimeUnits = stts.readUnsignedIntToInt(); // Prepare to read sample timestamp offsets, if ctts is present. int remainingSamplesAtTimestampOffset = 0; int remainingTimestampOffsetChanges = 0; int timestampOffset = 0; if (ctts != null) { ctts.setPosition(Atom.FULL_HEADER_SIZE); remainingTimestampOffsetChanges = ctts.readUnsignedIntToInt(); } int nextSynchronizationSampleIndex = C.INDEX_UNSET; int remainingSynchronizationSamples = 0; if (stss != null) { stss.setPosition(Atom.FULL_HEADER_SIZE); remainingSynchronizationSamples = stss.readUnsignedIntToInt(); if (remainingSynchronizationSamples > 0) { nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } else { // Ignore empty stss boxes, which causes all samples to be treated as sync samples. stss = null; } } // Fixed sample size raw audio may need to be rechunked. boolean isFixedSampleSizeRawAudio = sampleSizeBox.isFixedSampleSize() && MimeTypes.AUDIO_RAW.equals(track.format.sampleMimeType) && remainingTimestampDeltaChanges == 0 && remainingTimestampOffsetChanges == 0 && remainingSynchronizationSamples == 0; long[] offsets; int[] sizes; int maximumSize = 0; long[] timestamps; int[] flags; long timestampTimeUnits = 0; long duration; if (!isFixedSampleSizeRawAudio) { offsets = new long[sampleCount]; sizes = new int[sampleCount]; timestamps = new long[sampleCount]; flags = new int[sampleCount]; long offset = 0; int remainingSamplesInChunk = 0; for (int i = 0; i < sampleCount; i++) { // Advance to the next chunk if necessary. boolean chunkDataComplete = true; while (remainingSamplesInChunk == 0 && (chunkDataComplete = chunkIterator.moveNext())) { offset = chunkIterator.offset; remainingSamplesInChunk = chunkIterator.numSamples; } if (!chunkDataComplete) { Log.w(TAG, "Unexpected end of chunk data"); sampleCount = i; offsets = Arrays.copyOf(offsets, sampleCount); sizes = Arrays.copyOf(sizes, sampleCount); timestamps = Arrays.copyOf(timestamps, sampleCount); flags = Arrays.copyOf(flags, sampleCount); break; } // Add on the timestamp offset if ctts is present. if (ctts != null) { while (remainingSamplesAtTimestampOffset == 0 && remainingTimestampOffsetChanges > 0) { remainingSamplesAtTimestampOffset = ctts.readUnsignedIntToInt(); // The BMFF spec (ISO 14496-12) states that sample offsets should be unsigned integers // in version 0 ctts boxes, however some streams violate the spec and use signed // integers instead. It's safe to always decode sample offsets as signed integers here, // because unsigned integers will still be parsed correctly (unless their top bit is // set, which is never true in practice because sample offsets are always small). timestampOffset = ctts.readInt(); remainingTimestampOffsetChanges--; } remainingSamplesAtTimestampOffset--; } offsets[i] = offset; sizes[i] = sampleSizeBox.readNextSampleSize(); if (sizes[i] > maximumSize) { maximumSize = sizes[i]; } timestamps[i] = timestampTimeUnits + timestampOffset; // All samples are synchronization samples if the stss is not present. flags[i] = stss == null ? C.BUFFER_FLAG_KEY_FRAME : 0; if (i == nextSynchronizationSampleIndex) { flags[i] = C.BUFFER_FLAG_KEY_FRAME; remainingSynchronizationSamples--; if (remainingSynchronizationSamples > 0) { nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } } // Add on the duration of this sample. timestampTimeUnits += timestampDeltaInTimeUnits; remainingSamplesAtTimestampDelta--; if (remainingSamplesAtTimestampDelta == 0 && remainingTimestampDeltaChanges > 0) { remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); // The BMFF spec (ISO 14496-12) states that sample deltas should be unsigned integers // in stts boxes, however some streams violate the spec and use signed integers instead. // See https://github.com/google/ExoPlayer/issues/3384. It's safe to always decode sample // deltas as signed integers here, because unsigned integers will still be parsed // correctly (unless their top bit is set, which is never true in practice because sample // deltas are always small). timestampDeltaInTimeUnits = stts.readInt(); remainingTimestampDeltaChanges--; } offset += sizes[i]; remainingSamplesInChunk--; } duration = timestampTimeUnits + timestampOffset; // If the stbl's child boxes are not consistent the container is malformed, but the stream may // still be playable. boolean isCttsValid = true; while (remainingTimestampOffsetChanges > 0) { if (ctts.readUnsignedIntToInt() != 0) { isCttsValid = false; break; } ctts.readInt(); // Ignore offset. remainingTimestampOffsetChanges--; } if (remainingSynchronizationSamples != 0 || remainingSamplesAtTimestampDelta != 0 || remainingSamplesInChunk != 0 || remainingTimestampDeltaChanges != 0 || remainingSamplesAtTimestampOffset != 0 || !isCttsValid) { Log.w( TAG, "Inconsistent stbl box for track " + track.id + ": remainingSynchronizationSamples " + remainingSynchronizationSamples + ", remainingSamplesAtTimestampDelta " + remainingSamplesAtTimestampDelta + ", remainingSamplesInChunk " + remainingSamplesInChunk + ", remainingTimestampDeltaChanges " + remainingTimestampDeltaChanges + ", remainingSamplesAtTimestampOffset " + remainingSamplesAtTimestampOffset + (!isCttsValid ? ", ctts invalid" : "")); } } else { long[] chunkOffsetsBytes = new long[chunkIterator.length]; int[] chunkSampleCounts = new int[chunkIterator.length]; while (chunkIterator.moveNext()) { chunkOffsetsBytes[chunkIterator.index] = chunkIterator.offset; chunkSampleCounts[chunkIterator.index] = chunkIterator.numSamples; } int fixedSampleSize = Util.getPcmFrameSize(track.format.pcmEncoding, track.format.channelCount); FixedSampleSizeRechunker.Results rechunkedResults = FixedSampleSizeRechunker.rechunk( fixedSampleSize, chunkOffsetsBytes, chunkSampleCounts, timestampDeltaInTimeUnits); offsets = rechunkedResults.offsets; sizes = rechunkedResults.sizes; maximumSize = rechunkedResults.maximumSize; timestamps = rechunkedResults.timestamps; flags = rechunkedResults.flags; duration = rechunkedResults.duration; } long durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, track.timescale); if (track.editListDurations == null || gaplessInfoHolder.hasGaplessInfo()) { // There is no edit list, or we are ignoring it as we already have gapless metadata to apply. // This implementation does not support applying both gapless metadata and an edit list. Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, durationUs); } // See the BMFF spec (ISO 14496-12) subsection 8.6.6. Edit lists that require prerolling from a // sync sample after reordering are not supported. Partial audio sample truncation is only // supported in edit lists with one edit that removes less than MAX_GAPLESS_TRIM_SIZE_SAMPLES // samples from the start/end of the track. This implementation handles simple // discarding/delaying of samples. The extractor may place further restrictions on what edited // streams are playable. if (track.editListDurations.length == 1 && track.type == C.TRACK_TYPE_AUDIO && timestamps.length >= 2) { long editStartTime = track.editListMediaTimes[0]; long editEndTime = editStartTime + Util.scaleLargeTimestamp(track.editListDurations[0], track.timescale, track.movieTimescale); if (canApplyEditWithGaplessInfo(timestamps, duration, editStartTime, editEndTime)) { long paddingTimeUnits = duration - editEndTime; long encoderDelay = Util.scaleLargeTimestamp(editStartTime - timestamps[0], track.format.sampleRate, track.timescale); long encoderPadding = Util.scaleLargeTimestamp(paddingTimeUnits, track.format.sampleRate, track.timescale); if ((encoderDelay != 0 || encoderPadding != 0) && encoderDelay <= Integer.MAX_VALUE && encoderPadding <= Integer.MAX_VALUE) { gaplessInfoHolder.encoderDelay = (int) encoderDelay; gaplessInfoHolder.encoderPadding = (int) encoderPadding; Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale); long editedDurationUs = Util.scaleLargeTimestamp( track.editListDurations[0], C.MICROS_PER_SECOND, track.movieTimescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, editedDurationUs); } } } if (track.editListDurations.length == 1 && track.editListDurations[0] == 0) { // The current version of the spec leaves handling of an edit with zero segment_duration in // unfragmented files open to interpretation. We handle this as a special case and include all // samples in the edit. long editStartTime = track.editListMediaTimes[0]; for (int i = 0; i < timestamps.length; i++) { timestamps[i] = Util.scaleLargeTimestamp( timestamps[i] - editStartTime, C.MICROS_PER_SECOND, track.timescale); } durationUs = Util.scaleLargeTimestamp(duration - editStartTime, C.MICROS_PER_SECOND, track.timescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, durationUs); } // Omit any sample at the end point of an edit for audio tracks. boolean omitClippedSample = track.type == C.TRACK_TYPE_AUDIO; // Count the number of samples after applying edits. int editedSampleCount = 0; int nextSampleIndex = 0; boolean copyMetadata = false; int[] startIndices = new int[track.editListDurations.length]; int[] endIndices = new int[track.editListDurations.length]; for (int i = 0; i < track.editListDurations.length; i++) { long editMediaTime = track.editListMediaTimes[i]; if (editMediaTime != -1) { long editDuration = Util.scaleLargeTimestamp( track.editListDurations[i], track.timescale, track.movieTimescale); startIndices[i] = Util.binarySearchCeil(timestamps, editMediaTime, true, true); endIndices[i] = Util.binarySearchCeil( timestamps, editMediaTime + editDuration, omitClippedSample, false); while (startIndices[i] < endIndices[i] && (flags[startIndices[i]] & C.BUFFER_FLAG_KEY_FRAME) == 0) { // Applying the edit correctly would require prerolling from the previous sync sample. In // the current implementation we advance to the next sync sample instead. Only other // tracks (i.e. audio) will be rendered until the time of the first sync sample. // See https://github.com/google/ExoPlayer/issues/1659. startIndices[i]++; } editedSampleCount += endIndices[i] - startIndices[i]; copyMetadata |= nextSampleIndex != startIndices[i]; nextSampleIndex = endIndices[i]; } } copyMetadata |= editedSampleCount != sampleCount; // Calculate edited sample timestamps and update the corresponding metadata arrays. long[] editedOffsets = copyMetadata ? new long[editedSampleCount] : offsets; int[] editedSizes = copyMetadata ? new int[editedSampleCount] : sizes; int editedMaximumSize = copyMetadata ? 0 : maximumSize; int[] editedFlags = copyMetadata ? new int[editedSampleCount] : flags; long[] editedTimestamps = new long[editedSampleCount]; long pts = 0; int sampleIndex = 0; for (int i = 0; i < track.editListDurations.length; i++) { long editMediaTime = track.editListMediaTimes[i]; int startIndex = startIndices[i]; int endIndex = endIndices[i]; if (copyMetadata) { int count = endIndex - startIndex; System.arraycopy(offsets, startIndex, editedOffsets, sampleIndex, count); System.arraycopy(sizes, startIndex, editedSizes, sampleIndex, count); System.arraycopy(flags, startIndex, editedFlags, sampleIndex, count); } for (int j = startIndex; j < endIndex; j++) { long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale); long timeInSegmentUs = Util.scaleLargeTimestamp( timestamps[j] - editMediaTime, C.MICROS_PER_SECOND, track.timescale); editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs; if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) { editedMaximumSize = sizes[j]; } sampleIndex++; } pts += track.editListDurations[i]; } long editedDurationUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale); return new TrackSampleTable( track, editedOffsets, editedSizes, editedMaximumSize, editedTimestamps, editedFlags, editedDurationUs); } /** * Parses a udta atom. * * @param udtaAtom The udta (user data) atom to decode. * @param isQuickTime True for QuickTime media. False otherwise. * @return Parsed metadata, or null. */ @Nullable public static Metadata parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) { if (isQuickTime) { // Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and // decode one. return null; } ParsableByteArray udtaData = udtaAtom.data; udtaData.setPosition(Atom.HEADER_SIZE); while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) { int atomPosition = udtaData.getPosition(); int atomSize = udtaData.readInt(); int atomType = udtaData.readInt(); if (atomType == Atom.TYPE_meta) { udtaData.setPosition(atomPosition); return parseUdtaMeta(udtaData, atomPosition + atomSize); } udtaData.setPosition(atomPosition + atomSize); } return null; } /** * Parses a metadata meta atom if it contains metadata with handler 'mdta'. * * @param meta The metadata atom to decode. * @return Parsed metadata, or null. */ @Nullable public static Metadata parseMdtaFromMeta(Atom.ContainerAtom meta) { Atom.LeafAtom hdlrAtom = meta.getLeafAtomOfType(Atom.TYPE_hdlr); Atom.LeafAtom keysAtom = meta.getLeafAtomOfType(Atom.TYPE_keys); Atom.LeafAtom ilstAtom = meta.getLeafAtomOfType(Atom.TYPE_ilst); if (hdlrAtom == null || keysAtom == null || ilstAtom == null || AtomParsers.parseHdlr(hdlrAtom.data) != TYPE_mdta) { // There isn't enough information to parse the metadata, or the handler type is unexpected. return null; } // Parse metadata keys. ParsableByteArray keys = keysAtom.data; keys.setPosition(Atom.FULL_HEADER_SIZE); int entryCount = keys.readInt(); String[] keyNames = new String[entryCount]; for (int i = 0; i < entryCount; i++) { int entrySize = keys.readInt(); keys.skipBytes(4); // keyNamespace int keySize = entrySize - 8; keyNames[i] = keys.readString(keySize); } // Parse metadata items. ParsableByteArray ilst = ilstAtom.data; ilst.setPosition(Atom.HEADER_SIZE); ArrayList<Metadata.Entry> entries = new ArrayList<>(); while (ilst.bytesLeft() > Atom.HEADER_SIZE) { int atomPosition = ilst.getPosition(); int atomSize = ilst.readInt(); int keyIndex = ilst.readInt() - 1; if (keyIndex >= 0 && keyIndex < keyNames.length) { String key = keyNames[keyIndex]; Metadata.Entry entry = MetadataUtil.parseMdtaMetadataEntryFromIlst(ilst, atomPosition + atomSize, key); if (entry != null) { entries.add(entry); } } else { Log.w(TAG, "Skipped metadata with unknown key index: " + keyIndex); } ilst.setPosition(atomPosition + atomSize); } return entries.isEmpty() ? null : new Metadata(entries); } @Nullable private static Metadata parseUdtaMeta(ParsableByteArray meta, int limit) { meta.skipBytes(Atom.FULL_HEADER_SIZE); while (meta.getPosition() < limit) { int atomPosition = meta.getPosition(); int atomSize = meta.readInt(); int atomType = meta.readInt(); if (atomType == Atom.TYPE_ilst) { meta.setPosition(atomPosition); return parseIlst(meta, atomPosition + atomSize); } meta.setPosition(atomPosition + atomSize); } return null; } @Nullable private static Metadata parseIlst(ParsableByteArray ilst, int limit) { ilst.skipBytes(Atom.HEADER_SIZE); ArrayList<Metadata.Entry> entries = new ArrayList<>(); while (ilst.getPosition() < limit) { Metadata.Entry entry = MetadataUtil.parseIlstElement(ilst); if (entry != null) { entries.add(entry); } } return entries.isEmpty() ? null : new Metadata(entries); } /** * Parses a mvhd atom (defined in 14496-12), returning the timescale for the movie. * * @param mvhd Contents of the mvhd atom to be parsed. * @return Timescale for the movie. */ private static long parseMvhd(ParsableByteArray mvhd) { mvhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mvhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mvhd.skipBytes(version == 0 ? 8 : 16); return mvhd.readUnsignedInt(); } /** * Parses a tkhd atom (defined in 14496-12). * * @return An object containing the parsed data. */ private static TkhdData parseTkhd(ParsableByteArray tkhd) { tkhd.setPosition(Atom.HEADER_SIZE); int fullAtom = tkhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); tkhd.skipBytes(version == 0 ? 8 : 16); int trackId = tkhd.readInt(); tkhd.skipBytes(4); boolean durationUnknown = true; int durationPosition = tkhd.getPosition(); int durationByteCount = version == 0 ? 4 : 8; for (int i = 0; i < durationByteCount; i++) { if (tkhd.data[durationPosition + i] != -1) { durationUnknown = false; break; } } long duration; if (durationUnknown) { tkhd.skipBytes(durationByteCount); duration = C.TIME_UNSET; } else { duration = version == 0 ? tkhd.readUnsignedInt() : tkhd.readUnsignedLongToLong(); if (duration == 0) { // 0 duration normally indicates that the file is fully fragmented (i.e. all of the media // samples are in fragments). Treat as unknown. duration = C.TIME_UNSET; } } tkhd.skipBytes(16); int a00 = tkhd.readInt(); int a01 = tkhd.readInt(); tkhd.skipBytes(4); int a10 = tkhd.readInt(); int a11 = tkhd.readInt(); int rotationDegrees; int fixedOne = 65536; if (a00 == 0 && a01 == fixedOne && a10 == -fixedOne && a11 == 0) { rotationDegrees = 90; } else if (a00 == 0 && a01 == -fixedOne && a10 == fixedOne && a11 == 0) { rotationDegrees = 270; } else if (a00 == -fixedOne && a01 == 0 && a10 == 0 && a11 == -fixedOne) { rotationDegrees = 180; } else { // Only 0, 90, 180 and 270 are supported. Treat anything else as 0. rotationDegrees = 0; } return new TkhdData(trackId, duration, rotationDegrees); } /** * Parses an hdlr atom. * * @param hdlr The hdlr atom to decode. * @return The handler value. */ private static int parseHdlr(ParsableByteArray hdlr) { hdlr.setPosition(Atom.FULL_HEADER_SIZE + 4); return hdlr.readInt(); } /** Returns the track type for a given handler value. */ private static int getTrackTypeForHdlr(int hdlr) { if (hdlr == TYPE_soun) { return C.TRACK_TYPE_AUDIO; } else if (hdlr == TYPE_vide) { return C.TRACK_TYPE_VIDEO; } else if (hdlr == TYPE_text || hdlr == TYPE_sbtl || hdlr == TYPE_subt || hdlr == TYPE_clcp) { return C.TRACK_TYPE_TEXT; } else if (hdlr == TYPE_meta) { return C.TRACK_TYPE_METADATA; } else { return C.TRACK_TYPE_UNKNOWN; } } /** * Parses an mdhd atom (defined in 14496-12). * * @param mdhd The mdhd atom to decode. * @return A pair consisting of the media timescale defined as the number of time units that pass * in one second, and the language code. */ private static Pair<Long, String> parseMdhd(ParsableByteArray mdhd) { mdhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mdhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mdhd.skipBytes(version == 0 ? 8 : 16); long timescale = mdhd.readUnsignedInt(); mdhd.skipBytes(version == 0 ? 4 : 8); int languageCode = mdhd.readUnsignedShort(); String language = "" + (char) (((languageCode >> 10) & 0x1F) + 0x60) + (char) (((languageCode >> 5) & 0x1F) + 0x60) + (char) ((languageCode & 0x1F) + 0x60); return Pair.create(timescale, language); } /** * Parses a stsd atom (defined in 14496-12). * * @param stsd The stsd atom to decode. * @param trackId The track's identifier in its container. * @param rotationDegrees The rotation of the track in degrees. * @param language The language of the track. * @param drmInitData {@link DrmInitData} to be included in the format. * @param isQuickTime True for QuickTime media. False otherwise. * @return An object containing the parsed data. */ private static StsdData parseStsd(ParsableByteArray stsd, int trackId, int rotationDegrees, String language, DrmInitData drmInitData, boolean isQuickTime) throws ParserException { stsd.setPosition(Atom.FULL_HEADER_SIZE); int numberOfEntries = stsd.readInt(); StsdData out = new StsdData(numberOfEntries); for (int i = 0; i < numberOfEntries; i++) { int childStartPosition = stsd.getPosition(); int childAtomSize = stsd.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = stsd.readInt(); if (childAtomType == Atom.TYPE_avc1 || childAtomType == Atom.TYPE_avc3 || childAtomType == Atom.TYPE_encv || childAtomType == Atom.TYPE_mp4v || childAtomType == Atom.TYPE_hvc1 || childAtomType == Atom.TYPE_hev1 || childAtomType == Atom.TYPE_s263 || childAtomType == Atom.TYPE_vp08 || childAtomType == Atom.TYPE_vp09 || childAtomType == Atom.TYPE_av01 || childAtomType == Atom.TYPE_dvav || childAtomType == Atom.TYPE_dva1 || childAtomType == Atom.TYPE_dvhe || childAtomType == Atom.TYPE_dvh1) { parseVideoSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, rotationDegrees, drmInitData, out, i); } else if (childAtomType == Atom.TYPE_mp4a || childAtomType == Atom.TYPE_enca || childAtomType == Atom.TYPE_ac_3 || childAtomType == Atom.TYPE_ec_3 || childAtomType == Atom.TYPE_ac_4 || childAtomType == Atom.TYPE_dtsc || childAtomType == Atom.TYPE_dtse || childAtomType == Atom.TYPE_dtsh || childAtomType == Atom.TYPE_dtsl || childAtomType == Atom.TYPE_samr || childAtomType == Atom.TYPE_sawb || childAtomType == Atom.TYPE_lpcm || childAtomType == Atom.TYPE_sowt || childAtomType == Atom.TYPE__mp3 || childAtomType == Atom.TYPE_alac || childAtomType == Atom.TYPE_alaw || childAtomType == Atom.TYPE_ulaw || childAtomType == Atom.TYPE_Opus || childAtomType == Atom.TYPE_fLaC) { parseAudioSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, language, isQuickTime, drmInitData, out, i); } else if (childAtomType == Atom.TYPE_TTML || childAtomType == Atom.TYPE_tx3g || childAtomType == Atom.TYPE_wvtt || childAtomType == Atom.TYPE_stpp || childAtomType == Atom.TYPE_c608) { parseTextSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, language, out); } else if (childAtomType == Atom.TYPE_camm) { out.format = Format.createSampleFormat(Integer.toString(trackId), MimeTypes.APPLICATION_CAMERA_MOTION, null, Format.NO_VALUE, null); } stsd.setPosition(childStartPosition + childAtomSize); } return out; } private static void parseTextSampleEntry(ParsableByteArray parent, int atomType, int position, int atomSize, int trackId, String language, StsdData out) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); // Default values. List<byte[]> initializationData = null; long subsampleOffsetUs = Format.OFFSET_SAMPLE_RELATIVE; String mimeType; if (atomType == Atom.TYPE_TTML) { mimeType = MimeTypes.APPLICATION_TTML; } else if (atomType == Atom.TYPE_tx3g) { mimeType = MimeTypes.APPLICATION_TX3G; int sampleDescriptionLength = atomSize - Atom.HEADER_SIZE - 8; byte[] sampleDescriptionData = new byte[sampleDescriptionLength]; parent.readBytes(sampleDescriptionData, 0, sampleDescriptionLength); initializationData = Collections.singletonList(sampleDescriptionData); } else if (atomType == Atom.TYPE_wvtt) { mimeType = MimeTypes.APPLICATION_MP4VTT; } else if (atomType == Atom.TYPE_stpp) { mimeType = MimeTypes.APPLICATION_TTML; subsampleOffsetUs = 0; // Subsample timing is absolute. } else if (atomType == Atom.TYPE_c608) { // Defined by the QuickTime File Format specification. mimeType = MimeTypes.APPLICATION_MP4CEA608; out.requiredSampleTransformation = Track.TRANSFORMATION_CEA608_CDAT; } else { // Never happens. throw new IllegalStateException(); } out.format = Format.createTextSampleFormat( Integer.toString(trackId), mimeType, /* codecs= */ null, /* bitrate= */ Format.NO_VALUE, /* selectionFlags= */ 0, language, /* accessibilityChannel= */ Format.NO_VALUE, /* drmInitData= */ null, subsampleOffsetUs, initializationData); } private static void parseVideoSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, int rotationDegrees, DrmInitData drmInitData, StsdData out, int entryIndex) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); parent.skipBytes(16); int width = parent.readUnsignedShort(); int height = parent.readUnsignedShort(); boolean pixelWidthHeightRatioFromPasp = false; float pixelWidthHeightRatio = 1; parent.skipBytes(50); int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_encv) { Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData = parseSampleEntryEncryptionData( parent, position, size); if (sampleEntryEncryptionData != null) { atomType = sampleEntryEncryptionData.first; drmInitData = drmInitData == null ? null : drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType); out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second; } parent.setPosition(childPosition); } // TODO: Uncomment when [Internal: b/63092960] is fixed. // else { // drmInitData = null; // } List<byte[]> initializationData = null; String mimeType = null; String codecs = null; byte[] projectionData = null; @C.StereoMode int stereoMode = Format.NO_VALUE; while (childPosition - position < size) { parent.setPosition(childPosition); int childStartPosition = parent.getPosition(); int childAtomSize = parent.readInt(); if (childAtomSize == 0 && parent.getPosition() - position == size) { // Handle optional terminating four zero bytes in MOV files. break; } Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_avcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H264; parent.setPosition(childStartPosition + Atom.HEADER_SIZE); AvcConfig avcConfig = AvcConfig.parse(parent); initializationData = avcConfig.initializationData; out.nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength; if (!pixelWidthHeightRatioFromPasp) { pixelWidthHeightRatio = avcConfig.pixelWidthAspectRatio; } } else if (childAtomType == Atom.TYPE_hvcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H265; parent.setPosition(childStartPosition + Atom.HEADER_SIZE); HevcConfig hevcConfig = HevcConfig.parse(parent); initializationData = hevcConfig.initializationData; out.nalUnitLengthFieldLength = hevcConfig.nalUnitLengthFieldLength; } else if (childAtomType == Atom.TYPE_dvcC || childAtomType == Atom.TYPE_dvvC) { DolbyVisionConfig dolbyVisionConfig = DolbyVisionConfig.parse(parent); // TODO: Support profiles 4, 8 and 9 once we have a way to fall back to AVC/HEVC decoding. if (dolbyVisionConfig != null && dolbyVisionConfig.profile == 5) { codecs = dolbyVisionConfig.codecs; mimeType = MimeTypes.VIDEO_DOLBY_VISION; } } else if (childAtomType == Atom.TYPE_vpcC) { Assertions.checkState(mimeType == null); mimeType = (atomType == Atom.TYPE_vp08) ? MimeTypes.VIDEO_VP8 : MimeTypes.VIDEO_VP9; } else if (childAtomType == Atom.TYPE_av1C) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_AV1; } else if (childAtomType == Atom.TYPE_d263) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H263; } else if (childAtomType == Atom.TYPE_esds) { Assertions.checkState(mimeType == null); Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, childStartPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = Collections.singletonList(mimeTypeAndInitializationData.second); } else if (childAtomType == Atom.TYPE_pasp) { pixelWidthHeightRatio = parsePaspFromParent(parent, childStartPosition); pixelWidthHeightRatioFromPasp = true; } else if (childAtomType == Atom.TYPE_sv3d) { projectionData = parseProjFromParent(parent, childStartPosition, childAtomSize); } else if (childAtomType == Atom.TYPE_st3d) { int version = parent.readUnsignedByte(); parent.skipBytes(3); // Flags. if (version == 0) { int layout = parent.readUnsignedByte(); switch (layout) { case 0: stereoMode = C.STEREO_MODE_MONO; break; case 1: stereoMode = C.STEREO_MODE_TOP_BOTTOM; break; case 2: stereoMode = C.STEREO_MODE_LEFT_RIGHT; break; case 3: stereoMode = C.STEREO_MODE_STEREO_MESH; break; default: break; } } } childPosition += childAtomSize; } // If the media type was not recognized, ignore the track. if (mimeType == null) { return; } out.format = Format.createVideoSampleFormat( Integer.toString(trackId), mimeType, codecs, /* bitrate= */ Format.NO_VALUE, /* maxInputSize= */ Format.NO_VALUE, width, height, /* frameRate= */ Format.NO_VALUE, initializationData, rotationDegrees, pixelWidthHeightRatio, projectionData, stereoMode, /* colorInfo= */ null, drmInitData); } /** * Parses the edts atom (defined in 14496-12 subsection 8.6.5). * * @param edtsAtom edts (edit box) atom to decode. * @return Pair of edit list durations and edit list media times, or a pair of nulls if they are * not present. */ private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) { Atom.LeafAtom elst; if (edtsAtom == null || (elst = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst)) == null) { return Pair.create(null, null); } ParsableByteArray elstData = elst.data; elstData.setPosition(Atom.HEADER_SIZE); int fullAtom = elstData.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); int entryCount = elstData.readUnsignedIntToInt(); long[] editListDurations = new long[entryCount]; long[] editListMediaTimes = new long[entryCount]; for (int i = 0; i < entryCount; i++) { editListDurations[i] = version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt(); editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt(); int mediaRateInteger = elstData.readShort(); if (mediaRateInteger != 1) { // The extractor does not handle dwell edits (mediaRateInteger == 0). throw new IllegalArgumentException("Unsupported media rate."); } elstData.skipBytes(2); } return Pair.create(editListDurations, editListMediaTimes); } private static float parsePaspFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE); int hSpacing = parent.readUnsignedIntToInt(); int vSpacing = parent.readUnsignedIntToInt(); return (float) hSpacing / vSpacing; } private static void parseAudioSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, String language, boolean isQuickTime, DrmInitData drmInitData, StsdData out, int entryIndex) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); int quickTimeSoundDescriptionVersion = 0; if (isQuickTime) { quickTimeSoundDescriptionVersion = parent.readUnsignedShort(); parent.skipBytes(6); } else { parent.skipBytes(8); } int channelCount; int sampleRate; if (quickTimeSoundDescriptionVersion == 0 || quickTimeSoundDescriptionVersion == 1) { channelCount = parent.readUnsignedShort(); parent.skipBytes(6); // sampleSize, compressionId, packetSize. sampleRate = parent.readUnsignedFixedPoint1616(); if (quickTimeSoundDescriptionVersion == 1) { parent.skipBytes(16); } } else if (quickTimeSoundDescriptionVersion == 2) { parent.skipBytes(16); // always[3,16,Minus2,0,65536], sizeOfStructOnly sampleRate = (int) Math.round(parent.readDouble()); channelCount = parent.readUnsignedIntToInt(); // Skip always7F000000, sampleSize, formatSpecificFlags, constBytesPerAudioPacket, // constLPCMFramesPerAudioPacket. parent.skipBytes(20); } else { // Unsupported version. return; } int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_enca) { Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData = parseSampleEntryEncryptionData( parent, position, size); if (sampleEntryEncryptionData != null) { atomType = sampleEntryEncryptionData.first; drmInitData = drmInitData == null ? null : drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType); out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second; } parent.setPosition(childPosition); } // TODO: Uncomment when [Internal: b/63092960] is fixed. // else { // drmInitData = null; // } // If the atom type determines a MIME type, set it immediately. String mimeType = null; if (atomType == Atom.TYPE_ac_3) { mimeType = MimeTypes.AUDIO_AC3; } else if (atomType == Atom.TYPE_ec_3) { mimeType = MimeTypes.AUDIO_E_AC3; } else if (atomType == Atom.TYPE_ac_4) { mimeType = MimeTypes.AUDIO_AC4; } else if (atomType == Atom.TYPE_dtsc) { mimeType = MimeTypes.AUDIO_DTS; } else if (atomType == Atom.TYPE_dtsh || atomType == Atom.TYPE_dtsl) { mimeType = MimeTypes.AUDIO_DTS_HD; } else if (atomType == Atom.TYPE_dtse) { mimeType = MimeTypes.AUDIO_DTS_EXPRESS; } else if (atomType == Atom.TYPE_samr) { mimeType = MimeTypes.AUDIO_AMR_NB; } else if (atomType == Atom.TYPE_sawb) { mimeType = MimeTypes.AUDIO_AMR_WB; } else if (atomType == Atom.TYPE_lpcm || atomType == Atom.TYPE_sowt) { mimeType = MimeTypes.AUDIO_RAW; } else if (atomType == Atom.TYPE__mp3) { mimeType = MimeTypes.AUDIO_MPEG; } else if (atomType == Atom.TYPE_alac) { mimeType = MimeTypes.AUDIO_ALAC; } else if (atomType == Atom.TYPE_alaw) { mimeType = MimeTypes.AUDIO_ALAW; } else if (atomType == Atom.TYPE_ulaw) { mimeType = MimeTypes.AUDIO_MLAW; } else if (atomType == Atom.TYPE_Opus) { mimeType = MimeTypes.AUDIO_OPUS; } else if (atomType == Atom.TYPE_fLaC) { mimeType = MimeTypes.AUDIO_FLAC; } byte[] initializationData = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_esds || (isQuickTime && childAtomType == Atom.TYPE_wave)) { int esdsAtomPosition = childAtomType == Atom.TYPE_esds ? childPosition : findEsdsPosition(parent, childPosition, childAtomSize); if (esdsAtomPosition != C.POSITION_UNSET) { Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, esdsAtomPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = mimeTypeAndInitializationData.second; if (MimeTypes.AUDIO_AAC.equals(mimeType)) { // TODO: Do we really need to do this? See [Internal: b/10903778] // Update sampleRate and channelCount from the AudioSpecificConfig initialization data. Pair<Integer, Integer> audioSpecificConfig = CodecSpecificDataUtil.parseAacAudioSpecificConfig(initializationData); sampleRate = audioSpecificConfig.first; channelCount = audioSpecificConfig.second; } } } else if (childAtomType == Atom.TYPE_dac3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac3Util.parseAc3AnnexFFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_dec3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac3Util.parseEAc3AnnexFFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_dac4) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac4Util.parseAc4AnnexEFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_ddts) { out.format = Format.createAudioSampleFormat(Integer.toString(trackId), mimeType, null, Format.NO_VALUE, Format.NO_VALUE, channelCount, sampleRate, null, drmInitData, 0, language); } else if (childAtomType == Atom.TYPE_alac) { initializationData = new byte[childAtomSize]; parent.setPosition(childPosition); parent.readBytes(initializationData, /* offset= */ 0, childAtomSize); } else if (childAtomType == Atom.TYPE_dOps) { // Build an Opus Identification Header (defined in RFC-7845) by concatenating the Opus Magic // Signature and the body of the dOps atom. int childAtomBodySize = childAtomSize - Atom.HEADER_SIZE; initializationData = new byte[opusMagic.length + childAtomBodySize]; System.arraycopy(opusMagic, 0, initializationData, 0, opusMagic.length); parent.setPosition(childPosition + Atom.HEADER_SIZE); parent.readBytes(initializationData, opusMagic.length, childAtomBodySize); } else if (childAtomSize == Atom.TYPE_dfLa) { int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE; initializationData = new byte[childAtomBodySize]; parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE); parent.readBytes(initializationData, /* offset= */ 0, childAtomBodySize); } childPosition += childAtomSize; } if (out.format == null && mimeType != null) { // TODO: Determine the correct PCM encoding. @C.PcmEncoding int pcmEncoding = MimeTypes.AUDIO_RAW.equals(mimeType) ? C.ENCODING_PCM_16BIT : Format.NO_VALUE; out.format = Format.createAudioSampleFormat(Integer.toString(trackId), mimeType, null, Format.NO_VALUE, Format.NO_VALUE, channelCount, sampleRate, pcmEncoding, initializationData == null ? null : Collections.singletonList(initializationData), drmInitData, 0, language); } } /** * Returns the position of the esds box within a parent, or {@link C#POSITION_UNSET} if no esds * box is found */ private static int findEsdsPosition(ParsableByteArray parent, int position, int size) { int childAtomPosition = parent.getPosition(); while (childAtomPosition - position < size) { parent.setPosition(childAtomPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childType = parent.readInt(); if (childType == Atom.TYPE_esds) { return childAtomPosition; } childAtomPosition += childAtomSize; } return C.POSITION_UNSET; } /** * Returns codec-specific initialization data contained in an esds box. */ private static Pair<String, byte[]> parseEsdsFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE + 4); // Start of the ES_Descriptor (defined in 14496-1) parent.skipBytes(1); // ES_Descriptor tag parseExpandableClassSize(parent); parent.skipBytes(2); // ES_ID int flags = parent.readUnsignedByte(); if ((flags & 0x80 /* streamDependenceFlag */) != 0) { parent.skipBytes(2); } if ((flags & 0x40 /* URL_Flag */) != 0) { parent.skipBytes(parent.readUnsignedShort()); } if ((flags & 0x20 /* OCRstreamFlag */) != 0) { parent.skipBytes(2); } // Start of the DecoderConfigDescriptor (defined in 14496-1) parent.skipBytes(1); // DecoderConfigDescriptor tag parseExpandableClassSize(parent); // Set the MIME type based on the object type indication (14496-1 table 5). int objectTypeIndication = parent.readUnsignedByte(); String mimeType = getMimeTypeFromMp4ObjectType(objectTypeIndication); if (MimeTypes.AUDIO_MPEG.equals(mimeType) || MimeTypes.AUDIO_DTS.equals(mimeType) || MimeTypes.AUDIO_DTS_HD.equals(mimeType)) { return Pair.create(mimeType, null); } parent.skipBytes(12); // Start of the DecoderSpecificInfo. parent.skipBytes(1); // DecoderSpecificInfo tag int initializationDataSize = parseExpandableClassSize(parent); byte[] initializationData = new byte[initializationDataSize]; parent.readBytes(initializationData, 0, initializationDataSize); return Pair.create(mimeType, initializationData); } /** * Parses encryption data from an audio/video sample entry, returning a pair consisting of the * unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common * encryption sinf atom was present. */ private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData( ParsableByteArray parent, int position, int size) { int childPosition = parent.getPosition(); while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_sinf) { Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent, childPosition, childAtomSize); if (result != null) { return result; } } childPosition += childAtomSize; } return null; } /* package */ static Pair<Integer, TrackEncryptionBox> parseCommonEncryptionSinfFromParent( ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; int schemeInformationBoxPosition = C.POSITION_UNSET; int schemeInformationBoxSize = 0; String schemeType = null; Integer dataFormat = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_frma) { dataFormat = parent.readInt(); } else if (childAtomType == Atom.TYPE_schm) { parent.skipBytes(4); // Common encryption scheme_type values are defined in ISO/IEC 23001-7:2016, section 4.1. schemeType = parent.readString(4); } else if (childAtomType == Atom.TYPE_schi) { schemeInformationBoxPosition = childPosition; schemeInformationBoxSize = childAtomSize; } childPosition += childAtomSize; } if (C.CENC_TYPE_cenc.equals(schemeType) || C.CENC_TYPE_cbc1.equals(schemeType) || C.CENC_TYPE_cens.equals(schemeType) || C.CENC_TYPE_cbcs.equals(schemeType)) { Assertions.checkArgument(dataFormat != null, "frma atom is mandatory"); Assertions.checkArgument(schemeInformationBoxPosition != C.POSITION_UNSET, "schi atom is mandatory"); TrackEncryptionBox encryptionBox = parseSchiFromParent(parent, schemeInformationBoxPosition, schemeInformationBoxSize, schemeType); Assertions.checkArgument(encryptionBox != null, "tenc atom is mandatory"); return Pair.create(dataFormat, encryptionBox); } else { return null; } } private static TrackEncryptionBox parseSchiFromParent(ParsableByteArray parent, int position, int size, String schemeType) { int childPosition = position + Atom.HEADER_SIZE; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_tenc) { int fullAtom = parent.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); parent.skipBytes(1); // reserved = 0. int defaultCryptByteBlock = 0; int defaultSkipByteBlock = 0; if (version == 0) { parent.skipBytes(1); // reserved = 0. } else /* version 1 or greater */ { int patternByte = parent.readUnsignedByte(); defaultCryptByteBlock = (patternByte & 0xF0) >> 4; defaultSkipByteBlock = patternByte & 0x0F; } boolean defaultIsProtected = parent.readUnsignedByte() == 1; int defaultPerSampleIvSize = parent.readUnsignedByte(); byte[] defaultKeyId = new byte[16]; parent.readBytes(defaultKeyId, 0, defaultKeyId.length); byte[] constantIv = null; if (defaultIsProtected && defaultPerSampleIvSize == 0) { int constantIvSize = parent.readUnsignedByte(); constantIv = new byte[constantIvSize]; parent.readBytes(constantIv, 0, constantIvSize); } return new TrackEncryptionBox(defaultIsProtected, schemeType, defaultPerSampleIvSize, defaultKeyId, defaultCryptByteBlock, defaultSkipByteBlock, constantIv); } childPosition += childAtomSize; } return null; } /** * Parses the proj box from sv3d box, as specified by https://github.com/google/spatial-media. */ private static byte[] parseProjFromParent(ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_proj) { return Arrays.copyOfRange(parent.data, childPosition, childPosition + childAtomSize); } childPosition += childAtomSize; } return null; } /** * Parses the size of an expandable class, as specified by ISO 14496-1 subsection 8.3.3. */ private static int parseExpandableClassSize(ParsableByteArray data) { int currentByte = data.readUnsignedByte(); int size = currentByte & 0x7F; while ((currentByte & 0x80) == 0x80) { currentByte = data.readUnsignedByte(); size = (size << 7) | (currentByte & 0x7F); } return size; } /** Returns whether it's possible to apply the specified edit using gapless playback info. */ private static boolean canApplyEditWithGaplessInfo( long[] timestamps, long duration, long editStartTime, long editEndTime) { int lastIndex = timestamps.length - 1; int latestDelayIndex = Util.constrainValue(MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex); int earliestPaddingIndex = Util.constrainValue(timestamps.length - MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex); return timestamps[0] <= editStartTime && editStartTime < timestamps[latestDelayIndex] && timestamps[earliestPaddingIndex] < editEndTime && editEndTime <= duration; } private AtomParsers() { // Prevent instantiation. } private static final class ChunkIterator { public final int length; public int index; public int numSamples; public long offset; private final boolean chunkOffsetsAreLongs; private final ParsableByteArray chunkOffsets; private final ParsableByteArray stsc; private int nextSamplesPerChunkChangeIndex; private int remainingSamplesPerChunkChanges; public ChunkIterator(ParsableByteArray stsc, ParsableByteArray chunkOffsets, boolean chunkOffsetsAreLongs) { this.stsc = stsc; this.chunkOffsets = chunkOffsets; this.chunkOffsetsAreLongs = chunkOffsetsAreLongs; chunkOffsets.setPosition(Atom.FULL_HEADER_SIZE); length = chunkOffsets.readUnsignedIntToInt(); stsc.setPosition(Atom.FULL_HEADER_SIZE); remainingSamplesPerChunkChanges = stsc.readUnsignedIntToInt(); Assertions.checkState(stsc.readInt() == 1, "first_chunk must be 1"); index = -1; } public boolean moveNext() { if (++index == length) { return false; } offset = chunkOffsetsAreLongs ? chunkOffsets.readUnsignedLongToLong() : chunkOffsets.readUnsignedInt(); if (index == nextSamplesPerChunkChangeIndex) { numSamples = stsc.readUnsignedIntToInt(); stsc.skipBytes(4); // Skip sample_description_index nextSamplesPerChunkChangeIndex = --remainingSamplesPerChunkChanges > 0 ? (stsc.readUnsignedIntToInt() - 1) : C.INDEX_UNSET; } return true; } } /** * Holds data parsed from a tkhd atom. */ private static final class TkhdData { private final int id; private final long duration; private final int rotationDegrees; public TkhdData(int id, long duration, int rotationDegrees) { this.id = id; this.duration = duration; this.rotationDegrees = rotationDegrees; } } /** * Holds data parsed from an stsd atom and its children. */ private static final class StsdData { public static final int STSD_HEADER_SIZE = 8; public final TrackEncryptionBox[] trackEncryptionBoxes; public Format format; public int nalUnitLengthFieldLength; @Track.Transformation public int requiredSampleTransformation; public StsdData(int numberOfEntries) { trackEncryptionBoxes = new TrackEncryptionBox[numberOfEntries]; requiredSampleTransformation = Track.TRANSFORMATION_NONE; } } /** * A box containing sample sizes (e.g. stsz, stz2). */ private interface SampleSizeBox { /** * Returns the number of samples. */ int getSampleCount(); /** * Returns the size for the next sample. */ int readNextSampleSize(); /** * Returns whether samples have a fixed size. */ boolean isFixedSampleSize(); } /** * An stsz sample size box. */ /* package */ static final class StszSampleSizeBox implements SampleSizeBox { private final int fixedSampleSize; private final int sampleCount; private final ParsableByteArray data; public StszSampleSizeBox(Atom.LeafAtom stszAtom) { data = stszAtom.data; data.setPosition(Atom.FULL_HEADER_SIZE); fixedSampleSize = data.readUnsignedIntToInt(); sampleCount = data.readUnsignedIntToInt(); } @Override public int getSampleCount() { return sampleCount; } @Override public int readNextSampleSize() { return fixedSampleSize == 0 ? data.readUnsignedIntToInt() : fixedSampleSize; } @Override public boolean isFixedSampleSize() { return fixedSampleSize != 0; } } /** * An stz2 sample size box. */ /* package */ static final class Stz2SampleSizeBox implements SampleSizeBox { private final ParsableByteArray data; private final int sampleCount; private final int fieldSize; // Can be 4, 8, or 16. // Used only if fieldSize == 4. private int sampleIndex; private int currentByte; public Stz2SampleSizeBox(Atom.LeafAtom stz2Atom) { data = stz2Atom.data; data.setPosition(Atom.FULL_HEADER_SIZE); fieldSize = data.readUnsignedIntToInt() & 0x000000FF; sampleCount = data.readUnsignedIntToInt(); } @Override public int getSampleCount() { return sampleCount; } @Override public int readNextSampleSize() { if (fieldSize == 8) { return data.readUnsignedByte(); } else if (fieldSize == 16) { return data.readUnsignedShort(); } else { // fieldSize == 4. if ((sampleIndex++ % 2) == 0) { // Read the next byte into our cached byte when we are reading the upper bits. currentByte = data.readUnsignedByte(); // Read the upper bits from the byte and shift them to the lower 4 bits. return (currentByte & 0xF0) >> 4; } else { // Mask out the upper 4 bits of the last byte we read. return currentByte & 0x0F; } } } @Override public boolean isFixedSampleSize() { return false; } } }
library/core/src/main/java/com/google/android/exoplayer2/extractor/mp4/AtomParsers.java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.extractor.mp4; import static com.google.android.exoplayer2.util.MimeTypes.getMimeTypeFromMp4ObjectType; import androidx.annotation.Nullable; import android.util.Pair; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.ParserException; import com.google.android.exoplayer2.audio.Ac3Util; import com.google.android.exoplayer2.audio.Ac4Util; import com.google.android.exoplayer2.drm.DrmInitData; import com.google.android.exoplayer2.extractor.GaplessInfoHolder; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.CodecSpecificDataUtil; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.ParsableByteArray; import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.video.AvcConfig; import com.google.android.exoplayer2.video.DolbyVisionConfig; import com.google.android.exoplayer2.video.HevcConfig; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** Utility methods for parsing MP4 format atom payloads according to ISO 14496-12. */ @SuppressWarnings({"ConstantField", "ConstantCaseForConstants"}) /* package */ final class AtomParsers { private static final String TAG = "AtomParsers"; private static final int TYPE_vide = Util.getIntegerCodeForString("vide"); private static final int TYPE_soun = Util.getIntegerCodeForString("soun"); private static final int TYPE_text = Util.getIntegerCodeForString("text"); private static final int TYPE_sbtl = Util.getIntegerCodeForString("sbtl"); private static final int TYPE_subt = Util.getIntegerCodeForString("subt"); private static final int TYPE_clcp = Util.getIntegerCodeForString("clcp"); private static final int TYPE_meta = Util.getIntegerCodeForString("meta"); private static final int TYPE_mdta = Util.getIntegerCodeForString("mdta"); /** * The threshold number of samples to trim from the start/end of an audio track when applying an * edit below which gapless info can be used (rather than removing samples from the sample table). */ private static final int MAX_GAPLESS_TRIM_SIZE_SAMPLES = 3; /** The magic signature for an Opus Identification header, as defined in RFC-7845. */ private static final byte[] opusMagic = Util.getUtf8Bytes("OpusHead"); /** * Parses a trak atom (defined in 14496-12). * * @param trak Atom to decode. * @param mvhd Movie header atom, used to get the timescale. * @param duration The duration in units of the timescale declared in the mvhd atom, or * {@link C#TIME_UNSET} if the duration should be parsed from the tkhd atom. * @param drmInitData {@link DrmInitData} to be included in the format. * @param ignoreEditLists Whether to ignore any edit lists in the trak box. * @param isQuickTime True for QuickTime media. False otherwise. * @return A {@link Track} instance, or {@code null} if the track's type isn't supported. */ public static Track parseTrak(Atom.ContainerAtom trak, Atom.LeafAtom mvhd, long duration, DrmInitData drmInitData, boolean ignoreEditLists, boolean isQuickTime) throws ParserException { Atom.ContainerAtom mdia = trak.getContainerAtomOfType(Atom.TYPE_mdia); int trackType = getTrackTypeForHdlr(parseHdlr(mdia.getLeafAtomOfType(Atom.TYPE_hdlr).data)); if (trackType == C.TRACK_TYPE_UNKNOWN) { return null; } TkhdData tkhdData = parseTkhd(trak.getLeafAtomOfType(Atom.TYPE_tkhd).data); if (duration == C.TIME_UNSET) { duration = tkhdData.duration; } long movieTimescale = parseMvhd(mvhd.data); long durationUs; if (duration == C.TIME_UNSET) { durationUs = C.TIME_UNSET; } else { durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, movieTimescale); } Atom.ContainerAtom stbl = mdia.getContainerAtomOfType(Atom.TYPE_minf) .getContainerAtomOfType(Atom.TYPE_stbl); Pair<Long, String> mdhdData = parseMdhd(mdia.getLeafAtomOfType(Atom.TYPE_mdhd).data); StsdData stsdData = parseStsd(stbl.getLeafAtomOfType(Atom.TYPE_stsd).data, tkhdData.id, tkhdData.rotationDegrees, mdhdData.second, drmInitData, isQuickTime); long[] editListDurations = null; long[] editListMediaTimes = null; if (!ignoreEditLists) { Pair<long[], long[]> edtsData = parseEdts(trak.getContainerAtomOfType(Atom.TYPE_edts)); editListDurations = edtsData.first; editListMediaTimes = edtsData.second; } return stsdData.format == null ? null : new Track(tkhdData.id, trackType, mdhdData.first, movieTimescale, durationUs, stsdData.format, stsdData.requiredSampleTransformation, stsdData.trackEncryptionBoxes, stsdData.nalUnitLengthFieldLength, editListDurations, editListMediaTimes); } /** * Parses an stbl atom (defined in 14496-12). * * @param track Track to which this sample table corresponds. * @param stblAtom stbl (sample table) atom to decode. * @param gaplessInfoHolder Holder to populate with gapless playback information. * @return Sample table described by the stbl atom. * @throws ParserException Thrown if the stbl atom can't be parsed. */ public static TrackSampleTable parseStbl( Track track, Atom.ContainerAtom stblAtom, GaplessInfoHolder gaplessInfoHolder) throws ParserException { SampleSizeBox sampleSizeBox; Atom.LeafAtom stszAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stsz); if (stszAtom != null) { sampleSizeBox = new StszSampleSizeBox(stszAtom); } else { Atom.LeafAtom stz2Atom = stblAtom.getLeafAtomOfType(Atom.TYPE_stz2); if (stz2Atom == null) { throw new ParserException("Track has no sample table size information"); } sampleSizeBox = new Stz2SampleSizeBox(stz2Atom); } int sampleCount = sampleSizeBox.getSampleCount(); if (sampleCount == 0) { return new TrackSampleTable( track, /* offsets= */ new long[0], /* sizes= */ new int[0], /* maximumSize= */ 0, /* timestampsUs= */ new long[0], /* flags= */ new int[0], /* durationUs= */ C.TIME_UNSET); } // Entries are byte offsets of chunks. boolean chunkOffsetsAreLongs = false; Atom.LeafAtom chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stco); if (chunkOffsetsAtom == null) { chunkOffsetsAreLongs = true; chunkOffsetsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_co64); } ParsableByteArray chunkOffsets = chunkOffsetsAtom.data; // Entries are (chunk number, number of samples per chunk, sample description index). ParsableByteArray stsc = stblAtom.getLeafAtomOfType(Atom.TYPE_stsc).data; // Entries are (number of samples, timestamp delta between those samples). ParsableByteArray stts = stblAtom.getLeafAtomOfType(Atom.TYPE_stts).data; // Entries are the indices of samples that are synchronization samples. Atom.LeafAtom stssAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_stss); ParsableByteArray stss = stssAtom != null ? stssAtom.data : null; // Entries are (number of samples, timestamp offset). Atom.LeafAtom cttsAtom = stblAtom.getLeafAtomOfType(Atom.TYPE_ctts); ParsableByteArray ctts = cttsAtom != null ? cttsAtom.data : null; // Prepare to read chunk information. ChunkIterator chunkIterator = new ChunkIterator(stsc, chunkOffsets, chunkOffsetsAreLongs); // Prepare to read sample timestamps. stts.setPosition(Atom.FULL_HEADER_SIZE); int remainingTimestampDeltaChanges = stts.readUnsignedIntToInt() - 1; int remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); int timestampDeltaInTimeUnits = stts.readUnsignedIntToInt(); // Prepare to read sample timestamp offsets, if ctts is present. int remainingSamplesAtTimestampOffset = 0; int remainingTimestampOffsetChanges = 0; int timestampOffset = 0; if (ctts != null) { ctts.setPosition(Atom.FULL_HEADER_SIZE); remainingTimestampOffsetChanges = ctts.readUnsignedIntToInt(); } int nextSynchronizationSampleIndex = C.INDEX_UNSET; int remainingSynchronizationSamples = 0; if (stss != null) { stss.setPosition(Atom.FULL_HEADER_SIZE); remainingSynchronizationSamples = stss.readUnsignedIntToInt(); if (remainingSynchronizationSamples > 0) { nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } else { // Ignore empty stss boxes, which causes all samples to be treated as sync samples. stss = null; } } // Fixed sample size raw audio may need to be rechunked. boolean isFixedSampleSizeRawAudio = sampleSizeBox.isFixedSampleSize() && MimeTypes.AUDIO_RAW.equals(track.format.sampleMimeType) && remainingTimestampDeltaChanges == 0 && remainingTimestampOffsetChanges == 0 && remainingSynchronizationSamples == 0; long[] offsets; int[] sizes; int maximumSize = 0; long[] timestamps; int[] flags; long timestampTimeUnits = 0; long duration; if (!isFixedSampleSizeRawAudio) { offsets = new long[sampleCount]; sizes = new int[sampleCount]; timestamps = new long[sampleCount]; flags = new int[sampleCount]; long offset = 0; int remainingSamplesInChunk = 0; for (int i = 0; i < sampleCount; i++) { // Advance to the next chunk if necessary. boolean chunkDataComplete = true; while (remainingSamplesInChunk == 0 && (chunkDataComplete = chunkIterator.moveNext())) { offset = chunkIterator.offset; remainingSamplesInChunk = chunkIterator.numSamples; } if (!chunkDataComplete) { Log.w(TAG, "Unexpected end of chunk data"); sampleCount = i; offsets = Arrays.copyOf(offsets, sampleCount); sizes = Arrays.copyOf(sizes, sampleCount); timestamps = Arrays.copyOf(timestamps, sampleCount); flags = Arrays.copyOf(flags, sampleCount); break; } // Add on the timestamp offset if ctts is present. if (ctts != null) { while (remainingSamplesAtTimestampOffset == 0 && remainingTimestampOffsetChanges > 0) { remainingSamplesAtTimestampOffset = ctts.readUnsignedIntToInt(); // The BMFF spec (ISO 14496-12) states that sample offsets should be unsigned integers // in version 0 ctts boxes, however some streams violate the spec and use signed // integers instead. It's safe to always decode sample offsets as signed integers here, // because unsigned integers will still be parsed correctly (unless their top bit is // set, which is never true in practice because sample offsets are always small). timestampOffset = ctts.readInt(); remainingTimestampOffsetChanges--; } remainingSamplesAtTimestampOffset--; } offsets[i] = offset; sizes[i] = sampleSizeBox.readNextSampleSize(); if (sizes[i] > maximumSize) { maximumSize = sizes[i]; } timestamps[i] = timestampTimeUnits + timestampOffset; // All samples are synchronization samples if the stss is not present. flags[i] = stss == null ? C.BUFFER_FLAG_KEY_FRAME : 0; if (i == nextSynchronizationSampleIndex) { flags[i] = C.BUFFER_FLAG_KEY_FRAME; remainingSynchronizationSamples--; if (remainingSynchronizationSamples > 0) { nextSynchronizationSampleIndex = stss.readUnsignedIntToInt() - 1; } } // Add on the duration of this sample. timestampTimeUnits += timestampDeltaInTimeUnits; remainingSamplesAtTimestampDelta--; if (remainingSamplesAtTimestampDelta == 0 && remainingTimestampDeltaChanges > 0) { remainingSamplesAtTimestampDelta = stts.readUnsignedIntToInt(); // The BMFF spec (ISO 14496-12) states that sample deltas should be unsigned integers // in stts boxes, however some streams violate the spec and use signed integers instead. // See https://github.com/google/ExoPlayer/issues/3384. It's safe to always decode sample // deltas as signed integers here, because unsigned integers will still be parsed // correctly (unless their top bit is set, which is never true in practice because sample // deltas are always small). timestampDeltaInTimeUnits = stts.readInt(); remainingTimestampDeltaChanges--; } offset += sizes[i]; remainingSamplesInChunk--; } duration = timestampTimeUnits + timestampOffset; // If the stbl's child boxes are not consistent the container is malformed, but the stream may // still be playable. boolean isCttsValid = true; while (remainingTimestampOffsetChanges > 0) { if (ctts.readUnsignedIntToInt() != 0) { isCttsValid = false; break; } ctts.readInt(); // Ignore offset. remainingTimestampOffsetChanges--; } if (remainingSynchronizationSamples != 0 || remainingSamplesAtTimestampDelta != 0 || remainingSamplesInChunk != 0 || remainingTimestampDeltaChanges != 0 || remainingSamplesAtTimestampOffset != 0 || !isCttsValid) { Log.w( TAG, "Inconsistent stbl box for track " + track.id + ": remainingSynchronizationSamples " + remainingSynchronizationSamples + ", remainingSamplesAtTimestampDelta " + remainingSamplesAtTimestampDelta + ", remainingSamplesInChunk " + remainingSamplesInChunk + ", remainingTimestampDeltaChanges " + remainingTimestampDeltaChanges + ", remainingSamplesAtTimestampOffset " + remainingSamplesAtTimestampOffset + (!isCttsValid ? ", ctts invalid" : "")); } } else { long[] chunkOffsetsBytes = new long[chunkIterator.length]; int[] chunkSampleCounts = new int[chunkIterator.length]; while (chunkIterator.moveNext()) { chunkOffsetsBytes[chunkIterator.index] = chunkIterator.offset; chunkSampleCounts[chunkIterator.index] = chunkIterator.numSamples; } int fixedSampleSize = Util.getPcmFrameSize(track.format.pcmEncoding, track.format.channelCount); FixedSampleSizeRechunker.Results rechunkedResults = FixedSampleSizeRechunker.rechunk( fixedSampleSize, chunkOffsetsBytes, chunkSampleCounts, timestampDeltaInTimeUnits); offsets = rechunkedResults.offsets; sizes = rechunkedResults.sizes; maximumSize = rechunkedResults.maximumSize; timestamps = rechunkedResults.timestamps; flags = rechunkedResults.flags; duration = rechunkedResults.duration; } long durationUs = Util.scaleLargeTimestamp(duration, C.MICROS_PER_SECOND, track.timescale); if (track.editListDurations == null || gaplessInfoHolder.hasGaplessInfo()) { // There is no edit list, or we are ignoring it as we already have gapless metadata to apply. // This implementation does not support applying both gapless metadata and an edit list. Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, durationUs); } // See the BMFF spec (ISO 14496-12) subsection 8.6.6. Edit lists that require prerolling from a // sync sample after reordering are not supported. Partial audio sample truncation is only // supported in edit lists with one edit that removes less than MAX_GAPLESS_TRIM_SIZE_SAMPLES // samples from the start/end of the track. This implementation handles simple // discarding/delaying of samples. The extractor may place further restrictions on what edited // streams are playable. if (track.editListDurations.length == 1 && track.type == C.TRACK_TYPE_AUDIO && timestamps.length >= 2) { long editStartTime = track.editListMediaTimes[0]; long editEndTime = editStartTime + Util.scaleLargeTimestamp(track.editListDurations[0], track.timescale, track.movieTimescale); if (canApplyEditWithGaplessInfo(timestamps, duration, editStartTime, editEndTime)) { long paddingTimeUnits = duration - editEndTime; long encoderDelay = Util.scaleLargeTimestamp(editStartTime - timestamps[0], track.format.sampleRate, track.timescale); long encoderPadding = Util.scaleLargeTimestamp(paddingTimeUnits, track.format.sampleRate, track.timescale); if ((encoderDelay != 0 || encoderPadding != 0) && encoderDelay <= Integer.MAX_VALUE && encoderPadding <= Integer.MAX_VALUE) { gaplessInfoHolder.encoderDelay = (int) encoderDelay; gaplessInfoHolder.encoderPadding = (int) encoderPadding; Util.scaleLargeTimestampsInPlace(timestamps, C.MICROS_PER_SECOND, track.timescale); long editedDurationUs = Util.scaleLargeTimestamp( track.editListDurations[0], C.MICROS_PER_SECOND, track.movieTimescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, editedDurationUs); } } } if (track.editListDurations.length == 1 && track.editListDurations[0] == 0) { // The current version of the spec leaves handling of an edit with zero segment_duration in // unfragmented files open to interpretation. We handle this as a special case and include all // samples in the edit. long editStartTime = track.editListMediaTimes[0]; for (int i = 0; i < timestamps.length; i++) { timestamps[i] = Util.scaleLargeTimestamp( timestamps[i] - editStartTime, C.MICROS_PER_SECOND, track.timescale); } durationUs = Util.scaleLargeTimestamp(duration - editStartTime, C.MICROS_PER_SECOND, track.timescale); return new TrackSampleTable( track, offsets, sizes, maximumSize, timestamps, flags, durationUs); } // Omit any sample at the end point of an edit for audio tracks. boolean omitClippedSample = track.type == C.TRACK_TYPE_AUDIO; // Count the number of samples after applying edits. int editedSampleCount = 0; int nextSampleIndex = 0; boolean copyMetadata = false; int[] startIndices = new int[track.editListDurations.length]; int[] endIndices = new int[track.editListDurations.length]; for (int i = 0; i < track.editListDurations.length; i++) { long editMediaTime = track.editListMediaTimes[i]; if (editMediaTime != -1) { long editDuration = Util.scaleLargeTimestamp( track.editListDurations[i], track.timescale, track.movieTimescale); startIndices[i] = Util.binarySearchCeil(timestamps, editMediaTime, true, true); endIndices[i] = Util.binarySearchCeil( timestamps, editMediaTime + editDuration, omitClippedSample, false); while (startIndices[i] < endIndices[i] && (flags[startIndices[i]] & C.BUFFER_FLAG_KEY_FRAME) == 0) { // Applying the edit correctly would require prerolling from the previous sync sample. In // the current implementation we advance to the next sync sample instead. Only other // tracks (i.e. audio) will be rendered until the time of the first sync sample. // See https://github.com/google/ExoPlayer/issues/1659. startIndices[i]++; } editedSampleCount += endIndices[i] - startIndices[i]; copyMetadata |= nextSampleIndex != startIndices[i]; nextSampleIndex = endIndices[i]; } } copyMetadata |= editedSampleCount != sampleCount; // Calculate edited sample timestamps and update the corresponding metadata arrays. long[] editedOffsets = copyMetadata ? new long[editedSampleCount] : offsets; int[] editedSizes = copyMetadata ? new int[editedSampleCount] : sizes; int editedMaximumSize = copyMetadata ? 0 : maximumSize; int[] editedFlags = copyMetadata ? new int[editedSampleCount] : flags; long[] editedTimestamps = new long[editedSampleCount]; long pts = 0; int sampleIndex = 0; for (int i = 0; i < track.editListDurations.length; i++) { long editMediaTime = track.editListMediaTimes[i]; int startIndex = startIndices[i]; int endIndex = endIndices[i]; if (copyMetadata) { int count = endIndex - startIndex; System.arraycopy(offsets, startIndex, editedOffsets, sampleIndex, count); System.arraycopy(sizes, startIndex, editedSizes, sampleIndex, count); System.arraycopy(flags, startIndex, editedFlags, sampleIndex, count); } for (int j = startIndex; j < endIndex; j++) { long ptsUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale); long timeInSegmentUs = Util.scaleLargeTimestamp( timestamps[j] - editMediaTime, C.MICROS_PER_SECOND, track.timescale); editedTimestamps[sampleIndex] = ptsUs + timeInSegmentUs; if (copyMetadata && editedSizes[sampleIndex] > editedMaximumSize) { editedMaximumSize = sizes[j]; } sampleIndex++; } pts += track.editListDurations[i]; } long editedDurationUs = Util.scaleLargeTimestamp(pts, C.MICROS_PER_SECOND, track.movieTimescale); return new TrackSampleTable( track, editedOffsets, editedSizes, editedMaximumSize, editedTimestamps, editedFlags, editedDurationUs); } /** * Parses a udta atom. * * @param udtaAtom The udta (user data) atom to decode. * @param isQuickTime True for QuickTime media. False otherwise. * @return Parsed metadata, or null. */ @Nullable public static Metadata parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) { if (isQuickTime) { // Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and // decode one. return null; } ParsableByteArray udtaData = udtaAtom.data; udtaData.setPosition(Atom.HEADER_SIZE); while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) { int atomPosition = udtaData.getPosition(); int atomSize = udtaData.readInt(); int atomType = udtaData.readInt(); if (atomType == Atom.TYPE_meta) { udtaData.setPosition(atomPosition); return parseUdtaMeta(udtaData, atomPosition + atomSize); } udtaData.setPosition(atomPosition + atomSize); } return null; } /** * Parses a metadata meta atom if it contains metadata with handler 'mdta'. * * @param meta The metadata atom to decode. * @return Parsed metadata, or null. */ @Nullable public static Metadata parseMdtaFromMeta(Atom.ContainerAtom meta) { Atom.LeafAtom hdlrAtom = meta.getLeafAtomOfType(Atom.TYPE_hdlr); Atom.LeafAtom keysAtom = meta.getLeafAtomOfType(Atom.TYPE_keys); Atom.LeafAtom ilstAtom = meta.getLeafAtomOfType(Atom.TYPE_ilst); if (hdlrAtom == null || keysAtom == null || ilstAtom == null || AtomParsers.parseHdlr(hdlrAtom.data) != TYPE_mdta) { // There isn't enough information to parse the metadata, or the handler type is unexpected. return null; } // Parse metadata keys. ParsableByteArray keys = keysAtom.data; keys.setPosition(Atom.FULL_HEADER_SIZE); int entryCount = keys.readInt(); String[] keyNames = new String[entryCount]; for (int i = 0; i < entryCount; i++) { int entrySize = keys.readInt(); keys.skipBytes(4); // keyNamespace int keySize = entrySize - 8; keyNames[i] = keys.readString(keySize); } // Parse metadata items. ParsableByteArray ilst = ilstAtom.data; ilst.setPosition(Atom.HEADER_SIZE); ArrayList<Metadata.Entry> entries = new ArrayList<>(); while (ilst.bytesLeft() > Atom.HEADER_SIZE) { int atomPosition = ilst.getPosition(); int atomSize = ilst.readInt(); int keyIndex = ilst.readInt() - 1; if (keyIndex >= 0 && keyIndex < keyNames.length) { String key = keyNames[keyIndex]; Metadata.Entry entry = MetadataUtil.parseMdtaMetadataEntryFromIlst(ilst, atomPosition + atomSize, key); if (entry != null) { entries.add(entry); } } else { Log.w(TAG, "Skipped metadata with unknown key index: " + keyIndex); } ilst.setPosition(atomPosition + atomSize); } return entries.isEmpty() ? null : new Metadata(entries); } @Nullable private static Metadata parseUdtaMeta(ParsableByteArray meta, int limit) { meta.skipBytes(Atom.FULL_HEADER_SIZE); while (meta.getPosition() < limit) { int atomPosition = meta.getPosition(); int atomSize = meta.readInt(); int atomType = meta.readInt(); if (atomType == Atom.TYPE_ilst) { meta.setPosition(atomPosition); return parseIlst(meta, atomPosition + atomSize); } meta.setPosition(atomPosition + atomSize); } return null; } @Nullable private static Metadata parseIlst(ParsableByteArray ilst, int limit) { ilst.skipBytes(Atom.HEADER_SIZE); ArrayList<Metadata.Entry> entries = new ArrayList<>(); while (ilst.getPosition() < limit) { Metadata.Entry entry = MetadataUtil.parseIlstElement(ilst); if (entry != null) { entries.add(entry); } } return entries.isEmpty() ? null : new Metadata(entries); } /** * Parses a mvhd atom (defined in 14496-12), returning the timescale for the movie. * * @param mvhd Contents of the mvhd atom to be parsed. * @return Timescale for the movie. */ private static long parseMvhd(ParsableByteArray mvhd) { mvhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mvhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mvhd.skipBytes(version == 0 ? 8 : 16); return mvhd.readUnsignedInt(); } /** * Parses a tkhd atom (defined in 14496-12). * * @return An object containing the parsed data. */ private static TkhdData parseTkhd(ParsableByteArray tkhd) { tkhd.setPosition(Atom.HEADER_SIZE); int fullAtom = tkhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); tkhd.skipBytes(version == 0 ? 8 : 16); int trackId = tkhd.readInt(); tkhd.skipBytes(4); boolean durationUnknown = true; int durationPosition = tkhd.getPosition(); int durationByteCount = version == 0 ? 4 : 8; for (int i = 0; i < durationByteCount; i++) { if (tkhd.data[durationPosition + i] != -1) { durationUnknown = false; break; } } long duration; if (durationUnknown) { tkhd.skipBytes(durationByteCount); duration = C.TIME_UNSET; } else { duration = version == 0 ? tkhd.readUnsignedInt() : tkhd.readUnsignedLongToLong(); if (duration == 0) { // 0 duration normally indicates that the file is fully fragmented (i.e. all of the media // samples are in fragments). Treat as unknown. duration = C.TIME_UNSET; } } tkhd.skipBytes(16); int a00 = tkhd.readInt(); int a01 = tkhd.readInt(); tkhd.skipBytes(4); int a10 = tkhd.readInt(); int a11 = tkhd.readInt(); int rotationDegrees; int fixedOne = 65536; if (a00 == 0 && a01 == fixedOne && a10 == -fixedOne && a11 == 0) { rotationDegrees = 90; } else if (a00 == 0 && a01 == -fixedOne && a10 == fixedOne && a11 == 0) { rotationDegrees = 270; } else if (a00 == -fixedOne && a01 == 0 && a10 == 0 && a11 == -fixedOne) { rotationDegrees = 180; } else { // Only 0, 90, 180 and 270 are supported. Treat anything else as 0. rotationDegrees = 0; } return new TkhdData(trackId, duration, rotationDegrees); } /** * Parses an hdlr atom. * * @param hdlr The hdlr atom to decode. * @return The handler value. */ private static int parseHdlr(ParsableByteArray hdlr) { hdlr.setPosition(Atom.FULL_HEADER_SIZE + 4); return hdlr.readInt(); } /** Returns the track type for a given handler value. */ private static int getTrackTypeForHdlr(int hdlr) { if (hdlr == TYPE_soun) { return C.TRACK_TYPE_AUDIO; } else if (hdlr == TYPE_vide) { return C.TRACK_TYPE_VIDEO; } else if (hdlr == TYPE_text || hdlr == TYPE_sbtl || hdlr == TYPE_subt || hdlr == TYPE_clcp) { return C.TRACK_TYPE_TEXT; } else if (hdlr == TYPE_meta) { return C.TRACK_TYPE_METADATA; } else { return C.TRACK_TYPE_UNKNOWN; } } /** * Parses an mdhd atom (defined in 14496-12). * * @param mdhd The mdhd atom to decode. * @return A pair consisting of the media timescale defined as the number of time units that pass * in one second, and the language code. */ private static Pair<Long, String> parseMdhd(ParsableByteArray mdhd) { mdhd.setPosition(Atom.HEADER_SIZE); int fullAtom = mdhd.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); mdhd.skipBytes(version == 0 ? 8 : 16); long timescale = mdhd.readUnsignedInt(); mdhd.skipBytes(version == 0 ? 4 : 8); int languageCode = mdhd.readUnsignedShort(); String language = "" + (char) (((languageCode >> 10) & 0x1F) + 0x60) + (char) (((languageCode >> 5) & 0x1F) + 0x60) + (char) ((languageCode & 0x1F) + 0x60); return Pair.create(timescale, language); } /** * Parses a stsd atom (defined in 14496-12). * * @param stsd The stsd atom to decode. * @param trackId The track's identifier in its container. * @param rotationDegrees The rotation of the track in degrees. * @param language The language of the track. * @param drmInitData {@link DrmInitData} to be included in the format. * @param isQuickTime True for QuickTime media. False otherwise. * @return An object containing the parsed data. */ private static StsdData parseStsd(ParsableByteArray stsd, int trackId, int rotationDegrees, String language, DrmInitData drmInitData, boolean isQuickTime) throws ParserException { stsd.setPosition(Atom.FULL_HEADER_SIZE); int numberOfEntries = stsd.readInt(); StsdData out = new StsdData(numberOfEntries); for (int i = 0; i < numberOfEntries; i++) { int childStartPosition = stsd.getPosition(); int childAtomSize = stsd.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = stsd.readInt(); if (childAtomType == Atom.TYPE_avc1 || childAtomType == Atom.TYPE_avc3 || childAtomType == Atom.TYPE_encv || childAtomType == Atom.TYPE_mp4v || childAtomType == Atom.TYPE_hvc1 || childAtomType == Atom.TYPE_hev1 || childAtomType == Atom.TYPE_s263 || childAtomType == Atom.TYPE_vp08 || childAtomType == Atom.TYPE_vp09 || childAtomType == Atom.TYPE_av01 || childAtomType == Atom.TYPE_dvav || childAtomType == Atom.TYPE_dva1 || childAtomType == Atom.TYPE_dvhe || childAtomType == Atom.TYPE_dvh1) { parseVideoSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, rotationDegrees, drmInitData, out, i); } else if (childAtomType == Atom.TYPE_mp4a || childAtomType == Atom.TYPE_enca || childAtomType == Atom.TYPE_ac_3 || childAtomType == Atom.TYPE_ec_3 || childAtomType == Atom.TYPE_ac_4 || childAtomType == Atom.TYPE_dtsc || childAtomType == Atom.TYPE_dtse || childAtomType == Atom.TYPE_dtsh || childAtomType == Atom.TYPE_dtsl || childAtomType == Atom.TYPE_samr || childAtomType == Atom.TYPE_sawb || childAtomType == Atom.TYPE_lpcm || childAtomType == Atom.TYPE_sowt || childAtomType == Atom.TYPE__mp3 || childAtomType == Atom.TYPE_alac || childAtomType == Atom.TYPE_alaw || childAtomType == Atom.TYPE_ulaw || childAtomType == Atom.TYPE_Opus || childAtomType == Atom.TYPE_fLaC) { parseAudioSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, language, isQuickTime, drmInitData, out, i); } else if (childAtomType == Atom.TYPE_TTML || childAtomType == Atom.TYPE_tx3g || childAtomType == Atom.TYPE_wvtt || childAtomType == Atom.TYPE_stpp || childAtomType == Atom.TYPE_c608) { parseTextSampleEntry(stsd, childAtomType, childStartPosition, childAtomSize, trackId, language, out); } else if (childAtomType == Atom.TYPE_camm) { out.format = Format.createSampleFormat(Integer.toString(trackId), MimeTypes.APPLICATION_CAMERA_MOTION, null, Format.NO_VALUE, null); } stsd.setPosition(childStartPosition + childAtomSize); } return out; } private static void parseTextSampleEntry(ParsableByteArray parent, int atomType, int position, int atomSize, int trackId, String language, StsdData out) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); // Default values. List<byte[]> initializationData = null; long subsampleOffsetUs = Format.OFFSET_SAMPLE_RELATIVE; String mimeType; if (atomType == Atom.TYPE_TTML) { mimeType = MimeTypes.APPLICATION_TTML; } else if (atomType == Atom.TYPE_tx3g) { mimeType = MimeTypes.APPLICATION_TX3G; int sampleDescriptionLength = atomSize - Atom.HEADER_SIZE - 8; byte[] sampleDescriptionData = new byte[sampleDescriptionLength]; parent.readBytes(sampleDescriptionData, 0, sampleDescriptionLength); initializationData = Collections.singletonList(sampleDescriptionData); } else if (atomType == Atom.TYPE_wvtt) { mimeType = MimeTypes.APPLICATION_MP4VTT; } else if (atomType == Atom.TYPE_stpp) { mimeType = MimeTypes.APPLICATION_TTML; subsampleOffsetUs = 0; // Subsample timing is absolute. } else if (atomType == Atom.TYPE_c608) { // Defined by the QuickTime File Format specification. mimeType = MimeTypes.APPLICATION_MP4CEA608; out.requiredSampleTransformation = Track.TRANSFORMATION_CEA608_CDAT; } else { // Never happens. throw new IllegalStateException(); } out.format = Format.createTextSampleFormat( Integer.toString(trackId), mimeType, /* codecs= */ null, /* bitrate= */ Format.NO_VALUE, /* selectionFlags= */ 0, language, /* accessibilityChannel= */ Format.NO_VALUE, /* drmInitData= */ null, subsampleOffsetUs, initializationData); } private static void parseVideoSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, int rotationDegrees, DrmInitData drmInitData, StsdData out, int entryIndex) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); parent.skipBytes(16); int width = parent.readUnsignedShort(); int height = parent.readUnsignedShort(); boolean pixelWidthHeightRatioFromPasp = false; float pixelWidthHeightRatio = 1; parent.skipBytes(50); int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_encv) { Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData = parseSampleEntryEncryptionData( parent, position, size); if (sampleEntryEncryptionData != null) { atomType = sampleEntryEncryptionData.first; drmInitData = drmInitData == null ? null : drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType); out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second; } parent.setPosition(childPosition); } // TODO: Uncomment when [Internal: b/63092960] is fixed. // else { // drmInitData = null; // } List<byte[]> initializationData = null; String mimeType = null; String codecs = null; byte[] projectionData = null; @C.StereoMode int stereoMode = Format.NO_VALUE; while (childPosition - position < size) { parent.setPosition(childPosition); int childStartPosition = parent.getPosition(); int childAtomSize = parent.readInt(); if (childAtomSize == 0 && parent.getPosition() - position == size) { // Handle optional terminating four zero bytes in MOV files. break; } Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_avcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H264; parent.setPosition(childStartPosition + Atom.HEADER_SIZE); AvcConfig avcConfig = AvcConfig.parse(parent); initializationData = avcConfig.initializationData; out.nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength; if (!pixelWidthHeightRatioFromPasp) { pixelWidthHeightRatio = avcConfig.pixelWidthAspectRatio; } } else if (childAtomType == Atom.TYPE_hvcC) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H265; parent.setPosition(childStartPosition + Atom.HEADER_SIZE); HevcConfig hevcConfig = HevcConfig.parse(parent); initializationData = hevcConfig.initializationData; out.nalUnitLengthFieldLength = hevcConfig.nalUnitLengthFieldLength; } else if (childAtomType == Atom.TYPE_dvcC || childAtomType == Atom.TYPE_dvvC) { DolbyVisionConfig dolbyVisionConfig = DolbyVisionConfig.parse(parent); // TODO: Support profiles 4, 8 and 9 once we have a way to fall back to AVC/HEVC decoding. if (dolbyVisionConfig != null && dolbyVisionConfig.profile == 5) { codecs = dolbyVisionConfig.codecs; mimeType = MimeTypes.VIDEO_DOLBY_VISION; } } else if (childAtomType == Atom.TYPE_vpcC) { Assertions.checkState(mimeType == null); mimeType = (atomType == Atom.TYPE_vp08) ? MimeTypes.VIDEO_VP8 : MimeTypes.VIDEO_VP9; } else if (childAtomType == Atom.TYPE_av1C) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_AV1; } else if (childAtomType == Atom.TYPE_d263) { Assertions.checkState(mimeType == null); mimeType = MimeTypes.VIDEO_H263; } else if (childAtomType == Atom.TYPE_esds) { Assertions.checkState(mimeType == null); Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, childStartPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = Collections.singletonList(mimeTypeAndInitializationData.second); } else if (childAtomType == Atom.TYPE_pasp) { pixelWidthHeightRatio = parsePaspFromParent(parent, childStartPosition); pixelWidthHeightRatioFromPasp = true; } else if (childAtomType == Atom.TYPE_sv3d) { projectionData = parseProjFromParent(parent, childStartPosition, childAtomSize); } else if (childAtomType == Atom.TYPE_st3d) { int version = parent.readUnsignedByte(); parent.skipBytes(3); // Flags. if (version == 0) { int layout = parent.readUnsignedByte(); switch (layout) { case 0: stereoMode = C.STEREO_MODE_MONO; break; case 1: stereoMode = C.STEREO_MODE_TOP_BOTTOM; break; case 2: stereoMode = C.STEREO_MODE_LEFT_RIGHT; break; case 3: stereoMode = C.STEREO_MODE_STEREO_MESH; break; default: break; } } } childPosition += childAtomSize; } // If the media type was not recognized, ignore the track. if (mimeType == null) { return; } out.format = Format.createVideoSampleFormat( Integer.toString(trackId), mimeType, codecs, /* bitrate= */ Format.NO_VALUE, /* maxInputSize= */ Format.NO_VALUE, width, height, /* frameRate= */ Format.NO_VALUE, initializationData, rotationDegrees, pixelWidthHeightRatio, projectionData, stereoMode, /* colorInfo= */ null, drmInitData); } /** * Parses the edts atom (defined in 14496-12 subsection 8.6.5). * * @param edtsAtom edts (edit box) atom to decode. * @return Pair of edit list durations and edit list media times, or a pair of nulls if they are * not present. */ private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) { Atom.LeafAtom elst; if (edtsAtom == null || (elst = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst)) == null) { return Pair.create(null, null); } ParsableByteArray elstData = elst.data; elstData.setPosition(Atom.HEADER_SIZE); int fullAtom = elstData.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); int entryCount = elstData.readUnsignedIntToInt(); long[] editListDurations = new long[entryCount]; long[] editListMediaTimes = new long[entryCount]; for (int i = 0; i < entryCount; i++) { editListDurations[i] = version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt(); editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt(); int mediaRateInteger = elstData.readShort(); if (mediaRateInteger != 1) { // The extractor does not handle dwell edits (mediaRateInteger == 0). throw new IllegalArgumentException("Unsupported media rate."); } elstData.skipBytes(2); } return Pair.create(editListDurations, editListMediaTimes); } private static float parsePaspFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE); int hSpacing = parent.readUnsignedIntToInt(); int vSpacing = parent.readUnsignedIntToInt(); return (float) hSpacing / vSpacing; } private static void parseAudioSampleEntry(ParsableByteArray parent, int atomType, int position, int size, int trackId, String language, boolean isQuickTime, DrmInitData drmInitData, StsdData out, int entryIndex) throws ParserException { parent.setPosition(position + Atom.HEADER_SIZE + StsdData.STSD_HEADER_SIZE); int quickTimeSoundDescriptionVersion = 0; if (isQuickTime) { quickTimeSoundDescriptionVersion = parent.readUnsignedShort(); parent.skipBytes(6); } else { parent.skipBytes(8); } int channelCount; int sampleRate; if (quickTimeSoundDescriptionVersion == 0 || quickTimeSoundDescriptionVersion == 1) { channelCount = parent.readUnsignedShort(); parent.skipBytes(6); // sampleSize, compressionId, packetSize. sampleRate = parent.readUnsignedFixedPoint1616(); if (quickTimeSoundDescriptionVersion == 1) { parent.skipBytes(16); } } else if (quickTimeSoundDescriptionVersion == 2) { parent.skipBytes(16); // always[3,16,Minus2,0,65536], sizeOfStructOnly sampleRate = (int) Math.round(parent.readDouble()); channelCount = parent.readUnsignedIntToInt(); // Skip always7F000000, sampleSize, formatSpecificFlags, constBytesPerAudioPacket, // constLPCMFramesPerAudioPacket. parent.skipBytes(20); } else { // Unsupported version. return; } int childPosition = parent.getPosition(); if (atomType == Atom.TYPE_enca) { Pair<Integer, TrackEncryptionBox> sampleEntryEncryptionData = parseSampleEntryEncryptionData( parent, position, size); if (sampleEntryEncryptionData != null) { atomType = sampleEntryEncryptionData.first; drmInitData = drmInitData == null ? null : drmInitData.copyWithSchemeType(sampleEntryEncryptionData.second.schemeType); out.trackEncryptionBoxes[entryIndex] = sampleEntryEncryptionData.second; } parent.setPosition(childPosition); } // TODO: Uncomment when [Internal: b/63092960] is fixed. // else { // drmInitData = null; // } // If the atom type determines a MIME type, set it immediately. String mimeType = null; if (atomType == Atom.TYPE_ac_3) { mimeType = MimeTypes.AUDIO_AC3; } else if (atomType == Atom.TYPE_ec_3) { mimeType = MimeTypes.AUDIO_E_AC3; } else if (atomType == Atom.TYPE_ac_4) { mimeType = MimeTypes.AUDIO_AC4; } else if (atomType == Atom.TYPE_dtsc) { mimeType = MimeTypes.AUDIO_DTS; } else if (atomType == Atom.TYPE_dtsh || atomType == Atom.TYPE_dtsl) { mimeType = MimeTypes.AUDIO_DTS_HD; } else if (atomType == Atom.TYPE_dtse) { mimeType = MimeTypes.AUDIO_DTS_EXPRESS; } else if (atomType == Atom.TYPE_samr) { mimeType = MimeTypes.AUDIO_AMR_NB; } else if (atomType == Atom.TYPE_sawb) { mimeType = MimeTypes.AUDIO_AMR_WB; } else if (atomType == Atom.TYPE_lpcm || atomType == Atom.TYPE_sowt) { mimeType = MimeTypes.AUDIO_RAW; } else if (atomType == Atom.TYPE__mp3) { mimeType = MimeTypes.AUDIO_MPEG; } else if (atomType == Atom.TYPE_alac) { mimeType = MimeTypes.AUDIO_ALAC; } else if (atomType == Atom.TYPE_alaw) { mimeType = MimeTypes.AUDIO_ALAW; } else if (atomType == Atom.TYPE_ulaw) { mimeType = MimeTypes.AUDIO_MLAW; } else if (atomType == Atom.TYPE_Opus) { mimeType = MimeTypes.AUDIO_OPUS; } else if (atomType == Atom.TYPE_fLaC) { mimeType = MimeTypes.AUDIO_FLAC; } byte[] initializationData = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_esds || (isQuickTime && childAtomType == Atom.TYPE_wave)) { int esdsAtomPosition = childAtomType == Atom.TYPE_esds ? childPosition : findEsdsPosition(parent, childPosition, childAtomSize); if (esdsAtomPosition != C.POSITION_UNSET) { Pair<String, byte[]> mimeTypeAndInitializationData = parseEsdsFromParent(parent, esdsAtomPosition); mimeType = mimeTypeAndInitializationData.first; initializationData = mimeTypeAndInitializationData.second; if (MimeTypes.AUDIO_AAC.equals(mimeType)) { // TODO: Do we really need to do this? See [Internal: b/10903778] // Update sampleRate and channelCount from the AudioSpecificConfig initialization data. Pair<Integer, Integer> audioSpecificConfig = CodecSpecificDataUtil.parseAacAudioSpecificConfig(initializationData); sampleRate = audioSpecificConfig.first; channelCount = audioSpecificConfig.second; } } } else if (childAtomType == Atom.TYPE_dac3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac3Util.parseAc3AnnexFFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_dec3) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac3Util.parseEAc3AnnexFFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_dac4) { parent.setPosition(Atom.HEADER_SIZE + childPosition); out.format = Ac4Util.parseAc4AnnexEFormat(parent, Integer.toString(trackId), language, drmInitData); } else if (childAtomType == Atom.TYPE_ddts) { out.format = Format.createAudioSampleFormat(Integer.toString(trackId), mimeType, null, Format.NO_VALUE, Format.NO_VALUE, channelCount, sampleRate, null, drmInitData, 0, language); } else if (childAtomType == Atom.TYPE_alac) { initializationData = new byte[childAtomSize]; parent.setPosition(childPosition); parent.readBytes(initializationData, /* offset= */ 0, childAtomSize); } else if (childAtomType == Atom.TYPE_dOps) { // Build an Opus Identification Header (defined in RFC-7845) by concatenating the Opus Magic // Signature and the body of the dOps atom. int childAtomBodySize = childAtomSize - Atom.HEADER_SIZE; initializationData = new byte[opusMagic.length + childAtomBodySize]; System.arraycopy(opusMagic, 0, initializationData, 0, opusMagic.length); parent.setPosition(childPosition + Atom.HEADER_SIZE); parent.readBytes(initializationData, opusMagic.length, childAtomBodySize); } else if (childAtomSize == Atom.TYPE_dfLa) { int childAtomBodySize = childAtomSize - Atom.FULL_HEADER_SIZE; initializationData = new byte[childAtomBodySize]; parent.setPosition(childPosition + Atom.FULL_HEADER_SIZE); parent.readBytes(initializationData, /* offset= */ 0, childAtomBodySize); } childPosition += childAtomSize; } if (out.format == null && mimeType != null) { // TODO: Determine the correct PCM encoding. @C.PcmEncoding int pcmEncoding = MimeTypes.AUDIO_RAW.equals(mimeType) ? C.ENCODING_PCM_16BIT : Format.NO_VALUE; out.format = Format.createAudioSampleFormat(Integer.toString(trackId), mimeType, null, Format.NO_VALUE, Format.NO_VALUE, channelCount, sampleRate, pcmEncoding, initializationData == null ? null : Collections.singletonList(initializationData), drmInitData, 0, language); } } /** * Returns the position of the esds box within a parent, or {@link C#POSITION_UNSET} if no esds * box is found */ private static int findEsdsPosition(ParsableByteArray parent, int position, int size) { int childAtomPosition = parent.getPosition(); while (childAtomPosition - position < size) { parent.setPosition(childAtomPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childType = parent.readInt(); if (childType == Atom.TYPE_esds) { return childAtomPosition; } childAtomPosition += childAtomSize; } return C.POSITION_UNSET; } /** * Returns codec-specific initialization data contained in an esds box. */ private static Pair<String, byte[]> parseEsdsFromParent(ParsableByteArray parent, int position) { parent.setPosition(position + Atom.HEADER_SIZE + 4); // Start of the ES_Descriptor (defined in 14496-1) parent.skipBytes(1); // ES_Descriptor tag parseExpandableClassSize(parent); parent.skipBytes(2); // ES_ID int flags = parent.readUnsignedByte(); if ((flags & 0x80 /* streamDependenceFlag */) != 0) { parent.skipBytes(2); } if ((flags & 0x40 /* URL_Flag */) != 0) { parent.skipBytes(parent.readUnsignedShort()); } if ((flags & 0x20 /* OCRstreamFlag */) != 0) { parent.skipBytes(2); } // Start of the DecoderConfigDescriptor (defined in 14496-1) parent.skipBytes(1); // DecoderConfigDescriptor tag parseExpandableClassSize(parent); // Set the MIME type based on the object type indication (14496-1 table 5). int objectTypeIndication = parent.readUnsignedByte(); String mimeType = getMimeTypeFromMp4ObjectType(objectTypeIndication); if (MimeTypes.AUDIO_MPEG.equals(mimeType) || MimeTypes.AUDIO_DTS.equals(mimeType) || MimeTypes.AUDIO_DTS_HD.equals(mimeType)) { return Pair.create(mimeType, null); } parent.skipBytes(12); // Start of the DecoderSpecificInfo. parent.skipBytes(1); // DecoderSpecificInfo tag int initializationDataSize = parseExpandableClassSize(parent); byte[] initializationData = new byte[initializationDataSize]; parent.readBytes(initializationData, 0, initializationDataSize); return Pair.create(mimeType, initializationData); } /** * Parses encryption data from an audio/video sample entry, returning a pair consisting of the * unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common * encryption sinf atom was present. */ private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData( ParsableByteArray parent, int position, int size) { int childPosition = parent.getPosition(); while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive"); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_sinf) { Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent, childPosition, childAtomSize); if (result != null) { return result; } } childPosition += childAtomSize; } return null; } /* package */ static Pair<Integer, TrackEncryptionBox> parseCommonEncryptionSinfFromParent( ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; int schemeInformationBoxPosition = C.POSITION_UNSET; int schemeInformationBoxSize = 0; String schemeType = null; Integer dataFormat = null; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_frma) { dataFormat = parent.readInt(); } else if (childAtomType == Atom.TYPE_schm) { parent.skipBytes(4); // Common encryption scheme_type values are defined in ISO/IEC 23001-7:2016, section 4.1. schemeType = parent.readString(4); } else if (childAtomType == Atom.TYPE_schi) { schemeInformationBoxPosition = childPosition; schemeInformationBoxSize = childAtomSize; } childPosition += childAtomSize; } if (C.CENC_TYPE_cenc.equals(schemeType) || C.CENC_TYPE_cbc1.equals(schemeType) || C.CENC_TYPE_cens.equals(schemeType) || C.CENC_TYPE_cbcs.equals(schemeType)) { Assertions.checkArgument(dataFormat != null, "frma atom is mandatory"); Assertions.checkArgument(schemeInformationBoxPosition != C.POSITION_UNSET, "schi atom is mandatory"); TrackEncryptionBox encryptionBox = parseSchiFromParent(parent, schemeInformationBoxPosition, schemeInformationBoxSize, schemeType); Assertions.checkArgument(encryptionBox != null, "tenc atom is mandatory"); return Pair.create(dataFormat, encryptionBox); } else { return null; } } private static TrackEncryptionBox parseSchiFromParent(ParsableByteArray parent, int position, int size, String schemeType) { int childPosition = position + Atom.HEADER_SIZE; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_tenc) { int fullAtom = parent.readInt(); int version = Atom.parseFullAtomVersion(fullAtom); parent.skipBytes(1); // reserved = 0. int defaultCryptByteBlock = 0; int defaultSkipByteBlock = 0; if (version == 0) { parent.skipBytes(1); // reserved = 0. } else /* version 1 or greater */ { int patternByte = parent.readUnsignedByte(); defaultCryptByteBlock = (patternByte & 0xF0) >> 4; defaultSkipByteBlock = patternByte & 0x0F; } boolean defaultIsProtected = parent.readUnsignedByte() == 1; int defaultPerSampleIvSize = parent.readUnsignedByte(); byte[] defaultKeyId = new byte[16]; parent.readBytes(defaultKeyId, 0, defaultKeyId.length); byte[] constantIv = null; if (defaultIsProtected && defaultPerSampleIvSize == 0) { int constantIvSize = parent.readUnsignedByte(); constantIv = new byte[constantIvSize]; parent.readBytes(constantIv, 0, constantIvSize); } return new TrackEncryptionBox(defaultIsProtected, schemeType, defaultPerSampleIvSize, defaultKeyId, defaultCryptByteBlock, defaultSkipByteBlock, constantIv); } childPosition += childAtomSize; } return null; } /** * Parses the proj box from sv3d box, as specified by https://github.com/google/spatial-media. */ private static byte[] parseProjFromParent(ParsableByteArray parent, int position, int size) { int childPosition = position + Atom.HEADER_SIZE; while (childPosition - position < size) { parent.setPosition(childPosition); int childAtomSize = parent.readInt(); int childAtomType = parent.readInt(); if (childAtomType == Atom.TYPE_proj) { return Arrays.copyOfRange(parent.data, childPosition, childPosition + childAtomSize); } childPosition += childAtomSize; } return null; } /** * Parses the size of an expandable class, as specified by ISO 14496-1 subsection 8.3.3. */ private static int parseExpandableClassSize(ParsableByteArray data) { int currentByte = data.readUnsignedByte(); int size = currentByte & 0x7F; while ((currentByte & 0x80) == 0x80) { currentByte = data.readUnsignedByte(); size = (size << 7) | (currentByte & 0x7F); } return size; } /** Returns whether it's possible to apply the specified edit using gapless playback info. */ private static boolean canApplyEditWithGaplessInfo( long[] timestamps, long duration, long editStartTime, long editEndTime) { int lastIndex = timestamps.length - 1; int latestDelayIndex = Util.constrainValue(MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex); int earliestPaddingIndex = Util.constrainValue(timestamps.length - MAX_GAPLESS_TRIM_SIZE_SAMPLES, 0, lastIndex); return timestamps[0] <= editStartTime && editStartTime < timestamps[latestDelayIndex] && timestamps[earliestPaddingIndex] < editEndTime && editEndTime <= duration; } private AtomParsers() { // Prevent instantiation. } private static final class ChunkIterator { public final int length; public int index; public int numSamples; public long offset; private final boolean chunkOffsetsAreLongs; private final ParsableByteArray chunkOffsets; private final ParsableByteArray stsc; private int nextSamplesPerChunkChangeIndex; private int remainingSamplesPerChunkChanges; public ChunkIterator(ParsableByteArray stsc, ParsableByteArray chunkOffsets, boolean chunkOffsetsAreLongs) { this.stsc = stsc; this.chunkOffsets = chunkOffsets; this.chunkOffsetsAreLongs = chunkOffsetsAreLongs; chunkOffsets.setPosition(Atom.FULL_HEADER_SIZE); length = chunkOffsets.readUnsignedIntToInt(); stsc.setPosition(Atom.FULL_HEADER_SIZE); remainingSamplesPerChunkChanges = stsc.readUnsignedIntToInt(); Assertions.checkState(stsc.readInt() == 1, "first_chunk must be 1"); index = -1; } public boolean moveNext() { if (++index == length) { return false; } offset = chunkOffsetsAreLongs ? chunkOffsets.readUnsignedLongToLong() : chunkOffsets.readUnsignedInt(); if (index == nextSamplesPerChunkChangeIndex) { numSamples = stsc.readUnsignedIntToInt(); stsc.skipBytes(4); // Skip sample_description_index nextSamplesPerChunkChangeIndex = --remainingSamplesPerChunkChanges > 0 ? (stsc.readUnsignedIntToInt() - 1) : C.INDEX_UNSET; } return true; } } /** * Holds data parsed from a tkhd atom. */ private static final class TkhdData { private final int id; private final long duration; private final int rotationDegrees; public TkhdData(int id, long duration, int rotationDegrees) { this.id = id; this.duration = duration; this.rotationDegrees = rotationDegrees; } } /** * Holds data parsed from an stsd atom and its children. */ private static final class StsdData { public static final int STSD_HEADER_SIZE = 8; public final TrackEncryptionBox[] trackEncryptionBoxes; public Format format; public int nalUnitLengthFieldLength; @Track.Transformation public int requiredSampleTransformation; public StsdData(int numberOfEntries) { trackEncryptionBoxes = new TrackEncryptionBox[numberOfEntries]; requiredSampleTransformation = Track.TRANSFORMATION_NONE; } } /** * A box containing sample sizes (e.g. stsz, stz2). */ private interface SampleSizeBox { /** * Returns the number of samples. */ int getSampleCount(); /** * Returns the size for the next sample. */ int readNextSampleSize(); /** * Returns whether samples have a fixed size. */ boolean isFixedSampleSize(); } /** * An stsz sample size box. */ /* package */ static final class StszSampleSizeBox implements SampleSizeBox { private final int fixedSampleSize; private final int sampleCount; private final ParsableByteArray data; public StszSampleSizeBox(Atom.LeafAtom stszAtom) { data = stszAtom.data; data.setPosition(Atom.FULL_HEADER_SIZE); fixedSampleSize = data.readUnsignedIntToInt(); sampleCount = data.readUnsignedIntToInt(); } @Override public int getSampleCount() { return sampleCount; } @Override public int readNextSampleSize() { return fixedSampleSize == 0 ? data.readUnsignedIntToInt() : fixedSampleSize; } @Override public boolean isFixedSampleSize() { return fixedSampleSize != 0; } } /** * An stz2 sample size box. */ /* package */ static final class Stz2SampleSizeBox implements SampleSizeBox { private final ParsableByteArray data; private final int sampleCount; private final int fieldSize; // Can be 4, 8, or 16. // Used only if fieldSize == 4. private int sampleIndex; private int currentByte; public Stz2SampleSizeBox(Atom.LeafAtom stz2Atom) { data = stz2Atom.data; data.setPosition(Atom.FULL_HEADER_SIZE); fieldSize = data.readUnsignedIntToInt() & 0x000000FF; sampleCount = data.readUnsignedIntToInt(); } @Override public int getSampleCount() { return sampleCount; } @Override public int readNextSampleSize() { if (fieldSize == 8) { return data.readUnsignedByte(); } else if (fieldSize == 16) { return data.readUnsignedShort(); } else { // fieldSize == 4. if ((sampleIndex++ % 2) == 0) { // Read the next byte into our cached byte when we are reading the upper bits. currentByte = data.readUnsignedByte(); // Read the upper bits from the byte and shift them to the lower 4 bits. return (currentByte & 0xF0) >> 4; } else { // Mask out the upper 4 bits of the last byte we read. return currentByte & 0x0F; } } } @Override public boolean isFixedSampleSize() { return false; } } }
Increase gapless trim sample count PiperOrigin-RevId: 247348352
library/core/src/main/java/com/google/android/exoplayer2/extractor/mp4/AtomParsers.java
Increase gapless trim sample count
Java
apache-2.0
c78527989c312e02cadb6595c876613eec37c1fd
0
Tom-Willemsen/PicoBramble,Tom-Willemsen/PicoBramble,Tom-Willemsen/PicoBramble
package bramble.node.controller; import java.util.ArrayList; import java.util.Collection; import bramble.networking.JobMetadata; public class JobList { private ArrayList<JobMetadata> unstartedJobs; private ArrayList<JobMetadata> startedJobs; private ArrayList<JobMetadata> completedJobs; /** * Initializes an empty job list. */ public JobList(){ this.unstartedJobs = new ArrayList<>(); this.startedJobs = new ArrayList<>(); this.completedJobs = new ArrayList<>(); } /** * Sets all the jobs to be contained in this list. * @param allJobNumbers all of the job numbers */ public synchronized void setUnstartedJobs(Collection<Integer> allJobNumbers) { for(Integer jobNumber : allJobNumbers){ JobMetadata job = new JobMetadata(jobNumber); if(!isJobInAnyList(job)){ unstartedJobs.add(job); } } } private boolean isJobInAnyList(final JobMetadata job){ if(unstartedJobs.contains(job)){ return true; } if(startedJobs.contains(job)){ return true; } if(completedJobs.contains(job)){ return true; } return false; } /** * Gets all the jobs that this controller node has. * @return all the jobs that this controller node has */ public int getTotalNumberOfJobs(){ return unstartedJobs.size() + startedJobs.size() + completedJobs.size(); } /** * Gets all the jobs that have been completed. * @return all the jobs that have been completed */ public int getNumberOfCompletedJobs(){ return completedJobs.size(); } /** * Gets all the jobs which have been started, including completed ones. * @return all the jobs which have been started, including completed ones */ public int getNumberOfJobsInProgress(){ return startedJobs.size(); } /** * Gets whether all the jobs have been completed. * @return true if all jobs are complete, false otherwise */ public boolean areAllJobsFinished(){ if(unstartedJobs.size() == 0 && startedJobs.size() == 0){ return true; } return false; } /** * Gets the job identifier of the next job that should be run. * @return the job identifier of the next job that should be run * or null if there are no suitable jobs */ public synchronized JobMetadata getNextJob(){ try{ return unstartedJobs.get(0); } catch (IndexOutOfBoundsException ex){ return null; } } /** * Cancels a job. * @param job the job to cancel */ public synchronized void cancelJob(final JobMetadata job) { startedJobs.remove(job); unstartedJobs.add(job); } /** * Marks a job as completed. * @param job the job that is complete */ public synchronized void jobCompleted(final JobMetadata job) { startedJobs.remove(job); completedJobs.add(job); } /** * Marks a job as started. * @param job the job that has been started */ public synchronized void jobStarted(final JobMetadata job) { unstartedJobs.remove(job); startedJobs.add(job); } }
PicoBramble/src/bramble/node/controller/JobList.java
package bramble.node.controller; import java.util.ArrayList; import java.util.Collection; import bramble.networking.JobMetadata; public class JobList { private ArrayList<JobMetadata> unstartedJobs; private ArrayList<JobMetadata> startedJobs; private ArrayList<JobMetadata> completedJobs; /** * Initializes an empty job list. */ public JobList(){ this.unstartedJobs = new ArrayList<>(); this.startedJobs = new ArrayList<>(); this.completedJobs = new ArrayList<>(); } /** * Sets all the jobs to be contained in this list. * @param allJobNumbers all of the job numbers */ public synchronized void setUnstartedJobs(Collection<Integer> allJobNumbers) { for(Integer jobNumber : allJobNumbers){ JobMetadata job = new JobMetadata(jobNumber); if(!isJobInAnyList(job)){ unstartedJobs.add(job); } } } private boolean isJobInAnyList(final JobMetadata job){ if(unstartedJobs.contains(job)){ return true; } if(startedJobs.contains(job)){ return true; } if(completedJobs.contains(job)){ return true; } return false; } /** * Gets all the jobs that this controller node has. * @return all the jobs that this controller node has */ public int getTotalNumberOfJobs(){ return unstartedJobs.size() + startedJobs.size() + completedJobs.size(); } /** * Gets all the jobs that have been completed. * @return all the jobs that have been completed */ public int getNumberOfCompletedJobs(){ return completedJobs.size(); } /** * Gets all the jobs which have been started, including completed ones. * @return all the jobs which have been started, including completed ones */ public int getNumberOfJobsInProgress(){ return startedJobs.size(); } /** * Gets whether all the jobs have been completed. * @return true if all jobs are complete, false otherwise */ public boolean areAllJobsFinished(){ if(unstartedJobs.size() == 0 && startedJobs.size() == 0){ return true; } return false; } /** * Gets the job identifier of the next job that should be run. * @return the job identifier of the next job that should be run * or null if there are no suitable jobs */ public synchronized JobMetadata getNextJob(){ try{ return unstartedJobs.get(0); } catch (IndexOutOfBoundsException ex){ return null; } } /** * Cancels a job. * @param job the job to cancel */ public synchronized void cancelJob(final JobMetadata job) { startedJobs.remove(job); unstartedJobs.add(job); } /** * Marks a job as completed. * @param job the job that is complete */ public synchronized void jobCompleted(final JobMetadata job) { startedJobs.remove(job); completedJobs.add(job); } /** * Marks a job as started. * @param job the job that has been started */ public synchronized void jobStarted(final JobMetadata job) { unstartedJobs.remove(job); startedJobs.add(job); } }
Fix indentation
PicoBramble/src/bramble/node/controller/JobList.java
Fix indentation
Java
apache-2.0
a67848676be61fcdd77e35c25b205080a5dc0de5
0
gbif/occurrence,gbif/occurrence,gbif/occurrence
package org.gbif.occurrence.download.hive; import org.apache.commons.lang3.tuple.Pair; import org.gbif.dwc.terms.DcTerm; import org.gbif.dwc.terms.DwcTerm; import org.gbif.dwc.terms.GbifInternalTerm; import org.gbif.dwc.terms.GbifTerm; import org.gbif.dwc.terms.Term; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.gbif.occurrence.common.TermUtils; /** * Definitions of terms used in downloading, and in create tables used during the download process. */ public class DownloadTerms { /** * Whether the term is from the verbatim fields, or the interpreted fields. */ public enum Group { VERBATIM, INTERPRETED } // This list of exclusion is used for the download query only // Ensure it corresponds with org.gbif.occurrence.download.util.HeadersFileUtil! public static final Set<Term> EXCLUSIONS_INTERPRETED = ImmutableSet.of( GbifTerm.gbifID, // returned multiple times, so excluded and treated by adding once at the beginning GbifInternalTerm.fragmentHash, // omitted entirely GbifInternalTerm.fragment, // omitted entirely GbifTerm.numberOfOccurrences, //this is for aggregation only GbifInternalTerm.hostingOrganizationKey //temporary removing this term since it is not populated ); // This set is used fot the HDFS table definition public static final Set<Term> EXCLUSIONS = new ImmutableSet.Builder<Term>() .addAll(EXCLUSIONS_INTERPRETED) .add(GbifTerm.verbatimScientificName).build(); public static final Set<Term> DOWNLOAD_INTERPRETED_TERMS_HDFS = Sets.difference(ImmutableSet.copyOf(TermUtils.interpretedTerms()), EXCLUSIONS).immutableCopy(); public static final Set<Term> DOWNLOAD_INTERPRETED_TERMS = Sets.difference(ImmutableSet.copyOf(TermUtils.interpretedTerms()), EXCLUSIONS_INTERPRETED).immutableCopy(); public static final Set<Term> DOWNLOAD_VERBATIM_TERMS = Sets.difference(ImmutableSet.copyOf(TermUtils.verbatimTerms()), EXCLUSIONS).immutableCopy(); /** * The terms that will be included in the interpreted table if also present in ${@link * org.gbif.occurrence.common.TermUtils#interpretedTerms()} */ public static final Set<Pair<Group, Term>> SIMPLE_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.gbifID), Pair.of(Group.INTERPRETED, GbifTerm.datasetKey), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceID), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, DwcTerm.infraspecificEpithet), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.VERBATIM, DwcTerm.scientificName), Pair.of(Group.VERBATIM, DwcTerm.scientificNameAuthorship), Pair.of(Group.INTERPRETED, DwcTerm.countryCode), Pair.of(Group.INTERPRETED, DwcTerm.locality), Pair.of(Group.INTERPRETED, DwcTerm.stateProvince), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceStatus), Pair.of(Group.INTERPRETED, DwcTerm.individualCount), Pair.of(Group.INTERPRETED, GbifInternalTerm.publishingOrgKey), Pair.of(Group.INTERPRETED, DwcTerm.decimalLatitude), Pair.of(Group.INTERPRETED, DwcTerm.decimalLongitude), Pair.of(Group.INTERPRETED, DwcTerm.coordinateUncertaintyInMeters), Pair.of(Group.INTERPRETED, DwcTerm.coordinatePrecision), Pair.of(Group.INTERPRETED, GbifTerm.elevation), Pair.of(Group.INTERPRETED, GbifTerm.elevationAccuracy), Pair.of(Group.INTERPRETED, GbifTerm.depth), Pair.of(Group.INTERPRETED, GbifTerm.depthAccuracy), Pair.of(Group.INTERPRETED, DwcTerm.eventDate), Pair.of(Group.INTERPRETED, DwcTerm.day), Pair.of(Group.INTERPRETED, DwcTerm.month), Pair.of(Group.INTERPRETED, DwcTerm.year), Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey), Pair.of(Group.INTERPRETED, DwcTerm.basisOfRecord), Pair.of(Group.INTERPRETED, DwcTerm.institutionCode), Pair.of(Group.INTERPRETED, DwcTerm.collectionCode), Pair.of(Group.INTERPRETED, DwcTerm.catalogNumber), Pair.of(Group.INTERPRETED, DwcTerm.recordNumber), Pair.of(Group.INTERPRETED, DwcTerm.identifiedBy), Pair.of(Group.INTERPRETED, DwcTerm.dateIdentified), Pair.of(Group.INTERPRETED, DcTerm.license), Pair.of(Group.INTERPRETED, DcTerm.rightsHolder), Pair.of(Group.INTERPRETED, DwcTerm.recordedBy), Pair.of(Group.INTERPRETED, DwcTerm.typeStatus), Pair.of(Group.INTERPRETED, DwcTerm.establishmentMeans), Pair.of(Group.INTERPRETED, GbifTerm.lastInterpreted), Pair.of(Group.INTERPRETED, GbifTerm.mediaType), Pair.of(Group.INTERPRETED, GbifTerm.issue) ); /** * The additional terms that will be included in the SIMPLE_WITH_VERBATIM_AVRO download */ private static final Set<Pair<Group, Term>> ADDITIONAL_SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.publishingCountry)); /** * The terms that will be included in the SIMPLE_WITH_VERBATIM_AVRO download */ public static final Set<Pair<Group, Term>> SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS = Sets.union( SIMPLE_DOWNLOAD_TERMS, ADDITIONAL_SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS).immutableCopy(); /** * The terms that will be included in the species list */ public static final Set<Pair<Group, Term>> SPECIES_LIST_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.gbifID), Pair.of(Group.INTERPRETED, GbifTerm.datasetKey), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceID), Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedTaxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedScientificName), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.taxonomicStatus), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey), Pair.of(Group.INTERPRETED, DcTerm.license) ); /** * The terms that will be included in the species list for downloads */ public static final Set<Pair<Group, Term>> SPECIES_LIST_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.INTERPRETED, GbifTerm.acceptedTaxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedScientificName), Pair.of(Group.INTERPRETED, GbifTerm.numberOfOccurrences), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.taxonomicStatus), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey) ); /** * GBIF-Internal terms */ public static final Set<Term> INTERNAL_DOWNLOAD_TERMS = ImmutableSet.of( GbifInternalTerm.publishingOrgKey ); public static String simpleName(Pair<Group, Term> termPair) { Term term = termPair.getRight(); if (termPair.getLeft().equals(Group.VERBATIM)) { return "verbatim" + Character.toUpperCase(term.simpleName().charAt(0)) + term.simpleName().substring(1); } else { return term.simpleName(); } } }
occurrence-hdfs-table/src/main/java/org/gbif/occurrence/download/hive/DownloadTerms.java
package org.gbif.occurrence.download.hive; import org.apache.commons.lang3.tuple.Pair; import org.gbif.dwc.terms.DcTerm; import org.gbif.dwc.terms.DwcTerm; import org.gbif.dwc.terms.GbifInternalTerm; import org.gbif.dwc.terms.GbifTerm; import org.gbif.dwc.terms.Term; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.gbif.occurrence.common.TermUtils; /** * Definitions of terms used in downloading, and in create tables used during the download process. */ public class DownloadTerms { /** * Whether the term is from the verbatim fields, or the interpreted fields. */ public enum Group { VERBATIM, INTERPRETED } // This list of exclusion is used for the download query only // Ensure it corresponds with org.gbif.occurrence.download.util.HeadersFileUtil! public static final Set<Term> EXCLUSIONS_INTERPRETED = ImmutableSet.of( GbifTerm.gbifID, // returned multiple times, so excluded and treated by adding once at the beginning GbifInternalTerm.fragmentHash, // omitted entirely GbifInternalTerm.fragment, // omitted entirely GbifTerm.numberOfOccurrences //this is for aggregation only ); // This set is used fot the HDFS table definition public static final Set<Term> EXCLUSIONS = new ImmutableSet.Builder<Term>() .addAll(EXCLUSIONS_INTERPRETED) .add(GbifTerm.verbatimScientificName).build(); public static final Set<Term> DOWNLOAD_INTERPRETED_TERMS_HDFS = Sets.difference(ImmutableSet.copyOf(TermUtils.interpretedTerms()), EXCLUSIONS).immutableCopy(); public static final Set<Term> DOWNLOAD_INTERPRETED_TERMS = Sets.difference(ImmutableSet.copyOf(TermUtils.interpretedTerms()), EXCLUSIONS_INTERPRETED).immutableCopy(); public static final Set<Term> DOWNLOAD_VERBATIM_TERMS = Sets.difference(ImmutableSet.copyOf(TermUtils.verbatimTerms()), EXCLUSIONS).immutableCopy(); /** * The terms that will be included in the interpreted table if also present in ${@link * org.gbif.occurrence.common.TermUtils#interpretedTerms()} */ public static final Set<Pair<Group, Term>> SIMPLE_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.gbifID), Pair.of(Group.INTERPRETED, GbifTerm.datasetKey), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceID), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, DwcTerm.infraspecificEpithet), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.VERBATIM, DwcTerm.scientificName), Pair.of(Group.VERBATIM, DwcTerm.scientificNameAuthorship), Pair.of(Group.INTERPRETED, DwcTerm.countryCode), Pair.of(Group.INTERPRETED, DwcTerm.locality), Pair.of(Group.INTERPRETED, DwcTerm.stateProvince), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceStatus), Pair.of(Group.INTERPRETED, DwcTerm.individualCount), Pair.of(Group.INTERPRETED, GbifInternalTerm.publishingOrgKey), Pair.of(Group.INTERPRETED, DwcTerm.decimalLatitude), Pair.of(Group.INTERPRETED, DwcTerm.decimalLongitude), Pair.of(Group.INTERPRETED, DwcTerm.coordinateUncertaintyInMeters), Pair.of(Group.INTERPRETED, DwcTerm.coordinatePrecision), Pair.of(Group.INTERPRETED, GbifTerm.elevation), Pair.of(Group.INTERPRETED, GbifTerm.elevationAccuracy), Pair.of(Group.INTERPRETED, GbifTerm.depth), Pair.of(Group.INTERPRETED, GbifTerm.depthAccuracy), Pair.of(Group.INTERPRETED, DwcTerm.eventDate), Pair.of(Group.INTERPRETED, DwcTerm.day), Pair.of(Group.INTERPRETED, DwcTerm.month), Pair.of(Group.INTERPRETED, DwcTerm.year), Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey), Pair.of(Group.INTERPRETED, DwcTerm.basisOfRecord), Pair.of(Group.INTERPRETED, DwcTerm.institutionCode), Pair.of(Group.INTERPRETED, DwcTerm.collectionCode), Pair.of(Group.INTERPRETED, DwcTerm.catalogNumber), Pair.of(Group.INTERPRETED, DwcTerm.recordNumber), Pair.of(Group.INTERPRETED, DwcTerm.identifiedBy), Pair.of(Group.INTERPRETED, DwcTerm.dateIdentified), Pair.of(Group.INTERPRETED, DcTerm.license), Pair.of(Group.INTERPRETED, DcTerm.rightsHolder), Pair.of(Group.INTERPRETED, DwcTerm.recordedBy), Pair.of(Group.INTERPRETED, DwcTerm.typeStatus), Pair.of(Group.INTERPRETED, DwcTerm.establishmentMeans), Pair.of(Group.INTERPRETED, GbifTerm.lastInterpreted), Pair.of(Group.INTERPRETED, GbifTerm.mediaType), Pair.of(Group.INTERPRETED, GbifTerm.issue) ); /** * The additional terms that will be included in the SIMPLE_WITH_VERBATIM_AVRO download */ private static final Set<Pair<Group, Term>> ADDITIONAL_SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.publishingCountry)); /** * The terms that will be included in the SIMPLE_WITH_VERBATIM_AVRO download */ public static final Set<Pair<Group, Term>> SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS = Sets.union( SIMPLE_DOWNLOAD_TERMS, ADDITIONAL_SIMPLE_WITH_VERBATIM_DOWNLOAD_TERMS).immutableCopy(); /** * The terms that will be included in the species list */ public static final Set<Pair<Group, Term>> SPECIES_LIST_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.gbifID), Pair.of(Group.INTERPRETED, GbifTerm.datasetKey), Pair.of(Group.INTERPRETED, DwcTerm.occurrenceID), Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedTaxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedScientificName), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.taxonomicStatus), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey), Pair.of(Group.INTERPRETED, DcTerm.license) ); /** * The terms that will be included in the species list for downloads */ public static final Set<Pair<Group, Term>> SPECIES_LIST_DOWNLOAD_TERMS = ImmutableSet.of( Pair.of(Group.INTERPRETED, GbifTerm.taxonKey), Pair.of(Group.INTERPRETED, DwcTerm.scientificName), Pair.of(Group.INTERPRETED, GbifTerm.acceptedTaxonKey), Pair.of(Group.INTERPRETED, GbifTerm.acceptedScientificName), Pair.of(Group.INTERPRETED, GbifTerm.numberOfOccurrences), Pair.of(Group.INTERPRETED, DwcTerm.taxonRank), Pair.of(Group.INTERPRETED, DwcTerm.taxonomicStatus), Pair.of(Group.INTERPRETED, DwcTerm.kingdom), Pair.of(Group.INTERPRETED, GbifTerm.kingdomKey), Pair.of(Group.INTERPRETED, DwcTerm.phylum), Pair.of(Group.INTERPRETED, GbifTerm.phylumKey), Pair.of(Group.INTERPRETED, DwcTerm.class_), Pair.of(Group.INTERPRETED, GbifTerm.classKey), Pair.of(Group.INTERPRETED, DwcTerm.order), Pair.of(Group.INTERPRETED, GbifTerm.orderKey), Pair.of(Group.INTERPRETED, DwcTerm.family), Pair.of(Group.INTERPRETED, GbifTerm.familyKey), Pair.of(Group.INTERPRETED, DwcTerm.genus), Pair.of(Group.INTERPRETED, GbifTerm.genusKey), Pair.of(Group.INTERPRETED, GbifTerm.species), Pair.of(Group.INTERPRETED, GbifTerm.speciesKey) ); /** * GBIF-Internal terms */ public static final Set<Term> INTERNAL_DOWNLOAD_TERMS = ImmutableSet.of( GbifInternalTerm.publishingOrgKey ); public static String simpleName(Pair<Group, Term> termPair) { Term term = termPair.getRight(); if (termPair.getLeft().equals(Group.VERBATIM)) { return "verbatim" + Character.toUpperCase(term.simpleName().charAt(0)) + term.simpleName().substring(1); } else { return term.simpleName(); } } }
excluding hostingOrganizationKey from downloads until it is populated
occurrence-hdfs-table/src/main/java/org/gbif/occurrence/download/hive/DownloadTerms.java
excluding hostingOrganizationKey from downloads until it is populated
Java
apache-2.0
17a6ccf4d8994fb590dd7d409d2d81ebbfd80433
0
SPBTV/DraggablePanel,tjose0101/Draggable-ui,Fiddl3/DraggablePanel,hoangsondev/DraggablePanel,FreeDao/DraggablePanel,ppamorim/DraggablePanel,hmit/DraggablePanel,frakc/DraggablePanel,Thornith/DraggablePanel,dfodor/DraggablePanel,MaTriXy/DraggablePanel,pedrovgs/DraggablePanel,murat8505/DraggablePanel,qiwx2012/DraggablePanel
package com.github.pedrovgs.sample.viewmodel; import com.pedrogomez.renderers.AdapteeCollection; import javax.inject.Inject; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class TvShowCollectionViewModel implements AdapteeCollection<TvShowViewModel> { private final List<TvShowViewModel> tvShows; @Inject public TvShowCollectionViewModel() { this.tvShows = new LinkedList<TvShowViewModel>(); TvShowViewModel tvShow = new TvShowViewModel("Breaking Bad", "http://thetvdb.com/banners/_cache/posters/81189-22.jpg", 5); tvShow.addEpisode(new EpisodeViewModel("Pilot", "2008-01-20")); tvShow.addEpisode(new EpisodeViewModel("Cat's in the Bag...", "2008-01-27")); tvShow.addEpisode(new EpisodeViewModel("...And the Bag's in the River", "2008-02-10")); tvShow.addEpisode(new EpisodeViewModel("Cancer Man", "2008-02-17")); tvShow.addEpisode(new EpisodeViewModel("Gray Matter", "2008-02-24")); tvShow.addEpisode(new EpisodeViewModel("Crazy Handful of Nothin'", "2008-03-02")); tvShow.addEpisode(new EpisodeViewModel("A No-Rough-Stuff-Type Deal'", "2008-03-09")); tvShows.add(tvShow); tvShow = new TvShowViewModel("Marvel's Agents of S.H.I.E.L.D.", "http://thetvdb.com/banners/_cache/posters/263365-3.jpg", 1); tvShow.addEpisode(new EpisodeViewModel("Pilot", "2013-09-24")); tvShow.addEpisode(new EpisodeViewModel("0-8-4", "2013-10-01")); tvShow.addEpisode(new EpisodeViewModel("The Asset", "2013-10-08")); tvShow.addEpisode(new EpisodeViewModel("Eye Spy", "2013-10-15")); tvShow.addEpisode(new EpisodeViewModel("Girl in the Flower Dress", "2013-10-22")); tvShow.addEpisode(new EpisodeViewModel("F.Z.Z.T.", "2013-11-05")); tvShow.addEpisode(new EpisodeViewModel("The Hub", "2013-11-12")); tvShow.addEpisode(new EpisodeViewModel("The Well", "2013-11-19")); tvShow.addEpisode(new EpisodeViewModel("Repairs", "2013-11-26")); tvShow.addEpisode(new EpisodeViewModel("The Bridge", "2013-12-10")); tvShow.addEpisode(new EpisodeViewModel("The Magical Place", "2014-01-07")); tvShow.addEpisode(new EpisodeViewModel("Seeds", "2014-01-14")); tvShow.addEpisode(new EpisodeViewModel("T.R.A.C.K.S.", "2014-02-04")); tvShow.addEpisode(new EpisodeViewModel("T.A.H.I.T.I.", "2014-03-04")); tvShow.addEpisode(new EpisodeViewModel("Yes Men", "2014-03-11")); tvShow.addEpisode(new EpisodeViewModel("End of the Beginning", "2014-04-01")); tvShow.addEpisode(new EpisodeViewModel("Turn, Turn, Turn", "2014-04-08")); tvShow.addEpisode(new EpisodeViewModel("Providence", "2014-04-15")); tvShows.add(tvShow); tvShow = new TvShowViewModel("Lost", "http://thetvdb.com/banners/_cache/posters/73739-7.jpg", 6); tvShow.addEpisode(new EpisodeViewModel("Pilot (1)", "2004-09-22")); tvShow.addEpisode(new EpisodeViewModel("Pilot (2)", "2004-09-29")); tvShow.addEpisode(new EpisodeViewModel("Tabula Rasa", "2004-10-06")); tvShow.addEpisode(new EpisodeViewModel("Walkabout", "2004-10-13")); tvShow.addEpisode(new EpisodeViewModel("White Rabbit", "2004-10-20")); tvShow.addEpisode(new EpisodeViewModel("House of the Rising Sun", "2004-10-27")); tvShow.addEpisode(new EpisodeViewModel("The Moth", "2004-11-03")); tvShow.addEpisode(new EpisodeViewModel("Confidence Man", "2004-11-10")); tvShow.addEpisode(new EpisodeViewModel("Solitary", "2004-11-17")); tvShow.addEpisode(new EpisodeViewModel("Raised by Another", "2004-12-01")); tvShow.addEpisode(new EpisodeViewModel("All the Best Cowboys Have Daddy Issues", "2004-12-08")); tvShow.addEpisode(new EpisodeViewModel("Whatever the Case May Be the Case May Be", "2005-01-05")); tvShow.addEpisode(new EpisodeViewModel("Hearts and Minds", "2005-01-12")); tvShow.addEpisode(new EpisodeViewModel("Special", "2005-01-19")); tvShow.addEpisode(new EpisodeViewModel("Homecoming", "2005-02-09")); tvShow.addEpisode(new EpisodeViewModel("Outlaws", "2005-02-16")); tvShow.addEpisode(new EpisodeViewModel("...In Translation", "2005-02-23")); tvShow.addEpisode(new EpisodeViewModel("Numbers", "2005-03-02")); tvShow.addEpisode(new EpisodeViewModel("Deus Ex Machina", "2005-03-30")); tvShow.addEpisode(new EpisodeViewModel("Do No Harm", "2005-04-06")); tvShow.addEpisode(new EpisodeViewModel("The Greater Good (a.k.a. Sides)", "2005-05-04")); tvShow.addEpisode(new EpisodeViewModel("Born to Run", "2005-05-11")); tvShow.addEpisode(new EpisodeViewModel("Exodus (1)", "2005-05-18")); tvShow.addEpisode(new EpisodeViewModel("Exodus (2)", "2005-05-25")); tvShows.add(tvShow); tvShow = new TvShowViewModel("Arrow", "http://thetvdb.com/banners/_cache/posters/257655-5.jpg", 2); tvShow.addEpisode(new EpisodeViewModel("Pilot", "2012-10-10")); tvShow.addEpisode(new EpisodeViewModel("Honor Thy Father", "2012-10-17")); tvShow.addEpisode(new EpisodeViewModel("Lone Gunmen", "2012-10-24")); tvShow.addEpisode(new EpisodeViewModel("An Innocent Man", "2012-10-31")); tvShow.addEpisode(new EpisodeViewModel("Damaged", "2012-11-07")); tvShow.addEpisode(new EpisodeViewModel("Legacies", "b2012-11-14")); tvShow.addEpisode(new EpisodeViewModel("Muse of Fire", "2012-11-28")); tvShow.addEpisode(new EpisodeViewModel("Vendetta", "2012-12-05")); tvShow.addEpisode(new EpisodeViewModel("Year's End", "2012-12-12")); tvShow.addEpisode(new EpisodeViewModel("Burned", "2013-01-16")); tvShow.addEpisode(new EpisodeViewModel("Trust But Verify", "2013-01-23")); tvShow.addEpisode(new EpisodeViewModel("Vertigo", "2013-02-06")); tvShow.addEpisode(new EpisodeViewModel("Betrayal", "2013-02-06")); tvShow.addEpisode(new EpisodeViewModel("The Odyssey", "2013-02-13")); tvShow.addEpisode(new EpisodeViewModel("Dodger", "2013-02-20")); tvShow.addEpisode(new EpisodeViewModel("Dead to Rights", "2013-02-27")); tvShow.addEpisode(new EpisodeViewModel("The Huntress Returns", "2013-03-20")); tvShow.addEpisode(new EpisodeViewModel("Salvation", "2013-03-27")); tvShow.addEpisode(new EpisodeViewModel("Unfinished Business", "2013-04-03")); tvShow.addEpisode(new EpisodeViewModel("Home Invasion", "2013-04-24")); tvShow.addEpisode(new EpisodeViewModel("The Undertaking", "2013-05-01")); tvShow.addEpisode(new EpisodeViewModel("Darkness on the Edge of Town", "2013-05-08")); tvShow.addEpisode(new EpisodeViewModel("Sacrifice", "2013-05-15")); tvShows.add(tvShow); } @Override public int size() { return tvShows.size(); } @Override public TvShowViewModel get(int i) { return tvShows.get(i); } @Override public void add(TvShowViewModel tvShowViewModel) { tvShows.add(tvShowViewModel); } @Override public void remove(TvShowViewModel tvShowViewModel) { tvShows.remove(tvShowViewModel); } @Override public void addAll(Collection<TvShowViewModel> tvShowViewModels) { tvShows.addAll(tvShowViewModels); } @Override public void removeAll(Collection<TvShowViewModel> tvShowViewModels) { tvShowViewModels.removeAll(tvShowViewModels); } }
sample/src/main/java/com/github/pedrovgs/sample/viewmodel/TvShowCollectionViewModel.java
package com.github.pedrovgs.sample.viewmodel; import com.pedrogomez.renderers.AdapteeCollection; import javax.inject.Inject; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class TvShowCollectionViewModel implements AdapteeCollection<TvShowViewModel> { private final List<TvShowViewModel> tvShows; @Inject public TvShowCollectionViewModel() { this.tvShows = new LinkedList<TvShowViewModel>(); TvShowViewModel tvShow = new TvShowViewModel("Breaking Bad", "http://thetvdb.com/banners/_cache/posters/81189-22.jpg", 5); tvShow.addEpisode(new EpisodeViewModel("Pilot", "2008-01-20")); tvShow.addEpisode(new EpisodeViewModel("Cat's in the Bag...", "2008-01-27")); tvShow.addEpisode(new EpisodeViewModel("...And the Bag's in the River", "2008-02-10")); tvShow.addEpisode(new EpisodeViewModel("Cancer Man", "2008-02-17")); tvShow.addEpisode(new EpisodeViewModel("Gray Matter", "2008-02-24")); tvShow.addEpisode(new EpisodeViewModel("Crazy Handful of Nothin'", "2008-03-02")); tvShow.addEpisode(new EpisodeViewModel("A No-Rough-Stuff-Type Deal'", "2008-03-09")); tvShows.add(tvShow); tvShow = new TvShowViewModel("Marvel's Agents of S.H.I.E.L.D.", "http://thetvdb.com/banners/_cache/posters/263365-3.jpg", 1); tvShow.addEpisode(new EpisodeViewModel("Pilot", "2013-09-24")); tvShow.addEpisode(new EpisodeViewModel("0-8-4", "2013-10-01")); tvShow.addEpisode(new EpisodeViewModel("The Asset", "2013-10-08")); tvShow.addEpisode(new EpisodeViewModel("Eye Spy", "2013-10-15")); tvShow.addEpisode(new EpisodeViewModel("Girl in the Flower Dress", "2013-10-22")); tvShow.addEpisode(new EpisodeViewModel("F.Z.Z.T.", "2013-11-05")); tvShow.addEpisode(new EpisodeViewModel("The Hub", "2013-11-12")); tvShow.addEpisode(new EpisodeViewModel("The Well", "2013-11-19")); tvShow.addEpisode(new EpisodeViewModel("Repairs", "2013-11-26")); tvShow.addEpisode(new EpisodeViewModel("The Bridge", "2013-12-10")); tvShow.addEpisode(new EpisodeViewModel("The Magical Place", "2014-01-07")); tvShow.addEpisode(new EpisodeViewModel("Seeds", "2014-01-14")); tvShow.addEpisode(new EpisodeViewModel("T.R.A.C.K.S.", "2014-02-04")); tvShow.addEpisode(new EpisodeViewModel("T.A.H.I.T.I.", "2014-03-04")); tvShow.addEpisode(new EpisodeViewModel("Yes Men", "2014-03-11")); tvShow.addEpisode(new EpisodeViewModel("End of the Beginning", "2014-04-01")); tvShow.addEpisode(new EpisodeViewModel("Turn, Turn, Turn", "2014-04-08")); tvShow.addEpisode(new EpisodeViewModel("Providence", "2014-04-15")); tvShows.add(tvShow); tvShow = new TvShowViewModel("Lost","http://thetvdb.com/banners/_cache/posters/73739-7.jpg",6); tvShow.addEpisode(new EpisodeViewModel("Pilot (1)","2004-09-22")); tvShow.addEpisode(new EpisodeViewModel("Pilot (2)","2004-09-29")); tvShow.addEpisode(new EpisodeViewModel("Tabula Rasa","2004-10-06")); tvShow.addEpisode(new EpisodeViewModel("Walkabout","2004-10-13")); tvShow.addEpisode(new EpisodeViewModel("White Rabbit","2004-10-20")); tvShow.addEpisode(new EpisodeViewModel("House of the Rising Sun","2004-10-27")); tvShow.addEpisode(new EpisodeViewModel("The Moth","2004-11-03")); tvShow.addEpisode(new EpisodeViewModel("Confidence Man","2004-11-10")); tvShow.addEpisode(new EpisodeViewModel("Solitary","2004-11-17")); tvShow.addEpisode(new EpisodeViewModel("Raised by Another","2004-12-01")); tvShow.addEpisode(new EpisodeViewModel("All the Best Cowboys Have Daddy Issues","2004-12-08")); tvShow.addEpisode(new EpisodeViewModel("Whatever the Case May Be the Case May Be","2005-01-05")); tvShow.addEpisode(new EpisodeViewModel("Hearts and Minds","2005-01-12")); tvShow.addEpisode(new EpisodeViewModel("Special","2005-01-19")); tvShow.addEpisode(new EpisodeViewModel("Homecoming","2005-02-09")); tvShow.addEpisode(new EpisodeViewModel("Outlaws","2005-02-16")); tvShow.addEpisode(new EpisodeViewModel("...In Translation","2005-02-23")); tvShow.addEpisode(new EpisodeViewModel("Numbers","2005-03-02")); tvShow.addEpisode(new EpisodeViewModel("Deus Ex Machina","2005-03-30")); tvShow.addEpisode(new EpisodeViewModel("Do No Harm","2005-04-06")); tvShow.addEpisode(new EpisodeViewModel("The Greater Good (a.k.a. Sides)","2005-05-04")); tvShow.addEpisode(new EpisodeViewModel("Born to Run","2005-05-11")); tvShow.addEpisode(new EpisodeViewModel("Exodus (1)","2005-05-18")); tvShow.addEpisode(new EpisodeViewModel("Exodus (2)","2005-05-25")); tvShows.add(tvShow); } @Override public int size() { return tvShows.size(); } @Override public TvShowViewModel get(int i) { return tvShows.get(i); } @Override public void add(TvShowViewModel tvShowViewModel) { tvShows.add(tvShowViewModel); } @Override public void remove(TvShowViewModel tvShowViewModel) { tvShows.remove(tvShowViewModel); } @Override public void addAll(Collection<TvShowViewModel> tvShowViewModels) { tvShows.addAll(tvShowViewModels); } @Override public void removeAll(Collection<TvShowViewModel> tvShowViewModels) { tvShowViewModels.removeAll(tvShowViewModels); } }
Add Arrow information
sample/src/main/java/com/github/pedrovgs/sample/viewmodel/TvShowCollectionViewModel.java
Add Arrow information
Java
apache-2.0
6de89118fabe6e660c581dd32628fe615051dc03
0
selckin/wicket,freiheit-com/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,freiheit-com/wicket,mosoft521/wicket,mosoft521/wicket,astrapi69/wicket,klopfdreh/wicket,astrapi69/wicket,klopfdreh/wicket,selckin/wicket,topicusonderwijs/wicket,freiheit-com/wicket,AlienQueen/wicket,mosoft521/wicket,dashorst/wicket,klopfdreh/wicket,dashorst/wicket,AlienQueen/wicket,klopfdreh/wicket,selckin/wicket,bitstorm/wicket,freiheit-com/wicket,topicusonderwijs/wicket,selckin/wicket,dashorst/wicket,bitstorm/wicket,topicusonderwijs/wicket,dashorst/wicket,apache/wicket,mosoft521/wicket,AlienQueen/wicket,AlienQueen/wicket,aldaris/wicket,bitstorm/wicket,dashorst/wicket,apache/wicket,aldaris/wicket,apache/wicket,bitstorm/wicket,apache/wicket,aldaris/wicket,bitstorm/wicket,klopfdreh/wicket,astrapi69/wicket,AlienQueen/wicket,freiheit-com/wicket,apache/wicket,mosoft521/wicket,aldaris/wicket,astrapi69/wicket,selckin/wicket,aldaris/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.util.iterator; import java.util.Iterator; import org.apache.wicket.util.collections.ArrayListStack; import org.apache.wicket.util.lang.Args; /** * This is a basic iterator for hierarchical structures such as Component hierarchies or HTML * markup. It supports child first and parent first traversal and intercepts while moving down or up * the hierarchy. * <p> * It assumes the container class implements <code>Iterable</code>. The leaf nodes don't need to. * <p> * Consecutive calls to <code>hasNext()</code> without <code>next()</code> in between, don't move * the cursor, but return the same value until <code>next()</code> is called. * <p> * Every call to <code>next()</code>, with or without <code>hasNext()</code>, will move the cursor * to the next element. * * @TODO Replace ChildFirst with a strategy * * @author Juergen Donnerstag * @param <I> * The type relevant for the iterator. What you expect to get back from next(), e.g. * Form. * @param <N> * The base type of all nodes, e.g. Component */ public abstract class AbstractHierarchyIterator<N, I extends N> implements Iterator<I>, Iterable<I> { // An iterator for each level we are down from root private ArrayListStack<LevelIterator<N>> stack = new ArrayListStack<>(); // The current level iterator private LevelIterator<N> data; // Whether we need to traverse into the next level with the next invocation of hasNext() private boolean traverse; // An easy way to configure child or parent first iterations private boolean childFirst; // If remaining siblings shall be ignored private boolean skipRemainingSiblings; // True, if hasNext() was called last or next() private boolean hasNextWasLast; /** * Construct. * * @param root */ public AbstractHierarchyIterator(final N root) { Args.notNull(root, "root"); if (hasChildren(root)) { data = new LevelIterator<>(root, newIterator(root)); } } /** * * @param childFirst * If true, than children are visited before their parent is. */ public final void setChildFirst(final boolean childFirst) { this.childFirst = childFirst; } /** * * @param node * @return True, if node is a container and has at least one child. */ abstract protected boolean hasChildren(final N node); /** * If node is a container than return an iterator for its children. * <p> * Gets only called if {@link #hasChildren(Object)} return true. * * @param node * @return container iterator */ abstract protected Iterator<N> newIterator(final N node); @Override public boolean hasNext() { // Did we reach the end already? if (data == null) { return false; } // We did not yet reach the end. Has next() been called already? if (hasNextWasLast == true) { // next() has not yet been called. return true; } // Remember that the last call was a hasNext() hasNextWasLast = true; // if (skipRemainingSiblings == true) { skipRemainingSiblings = false; return moveUp(); } // Do we need to traverse into the next level? if (!childFirst && traverse) { // Try to find the next element if (moveDown(data.lastNode) == false) { // No more elements return false; } // Found the next element in one the next levels hasNextWasLast = true; return true; } // Get the next node on the current level. If it's a container, than move downwards. If // there are no more elements, than move up again. return nextNode(); } /** * Move down into the next level * * @param node * @return False if no more elements were found */ private boolean moveDown(final N node) { // Remember all details of the current level stack.push(data); // Initialize the data for the next level data = new LevelIterator<>(node, newIterator(node)); // Get the next node on the current level. If it's a container, than move downwards. If // there are no more elements, than move up again. return nextNode(); } /** * Gets called for each element within the hierarchy (nodes and leafs) * * @param node * @return if false, than skip (filter) the element. It'll not stop the iterator from traversing * into children though. */ protected boolean onFilter(final N node) { return true; } /** * Gets called for each element where {@link #hasChildren(Object)} return true. * * @param node * @return if false, than do not traverse into the children and grand-children. */ protected boolean onTraversalFilter(final N node) { return true; } /** * Get the next node from the underlying iterator and handle it. * * @return true, if one more element was found */ private boolean nextNode() { // Get the next element while (data.hasNext()) { data.lastNode = data.next(); // Does it have children? traverse = hasChildren(data.lastNode); if (traverse) { traverse = onTraversalFilter(data.lastNode); } // If it does and we do childFirst, than try to find the next child if (childFirst && traverse) { if (moveDown(data.lastNode) == false) { // No more elements return false; } } // The user interested in the node? if (onFilter(data.lastNode)) { // Yes return true; } // If we are parent first but the user is not interested in the current node, than move // down. if (!childFirst && traverse) { if (moveDown(data.lastNode) == false) { // No more elements return false; } if (data == null) { return false; } hasNextWasLast = true; return true; } if (skipRemainingSiblings == true) { skipRemainingSiblings = false; break; } } // Nothing found. Move up and try to find the next element there return moveUp(); } /** * Move up until we found the next element * * @return false, if no more elements are found */ private boolean moveUp() { if (data == null) { return false; } // Are we back at the root node? if (stack.isEmpty()) { data = null; return false; } // Move up one level data = stack.pop(); // If we are on childFirst, then it's now time to handle the parent if (childFirst) { hasNextWasLast = true; if (onFilter(data.lastNode) == true) { return true; } return nextNode(); } // If we are on parent first, then get the next element else if (data.hasNext()) { return nextNode(); } else { // No more elements on the current level. Move up. return moveUp(); } } /** * Traverse the hierarchy and get the next element */ @Override @SuppressWarnings("unchecked") public I next() { // Did we reach the end already? if (data == null) { return null; } // hasNext() is responsible to get the next element if (hasNextWasLast == false) { if (hasNext() == false) { // No more elements return null; } } // Remember that we need to call hasNext() to get the next element hasNextWasLast = false; return (I)data.lastNode; } @Override public void remove() { if (data == null) { throw new IllegalStateException("Already reached the end of the iterator."); } data.remove(); } /** * Skip all remaining siblings and return to the parent node. * <p> * Can as well be called within {@link IteratorFilter#onFilter(Object)}. */ public void skipRemainingSiblings() { skipRemainingSiblings = true; traverse = false; } /** * Assuming we are currently at a container, than ignore all its children and grand-children and * continue with the next sibling. * <p> * Can as well be called within {@link IteratorFilter#onFilter(Object)}. */ public void dontGoDeeper() { traverse = false; } @Override public final Iterator<I> iterator() { return this; } @Override public String toString() { StringBuilder msg = new StringBuilder(500); msg.append("traverse=") .append(traverse) .append("; childFirst=") .append(childFirst) .append("; hasNextWasLast=") .append(hasNextWasLast) .append('\n'); msg.append("data.node=") .append(data.node) .append('\n') .append("data.lastNode=") .append(data.lastNode) .append('\n'); msg.append("stack.size=").append(stack.size()); return msg.toString(); } /** * We need a little helper to store the iterator of the level and the last node returned by * next(). * * @param <N> */ private static class LevelIterator<N> implements Iterator<N> { private final N node; private final Iterator<N> iter; private N lastNode; /** * Construct. * * @param node * For debugging purposes only * @param iter * The iterator for 'node' */ public LevelIterator(final N node, final Iterator<N> iter) { Args.notNull(iter, "iter"); this.node = node; this.iter = iter; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public N next() { lastNode = iter.next(); return lastNode; } @Override public void remove() { iter.remove(); } @Override public String toString() { StringBuilder msg = new StringBuilder(500); msg.append("node=") .append(node) .append('\n') .append("lastNode=") .append(lastNode) .append('\n'); return msg.toString(); } } }
wicket-core/src/main/java/org/apache/wicket/util/iterator/AbstractHierarchyIterator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.util.iterator; import java.util.Iterator; import org.apache.wicket.util.collections.ArrayListStack; import org.apache.wicket.util.lang.Args; /** * This is a basic iterator for hierarchical structures such as Component hierarchies or HTML * markup. It supports child first and parent first traversal and intercepts while moving down or up * the hierarchy. * <p> * It assumes the container class implements <code>Iterable</code>. The leaf nodes don't need to. * <p> * Consecutive calls to <code>hasNext()</code> without <code>next()</code> in between, don't move * the cursor, but return the same value until <code>next()</code> is called. * <p> * Every call to <code>next()</code>, with or without <code>hasNext()</code>, will move the cursor * to the next element. * * @TODO Replace ChildFirst with a strategy * * @author Juergen Donnerstag * @param <I> * The type relevant for the iterator. What you expect to get back from next(), e.g. * Form. * @param <N> * The base type of all nodes, e.g. Component */ public abstract class AbstractHierarchyIterator<N, I extends N> implements Iterator<I>, Iterable<I> { // An iterator for each level we are down from root private ArrayListStack<LevelIterator<N>> stack = new ArrayListStack<>(); // The current level iterator private LevelIterator<N> data; // Whether we need to traverse into the next level with the next invocation of hasNext() private boolean traverse; // An easy way to configure child or parent first iterations private boolean childFirst; // If remaining siblings shall be ignored private boolean skipRemainingSiblings; // True, if hasNext() was called last or next() private boolean hasNextWasLast; /** * Construct. * * @param root */ public AbstractHierarchyIterator(final N root) { Args.notNull(root, "root"); if (hasChildren(root)) { data = new LevelIterator<>(root, newIterator(root)); } } /** * * @param childFirst * If true, than children are visited before their parent is. */ public final void setChildFirst(final boolean childFirst) { this.childFirst = childFirst; } /** * * @param node * @return True, if node is a container and has at least one child. */ abstract protected boolean hasChildren(final N node); /** * If node is a container than return an iterator for its children. * <p> * Gets only called if {@link #hasChildren(Object)} return true. * * @param node * @return container iterator */ abstract protected Iterator<N> newIterator(final N node); @Override public boolean hasNext() { // Did we reach the end already? if (data == null) { return false; } // We did not yet reach the end. Has next() been called already? if (hasNextWasLast == true) { // next() has not yet been called. return true; } // Remember that the last call was a hasNext() hasNextWasLast = true; // if (skipRemainingSiblings == true) { skipRemainingSiblings = false; return moveUp(); } // Do we need to traverse into the next level? if (!childFirst && traverse) { // Try to find the next element if (moveDown(data.lastNode) == false) { // No more elements return false; } // Found the next element in one the next levels hasNextWasLast = true; return true; } // Get the next node on the current level. If it's a container, than move downwards. If // there are no more elements, than move up again. return nextNode(); } /** * Move down into the next level * * @param node * @return False if no more elements were found */ private boolean moveDown(final N node) { // Remember all details of the current level stack.push(data); // Initialize the data for the next level data = new LevelIterator<>(node, newIterator(node)); // Get the next node on the current level. If it's a container, than move downwards. If // there are no more elements, than move up again. return nextNode(); } /** * Gets called for each element within the hierarchy (nodes and leafs) * * @param node * @return if false, than skip (filter) the element. It'll not stop the iterator from traversing * into children though. */ protected boolean onFilter(final N node) { return true; } /** * Gets called for each element where {@link #hasChildren(Object)} return true. * * @param node * @return if false, than do not traverse into the children and grand-children. */ protected boolean onTraversalFilter(final N node) { return true; } /** * Get the next node from the underlying iterator and handle it. * * @return true, if one more element was found */ private boolean nextNode() { // Get the next element while (data.hasNext()) { data.lastNode = data.next(); // Does it have children? traverse = hasChildren(data.lastNode); if (traverse) { traverse = onTraversalFilter(data.lastNode); } // If it does and we do childFirst, than try to find the next child if (childFirst && traverse) { if (moveDown(data.lastNode) == false) { // No more elements return false; } } // The user interested in the node? if (onFilter(data.lastNode)) { // Yes return true; } // If we are parent first but the user is not interested in the current node, than move // down. if (!childFirst && traverse) { if (moveDown(data.lastNode) == false) { // No more elements return false; } if (data == null) { return false; } hasNextWasLast = true; return true; } if (skipRemainingSiblings == true) { skipRemainingSiblings = false; break; } } // Nothing found. Move up and try to find the next element there return moveUp(); } /** * Move up until we found the next element * * @return false, if no more elements are found */ private boolean moveUp() { if (data == null) { return false; } // Are we back at the root node? if (stack.isEmpty()) { data = null; return false; } // Move up one level data = stack.pop(); // If we are on childFirst, than it's now time to handle the parent if (childFirst) { hasNextWasLast = true; if (onFilter(data.lastNode) == true) { return true; } return nextNode(); } // If we are on parent first, than get the next element else if (data.hasNext()) { return nextNode(); } else { // No more elements on the current level. Move up. return moveUp(); } } /** * Traverse the hierarchy and get the next element */ @Override @SuppressWarnings("unchecked") public I next() { // Did we reach the end already? if (data == null) { return null; } // hasNext() is responsible to get the next element if (hasNextWasLast == false) { if (hasNext() == false) { // No more elements return null; } } // Remember that we need to call hasNext() to get the next element hasNextWasLast = false; return (I)data.lastNode; } @Override public void remove() { if (data == null) { throw new IllegalStateException("Already reached the end of the iterator."); } data.remove(); } /** * Skip all remaining siblings and return to the parent node. * <p> * Can as well be called within {@link IteratorFilter#onFilter(Object)}. */ public void skipRemainingSiblings() { skipRemainingSiblings = true; traverse = false; } /** * Assuming we are currently at a container, than ignore all its children and grand-children and * continue with the next sibling. * <p> * Can as well be called within {@link IteratorFilter#onFilter(Object)}. */ public void dontGoDeeper() { traverse = false; } @Override public final Iterator<I> iterator() { return this; } @Override public String toString() { StringBuilder msg = new StringBuilder(500); msg.append("traverse=") .append(traverse) .append("; childFirst=") .append(childFirst) .append("; hasNextWasLast=") .append(hasNextWasLast) .append("\n"); msg.append("data.node=") .append(data.node) .append("\n") .append("data.lastNode=") .append(data.lastNode) .append("\n"); msg.append("stack.size=").append(stack.size()); return msg.toString(); } /** * We need a little helper to store the iterator of the level and the last node returned by * next(). * * @param <N> */ private static class LevelIterator<N> implements Iterator<N> { private final N node; private final Iterator<N> iter; private N lastNode; /** * Construct. * * @param node * For debugging purposes only * @param iter * The iterator for 'node' */ public LevelIterator(final N node, final Iterator<N> iter) { Args.notNull(iter, "iter"); this.node = node; this.iter = iter; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public N next() { lastNode = iter.next(); return lastNode; } @Override public void remove() { iter.remove(); } @Override public String toString() { StringBuilder msg = new StringBuilder(500); msg.append("node=") .append(node) .append("\n") .append("lastNode=") .append(lastNode) .append("\n"); return msg.toString(); } } }
Non functional changes. Fix typos in comments. Use character instead of String where possible.
wicket-core/src/main/java/org/apache/wicket/util/iterator/AbstractHierarchyIterator.java
Non functional changes.
Java
apache-2.0
55c6d41d1af28f47807eaac7c468bdb2c74a9355
0
anishek/hive,anishek/hive,vergilchiu/hive,nishantmonu51/hive,vergilchiu/hive,nishantmonu51/hive,vineetgarg02/hive,lirui-apache/hive,vergilchiu/hive,sankarh/hive,nishantmonu51/hive,anishek/hive,jcamachor/hive,anishek/hive,vineetgarg02/hive,vineetgarg02/hive,nishantmonu51/hive,nishantmonu51/hive,vergilchiu/hive,sankarh/hive,b-slim/hive,jcamachor/hive,vineetgarg02/hive,vergilchiu/hive,jcamachor/hive,alanfgates/hive,alanfgates/hive,alanfgates/hive,vergilchiu/hive,alanfgates/hive,jcamachor/hive,alanfgates/hive,sankarh/hive,lirui-apache/hive,jcamachor/hive,lirui-apache/hive,alanfgates/hive,lirui-apache/hive,vergilchiu/hive,b-slim/hive,lirui-apache/hive,vineetgarg02/hive,lirui-apache/hive,jcamachor/hive,anishek/hive,sankarh/hive,vineetgarg02/hive,vergilchiu/hive,b-slim/hive,vineetgarg02/hive,sankarh/hive,sankarh/hive,nishantmonu51/hive,jcamachor/hive,jcamachor/hive,vineetgarg02/hive,b-slim/hive,b-slim/hive,sankarh/hive,vineetgarg02/hive,b-slim/hive,alanfgates/hive,lirui-apache/hive,alanfgates/hive,lirui-apache/hive,b-slim/hive,b-slim/hive,jcamachor/hive,anishek/hive,anishek/hive,nishantmonu51/hive,lirui-apache/hive,anishek/hive,nishantmonu51/hive,alanfgates/hive,sankarh/hive,anishek/hive,sankarh/hive,nishantmonu51/hive,b-slim/hive,vergilchiu/hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io.orc; import static com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.JavaUtils; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.io.IOConstants; import org.apache.hadoop.hive.ql.io.filters.BloomFilterIO; import org.apache.hadoop.hive.ql.io.orc.CompressionCodec.Modifier; import org.apache.hadoop.hive.ql.io.orc.OrcFile.CompressionStrategy; import org.apache.hadoop.hive.ql.io.orc.OrcFile.EncodingStrategy; import org.apache.hadoop.hive.ql.io.orc.OrcProto.RowIndexEntry; import org.apache.hadoop.hive.ql.io.orc.OrcProto.StripeStatistics; import org.apache.hadoop.hive.ql.io.orc.OrcProto.Type; import org.apache.hadoop.hive.ql.io.orc.OrcProto.UserMetadataItem; import org.apache.hadoop.hive.ql.util.JavaDataModel; import org.apache.hadoop.hive.serde2.io.DateWritable; import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.UnionObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.ByteObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.DateObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.DoubleObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.FloatObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.ShortObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.primitives.Longs; import com.google.protobuf.ByteString; import com.google.protobuf.CodedOutputStream; /** * An ORC file writer. The file is divided into stripes, which is the natural * unit of work when reading. Each stripe is buffered in memory until the * memory reaches the stripe size and then it is written out broken down by * columns. Each column is written by a TreeWriter that is specific to that * type of column. TreeWriters may have children TreeWriters that handle the * sub-types. Each of the TreeWriters writes the column's data as a set of * streams. * * This class is synchronized so that multi-threaded access is ok. In * particular, because the MemoryManager is shared between writers, this class * assumes that checkMemory may be called from a separate thread. */ public class WriterImpl implements Writer, MemoryManager.Callback { private static final Log LOG = LogFactory.getLog(WriterImpl.class); private static final int HDFS_BUFFER_SIZE = 256 * 1024; private static final int MIN_ROW_INDEX_STRIDE = 1000; // threshold above which buffer size will be automatically resized private static final int COLUMN_COUNT_THRESHOLD = 1000; private final FileSystem fs; private final Path path; private final long defaultStripeSize; private long adjustedStripeSize; private final int rowIndexStride; private final CompressionKind compress; private final CompressionCodec codec; private final boolean addBlockPadding; private final int bufferSize; private final long blockSize; private final float paddingTolerance; // the streams that make up the current stripe private final Map<StreamName, BufferedStream> streams = new TreeMap<StreamName, BufferedStream>(); private FSDataOutputStream rawWriter = null; // the compressed metadata information outStream private OutStream writer = null; // a protobuf outStream around streamFactory private CodedOutputStream protobufWriter = null; private long headerLength; private int columnCount; private long rowCount = 0; private long rowsInStripe = 0; private long rawDataSize = 0; private int rowsInIndex = 0; private int stripesAtLastFlush = -1; private final List<OrcProto.StripeInformation> stripes = new ArrayList<OrcProto.StripeInformation>(); private final Map<String, ByteString> userMetadata = new TreeMap<String, ByteString>(); private final StreamFactory streamFactory = new StreamFactory(); private final TreeWriter treeWriter; private final boolean buildIndex; private final MemoryManager memoryManager; private final OrcFile.Version version; private final Configuration conf; private final OrcFile.WriterCallback callback; private final OrcFile.WriterContext callbackContext; private final OrcFile.EncodingStrategy encodingStrategy; private final OrcFile.CompressionStrategy compressionStrategy; private final boolean[] bloomFilterColumns; private final double bloomFilterFpp; WriterImpl(FileSystem fs, Path path, Configuration conf, ObjectInspector inspector, long stripeSize, CompressionKind compress, int bufferSize, int rowIndexStride, MemoryManager memoryManager, boolean addBlockPadding, OrcFile.Version version, OrcFile.WriterCallback callback, EncodingStrategy encodingStrategy, CompressionStrategy compressionStrategy, float paddingTolerance, long blockSizeValue, String bloomFilterColumnNames, double bloomFilterFpp) throws IOException { this.fs = fs; this.path = path; this.conf = conf; this.callback = callback; if (callback != null) { callbackContext = new OrcFile.WriterContext(){ @Override public Writer getWriter() { return WriterImpl.this; } }; } else { callbackContext = null; } this.adjustedStripeSize = stripeSize; this.defaultStripeSize = stripeSize; this.version = version; this.encodingStrategy = encodingStrategy; this.compressionStrategy = compressionStrategy; this.addBlockPadding = addBlockPadding; this.blockSize = blockSizeValue; this.paddingTolerance = paddingTolerance; this.compress = compress; this.rowIndexStride = rowIndexStride; this.memoryManager = memoryManager; buildIndex = rowIndexStride > 0; codec = createCodec(compress); String allColumns = conf.get(IOConstants.COLUMNS); if (allColumns == null) { allColumns = getColumnNamesFromInspector(inspector); } this.bufferSize = getEstimatedBufferSize(allColumns, bufferSize); if (version == OrcFile.Version.V_0_11) { /* do not write bloom filters for ORC v11 */ this.bloomFilterColumns = OrcUtils.includeColumns(null, allColumns, inspector); } else { this.bloomFilterColumns = OrcUtils.includeColumns(bloomFilterColumnNames, allColumns, inspector); } this.bloomFilterFpp = bloomFilterFpp; treeWriter = createTreeWriter(inspector, streamFactory, false); if (buildIndex && rowIndexStride < MIN_ROW_INDEX_STRIDE) { throw new IllegalArgumentException("Row stride must be at least " + MIN_ROW_INDEX_STRIDE); } // ensure that we are able to handle callbacks before we register ourselves memoryManager.addWriter(path, stripeSize, this); } private String getColumnNamesFromInspector(ObjectInspector inspector) { List<String> fieldNames = Lists.newArrayList(); Joiner joiner = Joiner.on(","); if (inspector instanceof StructObjectInspector) { StructObjectInspector soi = (StructObjectInspector) inspector; List<? extends StructField> fields = soi.getAllStructFieldRefs(); for(StructField sf : fields) { fieldNames.add(sf.getFieldName()); } } return joiner.join(fieldNames); } @VisibleForTesting int getEstimatedBufferSize(int bs) { return getEstimatedBufferSize(conf.get(IOConstants.COLUMNS), bs); } int getEstimatedBufferSize(String colNames, int bs) { long availableMem = getMemoryAvailableForORC(); if (colNames != null) { final int numCols = colNames.split(",").length; if (numCols > COLUMN_COUNT_THRESHOLD) { // In BufferedStream, there are 3 outstream buffers (compressed, // uncompressed and overflow) and list of previously compressed buffers. // Since overflow buffer is rarely used, lets consider only 2 allocation. // Also, initially, the list of compression buffers will be empty. final int outStreamBuffers = codec == null ? 1 : 2; // max possible streams per column is 5. For string columns, there is // ROW_INDEX, PRESENT, DATA, LENGTH, DICTIONARY_DATA streams. final int maxStreams = 5; // Lets assume 10% memory for holding dictionary in memory and other // object allocations final long miscAllocation = (long) (0.1f * availableMem); // compute the available memory final long remainingMem = availableMem - miscAllocation; int estBufferSize = (int) (remainingMem / (maxStreams * outStreamBuffers * numCols)); estBufferSize = getClosestBufferSize(estBufferSize, bs); if (estBufferSize > bs) { estBufferSize = bs; } LOG.info("WIDE TABLE - Number of columns: " + numCols + " Chosen compression buffer size: " + estBufferSize); return estBufferSize; } } return bs; } private int getClosestBufferSize(int estBufferSize, int bs) { final int kb4 = 4 * 1024; final int kb8 = 8 * 1024; final int kb16 = 16 * 1024; final int kb32 = 32 * 1024; final int kb64 = 64 * 1024; final int kb128 = 128 * 1024; final int kb256 = 256 * 1024; if (estBufferSize <= kb4) { return kb4; } else if (estBufferSize > kb4 && estBufferSize <= kb8) { return kb8; } else if (estBufferSize > kb8 && estBufferSize <= kb16) { return kb16; } else if (estBufferSize > kb16 && estBufferSize <= kb32) { return kb32; } else if (estBufferSize > kb32 && estBufferSize <= kb64) { return kb64; } else if (estBufferSize > kb64 && estBufferSize <= kb128) { return kb128; } else { return kb256; } } // the assumption is only one ORC writer open at a time, which holds true for // most of the cases. HIVE-6455 forces single writer case. private long getMemoryAvailableForORC() { HiveConf.ConfVars poolVar = HiveConf.ConfVars.HIVE_ORC_FILE_MEMORY_POOL; double maxLoad = conf.getFloat(poolVar.varname, poolVar.defaultFloatVal); long totalMemoryPool = Math.round(ManagementFactory.getMemoryMXBean(). getHeapMemoryUsage().getMax() * maxLoad); return totalMemoryPool; } public static CompressionCodec createCodec(CompressionKind kind) { switch (kind) { case NONE: return null; case ZLIB: return new ZlibCodec(); case SNAPPY: return new SnappyCodec(); case LZO: try { Class<? extends CompressionCodec> lzo = (Class<? extends CompressionCodec>) JavaUtils.loadClass("org.apache.hadoop.hive.ql.io.orc.LzoCodec"); return lzo.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("LZO is not available.", e); } catch (InstantiationException e) { throw new IllegalArgumentException("Problem initializing LZO", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Insufficient access to LZO", e); } default: throw new IllegalArgumentException("Unknown compression codec: " + kind); } } @Override public synchronized boolean checkMemory(double newScale) throws IOException { long limit = (long) Math.round(adjustedStripeSize * newScale); long size = estimateStripeSize(); if (LOG.isDebugEnabled()) { LOG.debug("ORC writer " + path + " size = " + size + " limit = " + limit); } if (size > limit) { flushStripe(); return true; } return false; } /** * This class is used to hold the contents of streams as they are buffered. * The TreeWriters write to the outStream and the codec compresses the * data as buffers fill up and stores them in the output list. When the * stripe is being written, the whole stream is written to the file. */ private class BufferedStream implements OutStream.OutputReceiver { private final OutStream outStream; private final List<ByteBuffer> output = new ArrayList<ByteBuffer>(); BufferedStream(String name, int bufferSize, CompressionCodec codec) throws IOException { outStream = new OutStream(name, bufferSize, codec, this); } /** * Receive a buffer from the compression codec. * @param buffer the buffer to save * @throws IOException */ @Override public void output(ByteBuffer buffer) { output.add(buffer); } /** * Get the number of bytes in buffers that are allocated to this stream. * @return number of bytes in buffers */ public long getBufferSize() { long result = 0; for(ByteBuffer buf: output) { result += buf.capacity(); } return outStream.getBufferSize() + result; } /** * Flush the stream to the codec. * @throws IOException */ public void flush() throws IOException { outStream.flush(); } /** * Clear all of the buffers. * @throws IOException */ public void clear() throws IOException { outStream.clear(); output.clear(); } /** * Check the state of suppress flag in output stream * @return value of suppress flag */ public boolean isSuppressed() { return outStream.isSuppressed(); } /** * Get the number of bytes that will be written to the output. Assumes * the stream has already been flushed. * @return the number of bytes */ public long getOutputSize() { long result = 0; for(ByteBuffer buffer: output) { result += buffer.remaining(); } return result; } /** * Write the saved compressed buffers to the OutputStream. * @param out the stream to write to * @throws IOException */ void spillTo(OutputStream out) throws IOException { for(ByteBuffer buffer: output) { out.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } } @Override public String toString() { return outStream.toString(); } } /** * An output receiver that writes the ByteBuffers to the output stream * as they are received. */ private class DirectStream implements OutStream.OutputReceiver { private final FSDataOutputStream output; DirectStream(FSDataOutputStream output) { this.output = output; } @Override public void output(ByteBuffer buffer) throws IOException { output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } } private static class RowIndexPositionRecorder implements PositionRecorder { private final OrcProto.RowIndexEntry.Builder builder; RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { this.builder = builder; } @Override public void addPosition(long position) { builder.addPositions(position); } } /** * Interface from the Writer to the TreeWriters. This limits the visibility * that the TreeWriters have into the Writer. */ private class StreamFactory { /** * Create a stream to store part of a column. * @param column the column id for the stream * @param kind the kind of stream * @return The output outStream that the section needs to be written to. * @throws IOException */ public OutStream createStream(int column, OrcProto.Stream.Kind kind ) throws IOException { final StreamName name = new StreamName(column, kind); final EnumSet<CompressionCodec.Modifier> modifiers; switch (kind) { case BLOOM_FILTER: case DATA: case DICTIONARY_DATA: if (getCompressionStrategy() == CompressionStrategy.SPEED) { modifiers = EnumSet.of(Modifier.FAST, Modifier.TEXT); } else { modifiers = EnumSet.of(Modifier.DEFAULT, Modifier.TEXT); } break; case LENGTH: case DICTIONARY_COUNT: case PRESENT: case ROW_INDEX: case SECONDARY: // easily compressed using the fastest modes modifiers = EnumSet.of(Modifier.FASTEST, Modifier.BINARY); break; default: LOG.warn("Missing ORC compression modifiers for " + kind); modifiers = null; break; } BufferedStream result = streams.get(name); if (result == null) { result = new BufferedStream(name.toString(), bufferSize, codec == null ? codec : codec.modify(modifiers)); streams.put(name, result); } return result.outStream; } /** * Get the next column id. * @return a number from 0 to the number of columns - 1 */ public int getNextColumnId() { return columnCount++; } /** * Get the current column id. After creating all tree writers this count should tell how many * columns (including columns within nested complex objects) are created in total. * @return current column id */ public int getCurrentColumnId() { return columnCount; } /** * Get the stride rate of the row index. */ public int getRowIndexStride() { return rowIndexStride; } /** * Should be building the row index. * @return true if we are building the index */ public boolean buildIndex() { return buildIndex; } /** * Is the ORC file compressed? * @return are the streams compressed */ public boolean isCompressed() { return codec != null; } /** * Get the encoding strategy to use. * @return encoding strategy */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Get the compression strategy to use. * @return compression strategy */ public CompressionStrategy getCompressionStrategy() { return compressionStrategy; } /** * Get the bloom filter columns * @return bloom filter columns */ public boolean[] getBloomFilterColumns() { return bloomFilterColumns; } /** * Get bloom filter false positive percentage. * @return fpp */ public double getBloomFilterFPP() { return bloomFilterFpp; } /** * Get the writer's configuration. * @return configuration */ public Configuration getConfiguration() { return conf; } /** * Get the version of the file to write. */ public OrcFile.Version getVersion() { return version; } } /** * The parent class of all of the writers for each column. Each column * is written by an instance of this class. The compound types (struct, * list, map, and union) have children tree writers that write the children * types. */ private abstract static class TreeWriter { protected final int id; protected final ObjectInspector inspector; private final BitFieldWriter isPresent; private final boolean isCompressed; protected final ColumnStatisticsImpl indexStatistics; protected final ColumnStatisticsImpl stripeColStatistics; private final ColumnStatisticsImpl fileStatistics; protected TreeWriter[] childrenWriters; protected final RowIndexPositionRecorder rowIndexPosition; private final OrcProto.RowIndex.Builder rowIndex; private final OrcProto.RowIndexEntry.Builder rowIndexEntry; private final PositionedOutputStream rowIndexStream; private final PositionedOutputStream bloomFilterStream; protected final BloomFilterIO bloomFilter; protected final boolean createBloomFilter; private final OrcProto.BloomFilterIndex.Builder bloomFilterIndex; private final OrcProto.BloomFilter.Builder bloomFilterEntry; private boolean foundNulls; private OutStream isPresentOutStream; private final List<StripeStatistics.Builder> stripeStatsBuilders; /** * Create a tree writer. * @param columnId the column id of the column to write * @param inspector the object inspector to use * @param streamFactory limited access to the Writer's data. * @param nullable can the value be null? * @throws IOException */ TreeWriter(int columnId, ObjectInspector inspector, StreamFactory streamFactory, boolean nullable) throws IOException { this.isCompressed = streamFactory.isCompressed(); this.id = columnId; this.inspector = inspector; if (nullable) { isPresentOutStream = streamFactory.createStream(id, OrcProto.Stream.Kind.PRESENT); isPresent = new BitFieldWriter(isPresentOutStream, 1); } else { isPresent = null; } this.foundNulls = false; createBloomFilter = streamFactory.getBloomFilterColumns()[columnId]; indexStatistics = ColumnStatisticsImpl.create(inspector); stripeColStatistics = ColumnStatisticsImpl.create(inspector); fileStatistics = ColumnStatisticsImpl.create(inspector); childrenWriters = new TreeWriter[0]; rowIndex = OrcProto.RowIndex.newBuilder(); rowIndexEntry = OrcProto.RowIndexEntry.newBuilder(); rowIndexPosition = new RowIndexPositionRecorder(rowIndexEntry); stripeStatsBuilders = Lists.newArrayList(); if (streamFactory.buildIndex()) { rowIndexStream = streamFactory.createStream(id, OrcProto.Stream.Kind.ROW_INDEX); } else { rowIndexStream = null; } if (createBloomFilter) { bloomFilterEntry = OrcProto.BloomFilter.newBuilder(); bloomFilterIndex = OrcProto.BloomFilterIndex.newBuilder(); bloomFilterStream = streamFactory.createStream(id, OrcProto.Stream.Kind.BLOOM_FILTER); bloomFilter = new BloomFilterIO(streamFactory.getRowIndexStride(), streamFactory.getBloomFilterFPP()); } else { bloomFilterEntry = null; bloomFilterIndex = null; bloomFilterStream = null; bloomFilter = null; } } protected OrcProto.RowIndex.Builder getRowIndex() { return rowIndex; } protected ColumnStatisticsImpl getStripeStatistics() { return stripeColStatistics; } protected ColumnStatisticsImpl getFileStatistics() { return fileStatistics; } protected OrcProto.RowIndexEntry.Builder getRowIndexEntry() { return rowIndexEntry; } IntegerWriter createIntegerWriter(PositionedOutputStream output, boolean signed, boolean isDirectV2, StreamFactory writer) { if (isDirectV2) { boolean alignedBitpacking = false; if (writer.getEncodingStrategy().equals(EncodingStrategy.SPEED)) { alignedBitpacking = true; } return new RunLengthIntegerWriterV2(output, signed, alignedBitpacking); } else { return new RunLengthIntegerWriter(output, signed); } } boolean isNewWriteFormat(StreamFactory writer) { return writer.getVersion() != OrcFile.Version.V_0_11; } /** * Add a new value to the column. * @param obj * @throws IOException */ void write(Object obj) throws IOException { if (obj != null) { indexStatistics.increment(); } else { indexStatistics.setNull(); } if (isPresent != null) { isPresent.write(obj == null ? 0 : 1); if(obj == null) { foundNulls = true; } } } private void removeIsPresentPositions() { for(int i=0; i < rowIndex.getEntryCount(); ++i) { RowIndexEntry.Builder entry = rowIndex.getEntryBuilder(i); List<Long> positions = entry.getPositionsList(); // bit streams use 3 positions if uncompressed, 4 if compressed positions = positions.subList(isCompressed ? 4 : 3, positions.size()); entry.clearPositions(); entry.addAllPositions(positions); } } /** * Write the stripe out to the file. * @param builder the stripe footer that contains the information about the * layout of the stripe. The TreeWriter is required to update * the footer with its information. * @param requiredIndexEntries the number of index entries that are * required. this is to check to make sure the * row index is well formed. * @throws IOException */ void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); // if no nulls are found in a stream, then suppress the stream if(!foundNulls) { isPresentOutStream.suppress(); // since isPresent bitstream is suppressed, update the index to // remove the positions of the isPresent stream if (rowIndexStream != null) { removeIsPresentPositions(); } } } // merge stripe-level column statistics to file statistics and write it to // stripe statistics OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); // reset the flag for next stripe foundNulls = false; builder.addColumns(getEncoding()); builder.setWriterTimezone(TimeZone.getDefault().getID()); if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); // write the bloom filter to out stream if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } } private void writeStripeStatistics(OrcProto.StripeStatistics.Builder builder, TreeWriter treeWriter) { treeWriter.fileStatistics.merge(treeWriter.stripeColStatistics); builder.addColStats(treeWriter.stripeColStatistics.serialize().build()); treeWriter.stripeColStatistics.reset(); for (TreeWriter child : treeWriter.getChildrenWriters()) { writeStripeStatistics(builder, child); } } TreeWriter[] getChildrenWriters() { return childrenWriters; } /** * Get the encoding for this column. * @return the information about the encoding of this column */ OrcProto.ColumnEncoding getEncoding() { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT).build(); } /** * Create a row index entry with the previous location and the current * index statistics. Also merges the index statistics into the file * statistics before they are cleared. Finally, it records the start of the * next index and ensures all of the children columns also create an entry. * @throws IOException */ void createRowIndexEntry() throws IOException { stripeColStatistics.merge(indexStatistics); rowIndexEntry.setStatistics(indexStatistics.serialize()); indexStatistics.reset(); rowIndex.addEntry(rowIndexEntry); rowIndexEntry.clear(); addBloomFilterEntry(); recordPosition(rowIndexPosition); for(TreeWriter child: childrenWriters) { child.createRowIndexEntry(); } } void addBloomFilterEntry() { if (createBloomFilter) { bloomFilterEntry.setNumHashFunctions(bloomFilter.getNumHashFunctions()); bloomFilterEntry.addAllBitset(Longs.asList(bloomFilter.getBitSet())); bloomFilterIndex.addBloomFilter(bloomFilterEntry.build()); bloomFilter.reset(); bloomFilterEntry.clear(); } } /** * Record the current position in each of this column's streams. * @param recorder where should the locations be recorded * @throws IOException */ void recordPosition(PositionRecorder recorder) throws IOException { if (isPresent != null) { isPresent.getPosition(recorder); } } /** * Estimate how much memory the writer is consuming excluding the streams. * @return the number of bytes. */ long estimateMemory() { long result = 0; for (TreeWriter child: childrenWriters) { result += child.estimateMemory(); } return result; } } private static class BooleanTreeWriter extends TreeWriter { private final BitFieldWriter writer; BooleanTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); PositionedOutputStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.writer = new BitFieldWriter(out, 1); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { boolean val = ((BooleanObjectInspector) inspector).get(obj); indexStatistics.updateBoolean(val); writer.write(val ? 1 : 0); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class ByteTreeWriter extends TreeWriter { private final RunLengthByteWriter writer; ByteTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.writer = new RunLengthByteWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA)); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { byte val = ((ByteObjectInspector) inspector).get(obj); indexStatistics.updateInteger(val); if (createBloomFilter) { bloomFilter.addLong(val); } writer.write(val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class IntegerTreeWriter extends TreeWriter { private final IntegerWriter writer; private final ShortObjectInspector shortInspector; private final IntObjectInspector intInspector; private final LongObjectInspector longInspector; private boolean isDirectV2 = true; IntegerTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); OutStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.writer = createIntegerWriter(out, true, isDirectV2, writer); if (inspector instanceof IntObjectInspector) { intInspector = (IntObjectInspector) inspector; shortInspector = null; longInspector = null; } else { intInspector = null; if (inspector instanceof LongObjectInspector) { longInspector = (LongObjectInspector) inspector; shortInspector = null; } else { shortInspector = (ShortObjectInspector) inspector; longInspector = null; } } recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { long val; if (intInspector != null) { val = intInspector.get(obj); } else if (longInspector != null) { val = longInspector.get(obj); } else { val = shortInspector.get(obj); } indexStatistics.updateInteger(val); if (createBloomFilter) { // integers are converted to longs in column statistics and during SARG evaluation bloomFilter.addLong(val); } writer.write(val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class FloatTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; FloatTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { float val = ((FloatObjectInspector) inspector).get(obj); indexStatistics.updateDouble(val); if (createBloomFilter) { // floats are converted to doubles in column statistics and during SARG evaluation bloomFilter.addDouble(val); } utils.writeFloat(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } private static class DoubleTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; DoubleTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { double val = ((DoubleObjectInspector) inspector).get(obj); indexStatistics.updateDouble(val); if (createBloomFilter) { bloomFilter.addDouble(val); } utils.writeDouble(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } private static class StringTreeWriter extends TreeWriter { private static final int INITIAL_DICTIONARY_SIZE = 4096; private final OutStream stringOutput; private final IntegerWriter lengthOutput; private final IntegerWriter rowOutput; private final StringRedBlackTree dictionary = new StringRedBlackTree(INITIAL_DICTIONARY_SIZE); private final DynamicIntArray rows = new DynamicIntArray(); private final PositionedOutputStream directStreamOutput; private final IntegerWriter directLengthOutput; private final List<OrcProto.RowIndexEntry> savedRowIndex = new ArrayList<OrcProto.RowIndexEntry>(); private final boolean buildIndex; private final List<Long> rowIndexValueCount = new ArrayList<Long>(); // If the number of keys in a dictionary is greater than this fraction of //the total number of non-null rows, turn off dictionary encoding private final float dictionaryKeySizeThreshold; private boolean useDictionaryEncoding = true; private boolean isDirectV2 = true; private boolean doneDictionaryCheck; private final boolean strideDictionaryCheck; StringTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); stringOutput = writer.createStream(id, OrcProto.Stream.Kind.DICTIONARY_DATA); lengthOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); rowOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA), false, isDirectV2, writer); recordPosition(rowIndexPosition); rowIndexValueCount.add(0L); buildIndex = writer.buildIndex(); directStreamOutput = writer.createStream(id, OrcProto.Stream.Kind.DATA); directLengthOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); dictionaryKeySizeThreshold = writer.getConfiguration().getFloat( HiveConf.ConfVars.HIVE_ORC_DICTIONARY_KEY_SIZE_THRESHOLD.varname, HiveConf.ConfVars.HIVE_ORC_DICTIONARY_KEY_SIZE_THRESHOLD. defaultFloatVal); strideDictionaryCheck = writer.getConfiguration().getBoolean( HiveConf.ConfVars.HIVE_ORC_ROW_INDEX_STRIDE_DICTIONARY_CHECK.varname, HiveConf.ConfVars.HIVE_ORC_ROW_INDEX_STRIDE_DICTIONARY_CHECK. defaultBoolVal); doneDictionaryCheck = false; } /** * Method to retrieve text values from the value object, which can be overridden * by subclasses. * @param obj value * @return Text text value from obj */ Text getTextValue(Object obj) { return ((StringObjectInspector) inspector).getPrimitiveWritableObject(obj); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { Text val = getTextValue(obj); if (useDictionaryEncoding || !strideDictionaryCheck) { rows.add(dictionary.add(val)); } else { // write data and length directStreamOutput.write(val.getBytes(), 0, val.getLength()); directLengthOutput.write(val.getLength()); } indexStatistics.updateString(val); if (createBloomFilter) { bloomFilter.addBytes(val.getBytes(), val.getLength()); } } } private boolean checkDictionaryEncoding() { if (!doneDictionaryCheck) { // Set the flag indicating whether or not to use dictionary encoding // based on whether or not the fraction of distinct keys over number of // non-null rows is less than the configured threshold float ratio = rows.size() > 0 ? (float) (dictionary.size()) / rows.size() : 0.0f; useDictionaryEncoding = !isDirectV2 || ratio <= dictionaryKeySizeThreshold; doneDictionaryCheck = true; } return useDictionaryEncoding; } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { // if rows in stripe is less than dictionaryCheckAfterRows, dictionary // checking would not have happened. So do it again here. checkDictionaryEncoding(); if (useDictionaryEncoding) { flushDictionary(); } else { // flushout any left over entries from dictionary if (rows.size() > 0) { flushDictionary(); } // suppress the stream for every stripe if dictionary is disabled stringOutput.suppress(); } // we need to build the rowindex before calling super, since it // writes it out. super.writeStripe(builder, requiredIndexEntries); stringOutput.flush(); lengthOutput.flush(); rowOutput.flush(); directStreamOutput.flush(); directLengthOutput.flush(); // reset all of the fields to be ready for the next stripe. dictionary.clear(); savedRowIndex.clear(); rowIndexValueCount.clear(); recordPosition(rowIndexPosition); rowIndexValueCount.add(0L); if (!useDictionaryEncoding) { // record the start positions of first index stride of next stripe i.e // beginning of the direct streams when dictionary is disabled recordDirectStreamPosition(); } } private void flushDictionary() throws IOException { final int[] dumpOrder = new int[dictionary.size()]; if (useDictionaryEncoding) { // Write the dictionary by traversing the red-black tree writing out // the bytes and lengths; and creating the map from the original order // to the final sorted order. dictionary.visit(new StringRedBlackTree.Visitor() { private int currentId = 0; @Override public void visit(StringRedBlackTree.VisitorContext context ) throws IOException { context.writeBytes(stringOutput); lengthOutput.write(context.getLength()); dumpOrder[context.getOriginalPosition()] = currentId++; } }); } else { // for direct encoding, we don't want the dictionary data stream stringOutput.suppress(); } int length = rows.size(); int rowIndexEntry = 0; OrcProto.RowIndex.Builder rowIndex = getRowIndex(); Text text = new Text(); // write the values translated into the dump order. for(int i = 0; i <= length; ++i) { // now that we are writing out the row values, we can finalize the // row index if (buildIndex) { while (i == rowIndexValueCount.get(rowIndexEntry) && rowIndexEntry < savedRowIndex.size()) { OrcProto.RowIndexEntry.Builder base = savedRowIndex.get(rowIndexEntry++).toBuilder(); if (useDictionaryEncoding) { rowOutput.getPosition(new RowIndexPositionRecorder(base)); } else { PositionRecorder posn = new RowIndexPositionRecorder(base); directStreamOutput.getPosition(posn); directLengthOutput.getPosition(posn); } rowIndex.addEntry(base.build()); } } if (i != length) { if (useDictionaryEncoding) { rowOutput.write(dumpOrder[rows.get(i)]); } else { dictionary.getText(text, rows.get(i)); directStreamOutput.write(text.getBytes(), 0, text.getLength()); directLengthOutput.write(text.getLength()); } } } rows.clear(); } @Override OrcProto.ColumnEncoding getEncoding() { // Returns the encoding used for the last call to writeStripe if (useDictionaryEncoding) { if(isDirectV2) { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DICTIONARY_V2). setDictionarySize(dictionary.size()).build(); } return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DICTIONARY). setDictionarySize(dictionary.size()).build(); } else { if(isDirectV2) { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT).build(); } } /** * This method doesn't call the super method, because unlike most of the * other TreeWriters, this one can't record the position in the streams * until the stripe is being flushed. Therefore it saves all of the entries * and augments them with the final information as the stripe is written. * @throws IOException */ @Override void createRowIndexEntry() throws IOException { getStripeStatistics().merge(indexStatistics); OrcProto.RowIndexEntry.Builder rowIndexEntry = getRowIndexEntry(); rowIndexEntry.setStatistics(indexStatistics.serialize()); indexStatistics.reset(); OrcProto.RowIndexEntry base = rowIndexEntry.build(); savedRowIndex.add(base); rowIndexEntry.clear(); addBloomFilterEntry(); recordPosition(rowIndexPosition); rowIndexValueCount.add(Long.valueOf(rows.size())); if (strideDictionaryCheck) { checkDictionaryEncoding(); } if (!useDictionaryEncoding) { if (rows.size() > 0) { flushDictionary(); // just record the start positions of next index stride recordDirectStreamPosition(); } else { // record the start positions of next index stride recordDirectStreamPosition(); getRowIndex().addEntry(base); } } } private void recordDirectStreamPosition() throws IOException { directStreamOutput.getPosition(rowIndexPosition); directLengthOutput.getPosition(rowIndexPosition); } @Override long estimateMemory() { return rows.getSizeInBytes() + dictionary.getSizeInBytes(); } } /** * Under the covers, char is written to ORC the same way as string. */ private static class CharTreeWriter extends StringTreeWriter { CharTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); } /** * Override base class implementation to support char values. */ @Override Text getTextValue(Object obj) { return (((HiveCharObjectInspector) inspector) .getPrimitiveWritableObject(obj)).getTextValue(); } } /** * Under the covers, varchar is written to ORC the same way as string. */ private static class VarcharTreeWriter extends StringTreeWriter { VarcharTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); } /** * Override base class implementation to support varchar values. */ @Override Text getTextValue(Object obj) { return (((HiveVarcharObjectInspector) inspector) .getPrimitiveWritableObject(obj)).getTextValue(); } } private static class BinaryTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final IntegerWriter length; private boolean isDirectV2 = true; BinaryTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.length = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { BytesWritable val = ((BinaryObjectInspector) inspector).getPrimitiveWritableObject(obj); stream.write(val.getBytes(), 0, val.getLength()); length.write(val.getLength()); indexStatistics.updateBinary(val); if (createBloomFilter) { bloomFilter.addBytes(val.getBytes(), val.getLength()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); length.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); length.getPosition(recorder); } } static final int MILLIS_PER_SECOND = 1000; static final String BASE_TIMESTAMP_STRING = "2015-01-01 00:00:00"; private static class TimestampTreeWriter extends TreeWriter { private final IntegerWriter seconds; private final IntegerWriter nanos; private final boolean isDirectV2; private final long base_timestamp; TimestampTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); this.seconds = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA), true, isDirectV2, writer); this.nanos = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.SECONDARY), false, isDirectV2, writer); recordPosition(rowIndexPosition); // for unit tests to set different time zones this.base_timestamp = Timestamp.valueOf(BASE_TIMESTAMP_STRING).getTime() / MILLIS_PER_SECOND; } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { Timestamp val = ((TimestampObjectInspector) inspector). getPrimitiveJavaObject(obj); indexStatistics.updateTimestamp(val); seconds.write((val.getTime() / MILLIS_PER_SECOND) - base_timestamp); nanos.write(formatNanos(val.getNanos())); if (createBloomFilter) { bloomFilter.addLong(val.getTime()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); seconds.flush(); nanos.flush(); recordPosition(rowIndexPosition); } private static long formatNanos(int nanos) { if (nanos == 0) { return 0; } else if (nanos % 100 != 0) { return ((long) nanos) << 3; } else { nanos /= 100; int trailingZeros = 1; while (nanos % 10 == 0 && trailingZeros < 7) { nanos /= 10; trailingZeros += 1; } return ((long) nanos) << 3 | trailingZeros; } } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); seconds.getPosition(recorder); nanos.getPosition(recorder); } } private static class DateTreeWriter extends TreeWriter { private final IntegerWriter writer; private final boolean isDirectV2; DateTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); OutStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.writer = createIntegerWriter(out, true, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { // Using the Writable here as it's used directly for writing as well as for stats. DateWritable val = ((DateObjectInspector) inspector).getPrimitiveWritableObject(obj); indexStatistics.updateDate(val); writer.write(val.getDays()); if (createBloomFilter) { bloomFilter.addLong(val.getDays()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } } private static class DecimalTreeWriter extends TreeWriter { private final PositionedOutputStream valueStream; private final IntegerWriter scaleStream; private final boolean isDirectV2; DecimalTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); valueStream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.scaleStream = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.SECONDARY), true, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { HiveDecimal decimal = ((HiveDecimalObjectInspector) inspector). getPrimitiveJavaObject(obj); if (decimal == null) { return; } SerializationUtils.writeBigInteger(valueStream, decimal.unscaledValue()); scaleStream.write(decimal.scale()); indexStatistics.updateDecimal(decimal); if (createBloomFilter) { bloomFilter.addString(decimal.toString()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); valueStream.flush(); scaleStream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); valueStream.getPosition(recorder); scaleStream.getPosition(recorder); } } private static class StructTreeWriter extends TreeWriter { private final List<? extends StructField> fields; StructTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); StructObjectInspector structObjectInspector = (StructObjectInspector) inspector; fields = structObjectInspector.getAllStructFieldRefs(); childrenWriters = new TreeWriter[fields.size()]; for(int i=0; i < childrenWriters.length; ++i) { childrenWriters[i] = createTreeWriter( fields.get(i).getFieldObjectInspector(), writer, true); } recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { StructObjectInspector insp = (StructObjectInspector) inspector; for(int i = 0; i < fields.size(); ++i) { StructField field = fields.get(i); TreeWriter writer = childrenWriters[i]; writer.write(insp.getStructFieldData(obj, field)); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } } private static class ListTreeWriter extends TreeWriter { private final IntegerWriter lengths; private final boolean isDirectV2; ListTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); ListObjectInspector listObjectInspector = (ListObjectInspector) inspector; childrenWriters = new TreeWriter[1]; childrenWriters[0] = createTreeWriter(listObjectInspector.getListElementObjectInspector(), writer, true); lengths = createIntegerWriter(writer.createStream(columnId, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { ListObjectInspector insp = (ListObjectInspector) inspector; int len = insp.getListLength(obj); lengths.write(len); if (createBloomFilter) { bloomFilter.addLong(len); } for(int i=0; i < len; ++i) { childrenWriters[0].write(insp.getListElement(obj, i)); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); lengths.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); lengths.getPosition(recorder); } } private static class MapTreeWriter extends TreeWriter { private final IntegerWriter lengths; private final boolean isDirectV2; MapTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); MapObjectInspector insp = (MapObjectInspector) inspector; childrenWriters = new TreeWriter[2]; childrenWriters[0] = createTreeWriter(insp.getMapKeyObjectInspector(), writer, true); childrenWriters[1] = createTreeWriter(insp.getMapValueObjectInspector(), writer, true); lengths = createIntegerWriter(writer.createStream(columnId, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { MapObjectInspector insp = (MapObjectInspector) inspector; // this sucks, but it will have to do until we can get a better // accessor in the MapObjectInspector. Map<?, ?> valueMap = insp.getMap(obj); lengths.write(valueMap.size()); if (createBloomFilter) { bloomFilter.addLong(valueMap.size()); } for(Map.Entry<?, ?> entry: valueMap.entrySet()) { childrenWriters[0].write(entry.getKey()); childrenWriters[1].write(entry.getValue()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); lengths.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); lengths.getPosition(recorder); } } private static class UnionTreeWriter extends TreeWriter { private final RunLengthByteWriter tags; UnionTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); UnionObjectInspector insp = (UnionObjectInspector) inspector; List<ObjectInspector> choices = insp.getObjectInspectors(); childrenWriters = new TreeWriter[choices.size()]; for(int i=0; i < childrenWriters.length; ++i) { childrenWriters[i] = createTreeWriter(choices.get(i), writer, true); } tags = new RunLengthByteWriter(writer.createStream(columnId, OrcProto.Stream.Kind.DATA)); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { UnionObjectInspector insp = (UnionObjectInspector) inspector; byte tag = insp.getTag(obj); tags.write(tag); if (createBloomFilter) { bloomFilter.addLong(tag); } childrenWriters[tag].write(insp.getField(obj)); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); tags.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); tags.getPosition(recorder); } } private static TreeWriter createTreeWriter(ObjectInspector inspector, StreamFactory streamFactory, boolean nullable) throws IOException { switch (inspector.getCategory()) { case PRIMITIVE: switch (((PrimitiveObjectInspector) inspector).getPrimitiveCategory()) { case BOOLEAN: return new BooleanTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case BYTE: return new ByteTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case SHORT: case INT: case LONG: return new IntegerTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case FLOAT: return new FloatTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DOUBLE: return new DoubleTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case STRING: return new StringTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case CHAR: return new CharTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case VARCHAR: return new VarcharTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case BINARY: return new BinaryTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case TIMESTAMP: return new TimestampTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DATE: return new DateTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DECIMAL: return new DecimalTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); default: throw new IllegalArgumentException("Bad primitive category " + ((PrimitiveObjectInspector) inspector).getPrimitiveCategory()); } case STRUCT: return new StructTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case MAP: return new MapTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case LIST: return new ListTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case UNION: return new UnionTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); default: throw new IllegalArgumentException("Bad category: " + inspector.getCategory()); } } private static void writeTypes(OrcProto.Footer.Builder builder, TreeWriter treeWriter) { OrcProto.Type.Builder type = OrcProto.Type.newBuilder(); switch (treeWriter.inspector.getCategory()) { case PRIMITIVE: switch (((PrimitiveObjectInspector) treeWriter.inspector). getPrimitiveCategory()) { case BOOLEAN: type.setKind(OrcProto.Type.Kind.BOOLEAN); break; case BYTE: type.setKind(OrcProto.Type.Kind.BYTE); break; case SHORT: type.setKind(OrcProto.Type.Kind.SHORT); break; case INT: type.setKind(OrcProto.Type.Kind.INT); break; case LONG: type.setKind(OrcProto.Type.Kind.LONG); break; case FLOAT: type.setKind(OrcProto.Type.Kind.FLOAT); break; case DOUBLE: type.setKind(OrcProto.Type.Kind.DOUBLE); break; case STRING: type.setKind(OrcProto.Type.Kind.STRING); break; case CHAR: // The char length needs to be written to file and should be available // from the object inspector CharTypeInfo charTypeInfo = (CharTypeInfo) ((PrimitiveObjectInspector) treeWriter.inspector).getTypeInfo(); type.setKind(Type.Kind.CHAR); type.setMaximumLength(charTypeInfo.getLength()); break; case VARCHAR: // The varchar length needs to be written to file and should be available // from the object inspector VarcharTypeInfo typeInfo = (VarcharTypeInfo) ((PrimitiveObjectInspector) treeWriter.inspector).getTypeInfo(); type.setKind(Type.Kind.VARCHAR); type.setMaximumLength(typeInfo.getLength()); break; case BINARY: type.setKind(OrcProto.Type.Kind.BINARY); break; case TIMESTAMP: type.setKind(OrcProto.Type.Kind.TIMESTAMP); break; case DATE: type.setKind(OrcProto.Type.Kind.DATE); break; case DECIMAL: DecimalTypeInfo decTypeInfo = (DecimalTypeInfo)((PrimitiveObjectInspector)treeWriter.inspector).getTypeInfo(); type.setKind(OrcProto.Type.Kind.DECIMAL); type.setPrecision(decTypeInfo.precision()); type.setScale(decTypeInfo.scale()); break; default: throw new IllegalArgumentException("Unknown primitive category: " + ((PrimitiveObjectInspector) treeWriter.inspector). getPrimitiveCategory()); } break; case LIST: type.setKind(OrcProto.Type.Kind.LIST); type.addSubtypes(treeWriter.childrenWriters[0].id); break; case MAP: type.setKind(OrcProto.Type.Kind.MAP); type.addSubtypes(treeWriter.childrenWriters[0].id); type.addSubtypes(treeWriter.childrenWriters[1].id); break; case STRUCT: type.setKind(OrcProto.Type.Kind.STRUCT); for(TreeWriter child: treeWriter.childrenWriters) { type.addSubtypes(child.id); } for(StructField field: ((StructTreeWriter) treeWriter).fields) { type.addFieldNames(field.getFieldName()); } break; case UNION: type.setKind(OrcProto.Type.Kind.UNION); for(TreeWriter child: treeWriter.childrenWriters) { type.addSubtypes(child.id); } break; default: throw new IllegalArgumentException("Unknown category: " + treeWriter.inspector.getCategory()); } builder.addTypes(type); for(TreeWriter child: treeWriter.childrenWriters) { writeTypes(builder, child); } } @VisibleForTesting FSDataOutputStream getStream() throws IOException { if (rawWriter == null) { rawWriter = fs.create(path, false, HDFS_BUFFER_SIZE, fs.getDefaultReplication(path), blockSize); rawWriter.writeBytes(OrcFile.MAGIC); headerLength = rawWriter.getPos(); writer = new OutStream("metadata", bufferSize, codec, new DirectStream(rawWriter)); protobufWriter = CodedOutputStream.newInstance(writer); } return rawWriter; } private void createRowIndexEntry() throws IOException { treeWriter.createRowIndexEntry(); rowsInIndex = 0; } private void flushStripe() throws IOException { getStream(); if (buildIndex && rowsInIndex != 0) { createRowIndexEntry(); } if (rowsInStripe != 0) { if (callback != null) { callback.preStripeWrite(callbackContext); } // finalize the data for the stripe int requiredIndexEntries = rowIndexStride == 0 ? 0 : (int) ((rowsInStripe + rowIndexStride - 1) / rowIndexStride); OrcProto.StripeFooter.Builder builder = OrcProto.StripeFooter.newBuilder(); treeWriter.writeStripe(builder, requiredIndexEntries); long indexSize = 0; long dataSize = 0; for(Map.Entry<StreamName, BufferedStream> pair: streams.entrySet()) { BufferedStream stream = pair.getValue(); if (!stream.isSuppressed()) { stream.flush(); StreamName name = pair.getKey(); long streamSize = pair.getValue().getOutputSize(); builder.addStreams(OrcProto.Stream.newBuilder() .setColumn(name.getColumn()) .setKind(name.getKind()) .setLength(streamSize)); if (StreamName.Area.INDEX == name.getArea()) { indexSize += streamSize; } else { dataSize += streamSize; } } } OrcProto.StripeFooter footer = builder.build(); // Do we need to pad the file so the stripe doesn't straddle a block // boundary? long start = rawWriter.getPos(); final long currentStripeSize = indexSize + dataSize + footer.getSerializedSize(); final long available = blockSize - (start % blockSize); final long overflow = currentStripeSize - adjustedStripeSize; final float availRatio = (float) available / (float) defaultStripeSize; if (availRatio > 0.0f && availRatio < 1.0f && availRatio > paddingTolerance) { // adjust default stripe size to fit into remaining space, also adjust // the next stripe for correction based on the current stripe size // and user specified padding tolerance. Since stripe size can overflow // the default stripe size we should apply this correction to avoid // writing portion of last stripe to next hdfs block. float correction = overflow > 0 ? (float) overflow / (float) adjustedStripeSize : 0.0f; // correction should not be greater than user specified padding // tolerance correction = correction > paddingTolerance ? paddingTolerance : correction; // adjust next stripe size based on current stripe estimate correction adjustedStripeSize = (long) ((1.0f - correction) * (availRatio * defaultStripeSize)); } else if (availRatio >= 1.0) { adjustedStripeSize = defaultStripeSize; } if (availRatio < paddingTolerance && addBlockPadding) { long padding = blockSize - (start % blockSize); byte[] pad = new byte[(int) Math.min(HDFS_BUFFER_SIZE, padding)]; LOG.info(String.format("Padding ORC by %d bytes (<= %.2f * %d)", padding, availRatio, defaultStripeSize)); start += padding; while (padding > 0) { int writeLen = (int) Math.min(padding, pad.length); rawWriter.write(pad, 0, writeLen); padding -= writeLen; } adjustedStripeSize = defaultStripeSize; } else if (currentStripeSize < blockSize && (start % blockSize) + currentStripeSize > blockSize) { // even if you don't pad, reset the default stripe size when crossing a // block boundary adjustedStripeSize = defaultStripeSize; } // write out the data streams for(Map.Entry<StreamName, BufferedStream> pair: streams.entrySet()) { BufferedStream stream = pair.getValue(); if (!stream.isSuppressed()) { stream.spillTo(rawWriter); } stream.clear(); } footer.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); long footerLength = rawWriter.getPos() - start - dataSize - indexSize; OrcProto.StripeInformation dirEntry = OrcProto.StripeInformation.newBuilder() .setOffset(start) .setNumberOfRows(rowsInStripe) .setIndexLength(indexSize) .setDataLength(dataSize) .setFooterLength(footerLength).build(); stripes.add(dirEntry); rowCount += rowsInStripe; rowsInStripe = 0; } } private long computeRawDataSize() { long result = 0; for (TreeWriter child : treeWriter.getChildrenWriters()) { result += getRawDataSizeFromInspectors(child, child.inspector); } return result; } private long getRawDataSizeFromInspectors(TreeWriter child, ObjectInspector oi) { long total = 0; switch (oi.getCategory()) { case PRIMITIVE: total += getRawDataSizeFromPrimitives(child, oi); break; case LIST: case MAP: case UNION: case STRUCT: for (TreeWriter tw : child.childrenWriters) { total += getRawDataSizeFromInspectors(tw, tw.inspector); } break; default: LOG.debug("Unknown object inspector category."); break; } return total; } private long getRawDataSizeFromPrimitives(TreeWriter child, ObjectInspector oi) { long result = 0; long numVals = child.fileStatistics.getNumberOfValues(); switch (((PrimitiveObjectInspector) oi).getPrimitiveCategory()) { case BOOLEAN: case BYTE: case SHORT: case INT: case FLOAT: return numVals * JavaDataModel.get().primitive1(); case LONG: case DOUBLE: return numVals * JavaDataModel.get().primitive2(); case STRING: case VARCHAR: case CHAR: // ORC strings are converted to java Strings. so use JavaDataModel to // compute the overall size of strings child = (StringTreeWriter) child; StringColumnStatistics scs = (StringColumnStatistics) child.fileStatistics; numVals = numVals == 0 ? 1 : numVals; int avgStringLen = (int) (scs.getSum() / numVals); return numVals * JavaDataModel.get().lengthForStringOfLength(avgStringLen); case DECIMAL: return numVals * JavaDataModel.get().lengthOfDecimal(); case DATE: return numVals * JavaDataModel.get().lengthOfDate(); case BINARY: // get total length of binary blob BinaryColumnStatistics bcs = (BinaryColumnStatistics) child.fileStatistics; return bcs.getSum(); case TIMESTAMP: return numVals * JavaDataModel.get().lengthOfTimestamp(); default: LOG.debug("Unknown primitive category."); break; } return result; } private OrcProto.CompressionKind writeCompressionKind(CompressionKind kind) { switch (kind) { case NONE: return OrcProto.CompressionKind.NONE; case ZLIB: return OrcProto.CompressionKind.ZLIB; case SNAPPY: return OrcProto.CompressionKind.SNAPPY; case LZO: return OrcProto.CompressionKind.LZO; default: throw new IllegalArgumentException("Unknown compression " + kind); } } private void writeFileStatistics(OrcProto.Footer.Builder builder, TreeWriter writer) throws IOException { builder.addStatistics(writer.fileStatistics.serialize()); for(TreeWriter child: writer.getChildrenWriters()) { writeFileStatistics(builder, child); } } private int writeMetadata(long bodyLength) throws IOException { getStream(); OrcProto.Metadata.Builder builder = OrcProto.Metadata.newBuilder(); for(OrcProto.StripeStatistics.Builder ssb : treeWriter.stripeStatsBuilders) { builder.addStripeStats(ssb.build()); } long startPosn = rawWriter.getPos(); OrcProto.Metadata metadata = builder.build(); metadata.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); return (int) (rawWriter.getPos() - startPosn); } private int writeFooter(long bodyLength) throws IOException { getStream(); OrcProto.Footer.Builder builder = OrcProto.Footer.newBuilder(); builder.setContentLength(bodyLength); builder.setHeaderLength(headerLength); builder.setNumberOfRows(rowCount); builder.setRowIndexStride(rowIndexStride); // populate raw data size rawDataSize = computeRawDataSize(); // serialize the types writeTypes(builder, treeWriter); // add the stripe information for(OrcProto.StripeInformation stripe: stripes) { builder.addStripes(stripe); } // add the column statistics writeFileStatistics(builder, treeWriter); // add all of the user metadata for(Map.Entry<String, ByteString> entry: userMetadata.entrySet()) { builder.addMetadata(OrcProto.UserMetadataItem.newBuilder() .setName(entry.getKey()).setValue(entry.getValue())); } long startPosn = rawWriter.getPos(); OrcProto.Footer footer = builder.build(); footer.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); return (int) (rawWriter.getPos() - startPosn); } private int writePostScript(int footerLength, int metadataLength) throws IOException { OrcProto.PostScript.Builder builder = OrcProto.PostScript.newBuilder() .setCompression(writeCompressionKind(compress)) .setFooterLength(footerLength) .setMetadataLength(metadataLength) .setMagic(OrcFile.MAGIC) .addVersion(version.getMajor()) .addVersion(version.getMinor()) .setWriterVersion(OrcFile.WriterVersion.HIVE_8732.getId()); if (compress != CompressionKind.NONE) { builder.setCompressionBlockSize(bufferSize); } OrcProto.PostScript ps = builder.build(); // need to write this uncompressed long startPosn = rawWriter.getPos(); ps.writeTo(rawWriter); long length = rawWriter.getPos() - startPosn; if (length > 255) { throw new IllegalArgumentException("PostScript too large at " + length); } return (int) length; } private long estimateStripeSize() { long result = 0; for(BufferedStream stream: streams.values()) { result += stream.getBufferSize(); } result += treeWriter.estimateMemory(); return result; } @Override public synchronized void addUserMetadata(String name, ByteBuffer value) { userMetadata.put(name, ByteString.copyFrom(value)); } @Override public void addRow(Object row) throws IOException { synchronized (this) { treeWriter.write(row); rowsInStripe += 1; if (buildIndex) { rowsInIndex += 1; if (rowsInIndex >= rowIndexStride) { createRowIndexEntry(); } } } memoryManager.addedRow(); } @Override public void close() throws IOException { if (callback != null) { callback.preFooterWrite(callbackContext); } // remove us from the memory manager so that we don't get any callbacks memoryManager.removeWriter(path); // actually close the file synchronized (this) { flushStripe(); int metadataLength = writeMetadata(rawWriter.getPos()); int footerLength = writeFooter(rawWriter.getPos() - metadataLength); rawWriter.writeByte(writePostScript(footerLength, metadataLength)); rawWriter.close(); } } /** * Raw data size will be compute when writing the file footer. Hence raw data * size value will be available only after closing the writer. */ @Override public long getRawDataSize() { return rawDataSize; } /** * Row count gets updated when flushing the stripes. To get accurate row * count call this method after writer is closed. */ @Override public long getNumberOfRows() { return rowCount; } @Override public synchronized long writeIntermediateFooter() throws IOException { // flush any buffered rows flushStripe(); // write a footer if (stripesAtLastFlush != stripes.size()) { if (callback != null) { callback.preFooterWrite(callbackContext); } int metaLength = writeMetadata(rawWriter.getPos()); int footLength = writeFooter(rawWriter.getPos() - metaLength); rawWriter.writeByte(writePostScript(footLength, metaLength)); stripesAtLastFlush = stripes.size(); OrcInputFormat.SHIMS.hflush(rawWriter); } return rawWriter.getPos(); } @Override public void appendStripe(byte[] stripe, int offset, int length, StripeInformation stripeInfo, OrcProto.StripeStatistics stripeStatistics) throws IOException { checkArgument(stripe != null, "Stripe must not be null"); checkArgument(length <= stripe.length, "Specified length must not be greater specified array length"); checkArgument(stripeInfo != null, "Stripe information must not be null"); checkArgument(stripeStatistics != null, "Stripe statistics must not be null"); getStream(); long start = rawWriter.getPos(); long stripeLen = length; long availBlockSpace = blockSize - (start % blockSize); // see if stripe can fit in the current hdfs block, else pad the remaining // space in the block if (stripeLen < blockSize && stripeLen > availBlockSpace && addBlockPadding) { byte[] pad = new byte[(int) Math.min(HDFS_BUFFER_SIZE, availBlockSpace)]; LOG.info(String.format("Padding ORC by %d bytes while merging..", availBlockSpace)); start += availBlockSpace; while (availBlockSpace > 0) { int writeLen = (int) Math.min(availBlockSpace, pad.length); rawWriter.write(pad, 0, writeLen); availBlockSpace -= writeLen; } } rawWriter.write(stripe); rowsInStripe = stripeStatistics.getColStats(0).getNumberOfValues(); rowCount += rowsInStripe; // since we have already written the stripe, just update stripe statistics treeWriter.stripeStatsBuilders.add(stripeStatistics.toBuilder()); // update file level statistics updateFileStatistics(stripeStatistics); // update stripe information OrcProto.StripeInformation dirEntry = OrcProto.StripeInformation .newBuilder() .setOffset(start) .setNumberOfRows(rowsInStripe) .setIndexLength(stripeInfo.getIndexLength()) .setDataLength(stripeInfo.getDataLength()) .setFooterLength(stripeInfo.getFooterLength()) .build(); stripes.add(dirEntry); // reset it after writing the stripe rowsInStripe = 0; } private void updateFileStatistics(OrcProto.StripeStatistics stripeStatistics) { List<OrcProto.ColumnStatistics> cs = stripeStatistics.getColStatsList(); List<TreeWriter> allWriters = getAllColumnTreeWriters(treeWriter); for (int i = 0; i < allWriters.size(); i++) { allWriters.get(i).fileStatistics.merge(ColumnStatisticsImpl.deserialize(cs.get(i))); } } private List<TreeWriter> getAllColumnTreeWriters(TreeWriter rootTreeWriter) { List<TreeWriter> result = Lists.newArrayList(); getAllColumnTreeWritersImpl(rootTreeWriter, result); return result; } private void getAllColumnTreeWritersImpl(TreeWriter tw, List<TreeWriter> result) { result.add(tw); for (TreeWriter child : tw.childrenWriters) { getAllColumnTreeWritersImpl(child, result); } } @Override public void appendUserMetadata(List<UserMetadataItem> userMetadata) { if (userMetadata != null) { for (UserMetadataItem item : userMetadata) { this.userMetadata.put(item.getName(), item.getValue()); } } } }
ql/src/java/org/apache/hadoop/hive/ql/io/orc/WriterImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io.orc; import static com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.JavaUtils; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.io.IOConstants; import org.apache.hadoop.hive.ql.io.filters.BloomFilterIO; import org.apache.hadoop.hive.ql.io.orc.CompressionCodec.Modifier; import org.apache.hadoop.hive.ql.io.orc.OrcFile.CompressionStrategy; import org.apache.hadoop.hive.ql.io.orc.OrcFile.EncodingStrategy; import org.apache.hadoop.hive.ql.io.orc.OrcProto.RowIndexEntry; import org.apache.hadoop.hive.ql.io.orc.OrcProto.StripeStatistics; import org.apache.hadoop.hive.ql.io.orc.OrcProto.Type; import org.apache.hadoop.hive.ql.io.orc.OrcProto.UserMetadataItem; import org.apache.hadoop.hive.ql.util.JavaDataModel; import org.apache.hadoop.hive.serde2.io.DateWritable; import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.UnionObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.ByteObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.DateObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.DoubleObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.FloatObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.ShortObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.primitives.Longs; import com.google.protobuf.ByteString; import com.google.protobuf.CodedOutputStream; /** * An ORC file writer. The file is divided into stripes, which is the natural * unit of work when reading. Each stripe is buffered in memory until the * memory reaches the stripe size and then it is written out broken down by * columns. Each column is written by a TreeWriter that is specific to that * type of column. TreeWriters may have children TreeWriters that handle the * sub-types. Each of the TreeWriters writes the column's data as a set of * streams. * * This class is synchronized so that multi-threaded access is ok. In * particular, because the MemoryManager is shared between writers, this class * assumes that checkMemory may be called from a separate thread. */ public class WriterImpl implements Writer, MemoryManager.Callback { private static final Log LOG = LogFactory.getLog(WriterImpl.class); private static final int HDFS_BUFFER_SIZE = 256 * 1024; private static final int MIN_ROW_INDEX_STRIDE = 1000; // threshold above which buffer size will be automatically resized private static final int COLUMN_COUNT_THRESHOLD = 1000; private final FileSystem fs; private final Path path; private final long defaultStripeSize; private long adjustedStripeSize; private final int rowIndexStride; private final CompressionKind compress; private final CompressionCodec codec; private final boolean addBlockPadding; private final int bufferSize; private final long blockSize; private final float paddingTolerance; // the streams that make up the current stripe private final Map<StreamName, BufferedStream> streams = new TreeMap<StreamName, BufferedStream>(); private FSDataOutputStream rawWriter = null; // the compressed metadata information outStream private OutStream writer = null; // a protobuf outStream around streamFactory private CodedOutputStream protobufWriter = null; private long headerLength; private int columnCount; private long rowCount = 0; private long rowsInStripe = 0; private long rawDataSize = 0; private int rowsInIndex = 0; private int stripesAtLastFlush = -1; private final List<OrcProto.StripeInformation> stripes = new ArrayList<OrcProto.StripeInformation>(); private final Map<String, ByteString> userMetadata = new TreeMap<String, ByteString>(); private final StreamFactory streamFactory = new StreamFactory(); private final TreeWriter treeWriter; private final boolean buildIndex; private final MemoryManager memoryManager; private final OrcFile.Version version; private final Configuration conf; private final OrcFile.WriterCallback callback; private final OrcFile.WriterContext callbackContext; private final OrcFile.EncodingStrategy encodingStrategy; private final OrcFile.CompressionStrategy compressionStrategy; private final boolean[] bloomFilterColumns; private final double bloomFilterFpp; WriterImpl(FileSystem fs, Path path, Configuration conf, ObjectInspector inspector, long stripeSize, CompressionKind compress, int bufferSize, int rowIndexStride, MemoryManager memoryManager, boolean addBlockPadding, OrcFile.Version version, OrcFile.WriterCallback callback, EncodingStrategy encodingStrategy, CompressionStrategy compressionStrategy, float paddingTolerance, long blockSizeValue, String bloomFilterColumnNames, double bloomFilterFpp) throws IOException { this.fs = fs; this.path = path; this.conf = conf; this.callback = callback; if (callback != null) { callbackContext = new OrcFile.WriterContext(){ @Override public Writer getWriter() { return WriterImpl.this; } }; } else { callbackContext = null; } this.adjustedStripeSize = stripeSize; this.defaultStripeSize = stripeSize; this.version = version; this.encodingStrategy = encodingStrategy; this.compressionStrategy = compressionStrategy; this.addBlockPadding = addBlockPadding; this.blockSize = blockSizeValue; this.paddingTolerance = paddingTolerance; this.compress = compress; this.rowIndexStride = rowIndexStride; this.memoryManager = memoryManager; buildIndex = rowIndexStride > 0; codec = createCodec(compress); String allColumns = conf.get(IOConstants.COLUMNS); if (allColumns == null) { allColumns = getColumnNamesFromInspector(inspector); } this.bufferSize = getEstimatedBufferSize(allColumns, bufferSize); if (version == OrcFile.Version.V_0_11) { /* do not write bloom filters for ORC v11 */ this.bloomFilterColumns = OrcUtils.includeColumns(null, allColumns, inspector); } else { this.bloomFilterColumns = OrcUtils.includeColumns(bloomFilterColumnNames, allColumns, inspector); } this.bloomFilterFpp = bloomFilterFpp; treeWriter = createTreeWriter(inspector, streamFactory, false); if (buildIndex && rowIndexStride < MIN_ROW_INDEX_STRIDE) { throw new IllegalArgumentException("Row stride must be at least " + MIN_ROW_INDEX_STRIDE); } // ensure that we are able to handle callbacks before we register ourselves memoryManager.addWriter(path, stripeSize, this); } private String getColumnNamesFromInspector(ObjectInspector inspector) { List<String> fieldNames = Lists.newArrayList(); Joiner joiner = Joiner.on(","); if (inspector instanceof StructObjectInspector) { StructObjectInspector soi = (StructObjectInspector) inspector; List<? extends StructField> fields = soi.getAllStructFieldRefs(); for(StructField sf : fields) { fieldNames.add(sf.getFieldName()); } } return joiner.join(fieldNames); } @VisibleForTesting int getEstimatedBufferSize(int bs) { return getEstimatedBufferSize(conf.get(IOConstants.COLUMNS), bs); } int getEstimatedBufferSize(String colNames, int bs) { long availableMem = getMemoryAvailableForORC(); if (colNames != null) { final int numCols = colNames.split(",").length; if (numCols > COLUMN_COUNT_THRESHOLD) { // In BufferedStream, there are 3 outstream buffers (compressed, // uncompressed and overflow) and list of previously compressed buffers. // Since overflow buffer is rarely used, lets consider only 2 allocation. // Also, initially, the list of compression buffers will be empty. final int outStreamBuffers = codec == null ? 1 : 2; // max possible streams per column is 5. For string columns, there is // ROW_INDEX, PRESENT, DATA, LENGTH, DICTIONARY_DATA streams. final int maxStreams = 5; // Lets assume 10% memory for holding dictionary in memory and other // object allocations final long miscAllocation = (long) (0.1f * availableMem); // compute the available memory final long remainingMem = availableMem - miscAllocation; int estBufferSize = (int) (remainingMem / (maxStreams * outStreamBuffers * numCols)); estBufferSize = getClosestBufferSize(estBufferSize, bs); if (estBufferSize > bs) { estBufferSize = bs; } LOG.info("WIDE TABLE - Number of columns: " + numCols + " Chosen compression buffer size: " + estBufferSize); return estBufferSize; } } return bs; } private int getClosestBufferSize(int estBufferSize, int bs) { final int kb4 = 4 * 1024; final int kb8 = 8 * 1024; final int kb16 = 16 * 1024; final int kb32 = 32 * 1024; final int kb64 = 64 * 1024; final int kb128 = 128 * 1024; final int kb256 = 256 * 1024; if (estBufferSize <= kb4) { return kb4; } else if (estBufferSize > kb4 && estBufferSize <= kb8) { return kb8; } else if (estBufferSize > kb8 && estBufferSize <= kb16) { return kb16; } else if (estBufferSize > kb16 && estBufferSize <= kb32) { return kb32; } else if (estBufferSize > kb32 && estBufferSize <= kb64) { return kb64; } else if (estBufferSize > kb64 && estBufferSize <= kb128) { return kb128; } else { return kb256; } } // the assumption is only one ORC writer open at a time, which holds true for // most of the cases. HIVE-6455 forces single writer case. private long getMemoryAvailableForORC() { HiveConf.ConfVars poolVar = HiveConf.ConfVars.HIVE_ORC_FILE_MEMORY_POOL; double maxLoad = conf.getFloat(poolVar.varname, poolVar.defaultFloatVal); long totalMemoryPool = Math.round(ManagementFactory.getMemoryMXBean(). getHeapMemoryUsage().getMax() * maxLoad); return totalMemoryPool; } public static CompressionCodec createCodec(CompressionKind kind) { switch (kind) { case NONE: return null; case ZLIB: return new ZlibCodec(); case SNAPPY: return new SnappyCodec(); case LZO: try { Class<? extends CompressionCodec> lzo = (Class<? extends CompressionCodec>) JavaUtils.loadClass("org.apache.hadoop.hive.ql.io.orc.LzoCodec"); return lzo.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("LZO is not available.", e); } catch (InstantiationException e) { throw new IllegalArgumentException("Problem initializing LZO", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Insufficient access to LZO", e); } default: throw new IllegalArgumentException("Unknown compression codec: " + kind); } } @Override public synchronized boolean checkMemory(double newScale) throws IOException { long limit = (long) Math.round(adjustedStripeSize * newScale); long size = estimateStripeSize(); if (LOG.isDebugEnabled()) { LOG.debug("ORC writer " + path + " size = " + size + " limit = " + limit); } if (size > limit) { flushStripe(); return true; } return false; } /** * This class is used to hold the contents of streams as they are buffered. * The TreeWriters write to the outStream and the codec compresses the * data as buffers fill up and stores them in the output list. When the * stripe is being written, the whole stream is written to the file. */ private class BufferedStream implements OutStream.OutputReceiver { private final OutStream outStream; private final List<ByteBuffer> output = new ArrayList<ByteBuffer>(); BufferedStream(String name, int bufferSize, CompressionCodec codec) throws IOException { outStream = new OutStream(name, bufferSize, codec, this); } /** * Receive a buffer from the compression codec. * @param buffer the buffer to save * @throws IOException */ @Override public void output(ByteBuffer buffer) { output.add(buffer); } /** * Get the number of bytes in buffers that are allocated to this stream. * @return number of bytes in buffers */ public long getBufferSize() { long result = 0; for(ByteBuffer buf: output) { result += buf.capacity(); } return outStream.getBufferSize() + result; } /** * Flush the stream to the codec. * @throws IOException */ public void flush() throws IOException { outStream.flush(); } /** * Clear all of the buffers. * @throws IOException */ public void clear() throws IOException { outStream.clear(); output.clear(); } /** * Check the state of suppress flag in output stream * @return value of suppress flag */ public boolean isSuppressed() { return outStream.isSuppressed(); } /** * Get the number of bytes that will be written to the output. Assumes * the stream has already been flushed. * @return the number of bytes */ public long getOutputSize() { long result = 0; for(ByteBuffer buffer: output) { result += buffer.remaining(); } return result; } /** * Write the saved compressed buffers to the OutputStream. * @param out the stream to write to * @throws IOException */ void spillTo(OutputStream out) throws IOException { for(ByteBuffer buffer: output) { out.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } } @Override public String toString() { return outStream.toString(); } } /** * An output receiver that writes the ByteBuffers to the output stream * as they are received. */ private class DirectStream implements OutStream.OutputReceiver { private final FSDataOutputStream output; DirectStream(FSDataOutputStream output) { this.output = output; } @Override public void output(ByteBuffer buffer) throws IOException { output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } } private static class RowIndexPositionRecorder implements PositionRecorder { private final OrcProto.RowIndexEntry.Builder builder; RowIndexPositionRecorder(OrcProto.RowIndexEntry.Builder builder) { this.builder = builder; } @Override public void addPosition(long position) { builder.addPositions(position); } } /** * Interface from the Writer to the TreeWriters. This limits the visibility * that the TreeWriters have into the Writer. */ private class StreamFactory { /** * Create a stream to store part of a column. * @param column the column id for the stream * @param kind the kind of stream * @return The output outStream that the section needs to be written to. * @throws IOException */ public OutStream createStream(int column, OrcProto.Stream.Kind kind ) throws IOException { final StreamName name = new StreamName(column, kind); final EnumSet<CompressionCodec.Modifier> modifiers; switch (kind) { case BLOOM_FILTER: case DATA: case DICTIONARY_DATA: if (getCompressionStrategy() == CompressionStrategy.SPEED) { modifiers = EnumSet.of(Modifier.FAST, Modifier.TEXT); } else { modifiers = EnumSet.of(Modifier.DEFAULT, Modifier.TEXT); } break; case LENGTH: case DICTIONARY_COUNT: case PRESENT: case ROW_INDEX: case SECONDARY: // easily compressed using the fastest modes modifiers = EnumSet.of(Modifier.FASTEST, Modifier.BINARY); break; default: LOG.warn("Missing ORC compression modifiers for " + kind); modifiers = null; break; } BufferedStream result = streams.get(name); if (result == null) { result = new BufferedStream(name.toString(), bufferSize, codec == null ? codec : codec.modify(modifiers)); streams.put(name, result); } return result.outStream; } /** * Get the next column id. * @return a number from 0 to the number of columns - 1 */ public int getNextColumnId() { return columnCount++; } /** * Get the current column id. After creating all tree writers this count should tell how many * columns (including columns within nested complex objects) are created in total. * @return current column id */ public int getCurrentColumnId() { return columnCount; } /** * Get the stride rate of the row index. */ public int getRowIndexStride() { return rowIndexStride; } /** * Should be building the row index. * @return true if we are building the index */ public boolean buildIndex() { return buildIndex; } /** * Is the ORC file compressed? * @return are the streams compressed */ public boolean isCompressed() { return codec != null; } /** * Get the encoding strategy to use. * @return encoding strategy */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Get the compression strategy to use. * @return compression strategy */ public CompressionStrategy getCompressionStrategy() { return compressionStrategy; } /** * Get the bloom filter columns * @return bloom filter columns */ public boolean[] getBloomFilterColumns() { return bloomFilterColumns; } /** * Get bloom filter false positive percentage. * @return fpp */ public double getBloomFilterFPP() { return bloomFilterFpp; } /** * Get the writer's configuration. * @return configuration */ public Configuration getConfiguration() { return conf; } /** * Get the version of the file to write. */ public OrcFile.Version getVersion() { return version; } } /** * The parent class of all of the writers for each column. Each column * is written by an instance of this class. The compound types (struct, * list, map, and union) have children tree writers that write the children * types. */ private abstract static class TreeWriter { protected final int id; protected final ObjectInspector inspector; private final BitFieldWriter isPresent; private final boolean isCompressed; protected final ColumnStatisticsImpl indexStatistics; protected final ColumnStatisticsImpl stripeColStatistics; private final ColumnStatisticsImpl fileStatistics; protected TreeWriter[] childrenWriters; protected final RowIndexPositionRecorder rowIndexPosition; private final OrcProto.RowIndex.Builder rowIndex; private final OrcProto.RowIndexEntry.Builder rowIndexEntry; private final PositionedOutputStream rowIndexStream; private final PositionedOutputStream bloomFilterStream; protected final BloomFilterIO bloomFilter; protected final boolean createBloomFilter; private final OrcProto.BloomFilterIndex.Builder bloomFilterIndex; private final OrcProto.BloomFilter.Builder bloomFilterEntry; private boolean foundNulls; private OutStream isPresentOutStream; private final List<StripeStatistics.Builder> stripeStatsBuilders; /** * Create a tree writer. * @param columnId the column id of the column to write * @param inspector the object inspector to use * @param streamFactory limited access to the Writer's data. * @param nullable can the value be null? * @throws IOException */ TreeWriter(int columnId, ObjectInspector inspector, StreamFactory streamFactory, boolean nullable) throws IOException { this.isCompressed = streamFactory.isCompressed(); this.id = columnId; this.inspector = inspector; if (nullable) { isPresentOutStream = streamFactory.createStream(id, OrcProto.Stream.Kind.PRESENT); isPresent = new BitFieldWriter(isPresentOutStream, 1); } else { isPresent = null; } this.foundNulls = false; createBloomFilter = streamFactory.getBloomFilterColumns()[columnId]; indexStatistics = ColumnStatisticsImpl.create(inspector); stripeColStatistics = ColumnStatisticsImpl.create(inspector); fileStatistics = ColumnStatisticsImpl.create(inspector); childrenWriters = new TreeWriter[0]; rowIndex = OrcProto.RowIndex.newBuilder(); rowIndexEntry = OrcProto.RowIndexEntry.newBuilder(); rowIndexPosition = new RowIndexPositionRecorder(rowIndexEntry); stripeStatsBuilders = Lists.newArrayList(); if (streamFactory.buildIndex()) { rowIndexStream = streamFactory.createStream(id, OrcProto.Stream.Kind.ROW_INDEX); } else { rowIndexStream = null; } if (createBloomFilter) { bloomFilterEntry = OrcProto.BloomFilter.newBuilder(); bloomFilterIndex = OrcProto.BloomFilterIndex.newBuilder(); bloomFilterStream = streamFactory.createStream(id, OrcProto.Stream.Kind.BLOOM_FILTER); bloomFilter = new BloomFilterIO(streamFactory.getRowIndexStride(), streamFactory.getBloomFilterFPP()); } else { bloomFilterEntry = null; bloomFilterIndex = null; bloomFilterStream = null; bloomFilter = null; } } protected OrcProto.RowIndex.Builder getRowIndex() { return rowIndex; } protected ColumnStatisticsImpl getStripeStatistics() { return stripeColStatistics; } protected ColumnStatisticsImpl getFileStatistics() { return fileStatistics; } protected OrcProto.RowIndexEntry.Builder getRowIndexEntry() { return rowIndexEntry; } IntegerWriter createIntegerWriter(PositionedOutputStream output, boolean signed, boolean isDirectV2, StreamFactory writer) { if (isDirectV2) { boolean alignedBitpacking = false; if (writer.getEncodingStrategy().equals(EncodingStrategy.SPEED)) { alignedBitpacking = true; } return new RunLengthIntegerWriterV2(output, signed, alignedBitpacking); } else { return new RunLengthIntegerWriter(output, signed); } } boolean isNewWriteFormat(StreamFactory writer) { return writer.getVersion() != OrcFile.Version.V_0_11; } /** * Add a new value to the column. * @param obj * @throws IOException */ void write(Object obj) throws IOException { if (obj != null) { indexStatistics.increment(); } else { indexStatistics.setNull(); } if (isPresent != null) { isPresent.write(obj == null ? 0 : 1); if(obj == null) { foundNulls = true; } } } private void removeIsPresentPositions() { for(int i=0; i < rowIndex.getEntryCount(); ++i) { RowIndexEntry.Builder entry = rowIndex.getEntryBuilder(i); List<Long> positions = entry.getPositionsList(); // bit streams use 3 positions if uncompressed, 4 if compressed positions = positions.subList(isCompressed ? 4 : 3, positions.size()); entry.clearPositions(); entry.addAllPositions(positions); } } /** * Write the stripe out to the file. * @param builder the stripe footer that contains the information about the * layout of the stripe. The TreeWriter is required to update * the footer with its information. * @param requiredIndexEntries the number of index entries that are * required. this is to check to make sure the * row index is well formed. * @throws IOException */ void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); // if no nulls are found in a stream, then suppress the stream if(!foundNulls) { isPresentOutStream.suppress(); // since isPresent bitstream is suppressed, update the index to // remove the positions of the isPresent stream if (rowIndexStream != null) { removeIsPresentPositions(); } } } // merge stripe-level column statistics to file statistics and write it to // stripe statistics OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); // reset the flag for next stripe foundNulls = false; builder.addColumns(getEncoding()); builder.setWriterTimezone(TimeZone.getDefault().getID()); if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); // write the bloom filter to out stream if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } } private void writeStripeStatistics(OrcProto.StripeStatistics.Builder builder, TreeWriter treeWriter) { treeWriter.fileStatistics.merge(treeWriter.stripeColStatistics); builder.addColStats(treeWriter.stripeColStatistics.serialize().build()); treeWriter.stripeColStatistics.reset(); for (TreeWriter child : treeWriter.getChildrenWriters()) { writeStripeStatistics(builder, child); } } TreeWriter[] getChildrenWriters() { return childrenWriters; } /** * Get the encoding for this column. * @return the information about the encoding of this column */ OrcProto.ColumnEncoding getEncoding() { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT).build(); } /** * Create a row index entry with the previous location and the current * index statistics. Also merges the index statistics into the file * statistics before they are cleared. Finally, it records the start of the * next index and ensures all of the children columns also create an entry. * @throws IOException */ void createRowIndexEntry() throws IOException { stripeColStatistics.merge(indexStatistics); rowIndexEntry.setStatistics(indexStatistics.serialize()); indexStatistics.reset(); rowIndex.addEntry(rowIndexEntry); rowIndexEntry.clear(); addBloomFilterEntry(); recordPosition(rowIndexPosition); for(TreeWriter child: childrenWriters) { child.createRowIndexEntry(); } } void addBloomFilterEntry() { if (createBloomFilter) { bloomFilterEntry.setNumHashFunctions(bloomFilter.getNumHashFunctions()); bloomFilterEntry.addAllBitset(Longs.asList(bloomFilter.getBitSet())); bloomFilterIndex.addBloomFilter(bloomFilterEntry.build()); bloomFilter.reset(); bloomFilterEntry.clear(); } } /** * Record the current position in each of this column's streams. * @param recorder where should the locations be recorded * @throws IOException */ void recordPosition(PositionRecorder recorder) throws IOException { if (isPresent != null) { isPresent.getPosition(recorder); } } /** * Estimate how much memory the writer is consuming excluding the streams. * @return the number of bytes. */ long estimateMemory() { long result = 0; for (TreeWriter child: childrenWriters) { result += child.estimateMemory(); } return result; } } private static class BooleanTreeWriter extends TreeWriter { private final BitFieldWriter writer; BooleanTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); PositionedOutputStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.writer = new BitFieldWriter(out, 1); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { boolean val = ((BooleanObjectInspector) inspector).get(obj); indexStatistics.updateBoolean(val); writer.write(val ? 1 : 0); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class ByteTreeWriter extends TreeWriter { private final RunLengthByteWriter writer; ByteTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.writer = new RunLengthByteWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA)); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { byte val = ((ByteObjectInspector) inspector).get(obj); indexStatistics.updateInteger(val); if (createBloomFilter) { bloomFilter.addLong(val); } writer.write(val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class IntegerTreeWriter extends TreeWriter { private final IntegerWriter writer; private final ShortObjectInspector shortInspector; private final IntObjectInspector intInspector; private final LongObjectInspector longInspector; private boolean isDirectV2 = true; IntegerTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); OutStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.writer = createIntegerWriter(out, true, isDirectV2, writer); if (inspector instanceof IntObjectInspector) { intInspector = (IntObjectInspector) inspector; shortInspector = null; longInspector = null; } else { intInspector = null; if (inspector instanceof LongObjectInspector) { longInspector = (LongObjectInspector) inspector; shortInspector = null; } else { shortInspector = (ShortObjectInspector) inspector; longInspector = null; } } recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { long val; if (intInspector != null) { val = intInspector.get(obj); } else if (longInspector != null) { val = longInspector.get(obj); } else { val = shortInspector.get(obj); } indexStatistics.updateInteger(val); if (createBloomFilter) { // integers are converted to longs in column statistics and during SARG evaluation bloomFilter.addLong(val); } writer.write(val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } } private static class FloatTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; FloatTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { float val = ((FloatObjectInspector) inspector).get(obj); indexStatistics.updateDouble(val); if (createBloomFilter) { // floats are converted to doubles in column statistics and during SARG evaluation bloomFilter.addDouble(val); } utils.writeFloat(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } private static class DoubleTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final SerializationUtils utils; DoubleTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.utils = new SerializationUtils(); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { double val = ((DoubleObjectInspector) inspector).get(obj); indexStatistics.updateDouble(val); if (createBloomFilter) { bloomFilter.addDouble(val); } utils.writeDouble(stream, val); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); } } private static class StringTreeWriter extends TreeWriter { private static final int INITIAL_DICTIONARY_SIZE = 4096; private final OutStream stringOutput; private final IntegerWriter lengthOutput; private final IntegerWriter rowOutput; private final StringRedBlackTree dictionary = new StringRedBlackTree(INITIAL_DICTIONARY_SIZE); private final DynamicIntArray rows = new DynamicIntArray(); private final PositionedOutputStream directStreamOutput; private final IntegerWriter directLengthOutput; private final List<OrcProto.RowIndexEntry> savedRowIndex = new ArrayList<OrcProto.RowIndexEntry>(); private final boolean buildIndex; private final List<Long> rowIndexValueCount = new ArrayList<Long>(); // If the number of keys in a dictionary is greater than this fraction of //the total number of non-null rows, turn off dictionary encoding private final float dictionaryKeySizeThreshold; private boolean useDictionaryEncoding = true; private boolean isDirectV2 = true; private boolean doneDictionaryCheck; private final boolean strideDictionaryCheck; StringTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); stringOutput = writer.createStream(id, OrcProto.Stream.Kind.DICTIONARY_DATA); lengthOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); rowOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA), false, isDirectV2, writer); recordPosition(rowIndexPosition); rowIndexValueCount.add(0L); buildIndex = writer.buildIndex(); directStreamOutput = writer.createStream(id, OrcProto.Stream.Kind.DATA); directLengthOutput = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); dictionaryKeySizeThreshold = writer.getConfiguration().getFloat( HiveConf.ConfVars.HIVE_ORC_DICTIONARY_KEY_SIZE_THRESHOLD.varname, HiveConf.ConfVars.HIVE_ORC_DICTIONARY_KEY_SIZE_THRESHOLD. defaultFloatVal); strideDictionaryCheck = writer.getConfiguration().getBoolean( HiveConf.ConfVars.HIVE_ORC_ROW_INDEX_STRIDE_DICTIONARY_CHECK.varname, HiveConf.ConfVars.HIVE_ORC_ROW_INDEX_STRIDE_DICTIONARY_CHECK. defaultBoolVal); doneDictionaryCheck = false; } /** * Method to retrieve text values from the value object, which can be overridden * by subclasses. * @param obj value * @return Text text value from obj */ Text getTextValue(Object obj) { return ((StringObjectInspector) inspector).getPrimitiveWritableObject(obj); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { Text val = getTextValue(obj); if (useDictionaryEncoding || !strideDictionaryCheck) { rows.add(dictionary.add(val)); } else { // write data and length directStreamOutput.write(val.getBytes(), 0, val.getLength()); directLengthOutput.write(val.getLength()); } indexStatistics.updateString(val); if (createBloomFilter) { bloomFilter.addBytes(val.getBytes(), val.getLength()); } } } private boolean checkDictionaryEncoding() { if (!doneDictionaryCheck) { // Set the flag indicating whether or not to use dictionary encoding // based on whether or not the fraction of distinct keys over number of // non-null rows is less than the configured threshold float ratio = rows.size() > 0 ? (float) (dictionary.size()) / rows.size() : 0.0f; useDictionaryEncoding = !isDirectV2 || ratio <= dictionaryKeySizeThreshold; doneDictionaryCheck = true; } return useDictionaryEncoding; } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { // if rows in stripe is less than dictionaryCheckAfterRows, dictionary // checking would not have happened. So do it again here. checkDictionaryEncoding(); if (useDictionaryEncoding) { flushDictionary(); } else { // flushout any left over entries from dictionary if (rows.size() > 0) { flushDictionary(); } // suppress the stream for every stripe if dictionary is disabled stringOutput.suppress(); } // we need to build the rowindex before calling super, since it // writes it out. super.writeStripe(builder, requiredIndexEntries); stringOutput.flush(); lengthOutput.flush(); rowOutput.flush(); directStreamOutput.flush(); directLengthOutput.flush(); // reset all of the fields to be ready for the next stripe. dictionary.clear(); savedRowIndex.clear(); rowIndexValueCount.clear(); recordPosition(rowIndexPosition); rowIndexValueCount.add(0L); if (!useDictionaryEncoding) { // record the start positions of first index stride of next stripe i.e // beginning of the direct streams when dictionary is disabled recordDirectStreamPosition(); } } private void flushDictionary() throws IOException { final int[] dumpOrder = new int[dictionary.size()]; if (useDictionaryEncoding) { // Write the dictionary by traversing the red-black tree writing out // the bytes and lengths; and creating the map from the original order // to the final sorted order. dictionary.visit(new StringRedBlackTree.Visitor() { private int currentId = 0; @Override public void visit(StringRedBlackTree.VisitorContext context ) throws IOException { context.writeBytes(stringOutput); lengthOutput.write(context.getLength()); dumpOrder[context.getOriginalPosition()] = currentId++; } }); } else { // for direct encoding, we don't want the dictionary data stream stringOutput.suppress(); } int length = rows.size(); int rowIndexEntry = 0; OrcProto.RowIndex.Builder rowIndex = getRowIndex(); Text text = new Text(); // write the values translated into the dump order. for(int i = 0; i <= length; ++i) { // now that we are writing out the row values, we can finalize the // row index if (buildIndex) { while (i == rowIndexValueCount.get(rowIndexEntry) && rowIndexEntry < savedRowIndex.size()) { OrcProto.RowIndexEntry.Builder base = savedRowIndex.get(rowIndexEntry++).toBuilder(); if (useDictionaryEncoding) { rowOutput.getPosition(new RowIndexPositionRecorder(base)); } else { PositionRecorder posn = new RowIndexPositionRecorder(base); directStreamOutput.getPosition(posn); directLengthOutput.getPosition(posn); } rowIndex.addEntry(base.build()); } } if (i != length) { if (useDictionaryEncoding) { rowOutput.write(dumpOrder[rows.get(i)]); } else { dictionary.getText(text, rows.get(i)); directStreamOutput.write(text.getBytes(), 0, text.getLength()); directLengthOutput.write(text.getLength()); } } } rows.clear(); } @Override OrcProto.ColumnEncoding getEncoding() { // Returns the encoding used for the last call to writeStripe if (useDictionaryEncoding) { if(isDirectV2) { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DICTIONARY_V2). setDictionarySize(dictionary.size()).build(); } return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DICTIONARY). setDictionarySize(dictionary.size()).build(); } else { if(isDirectV2) { return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder().setKind( OrcProto.ColumnEncoding.Kind.DIRECT).build(); } } /** * This method doesn't call the super method, because unlike most of the * other TreeWriters, this one can't record the position in the streams * until the stripe is being flushed. Therefore it saves all of the entries * and augments them with the final information as the stripe is written. * @throws IOException */ @Override void createRowIndexEntry() throws IOException { getStripeStatistics().merge(indexStatistics); OrcProto.RowIndexEntry.Builder rowIndexEntry = getRowIndexEntry(); rowIndexEntry.setStatistics(indexStatistics.serialize()); indexStatistics.reset(); OrcProto.RowIndexEntry base = rowIndexEntry.build(); savedRowIndex.add(base); rowIndexEntry.clear(); addBloomFilterEntry(); recordPosition(rowIndexPosition); rowIndexValueCount.add(Long.valueOf(rows.size())); if (strideDictionaryCheck) { checkDictionaryEncoding(); } if (!useDictionaryEncoding) { if (rows.size() > 0) { flushDictionary(); // just record the start positions of next index stride recordDirectStreamPosition(); } else { // record the start positions of next index stride recordDirectStreamPosition(); getRowIndex().addEntry(base); } } } private void recordDirectStreamPosition() throws IOException { directStreamOutput.getPosition(rowIndexPosition); directLengthOutput.getPosition(rowIndexPosition); } @Override long estimateMemory() { return rows.getSizeInBytes() + dictionary.getSizeInBytes(); } } /** * Under the covers, char is written to ORC the same way as string. */ private static class CharTreeWriter extends StringTreeWriter { CharTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); } /** * Override base class implementation to support char values. */ @Override Text getTextValue(Object obj) { return (((HiveCharObjectInspector) inspector) .getPrimitiveWritableObject(obj)).getTextValue(); } } /** * Under the covers, varchar is written to ORC the same way as string. */ private static class VarcharTreeWriter extends StringTreeWriter { VarcharTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); } /** * Override base class implementation to support varchar values. */ @Override Text getTextValue(Object obj) { return (((HiveVarcharObjectInspector) inspector) .getPrimitiveWritableObject(obj)).getTextValue(); } } private static class BinaryTreeWriter extends TreeWriter { private final PositionedOutputStream stream; private final IntegerWriter length; private boolean isDirectV2 = true; BinaryTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.stream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.length = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { BytesWritable val = ((BinaryObjectInspector) inspector).getPrimitiveWritableObject(obj); stream.write(val.getBytes(), 0, val.getLength()); length.write(val.getLength()); indexStatistics.updateBinary(val); if (createBloomFilter) { bloomFilter.addBytes(val.getBytes(), val.getLength()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); stream.flush(); length.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); stream.getPosition(recorder); length.getPosition(recorder); } } static final int MILLIS_PER_SECOND = 1000; static final String BASE_TIMESTAMP_STRING = "2015-01-01 00:00:00"; private static class TimestampTreeWriter extends TreeWriter { private final IntegerWriter seconds; private final IntegerWriter nanos; private final boolean isDirectV2; private final long base_timestamp; TimestampTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); this.seconds = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.DATA), true, isDirectV2, writer); this.nanos = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.SECONDARY), false, isDirectV2, writer); recordPosition(rowIndexPosition); // for unit tests to set different time zones this.base_timestamp = Timestamp.valueOf(BASE_TIMESTAMP_STRING).getTime() / MILLIS_PER_SECOND; } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { Timestamp val = ((TimestampObjectInspector) inspector). getPrimitiveJavaObject(obj); indexStatistics.updateTimestamp(val); seconds.write((val.getTime() / MILLIS_PER_SECOND) - base_timestamp); nanos.write(formatNanos(val.getNanos())); if (createBloomFilter) { bloomFilter.addLong(val.getTime()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); seconds.flush(); nanos.flush(); recordPosition(rowIndexPosition); } private static long formatNanos(int nanos) { if (nanos == 0) { return 0; } else if (nanos % 100 != 0) { return ((long) nanos) << 3; } else { nanos /= 100; int trailingZeros = 1; while (nanos % 10 == 0 && trailingZeros < 7) { nanos /= 10; trailingZeros += 1; } return ((long) nanos) << 3 | trailingZeros; } } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); seconds.getPosition(recorder); nanos.getPosition(recorder); } } private static class DateTreeWriter extends TreeWriter { private final IntegerWriter writer; private final boolean isDirectV2; DateTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); OutStream out = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.isDirectV2 = isNewWriteFormat(writer); this.writer = createIntegerWriter(out, true, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { // Using the Writable here as it's used directly for writing as well as for stats. DateWritable val = ((DateObjectInspector) inspector).getPrimitiveWritableObject(obj); indexStatistics.updateDate(val); writer.write(val.getDays()); if (createBloomFilter) { bloomFilter.addLong(val.getDays()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); writer.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); writer.getPosition(recorder); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } } private static class DecimalTreeWriter extends TreeWriter { private final PositionedOutputStream valueStream; private final IntegerWriter scaleStream; private final boolean isDirectV2; DecimalTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); valueStream = writer.createStream(id, OrcProto.Stream.Kind.DATA); this.scaleStream = createIntegerWriter(writer.createStream(id, OrcProto.Stream.Kind.SECONDARY), true, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { HiveDecimal decimal = ((HiveDecimalObjectInspector) inspector). getPrimitiveJavaObject(obj); if (decimal == null) { return; } SerializationUtils.writeBigInteger(valueStream, decimal.unscaledValue()); scaleStream.write(decimal.scale()); indexStatistics.updateDecimal(decimal); if (createBloomFilter) { bloomFilter.addString(decimal.toString()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); valueStream.flush(); scaleStream.flush(); recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); valueStream.getPosition(recorder); scaleStream.getPosition(recorder); } } private static class StructTreeWriter extends TreeWriter { private final List<? extends StructField> fields; StructTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); StructObjectInspector structObjectInspector = (StructObjectInspector) inspector; fields = structObjectInspector.getAllStructFieldRefs(); childrenWriters = new TreeWriter[fields.size()]; for(int i=0; i < childrenWriters.length; ++i) { childrenWriters[i] = createTreeWriter( fields.get(i).getFieldObjectInspector(), writer, true); } recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { StructObjectInspector insp = (StructObjectInspector) inspector; for(int i = 0; i < fields.size(); ++i) { StructField field = fields.get(i); TreeWriter writer = childrenWriters[i]; writer.write(insp.getStructFieldData(obj, field)); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } } private static class ListTreeWriter extends TreeWriter { private final IntegerWriter lengths; private final boolean isDirectV2; ListTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); ListObjectInspector listObjectInspector = (ListObjectInspector) inspector; childrenWriters = new TreeWriter[1]; childrenWriters[0] = createTreeWriter(listObjectInspector.getListElementObjectInspector(), writer, true); lengths = createIntegerWriter(writer.createStream(columnId, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { ListObjectInspector insp = (ListObjectInspector) inspector; int len = insp.getListLength(obj); lengths.write(len); if (createBloomFilter) { bloomFilter.addLong(len); } for(int i=0; i < len; ++i) { childrenWriters[0].write(insp.getListElement(obj, i)); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); lengths.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); lengths.getPosition(recorder); } } private static class MapTreeWriter extends TreeWriter { private final IntegerWriter lengths; private final boolean isDirectV2; MapTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); this.isDirectV2 = isNewWriteFormat(writer); MapObjectInspector insp = (MapObjectInspector) inspector; childrenWriters = new TreeWriter[2]; childrenWriters[0] = createTreeWriter(insp.getMapKeyObjectInspector(), writer, true); childrenWriters[1] = createTreeWriter(insp.getMapValueObjectInspector(), writer, true); lengths = createIntegerWriter(writer.createStream(columnId, OrcProto.Stream.Kind.LENGTH), false, isDirectV2, writer); recordPosition(rowIndexPosition); } @Override OrcProto.ColumnEncoding getEncoding() { if (isDirectV2) { return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT_V2).build(); } return OrcProto.ColumnEncoding.newBuilder() .setKind(OrcProto.ColumnEncoding.Kind.DIRECT).build(); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { MapObjectInspector insp = (MapObjectInspector) inspector; // this sucks, but it will have to do until we can get a better // accessor in the MapObjectInspector. Map<?, ?> valueMap = insp.getMap(obj); lengths.write(valueMap.size()); if (createBloomFilter) { bloomFilter.addLong(valueMap.size()); } for(Map.Entry<?, ?> entry: valueMap.entrySet()) { childrenWriters[0].write(entry.getKey()); childrenWriters[1].write(entry.getValue()); } } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); lengths.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); lengths.getPosition(recorder); } } private static class UnionTreeWriter extends TreeWriter { private final RunLengthByteWriter tags; UnionTreeWriter(int columnId, ObjectInspector inspector, StreamFactory writer, boolean nullable) throws IOException { super(columnId, inspector, writer, nullable); UnionObjectInspector insp = (UnionObjectInspector) inspector; List<ObjectInspector> choices = insp.getObjectInspectors(); childrenWriters = new TreeWriter[choices.size()]; for(int i=0; i < childrenWriters.length; ++i) { childrenWriters[i] = createTreeWriter(choices.get(i), writer, true); } tags = new RunLengthByteWriter(writer.createStream(columnId, OrcProto.Stream.Kind.DATA)); recordPosition(rowIndexPosition); } @Override void write(Object obj) throws IOException { super.write(obj); if (obj != null) { UnionObjectInspector insp = (UnionObjectInspector) inspector; byte tag = insp.getTag(obj); tags.write(tag); if (createBloomFilter) { bloomFilter.addLong(tag); } childrenWriters[tag].write(insp.getField(obj)); } } @Override void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { super.writeStripe(builder, requiredIndexEntries); tags.flush(); for(TreeWriter child: childrenWriters) { child.writeStripe(builder, requiredIndexEntries); } recordPosition(rowIndexPosition); } @Override void recordPosition(PositionRecorder recorder) throws IOException { super.recordPosition(recorder); tags.getPosition(recorder); } } private static TreeWriter createTreeWriter(ObjectInspector inspector, StreamFactory streamFactory, boolean nullable) throws IOException { switch (inspector.getCategory()) { case PRIMITIVE: switch (((PrimitiveObjectInspector) inspector).getPrimitiveCategory()) { case BOOLEAN: return new BooleanTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case BYTE: return new ByteTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case SHORT: case INT: case LONG: return new IntegerTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case FLOAT: return new FloatTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DOUBLE: return new DoubleTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case STRING: return new StringTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case CHAR: return new CharTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case VARCHAR: return new VarcharTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case BINARY: return new BinaryTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case TIMESTAMP: return new TimestampTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DATE: return new DateTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case DECIMAL: return new DecimalTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); default: throw new IllegalArgumentException("Bad primitive category " + ((PrimitiveObjectInspector) inspector).getPrimitiveCategory()); } case STRUCT: return new StructTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case MAP: return new MapTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case LIST: return new ListTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); case UNION: return new UnionTreeWriter(streamFactory.getNextColumnId(), inspector, streamFactory, nullable); default: throw new IllegalArgumentException("Bad category: " + inspector.getCategory()); } } private static void writeTypes(OrcProto.Footer.Builder builder, TreeWriter treeWriter) { OrcProto.Type.Builder type = OrcProto.Type.newBuilder(); switch (treeWriter.inspector.getCategory()) { case PRIMITIVE: switch (((PrimitiveObjectInspector) treeWriter.inspector). getPrimitiveCategory()) { case BOOLEAN: type.setKind(OrcProto.Type.Kind.BOOLEAN); break; case BYTE: type.setKind(OrcProto.Type.Kind.BYTE); break; case SHORT: type.setKind(OrcProto.Type.Kind.SHORT); break; case INT: type.setKind(OrcProto.Type.Kind.INT); break; case LONG: type.setKind(OrcProto.Type.Kind.LONG); break; case FLOAT: type.setKind(OrcProto.Type.Kind.FLOAT); break; case DOUBLE: type.setKind(OrcProto.Type.Kind.DOUBLE); break; case STRING: type.setKind(OrcProto.Type.Kind.STRING); break; case CHAR: // The char length needs to be written to file and should be available // from the object inspector CharTypeInfo charTypeInfo = (CharTypeInfo) ((PrimitiveObjectInspector) treeWriter.inspector).getTypeInfo(); type.setKind(Type.Kind.CHAR); type.setMaximumLength(charTypeInfo.getLength()); break; case VARCHAR: // The varchar length needs to be written to file and should be available // from the object inspector VarcharTypeInfo typeInfo = (VarcharTypeInfo) ((PrimitiveObjectInspector) treeWriter.inspector).getTypeInfo(); type.setKind(Type.Kind.VARCHAR); type.setMaximumLength(typeInfo.getLength()); break; case BINARY: type.setKind(OrcProto.Type.Kind.BINARY); break; case TIMESTAMP: type.setKind(OrcProto.Type.Kind.TIMESTAMP); break; case DATE: type.setKind(OrcProto.Type.Kind.DATE); break; case DECIMAL: DecimalTypeInfo decTypeInfo = (DecimalTypeInfo)((PrimitiveObjectInspector)treeWriter.inspector).getTypeInfo(); type.setKind(OrcProto.Type.Kind.DECIMAL); type.setPrecision(decTypeInfo.precision()); type.setScale(decTypeInfo.scale()); break; default: throw new IllegalArgumentException("Unknown primitive category: " + ((PrimitiveObjectInspector) treeWriter.inspector). getPrimitiveCategory()); } break; case LIST: type.setKind(OrcProto.Type.Kind.LIST); type.addSubtypes(treeWriter.childrenWriters[0].id); break; case MAP: type.setKind(OrcProto.Type.Kind.MAP); type.addSubtypes(treeWriter.childrenWriters[0].id); type.addSubtypes(treeWriter.childrenWriters[1].id); break; case STRUCT: type.setKind(OrcProto.Type.Kind.STRUCT); for(TreeWriter child: treeWriter.childrenWriters) { type.addSubtypes(child.id); } for(StructField field: ((StructTreeWriter) treeWriter).fields) { type.addFieldNames(field.getFieldName()); } break; case UNION: type.setKind(OrcProto.Type.Kind.UNION); for(TreeWriter child: treeWriter.childrenWriters) { type.addSubtypes(child.id); } break; default: throw new IllegalArgumentException("Unknown category: " + treeWriter.inspector.getCategory()); } builder.addTypes(type); for(TreeWriter child: treeWriter.childrenWriters) { writeTypes(builder, child); } } @VisibleForTesting FSDataOutputStream getStream() throws IOException { if (rawWriter == null) { rawWriter = fs.create(path, false, HDFS_BUFFER_SIZE, fs.getDefaultReplication(), blockSize); rawWriter.writeBytes(OrcFile.MAGIC); headerLength = rawWriter.getPos(); writer = new OutStream("metadata", bufferSize, codec, new DirectStream(rawWriter)); protobufWriter = CodedOutputStream.newInstance(writer); } return rawWriter; } private void createRowIndexEntry() throws IOException { treeWriter.createRowIndexEntry(); rowsInIndex = 0; } private void flushStripe() throws IOException { getStream(); if (buildIndex && rowsInIndex != 0) { createRowIndexEntry(); } if (rowsInStripe != 0) { if (callback != null) { callback.preStripeWrite(callbackContext); } // finalize the data for the stripe int requiredIndexEntries = rowIndexStride == 0 ? 0 : (int) ((rowsInStripe + rowIndexStride - 1) / rowIndexStride); OrcProto.StripeFooter.Builder builder = OrcProto.StripeFooter.newBuilder(); treeWriter.writeStripe(builder, requiredIndexEntries); long indexSize = 0; long dataSize = 0; for(Map.Entry<StreamName, BufferedStream> pair: streams.entrySet()) { BufferedStream stream = pair.getValue(); if (!stream.isSuppressed()) { stream.flush(); StreamName name = pair.getKey(); long streamSize = pair.getValue().getOutputSize(); builder.addStreams(OrcProto.Stream.newBuilder() .setColumn(name.getColumn()) .setKind(name.getKind()) .setLength(streamSize)); if (StreamName.Area.INDEX == name.getArea()) { indexSize += streamSize; } else { dataSize += streamSize; } } } OrcProto.StripeFooter footer = builder.build(); // Do we need to pad the file so the stripe doesn't straddle a block // boundary? long start = rawWriter.getPos(); final long currentStripeSize = indexSize + dataSize + footer.getSerializedSize(); final long available = blockSize - (start % blockSize); final long overflow = currentStripeSize - adjustedStripeSize; final float availRatio = (float) available / (float) defaultStripeSize; if (availRatio > 0.0f && availRatio < 1.0f && availRatio > paddingTolerance) { // adjust default stripe size to fit into remaining space, also adjust // the next stripe for correction based on the current stripe size // and user specified padding tolerance. Since stripe size can overflow // the default stripe size we should apply this correction to avoid // writing portion of last stripe to next hdfs block. float correction = overflow > 0 ? (float) overflow / (float) adjustedStripeSize : 0.0f; // correction should not be greater than user specified padding // tolerance correction = correction > paddingTolerance ? paddingTolerance : correction; // adjust next stripe size based on current stripe estimate correction adjustedStripeSize = (long) ((1.0f - correction) * (availRatio * defaultStripeSize)); } else if (availRatio >= 1.0) { adjustedStripeSize = defaultStripeSize; } if (availRatio < paddingTolerance && addBlockPadding) { long padding = blockSize - (start % blockSize); byte[] pad = new byte[(int) Math.min(HDFS_BUFFER_SIZE, padding)]; LOG.info(String.format("Padding ORC by %d bytes (<= %.2f * %d)", padding, availRatio, defaultStripeSize)); start += padding; while (padding > 0) { int writeLen = (int) Math.min(padding, pad.length); rawWriter.write(pad, 0, writeLen); padding -= writeLen; } adjustedStripeSize = defaultStripeSize; } else if (currentStripeSize < blockSize && (start % blockSize) + currentStripeSize > blockSize) { // even if you don't pad, reset the default stripe size when crossing a // block boundary adjustedStripeSize = defaultStripeSize; } // write out the data streams for(Map.Entry<StreamName, BufferedStream> pair: streams.entrySet()) { BufferedStream stream = pair.getValue(); if (!stream.isSuppressed()) { stream.spillTo(rawWriter); } stream.clear(); } footer.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); long footerLength = rawWriter.getPos() - start - dataSize - indexSize; OrcProto.StripeInformation dirEntry = OrcProto.StripeInformation.newBuilder() .setOffset(start) .setNumberOfRows(rowsInStripe) .setIndexLength(indexSize) .setDataLength(dataSize) .setFooterLength(footerLength).build(); stripes.add(dirEntry); rowCount += rowsInStripe; rowsInStripe = 0; } } private long computeRawDataSize() { long result = 0; for (TreeWriter child : treeWriter.getChildrenWriters()) { result += getRawDataSizeFromInspectors(child, child.inspector); } return result; } private long getRawDataSizeFromInspectors(TreeWriter child, ObjectInspector oi) { long total = 0; switch (oi.getCategory()) { case PRIMITIVE: total += getRawDataSizeFromPrimitives(child, oi); break; case LIST: case MAP: case UNION: case STRUCT: for (TreeWriter tw : child.childrenWriters) { total += getRawDataSizeFromInspectors(tw, tw.inspector); } break; default: LOG.debug("Unknown object inspector category."); break; } return total; } private long getRawDataSizeFromPrimitives(TreeWriter child, ObjectInspector oi) { long result = 0; long numVals = child.fileStatistics.getNumberOfValues(); switch (((PrimitiveObjectInspector) oi).getPrimitiveCategory()) { case BOOLEAN: case BYTE: case SHORT: case INT: case FLOAT: return numVals * JavaDataModel.get().primitive1(); case LONG: case DOUBLE: return numVals * JavaDataModel.get().primitive2(); case STRING: case VARCHAR: case CHAR: // ORC strings are converted to java Strings. so use JavaDataModel to // compute the overall size of strings child = (StringTreeWriter) child; StringColumnStatistics scs = (StringColumnStatistics) child.fileStatistics; numVals = numVals == 0 ? 1 : numVals; int avgStringLen = (int) (scs.getSum() / numVals); return numVals * JavaDataModel.get().lengthForStringOfLength(avgStringLen); case DECIMAL: return numVals * JavaDataModel.get().lengthOfDecimal(); case DATE: return numVals * JavaDataModel.get().lengthOfDate(); case BINARY: // get total length of binary blob BinaryColumnStatistics bcs = (BinaryColumnStatistics) child.fileStatistics; return bcs.getSum(); case TIMESTAMP: return numVals * JavaDataModel.get().lengthOfTimestamp(); default: LOG.debug("Unknown primitive category."); break; } return result; } private OrcProto.CompressionKind writeCompressionKind(CompressionKind kind) { switch (kind) { case NONE: return OrcProto.CompressionKind.NONE; case ZLIB: return OrcProto.CompressionKind.ZLIB; case SNAPPY: return OrcProto.CompressionKind.SNAPPY; case LZO: return OrcProto.CompressionKind.LZO; default: throw new IllegalArgumentException("Unknown compression " + kind); } } private void writeFileStatistics(OrcProto.Footer.Builder builder, TreeWriter writer) throws IOException { builder.addStatistics(writer.fileStatistics.serialize()); for(TreeWriter child: writer.getChildrenWriters()) { writeFileStatistics(builder, child); } } private int writeMetadata(long bodyLength) throws IOException { getStream(); OrcProto.Metadata.Builder builder = OrcProto.Metadata.newBuilder(); for(OrcProto.StripeStatistics.Builder ssb : treeWriter.stripeStatsBuilders) { builder.addStripeStats(ssb.build()); } long startPosn = rawWriter.getPos(); OrcProto.Metadata metadata = builder.build(); metadata.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); return (int) (rawWriter.getPos() - startPosn); } private int writeFooter(long bodyLength) throws IOException { getStream(); OrcProto.Footer.Builder builder = OrcProto.Footer.newBuilder(); builder.setContentLength(bodyLength); builder.setHeaderLength(headerLength); builder.setNumberOfRows(rowCount); builder.setRowIndexStride(rowIndexStride); // populate raw data size rawDataSize = computeRawDataSize(); // serialize the types writeTypes(builder, treeWriter); // add the stripe information for(OrcProto.StripeInformation stripe: stripes) { builder.addStripes(stripe); } // add the column statistics writeFileStatistics(builder, treeWriter); // add all of the user metadata for(Map.Entry<String, ByteString> entry: userMetadata.entrySet()) { builder.addMetadata(OrcProto.UserMetadataItem.newBuilder() .setName(entry.getKey()).setValue(entry.getValue())); } long startPosn = rawWriter.getPos(); OrcProto.Footer footer = builder.build(); footer.writeTo(protobufWriter); protobufWriter.flush(); writer.flush(); return (int) (rawWriter.getPos() - startPosn); } private int writePostScript(int footerLength, int metadataLength) throws IOException { OrcProto.PostScript.Builder builder = OrcProto.PostScript.newBuilder() .setCompression(writeCompressionKind(compress)) .setFooterLength(footerLength) .setMetadataLength(metadataLength) .setMagic(OrcFile.MAGIC) .addVersion(version.getMajor()) .addVersion(version.getMinor()) .setWriterVersion(OrcFile.WriterVersion.HIVE_8732.getId()); if (compress != CompressionKind.NONE) { builder.setCompressionBlockSize(bufferSize); } OrcProto.PostScript ps = builder.build(); // need to write this uncompressed long startPosn = rawWriter.getPos(); ps.writeTo(rawWriter); long length = rawWriter.getPos() - startPosn; if (length > 255) { throw new IllegalArgumentException("PostScript too large at " + length); } return (int) length; } private long estimateStripeSize() { long result = 0; for(BufferedStream stream: streams.values()) { result += stream.getBufferSize(); } result += treeWriter.estimateMemory(); return result; } @Override public synchronized void addUserMetadata(String name, ByteBuffer value) { userMetadata.put(name, ByteString.copyFrom(value)); } @Override public void addRow(Object row) throws IOException { synchronized (this) { treeWriter.write(row); rowsInStripe += 1; if (buildIndex) { rowsInIndex += 1; if (rowsInIndex >= rowIndexStride) { createRowIndexEntry(); } } } memoryManager.addedRow(); } @Override public void close() throws IOException { if (callback != null) { callback.preFooterWrite(callbackContext); } // remove us from the memory manager so that we don't get any callbacks memoryManager.removeWriter(path); // actually close the file synchronized (this) { flushStripe(); int metadataLength = writeMetadata(rawWriter.getPos()); int footerLength = writeFooter(rawWriter.getPos() - metadataLength); rawWriter.writeByte(writePostScript(footerLength, metadataLength)); rawWriter.close(); } } /** * Raw data size will be compute when writing the file footer. Hence raw data * size value will be available only after closing the writer. */ @Override public long getRawDataSize() { return rawDataSize; } /** * Row count gets updated when flushing the stripes. To get accurate row * count call this method after writer is closed. */ @Override public long getNumberOfRows() { return rowCount; } @Override public synchronized long writeIntermediateFooter() throws IOException { // flush any buffered rows flushStripe(); // write a footer if (stripesAtLastFlush != stripes.size()) { if (callback != null) { callback.preFooterWrite(callbackContext); } int metaLength = writeMetadata(rawWriter.getPos()); int footLength = writeFooter(rawWriter.getPos() - metaLength); rawWriter.writeByte(writePostScript(footLength, metaLength)); stripesAtLastFlush = stripes.size(); OrcInputFormat.SHIMS.hflush(rawWriter); } return rawWriter.getPos(); } @Override public void appendStripe(byte[] stripe, int offset, int length, StripeInformation stripeInfo, OrcProto.StripeStatistics stripeStatistics) throws IOException { checkArgument(stripe != null, "Stripe must not be null"); checkArgument(length <= stripe.length, "Specified length must not be greater specified array length"); checkArgument(stripeInfo != null, "Stripe information must not be null"); checkArgument(stripeStatistics != null, "Stripe statistics must not be null"); getStream(); long start = rawWriter.getPos(); long stripeLen = length; long availBlockSpace = blockSize - (start % blockSize); // see if stripe can fit in the current hdfs block, else pad the remaining // space in the block if (stripeLen < blockSize && stripeLen > availBlockSpace && addBlockPadding) { byte[] pad = new byte[(int) Math.min(HDFS_BUFFER_SIZE, availBlockSpace)]; LOG.info(String.format("Padding ORC by %d bytes while merging..", availBlockSpace)); start += availBlockSpace; while (availBlockSpace > 0) { int writeLen = (int) Math.min(availBlockSpace, pad.length); rawWriter.write(pad, 0, writeLen); availBlockSpace -= writeLen; } } rawWriter.write(stripe); rowsInStripe = stripeStatistics.getColStats(0).getNumberOfValues(); rowCount += rowsInStripe; // since we have already written the stripe, just update stripe statistics treeWriter.stripeStatsBuilders.add(stripeStatistics.toBuilder()); // update file level statistics updateFileStatistics(stripeStatistics); // update stripe information OrcProto.StripeInformation dirEntry = OrcProto.StripeInformation .newBuilder() .setOffset(start) .setNumberOfRows(rowsInStripe) .setIndexLength(stripeInfo.getIndexLength()) .setDataLength(stripeInfo.getDataLength()) .setFooterLength(stripeInfo.getFooterLength()) .build(); stripes.add(dirEntry); // reset it after writing the stripe rowsInStripe = 0; } private void updateFileStatistics(OrcProto.StripeStatistics stripeStatistics) { List<OrcProto.ColumnStatistics> cs = stripeStatistics.getColStatsList(); List<TreeWriter> allWriters = getAllColumnTreeWriters(treeWriter); for (int i = 0; i < allWriters.size(); i++) { allWriters.get(i).fileStatistics.merge(ColumnStatisticsImpl.deserialize(cs.get(i))); } } private List<TreeWriter> getAllColumnTreeWriters(TreeWriter rootTreeWriter) { List<TreeWriter> result = Lists.newArrayList(); getAllColumnTreeWritersImpl(rootTreeWriter, result); return result; } private void getAllColumnTreeWritersImpl(TreeWriter tw, List<TreeWriter> result) { result.add(tw); for (TreeWriter child : tw.childrenWriters) { getAllColumnTreeWritersImpl(child, result); } } @Override public void appendUserMetadata(List<UserMetadataItem> userMetadata) { if (userMetadata != null) { for (UserMetadataItem item : userMetadata) { this.userMetadata.put(item.getName(), item.getValue()); } } } }
HIVE-10790 : orc write on viewFS throws exception (Xioawei Wang via Ashutosh Chauhan) Signed-off-by: Ashutosh Chauhan <[email protected]>
ql/src/java/org/apache/hadoop/hive/ql/io/orc/WriterImpl.java
HIVE-10790 : orc write on viewFS throws exception (Xioawei Wang via Ashutosh Chauhan)
Java
apache-2.0
5c01cd3ad7a9ff14e00c978d17dc16c75f89d827
0
ProfilingIO/insight-ml
/* * Copyright (C) 2016 Stefan Henß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.insightml.data; import java.util.Collection; import javax.annotation.Nonnull; import com.insightml.data.features.selection.IgnoreFeatureFilter; import com.insightml.data.samples.Sample; import com.insightml.data.samples.SimpleSample; import com.insightml.utils.Check; import com.insightml.utils.IArguments; public final class SimpleDataset<I extends Sample, O> extends AbstractDataset<I, O> { private final @Nonnull Collection<I> training; private final FeaturesConfig<I, O> config; public SimpleDataset(final String name, final @Nonnull Collection<I> training, final FeaturesConfig<I, O> config) { super(name); this.training = training; this.config = config; } public static <S extends SimpleSample, O> SimpleDataset<S, O> create(final @Nonnull Collection<S> instances) { return new SimpleDataset<>("SimpleDataset", instances, new AnonymousFeaturesConfig<>(instances.stream(), SimpleSample::loadFeatures, -9999999.0, false, new IgnoreFeatureFilter())); } @Override public FeaturesConfig<I, O> getFeaturesConfig(final IArguments arguments) { return config; } @Override public Iterable<I> loadTraining(final Integer labelIndex) { Check.argument(labelIndex == null || labelIndex == 0); return training; } @Override public Collection<I> loadAll() { return training; } }
src/main/java/com/insightml/data/SimpleDataset.java
/* * Copyright (C) 2016 Stefan Henß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.insightml.data; import java.util.Collection; import javax.annotation.Nonnull; import com.insightml.data.features.selection.IgnoreFeatureFilter; import com.insightml.data.samples.Sample; import com.insightml.data.samples.SimpleSample; import com.insightml.utils.Check; import com.insightml.utils.IArguments; public final class SimpleDataset<I extends Sample, O> extends AbstractDataset<I, O> { private final @Nonnull Iterable<I> training; private final FeaturesConfig<I, O> config; public SimpleDataset(final String name, final @Nonnull Iterable<I> training, final FeaturesConfig<I, O> config) { super(name); this.training = training; this.config = config; } public static <S extends SimpleSample, O> SimpleDataset<S, O> create(final @Nonnull Collection<S> instances) { return new SimpleDataset<>("SimpleDataset", instances, new AnonymousFeaturesConfig<>(instances.stream(), SimpleSample::loadFeatures, -9999999.0, false, new IgnoreFeatureFilter())); } @Override public FeaturesConfig<I, O> getFeaturesConfig(final IArguments arguments) { return config; } @Override public Iterable<I> loadTraining(final Integer labelIndex) { Check.argument(labelIndex == null || labelIndex == 0); return training; } @Override public Iterable<I> loadAll() { return loadTraining(null); } }
SimpleDataset: restrict type of training data
src/main/java/com/insightml/data/SimpleDataset.java
SimpleDataset: restrict type of training data
Java
apache-2.0
696dd3c2f42018e49df00458ca8dbe5244e356a7
0
AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewGroupCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; /** * DrawerLayout acts as a top-level container for window content that allows for * interactive "drawer" views to be pulled out from the edge of the window. * * <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code> * attribute on child views corresponding to which side of the view you want the drawer * to emerge from: left or right. (Or start/end on platform versions that support layout direction.) * </p> * * <p>To use a DrawerLayout, position your primary content view as the first child with * a width and height of <code>match_parent</code>. Add drawers as child views after the main * content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use * <code>match_parent</code> for height with a fixed width.</p> * * <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views. * Avoid performing expensive operations such as layout during animation as it can cause * stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state. * {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p> * * <p>As per the <a href="{@docRoot}design/patterns/navigation-drawer.html">Android Design * guide</a>, any drawers positioned to the left/start should * always contain content for navigating around the application, whereas any drawers * positioned to the right/end should always contain actions to take on the current content. * This preserves the same navigation left, actions right structure present in the Action Bar * and elsewhere.</p> * * <p>For more information about how to use DrawerLayout, read <a * href="{@docRoot}training/implementing-navigation/nav-drawer.html">Creating a Navigation * Drawer</a>.</p> */ public class DrawerLayout extends ViewGroup implements DrawerLayoutImpl { private static final String TAG = "DrawerLayout"; @IntDef({STATE_IDLE, STATE_DRAGGING, STATE_SETTLING}) @Retention(RetentionPolicy.SOURCE) private @interface State {} /** * Indicates that any drawers are in an idle, settled state. No animation is in progress. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * Indicates that a drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * Indicates that a drawer is in the process of settling to a final position. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** @hide */ @IntDef({LOCK_MODE_UNLOCKED, LOCK_MODE_LOCKED_CLOSED, LOCK_MODE_LOCKED_OPEN}) @Retention(RetentionPolicy.SOURCE) private @interface LockMode {} /** * The drawer is unlocked. */ public static final int LOCK_MODE_UNLOCKED = 0; /** * The drawer is locked closed. The user may not open it, though * the app may open it programmatically. */ public static final int LOCK_MODE_LOCKED_CLOSED = 1; /** * The drawer is locked open. The user may not close it, though the app * may close it programmatically. */ public static final int LOCK_MODE_LOCKED_OPEN = 2; /** @hide */ @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END}) @Retention(RetentionPolicy.SOURCE) private @interface EdgeGravity {} private static final int MIN_DRAWER_MARGIN = 64; // dp private static final int DEFAULT_SCRIM_COLOR = 0x99000000; /** * Length of time to delay before peeking the drawer. */ private static final int PEEK_DELAY = 160; // ms /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second /** * Experimental feature. */ private static final boolean ALLOW_EDGE_LOCK = false; private static final boolean CHILDREN_DISALLOW_INTERCEPT = true; private static final float TOUCH_SLOP_SENSITIVITY = 1.f; private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; private final ChildAccessibilityDelegate mChildAccessibilityDelegate = new ChildAccessibilityDelegate(); private int mMinDrawerMargin; private int mScrimColor = DEFAULT_SCRIM_COLOR; private float mScrimOpacity; private Paint mScrimPaint = new Paint(); private final ViewDragHelper mLeftDragger; private final ViewDragHelper mRightDragger; private final ViewDragCallback mLeftCallback; private final ViewDragCallback mRightCallback; private int mDrawerState; private boolean mInLayout; private boolean mFirstLayout = true; private int mLockModeLeft; private int mLockModeRight; private boolean mDisallowInterceptRequested; private boolean mChildrenCanceledTouch; private DrawerListener mListener; private float mInitialMotionX; private float mInitialMotionY; private Drawable mShadowLeft; private Drawable mShadowRight; private Drawable mStatusBarBackground; private CharSequence mTitleLeft; private CharSequence mTitleRight; private Object mLastInsets; private boolean mDrawStatusBarBackground; /** * Listener for monitoring events about drawers. */ public interface DrawerListener { /** * Called when a drawer's position changes. * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ public void onDrawerSlide(View drawerView, float slideOffset); /** * Called when a drawer has settled in a completely open state. * The drawer is interactive at this point. * * @param drawerView Drawer view that is now open */ public void onDrawerOpened(View drawerView); /** * Called when a drawer has settled in a completely closed state. * * @param drawerView Drawer view that is now closed */ public void onDrawerClosed(View drawerView); /** * Called when the drawer motion state changes. The new state will * be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * * @param newState The new drawer motion state */ public void onDrawerStateChanged(@State int newState); } /** * Stub/no-op implementations of all methods of {@link DrawerListener}. * Override this if you only care about a few of the available callback methods. */ public static abstract class SimpleDrawerListener implements DrawerListener { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } } interface DrawerLayoutCompatImpl { void configureApplyInsets(View drawerLayout); void dispatchChildInsets(View child, Object insets, int drawerGravity); void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity); int getTopInset(Object lastInsets); } static class DrawerLayoutCompatImplBase implements DrawerLayoutCompatImpl { public void configureApplyInsets(View drawerLayout) { // This space for rent } public void dispatchChildInsets(View child, Object insets, int drawerGravity) { // This space for rent } public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) { // This space for rent } public int getTopInset(Object insets) { return 0; } } static class DrawerLayoutCompatImplApi21 implements DrawerLayoutCompatImpl { public void configureApplyInsets(View drawerLayout) { DrawerLayoutCompatApi21.configureApplyInsets(drawerLayout); } public void dispatchChildInsets(View child, Object insets, int drawerGravity) { DrawerLayoutCompatApi21.dispatchChildInsets(child, insets, drawerGravity); } public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) { DrawerLayoutCompatApi21.applyMarginInsets(lp, insets, drawerGravity); } public int getTopInset(Object insets) { return DrawerLayoutCompatApi21.getTopInset(insets); } } static { final int version = Build.VERSION.SDK_INT; if (version >= 21) { IMPL = new DrawerLayoutCompatImplApi21(); } else { IMPL = new DrawerLayoutCompatImplBase(); } } static final DrawerLayoutCompatImpl IMPL; public DrawerLayout(Context context) { this(context, null); } public DrawerLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DrawerLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); final float density = getResources().getDisplayMetrics().density; mMinDrawerMargin = (int) (MIN_DRAWER_MARGIN * density + 0.5f); final float minVel = MIN_FLING_VELOCITY * density; mLeftCallback = new ViewDragCallback(Gravity.LEFT); mRightCallback = new ViewDragCallback(Gravity.RIGHT); mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback); mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); mLeftDragger.setMinVelocity(minVel); mLeftCallback.setDragger(mLeftDragger); mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback); mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mRightDragger.setMinVelocity(minVel); mRightCallback.setDragger(mRightDragger); // So that we can catch the back button setFocusableInTouchMode(true); ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate()); ViewGroupCompat.setMotionEventSplittingEnabled(this, false); if (ViewCompat.getFitsSystemWindows(this)) { IMPL.configureApplyInsets(this); } } /** * @hide Internal use only; called to apply window insets when configured * with fitsSystemWindows="true" */ @Override public void setChildInsets(Object insets, boolean draw) { mLastInsets = insets; mDrawStatusBarBackground = draw; setWillNotDraw(!draw && getBackground() == null); requestLayout(); } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param shadowDrawable Shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(Drawable shadowDrawable, @EdgeGravity int gravity) { /* * TODO Someone someday might want to set more complex drawables here. * They're probably nuts, but we might want to consider registering callbacks, * setting states, etc. properly. */ final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); if ((absGravity & Gravity.LEFT) == Gravity.LEFT) { mShadowLeft = shadowDrawable; invalidate(); } if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) { mShadowRight = shadowDrawable; invalidate(); } } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param resId Resource id of a shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(@DrawableRes int resId, @EdgeGravity int gravity) { setDrawerShadow(getResources().getDrawable(resId), gravity); } /** * Set a color to use for the scrim that obscures primary content while a drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set a listener to be notified of drawer events. * * @param listener Listener to notify when drawer events occur * @see DrawerListener */ public void setDrawerListener(DrawerListener listener) { mListener = listener; } /** * Enable or disable interaction with all drawers. * * <p>This allows the application to restrict the user's ability to open or close * any drawer within this layout. DrawerLayout will still respond to calls to * {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking drawers open or closed will implicitly open or close * any drawers as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. */ public void setDrawerLockMode(@LockMode int lockMode) { setDrawerLockMode(lockMode, Gravity.LEFT); setDrawerLockMode(lockMode, Gravity.RIGHT); } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param edgeGravity Gravity.LEFT, RIGHT, START or END. * Expresses which drawer to change the mode for. * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(@LockMode int lockMode, @EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mLockModeLeft = lockMode; } else if (absGravity == Gravity.RIGHT) { mLockModeRight = lockMode; } if (lockMode != LOCK_MODE_UNLOCKED) { // Cancel interaction in progress final ViewDragHelper helper = absGravity == Gravity.LEFT ? mLeftDragger : mRightDragger; helper.cancel(); } switch (lockMode) { case LOCK_MODE_LOCKED_OPEN: final View toOpen = findDrawerWithGravity(absGravity); if (toOpen != null) { openDrawer(toOpen); } break; case LOCK_MODE_LOCKED_CLOSED: final View toClose = findDrawerWithGravity(absGravity); if (toClose != null) { closeDrawer(toClose); } break; // default: do nothing } } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param drawerView The drawer view to change the lock mode for * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(@LockMode int lockMode, View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity"); } final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; setDrawerLockMode(lockMode, gravity); } /** * Check the lock mode of the drawer with the given gravity. * * @param edgeGravity Gravity of the drawer to check * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ @LockMode public int getDrawerLockMode(@EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Check the lock mode of the given drawer view. * * @param drawerView Drawer view to check lock mode * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ @LockMode public int getDrawerLockMode(View drawerView) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Sets the title of the drawer with the given gravity. * <p> * When accessibility is turned on, this is the title that will be used to * identify the drawer to the active accessibility service. * * @param edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which * drawer to set the title for. * @param title The title for the drawer. */ public void setDrawerTitle(@EdgeGravity int edgeGravity, CharSequence title) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mTitleLeft = title; } else if (absGravity == Gravity.RIGHT) { mTitleRight = title; } } /** * Returns the title of the drawer with the given gravity. * * @param edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which * drawer to return the title for. * @return The title of the drawer, or null if none set. * @see #setDrawerTitle(int, CharSequence) */ @Nullable public CharSequence getDrawerTitle(@EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mTitleLeft; } else if (absGravity == Gravity.RIGHT) { return mTitleRight; } return null; } /** * Resolve the shared state of all drawers from the component ViewDragHelpers. * Should be called whenever a ViewDragHelper's state changes. */ void updateDrawerState(int forGravity, @State int activeState, View activeDrawer) { final int leftState = mLeftDragger.getViewDragState(); final int rightState = mRightDragger.getViewDragState(); final int state; if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) { state = STATE_DRAGGING; } else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) { state = STATE_SETTLING; } else { state = STATE_IDLE; } if (activeDrawer != null && activeState == STATE_IDLE) { final LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams(); if (lp.onScreen == 0) { dispatchOnDrawerClosed(activeDrawer); } else if (lp.onScreen == 1) { dispatchOnDrawerOpened(activeDrawer); } } if (state != mDrawerState) { mDrawerState = state; if (mListener != null) { mListener.onDrawerStateChanged(state); } } } void dispatchOnDrawerClosed(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (lp.knownOpen) { lp.knownOpen = false; if (mListener != null) { mListener.onDrawerClosed(drawerView); } // If no drawer is opened, all drawers are not shown // for accessibility and the content is shown. View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); // Only send WINDOW_STATE_CHANGE if the host has window focus. This // may change if support for multiple foreground windows (e.g. IME) // improves. if (hasWindowFocus()) { final View rootView = getRootView(); if (rootView != null) { rootView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } } } void dispatchOnDrawerOpened(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (!lp.knownOpen) { lp.knownOpen = true; if (mListener != null) { mListener.onDrawerOpened(drawerView); } // If a drawer is opened, only it is shown for // accessibility and the content is not shown. View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); drawerView.requestFocus(); } } void dispatchOnDrawerSlide(View drawerView, float slideOffset) { if (mListener != null) { mListener.onDrawerSlide(drawerView, slideOffset); } } void setDrawerViewOffset(View drawerView, float slideOffset) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (slideOffset == lp.onScreen) { return; } lp.onScreen = slideOffset; dispatchOnDrawerSlide(drawerView, slideOffset); } float getDrawerViewOffset(View drawerView) { return ((LayoutParams) drawerView.getLayoutParams()).onScreen; } /** * @return the absolute gravity of the child drawerView, resolved according * to the current layout direction */ int getDrawerViewAbsoluteGravity(View drawerView) { final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; return GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); } boolean checkDrawerViewAbsoluteGravity(View drawerView, int checkFor) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); return (absGravity & checkFor) == checkFor; } View findOpenDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (((LayoutParams) child.getLayoutParams()).knownOpen) { return child; } } return null; } void moveDrawerToOffset(View drawerView, float slideOffset) { final float oldOffset = getDrawerViewOffset(drawerView); final int width = drawerView.getWidth(); final int oldPos = (int) (width * oldOffset); final int newPos = (int) (width * slideOffset); final int dx = newPos - oldPos; drawerView.offsetLeftAndRight( checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT) ? dx : -dx); setDrawerViewOffset(drawerView, slideOffset); } /** * @param gravity the gravity of the child to return. If specified as a * relative value, it will be resolved according to the current * layout direction. * @return the drawer with the specified gravity */ View findDrawerWithGravity(int gravity) { final int absHorizGravity = GravityCompat.getAbsoluteGravity( gravity, ViewCompat.getLayoutDirection(this)) & Gravity.HORIZONTAL_GRAVITY_MASK; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childAbsGravity = getDrawerViewAbsoluteGravity(child); if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) { return child; } } return null; } /** * Simple gravity to string - only supports LEFT and RIGHT for debugging output. * * @param gravity Absolute gravity value * @return LEFT or RIGHT as appropriate, or a hex string */ static String gravityToString(@EdgeGravity int gravity) { if ((gravity & Gravity.LEFT) == Gravity.LEFT) { return "LEFT"; } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { return "RIGHT"; } return Integer.toHexString(gravity); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mFirstLayout = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { if (isInEditMode()) { // Don't crash the layout editor. Consume all of the space if specified // or pick a magic number from thin air otherwise. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (widthMode == MeasureSpec.AT_MOST) { widthMode = MeasureSpec.EXACTLY; } else if (widthMode == MeasureSpec.UNSPECIFIED) { widthMode = MeasureSpec.EXACTLY; widthSize = 300; } if (heightMode == MeasureSpec.AT_MOST) { heightMode = MeasureSpec.EXACTLY; } else if (heightMode == MeasureSpec.UNSPECIFIED) { heightMode = MeasureSpec.EXACTLY; heightSize = 300; } } else { throw new IllegalArgumentException( "DrawerLayout must be measured with MeasureSpec.EXACTLY."); } } setMeasuredDimension(widthSize, heightSize); final boolean applyInsets = mLastInsets != null && ViewCompat.getFitsSystemWindows(this); final int layoutDirection = ViewCompat.getLayoutDirection(this); // Gravity value for each drawer we've seen. Only one of each permitted. int foundDrawers = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (applyInsets) { final int cgrav = GravityCompat.getAbsoluteGravity(lp.gravity, layoutDirection); if (ViewCompat.getFitsSystemWindows(child)) { IMPL.dispatchChildInsets(child, mLastInsets, cgrav); } else { IMPL.applyMarginInsets(lp, mLastInsets, cgrav); } } if (isContentView(child)) { // Content views get measured at exactly the layout's size. final int contentWidthSpec = MeasureSpec.makeMeasureSpec( widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); final int contentHeightSpec = MeasureSpec.makeMeasureSpec( heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (isDrawerView(child)) { final int childGravity = getDrawerViewAbsoluteGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK; if ((foundDrawers & childGravity) != 0) { throw new IllegalStateException("Child drawer has absolute gravity " + gravityToString(childGravity) + " but this " + TAG + " already has a " + "drawer view along that edge"); } final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec, mMinDrawerMargin + lp.leftMargin + lp.rightMargin, lp.width); final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height); child.measure(drawerWidthSpec, drawerHeightSpec); } else { throw new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY"); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; final int width = r - l; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight()); } else { // Drawer, if it wasn't onMeasure would have thrown an exception. final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); int childLeft; final float newOffset; if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { childLeft = -childWidth + (int) (childWidth * lp.onScreen); newOffset = (float) (childWidth + childLeft) / childWidth; } else { // Right; onMeasure checked for us. childLeft = width - (int) (childWidth * lp.onScreen); newOffset = (float) (width - childLeft) / childWidth; } final boolean changeOffset = newOffset != lp.onScreen; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { default: case Gravity.TOP: { child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight); break; } case Gravity.BOTTOM: { final int height = b - t; child.layout(childLeft, height - lp.bottomMargin - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin); break; } case Gravity.CENTER_VERTICAL: { final int height = b - t; int childTop = (height - childHeight) / 2; // Offset for margins. If things don't fit right because of // bad measurement before, oh well. if (childTop < lp.topMargin) { childTop = lp.topMargin; } else if (childTop + childHeight > height - lp.bottomMargin) { childTop = height - lp.bottomMargin - childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); break; } } if (changeOffset) { setDrawerViewOffset(child, newOffset); } final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE; if (child.getVisibility() != newVisibility) { child.setVisibility(newVisibility); } } } mInLayout = false; mFirstLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override public void computeScroll() { final int childCount = getChildCount(); float scrimOpacity = 0; for (int i = 0; i < childCount; i++) { final float onscreen = ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen; scrimOpacity = Math.max(scrimOpacity, onscreen); } mScrimOpacity = scrimOpacity; // "|" used on purpose; both need to run. if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private static boolean hasOpaqueBackground(View v) { final Drawable bg = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param bg Background drawable to draw behind the status bar */ public void setStatusBarBackground(Drawable bg) { mStatusBarBackground = bg; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param resId Resource id of a background drawable to draw behind the status bar */ public void setStatusBarBackground(int resId) { mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param color Color to use as a background drawable to draw behind the status bar * in 0xAARRGGBB format. */ public void setStatusBarBackgroundColor(int color) { mStatusBarBackground = new ColorDrawable(color); } @Override public void onDraw(Canvas c) { super.onDraw(c); if (mDrawStatusBarBackground && mStatusBarBackground != null) { final int inset = IMPL.getTopInset(mLastInsets); if (inset > 0) { mStatusBarBackground.setBounds(0, 0, getWidth(), inset); mStatusBarBackground.draw(c); } } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final int height = getHeight(); final boolean drawingContent = isContentView(child); int clipLeft = 0, clipRight = getWidth(); final int restoreCount = canvas.save(); if (drawingContent) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); if (v == child || v.getVisibility() != VISIBLE || !hasOpaqueBackground(v) || !isDrawerView(v) || v.getHeight() < height) { continue; } if (checkDrawerViewAbsoluteGravity(v, Gravity.LEFT)) { final int vright = v.getRight(); if (vright > clipLeft) clipLeft = vright; } else { final int vleft = v.getLeft(); if (vleft < clipRight) clipRight = vleft; } } canvas.clipRect(clipLeft, 0, clipRight, getHeight()); } final boolean result = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(restoreCount); if (mScrimOpacity > 0 && drawingContent) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int imag = (int) (baseAlpha * mScrimOpacity); final int color = imag << 24 | (mScrimColor & 0xffffff); mScrimPaint.setColor(color); canvas.drawRect(clipLeft, 0, clipRight, getHeight(), mScrimPaint); } else if (mShadowLeft != null && checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { final int shadowWidth = mShadowLeft.getIntrinsicWidth(); final int childRight = child.getRight(); final int drawerPeekDistance = mLeftDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) childRight / drawerPeekDistance, 1.f)); mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom()); mShadowLeft.setAlpha((int) (0xff * alpha)); mShadowLeft.draw(canvas); } else if (mShadowRight != null && checkDrawerViewAbsoluteGravity(child, Gravity.RIGHT)) { final int shadowWidth = mShadowRight.getIntrinsicWidth(); final int childLeft = child.getLeft(); final int showing = getWidth() - childLeft; final int drawerPeekDistance = mRightDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) showing / drawerPeekDistance, 1.f)); mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); mShadowRight.setAlpha((int) (0xff * alpha)); mShadowRight.draw(canvas); } return result; } boolean isContentView(View child) { return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY; } boolean isDrawerView(View child) { final int gravity = ((LayoutParams) child.getLayoutParams()).gravity; final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(child)); return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); // "|" used deliberately here; both methods should be invoked. final boolean interceptForDrag = mLeftDragger.shouldInterceptTouchEvent(ev) | mRightDragger.shouldInterceptTouchEvent(ev); boolean interceptForTap = false; switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; if (mScrimOpacity > 0 && isContentView(mLeftDragger.findTopChildUnder((int) x, (int) y))) { interceptForTap = true; } mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_MOVE: { // If we cross the touch slop, don't perform the delayed peek for an edge touch. if (mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) { mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; } } return interceptForDrag || interceptForTap || hasPeekingDrawer() || mChildrenCanceledTouch; } @Override public boolean onTouchEvent(MotionEvent ev) { mLeftDragger.processTouchEvent(ev); mRightDragger.processTouchEvent(ev); final int action = ev.getAction(); boolean wantTouchEvents = true; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_UP: { final float x = ev.getX(); final float y = ev.getY(); boolean peekingOnly = true; final View touchedView = mLeftDragger.findTopChildUnder((int) x, (int) y); if (touchedView != null && isContentView(touchedView)) { final float dx = x - mInitialMotionX; final float dy = y - mInitialMotionY; final int slop = mLeftDragger.getTouchSlop(); if (dx * dx + dy * dy < slop * slop) { // Taps close a dimmed open drawer but only if it isn't locked open. final View openDrawer = findOpenDrawer(); if (openDrawer != null) { peekingOnly = getDrawerLockMode(openDrawer) == LOCK_MODE_LOCKED_OPEN; } } } closeDrawers(peekingOnly); mDisallowInterceptRequested = false; break; } case MotionEvent.ACTION_CANCEL: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } } return wantTouchEvents; } public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (CHILDREN_DISALLOW_INTERCEPT || (!mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) && !mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) { // If we have an edge touch we want to skip this and track it for later instead. super.requestDisallowInterceptTouchEvent(disallowIntercept); } mDisallowInterceptRequested = disallowIntercept; if (disallowIntercept) { closeDrawers(true); } } /** * Close all currently open drawer views by animating them out of view. */ public void closeDrawers() { closeDrawers(false); } void closeDrawers(boolean peekingOnly) { boolean needsInvalidate = false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!isDrawerView(child) || (peekingOnly && !lp.isPeeking)) { continue; } final int childWidth = child.getWidth(); if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { needsInvalidate |= mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop()); } else { needsInvalidate |= mRightDragger.smoothSlideViewTo(child, getWidth(), child.getTop()); } lp.isPeeking = false; } mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); if (needsInvalidate) { invalidate(); } } /** * Open the specified drawer view by animating it into view. * * @param drawerView Drawer view to open */ public void openDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 1.f; lp.knownOpen = true; View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(), drawerView.getTop()); } } invalidate(); } /** * Open the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void openDrawer(@EdgeGravity int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } openDrawer(drawerView); } /** * Close the specified drawer view by animating it into view. * * @param drawerView Drawer view to close */ public void closeDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 0.f; lp.knownOpen = false; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop()); } } invalidate(); } /** * Close the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void closeDrawer(@EdgeGravity int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } closeDrawer(drawerView); } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. To check for partial visibility use * {@link #isDrawerVisible(android.view.View)}. * * @param drawer Drawer view to check * @return true if the given drawer view is in an open state * @see #isDrawerVisible(android.view.View) */ public boolean isDrawerOpen(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).knownOpen; } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. If there is no drawer with the given gravity this method * will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer view is in an open state */ public boolean isDrawerOpen(@EdgeGravity int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerOpen(drawerView); } return false; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * * @param drawer Drawer view to check * @return true if the given drawer is visible on-screen * @see #isDrawerOpen(android.view.View) */ public boolean isDrawerVisible(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere in between. * If there is no drawer with the given gravity this method will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer is visible on-screen */ public boolean isDrawerVisible(@EdgeGravity int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerVisible(drawerView); } return false; } private boolean hasPeekingDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); if (lp.isPeeking) { return true; } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams ? new LayoutParams((LayoutParams) p) : p instanceof ViewGroup.MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } private boolean hasVisibleDrawer() { return findVisibleDrawer() != null; } private View findVisibleDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (isDrawerView(child) && isDrawerVisible(child)) { return child; } } return null; } void cancelChildViewTouch() { // Cancel child touches if (!mChildrenCanceledTouch) { final long now = SystemClock.uptimeMillis(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); mChildrenCanceledTouch = true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && hasVisibleDrawer()) { KeyEventCompat.startTracking(event); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == LOCK_MODE_UNLOCKED) { closeDrawers(); } return visibleDrawer != null; } return super.onKeyUp(keyCode, event); } @Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.openDrawerGravity != Gravity.NO_GRAVITY) { final View toOpen = findDrawerWithGravity(ss.openDrawerGravity); if (toOpen != null) { openDrawer(toOpen); } } setDrawerLockMode(ss.lockModeLeft, Gravity.LEFT); setDrawerLockMode(ss.lockModeRight, Gravity.RIGHT); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState ss = new SavedState(superState); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (!isDrawerView(child)) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.knownOpen) { ss.openDrawerGravity = lp.gravity; // Only one drawer can be open at a time. break; } } ss.lockModeLeft = mLockModeLeft; ss.lockModeRight = mLockModeRight; return ss; } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { // Until a drawer is open, it is hidden from accessibility. if (index > 0 || (index < 0 && getChildCount() > 0)) { ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); // Also set a delegate to break the child-parent relation if the // child is hidden. For details (see incluceChildForAccessibility). ViewCompat.setAccessibilityDelegate(child, mChildAccessibilityDelegate); } else { // Initially, the content is shown for accessibility. ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } super.addView(child, index, params); } private static boolean includeChildForAccessibility(View child) { // If the child is not important for accessibility we make // sure this hides the entire subtree rooted at it as the // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDATS is not // supported on older platforms but we want to hide the entire // content and not opened drawers if a drawer is opened. return ViewCompat.getImportantForAccessibility(child) != ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS && ViewCompat.getImportantForAccessibility(child) != ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; } /** * State persisted across instances */ protected static class SavedState extends BaseSavedState { int openDrawerGravity = Gravity.NO_GRAVITY; int lockModeLeft = LOCK_MODE_UNLOCKED; int lockModeRight = LOCK_MODE_UNLOCKED; public SavedState(Parcel in) { super(in); openDrawerGravity = in.readInt(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(openDrawerGravity); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel source) { return new SavedState(source); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class ViewDragCallback extends ViewDragHelper.Callback { private final int mAbsGravity; private ViewDragHelper mDragger; private final Runnable mPeekRunnable = new Runnable() { @Override public void run() { peekDrawer(); } }; public ViewDragCallback(int gravity) { mAbsGravity = gravity; } public void setDragger(ViewDragHelper dragger) { mDragger = dragger; } public void removeCallbacks() { DrawerLayout.this.removeCallbacks(mPeekRunnable); } @Override public boolean tryCaptureView(View child, int pointerId) { // Only capture views where the gravity matches what we're looking for. // This lets us use two ViewDragHelpers, one for each side drawer. return isDrawerView(child) && checkDrawerViewAbsoluteGravity(child, mAbsGravity) && getDrawerLockMode(child) == LOCK_MODE_UNLOCKED; } @Override public void onViewDragStateChanged(int state) { updateDrawerState(mAbsGravity, state, mDragger.getCapturedView()); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { float offset; final int childWidth = changedView.getWidth(); // This reverses the positioning shown in onLayout. if (checkDrawerViewAbsoluteGravity(changedView, Gravity.LEFT)) { offset = (float) (childWidth + left) / childWidth; } else { final int width = getWidth(); offset = (float) (width - left) / childWidth; } setDrawerViewOffset(changedView, offset); changedView.setVisibility(offset == 0 ? INVISIBLE : VISIBLE); invalidate(); } @Override public void onViewCaptured(View capturedChild, int activePointerId) { final LayoutParams lp = (LayoutParams) capturedChild.getLayoutParams(); lp.isPeeking = false; closeOtherDrawer(); } private void closeOtherDrawer() { final int otherGrav = mAbsGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT; final View toClose = findDrawerWithGravity(otherGrav); if (toClose != null) { closeDrawer(toClose); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { // Offset is how open the drawer is, therefore left/right values // are reversed from one another. final float offset = getDrawerViewOffset(releasedChild); final int childWidth = releasedChild.getWidth(); int left; if (checkDrawerViewAbsoluteGravity(releasedChild, Gravity.LEFT)) { left = xvel > 0 || xvel == 0 && offset > 0.5f ? 0 : -childWidth; } else { final int width = getWidth(); left = xvel < 0 || xvel == 0 && offset > 0.5f ? width - childWidth : width; } mDragger.settleCapturedViewAt(left, releasedChild.getTop()); invalidate(); } @Override public void onEdgeTouched(int edgeFlags, int pointerId) { postDelayed(mPeekRunnable, PEEK_DELAY); } private void peekDrawer() { final View toCapture; final int childLeft; final int peekDistance = mDragger.getEdgeSize(); final boolean leftEdge = mAbsGravity == Gravity.LEFT; if (leftEdge) { toCapture = findDrawerWithGravity(Gravity.LEFT); childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance; } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); childLeft = getWidth() - peekDistance; } // Only peek if it would mean making the drawer more visible and the drawer isn't locked if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { final LayoutParams lp = (LayoutParams) toCapture.getLayoutParams(); mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop()); lp.isPeeking = true; invalidate(); closeOtherDrawer(); cancelChildViewTouch(); } } @Override public boolean onEdgeLock(int edgeFlags) { if (ALLOW_EDGE_LOCK) { final View drawer = findDrawerWithGravity(mAbsGravity); if (drawer != null && !isDrawerOpen(drawer)) { closeDrawer(drawer); } return true; } return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { final View toCapture; if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) { toCapture = findDrawerWithGravity(Gravity.LEFT); } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); } if (toCapture != null && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { mDragger.captureChildView(toCapture, pointerId); } } @Override public int getViewHorizontalDragRange(View child) { return isDrawerView(child) ? child.getWidth() : 0; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { return Math.max(-child.getWidth(), Math.min(left, 0)); } else { final int width = getWidth(); return Math.max(width - child.getWidth(), Math.min(left, width)); } } @Override public int clampViewPositionVertical(View child, int top, int dy) { return child.getTop(); } } public static class LayoutParams extends ViewGroup.MarginLayoutParams { public int gravity = Gravity.NO_GRAVITY; float onScreen; boolean isPeeking; boolean knownOpen; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS); this.gravity = a.getInt(0, Gravity.NO_GRAVITY); a.recycle(); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(int width, int height, int gravity) { this(width, height); this.gravity = gravity; } public LayoutParams(LayoutParams source) { super(source); this.gravity = source.gravity; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } } class AccessibilityDelegate extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info); super.onInitializeAccessibilityNodeInfo(host, superNode); info.setClassName(DrawerLayout.class.getName()); info.setSource(host); final ViewParent parent = ViewCompat.getParentForAccessibility(host); if (parent instanceof View) { info.setParent((View) parent); } copyNodeInfoNoChildren(info, superNode); superNode.recycle(); addChildrenForAccessibility(info, (ViewGroup) host); } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(DrawerLayout.class.getName()); } @Override public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { // Special case to handle window state change events. As far as // accessibility services are concerned, state changes from // DrawerLayout invalidate the entire contents of the screen (like // an Activity or Dialog) and they should announce the title of the // new content. if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { final List<CharSequence> eventText = event.getText(); final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null) { final int edgeGravity = getDrawerViewAbsoluteGravity(visibleDrawer); final CharSequence title = getDrawerTitle(edgeGravity); if (title != null) { eventText.add(title); } } return true; } return super.dispatchPopulateAccessibilityEvent(host, event); } private void addChildrenForAccessibility(AccessibilityNodeInfoCompat info, ViewGroup v) { final int childCount = v.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = v.getChildAt(i); if (includeChildForAccessibility(child)) { info.addChild(child); } } } @Override public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { if (includeChildForAccessibility(child)) { return super.onRequestSendAccessibilityEvent(host, child, event); } return false; } /** * This should really be in AccessibilityNodeInfoCompat, but there unfortunately * seem to be a few elements that are not easily cloneable using the underlying API. * Leave it private here as it's not general-purpose useful. */ private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) { final Rect rect = mTmpRect; src.getBoundsInParent(rect); dest.setBoundsInParent(rect); src.getBoundsInScreen(rect); dest.setBoundsInScreen(rect); dest.setVisibleToUser(src.isVisibleToUser()); dest.setPackageName(src.getPackageName()); dest.setClassName(src.getClassName()); dest.setContentDescription(src.getContentDescription()); dest.setEnabled(src.isEnabled()); dest.setClickable(src.isClickable()); dest.setFocusable(src.isFocusable()); dest.setFocused(src.isFocused()); dest.setAccessibilityFocused(src.isAccessibilityFocused()); dest.setSelected(src.isSelected()); dest.setLongClickable(src.isLongClickable()); dest.addAction(src.getActions()); } } final class ChildAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityNodeInfo(View child, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(child, info); if (!includeChildForAccessibility(child)) { // If we are ignoring the sub-tree rooted at the child, // break the connection to the rest of the node tree. // For details refer to includeChildForAccessibility. info.setParent(null); } } } }
v4/java/android/support/v4/widget/DrawerLayout.java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewGroupCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; /** * DrawerLayout acts as a top-level container for window content that allows for * interactive "drawer" views to be pulled out from the edge of the window. * * <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code> * attribute on child views corresponding to which side of the view you want the drawer * to emerge from: left or right. (Or start/end on platform versions that support layout direction.) * </p> * * <p>To use a DrawerLayout, position your primary content view as the first child with * a width and height of <code>match_parent</code>. Add drawers as child views after the main * content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use * <code>match_parent</code> for height with a fixed width.</p> * * <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views. * Avoid performing expensive operations such as layout during animation as it can cause * stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state. * {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p> * * <p>As per the <a href="{@docRoot}design/patterns/navigation-drawer.html">Android Design * guide</a>, any drawers positioned to the left/start should * always contain content for navigating around the application, whereas any drawers * positioned to the right/end should always contain actions to take on the current content. * This preserves the same navigation left, actions right structure present in the Action Bar * and elsewhere.</p> * * <p>For more information about how to use DrawerLayout, read <a * href="{@docRoot}training/implementing-navigation/nav-drawer.html">Creating a Navigation * Drawer</a>.</p> */ public class DrawerLayout extends ViewGroup implements DrawerLayoutImpl { private static final String TAG = "DrawerLayout"; @IntDef({STATE_IDLE, STATE_DRAGGING, STATE_SETTLING}) @Retention(RetentionPolicy.SOURCE) private @interface State {} /** * Indicates that any drawers are in an idle, settled state. No animation is in progress. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * Indicates that a drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * Indicates that a drawer is in the process of settling to a final position. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** @hide */ @IntDef({LOCK_MODE_UNLOCKED, LOCK_MODE_LOCKED_CLOSED, LOCK_MODE_LOCKED_OPEN}) @Retention(RetentionPolicy.SOURCE) private @interface LockMode {} /** * The drawer is unlocked. */ public static final int LOCK_MODE_UNLOCKED = 0; /** * The drawer is locked closed. The user may not open it, though * the app may open it programmatically. */ public static final int LOCK_MODE_LOCKED_CLOSED = 1; /** * The drawer is locked open. The user may not close it, though the app * may close it programmatically. */ public static final int LOCK_MODE_LOCKED_OPEN = 2; /** @hide */ @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END}) @Retention(RetentionPolicy.SOURCE) private @interface EdgeGravity {} private static final int MIN_DRAWER_MARGIN = 64; // dp private static final int DEFAULT_SCRIM_COLOR = 0x99000000; /** * Length of time to delay before peeking the drawer. */ private static final int PEEK_DELAY = 160; // ms /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second /** * Experimental feature. */ private static final boolean ALLOW_EDGE_LOCK = false; private static final boolean CHILDREN_DISALLOW_INTERCEPT = true; private static final float TOUCH_SLOP_SENSITIVITY = 1.f; private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; private final ChildAccessibilityDelegate mChildAccessibilityDelegate = new ChildAccessibilityDelegate(); private int mMinDrawerMargin; private int mScrimColor = DEFAULT_SCRIM_COLOR; private float mScrimOpacity; private Paint mScrimPaint = new Paint(); private final ViewDragHelper mLeftDragger; private final ViewDragHelper mRightDragger; private final ViewDragCallback mLeftCallback; private final ViewDragCallback mRightCallback; private int mDrawerState; private boolean mInLayout; private boolean mFirstLayout = true; private int mLockModeLeft; private int mLockModeRight; private boolean mDisallowInterceptRequested; private boolean mChildrenCanceledTouch; private DrawerListener mListener; private float mInitialMotionX; private float mInitialMotionY; private Drawable mShadowLeft; private Drawable mShadowRight; private Drawable mStatusBarBackground; private CharSequence mTitleLeft; private CharSequence mTitleRight; private Object mLastInsets; private boolean mDrawStatusBarBackground; /** * Listener for monitoring events about drawers. */ public interface DrawerListener { /** * Called when a drawer's position changes. * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ public void onDrawerSlide(View drawerView, float slideOffset); /** * Called when a drawer has settled in a completely open state. * The drawer is interactive at this point. * * @param drawerView Drawer view that is now open */ public void onDrawerOpened(View drawerView); /** * Called when a drawer has settled in a completely closed state. * * @param drawerView Drawer view that is now closed */ public void onDrawerClosed(View drawerView); /** * Called when the drawer motion state changes. The new state will * be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * * @param newState The new drawer motion state */ public void onDrawerStateChanged(@State int newState); } /** * Stub/no-op implementations of all methods of {@link DrawerListener}. * Override this if you only care about a few of the available callback methods. */ public static abstract class SimpleDrawerListener implements DrawerListener { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } } interface DrawerLayoutCompatImpl { void configureApplyInsets(View drawerLayout); void dispatchChildInsets(View child, Object insets, int drawerGravity); void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity); int getTopInset(Object lastInsets); } static class DrawerLayoutCompatImplBase implements DrawerLayoutCompatImpl { public void configureApplyInsets(View drawerLayout) { // This space for rent } public void dispatchChildInsets(View child, Object insets, int drawerGravity) { // This space for rent } public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) { // This space for rent } public int getTopInset(Object insets) { return 0; } } static class DrawerLayoutCompatImplApi21 implements DrawerLayoutCompatImpl { public void configureApplyInsets(View drawerLayout) { DrawerLayoutCompatApi21.configureApplyInsets(drawerLayout); } public void dispatchChildInsets(View child, Object insets, int drawerGravity) { DrawerLayoutCompatApi21.dispatchChildInsets(child, insets, drawerGravity); } public void applyMarginInsets(MarginLayoutParams lp, Object insets, int drawerGravity) { DrawerLayoutCompatApi21.applyMarginInsets(lp, insets, drawerGravity); } public int getTopInset(Object insets) { return DrawerLayoutCompatApi21.getTopInset(insets); } } static { final int version = Build.VERSION.SDK_INT; if (version >= 21) { IMPL = new DrawerLayoutCompatImplApi21(); } else { IMPL = new DrawerLayoutCompatImplBase(); } } static final DrawerLayoutCompatImpl IMPL; public DrawerLayout(Context context) { this(context, null); } public DrawerLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DrawerLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); final float density = getResources().getDisplayMetrics().density; mMinDrawerMargin = (int) (MIN_DRAWER_MARGIN * density + 0.5f); final float minVel = MIN_FLING_VELOCITY * density; mLeftCallback = new ViewDragCallback(Gravity.LEFT); mRightCallback = new ViewDragCallback(Gravity.RIGHT); mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback); mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); mLeftDragger.setMinVelocity(minVel); mLeftCallback.setDragger(mLeftDragger); mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback); mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mRightDragger.setMinVelocity(minVel); mRightCallback.setDragger(mRightDragger); // So that we can catch the back button setFocusableInTouchMode(true); ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate()); ViewGroupCompat.setMotionEventSplittingEnabled(this, false); IMPL.configureApplyInsets(this); } /** * @hide Internal use only; called to apply window insets when configured * with fitsSystemWindows="true" */ @Override public void setChildInsets(Object insets, boolean draw) { mLastInsets = insets; mDrawStatusBarBackground = draw; setWillNotDraw(!draw && getBackground() == null); requestLayout(); } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param shadowDrawable Shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(Drawable shadowDrawable, @EdgeGravity int gravity) { /* * TODO Someone someday might want to set more complex drawables here. * They're probably nuts, but we might want to consider registering callbacks, * setting states, etc. properly. */ final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); if ((absGravity & Gravity.LEFT) == Gravity.LEFT) { mShadowLeft = shadowDrawable; invalidate(); } if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) { mShadowRight = shadowDrawable; invalidate(); } } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param resId Resource id of a shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(@DrawableRes int resId, @EdgeGravity int gravity) { setDrawerShadow(getResources().getDrawable(resId), gravity); } /** * Set a color to use for the scrim that obscures primary content while a drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set a listener to be notified of drawer events. * * @param listener Listener to notify when drawer events occur * @see DrawerListener */ public void setDrawerListener(DrawerListener listener) { mListener = listener; } /** * Enable or disable interaction with all drawers. * * <p>This allows the application to restrict the user's ability to open or close * any drawer within this layout. DrawerLayout will still respond to calls to * {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking drawers open or closed will implicitly open or close * any drawers as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. */ public void setDrawerLockMode(@LockMode int lockMode) { setDrawerLockMode(lockMode, Gravity.LEFT); setDrawerLockMode(lockMode, Gravity.RIGHT); } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param edgeGravity Gravity.LEFT, RIGHT, START or END. * Expresses which drawer to change the mode for. * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(@LockMode int lockMode, @EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mLockModeLeft = lockMode; } else if (absGravity == Gravity.RIGHT) { mLockModeRight = lockMode; } if (lockMode != LOCK_MODE_UNLOCKED) { // Cancel interaction in progress final ViewDragHelper helper = absGravity == Gravity.LEFT ? mLeftDragger : mRightDragger; helper.cancel(); } switch (lockMode) { case LOCK_MODE_LOCKED_OPEN: final View toOpen = findDrawerWithGravity(absGravity); if (toOpen != null) { openDrawer(toOpen); } break; case LOCK_MODE_LOCKED_CLOSED: final View toClose = findDrawerWithGravity(absGravity); if (toClose != null) { closeDrawer(toClose); } break; // default: do nothing } } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param drawerView The drawer view to change the lock mode for * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(@LockMode int lockMode, View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity"); } final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; setDrawerLockMode(lockMode, gravity); } /** * Check the lock mode of the drawer with the given gravity. * * @param edgeGravity Gravity of the drawer to check * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ @LockMode public int getDrawerLockMode(@EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Check the lock mode of the given drawer view. * * @param drawerView Drawer view to check lock mode * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ @LockMode public int getDrawerLockMode(View drawerView) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Sets the title of the drawer with the given gravity. * <p> * When accessibility is turned on, this is the title that will be used to * identify the drawer to the active accessibility service. * * @param edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which * drawer to set the title for. * @param title The title for the drawer. */ public void setDrawerTitle(@EdgeGravity int edgeGravity, CharSequence title) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mTitleLeft = title; } else if (absGravity == Gravity.RIGHT) { mTitleRight = title; } } /** * Returns the title of the drawer with the given gravity. * * @param edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which * drawer to return the title for. * @return The title of the drawer, or null if none set. * @see #setDrawerTitle(int, CharSequence) */ @Nullable public CharSequence getDrawerTitle(@EdgeGravity int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mTitleLeft; } else if (absGravity == Gravity.RIGHT) { return mTitleRight; } return null; } /** * Resolve the shared state of all drawers from the component ViewDragHelpers. * Should be called whenever a ViewDragHelper's state changes. */ void updateDrawerState(int forGravity, @State int activeState, View activeDrawer) { final int leftState = mLeftDragger.getViewDragState(); final int rightState = mRightDragger.getViewDragState(); final int state; if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) { state = STATE_DRAGGING; } else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) { state = STATE_SETTLING; } else { state = STATE_IDLE; } if (activeDrawer != null && activeState == STATE_IDLE) { final LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams(); if (lp.onScreen == 0) { dispatchOnDrawerClosed(activeDrawer); } else if (lp.onScreen == 1) { dispatchOnDrawerOpened(activeDrawer); } } if (state != mDrawerState) { mDrawerState = state; if (mListener != null) { mListener.onDrawerStateChanged(state); } } } void dispatchOnDrawerClosed(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (lp.knownOpen) { lp.knownOpen = false; if (mListener != null) { mListener.onDrawerClosed(drawerView); } // If no drawer is opened, all drawers are not shown // for accessibility and the content is shown. View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); // Only send WINDOW_STATE_CHANGE if the host has window focus. This // may change if support for multiple foreground windows (e.g. IME) // improves. if (hasWindowFocus()) { final View rootView = getRootView(); if (rootView != null) { rootView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } } } void dispatchOnDrawerOpened(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (!lp.knownOpen) { lp.knownOpen = true; if (mListener != null) { mListener.onDrawerOpened(drawerView); } // If a drawer is opened, only it is shown for // accessibility and the content is not shown. View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); drawerView.requestFocus(); } } void dispatchOnDrawerSlide(View drawerView, float slideOffset) { if (mListener != null) { mListener.onDrawerSlide(drawerView, slideOffset); } } void setDrawerViewOffset(View drawerView, float slideOffset) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (slideOffset == lp.onScreen) { return; } lp.onScreen = slideOffset; dispatchOnDrawerSlide(drawerView, slideOffset); } float getDrawerViewOffset(View drawerView) { return ((LayoutParams) drawerView.getLayoutParams()).onScreen; } /** * @return the absolute gravity of the child drawerView, resolved according * to the current layout direction */ int getDrawerViewAbsoluteGravity(View drawerView) { final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; return GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); } boolean checkDrawerViewAbsoluteGravity(View drawerView, int checkFor) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); return (absGravity & checkFor) == checkFor; } View findOpenDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (((LayoutParams) child.getLayoutParams()).knownOpen) { return child; } } return null; } void moveDrawerToOffset(View drawerView, float slideOffset) { final float oldOffset = getDrawerViewOffset(drawerView); final int width = drawerView.getWidth(); final int oldPos = (int) (width * oldOffset); final int newPos = (int) (width * slideOffset); final int dx = newPos - oldPos; drawerView.offsetLeftAndRight( checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT) ? dx : -dx); setDrawerViewOffset(drawerView, slideOffset); } /** * @param gravity the gravity of the child to return. If specified as a * relative value, it will be resolved according to the current * layout direction. * @return the drawer with the specified gravity */ View findDrawerWithGravity(int gravity) { final int absHorizGravity = GravityCompat.getAbsoluteGravity( gravity, ViewCompat.getLayoutDirection(this)) & Gravity.HORIZONTAL_GRAVITY_MASK; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childAbsGravity = getDrawerViewAbsoluteGravity(child); if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) { return child; } } return null; } /** * Simple gravity to string - only supports LEFT and RIGHT for debugging output. * * @param gravity Absolute gravity value * @return LEFT or RIGHT as appropriate, or a hex string */ static String gravityToString(@EdgeGravity int gravity) { if ((gravity & Gravity.LEFT) == Gravity.LEFT) { return "LEFT"; } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { return "RIGHT"; } return Integer.toHexString(gravity); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mFirstLayout = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { if (isInEditMode()) { // Don't crash the layout editor. Consume all of the space if specified // or pick a magic number from thin air otherwise. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (widthMode == MeasureSpec.AT_MOST) { widthMode = MeasureSpec.EXACTLY; } else if (widthMode == MeasureSpec.UNSPECIFIED) { widthMode = MeasureSpec.EXACTLY; widthSize = 300; } if (heightMode == MeasureSpec.AT_MOST) { heightMode = MeasureSpec.EXACTLY; } else if (heightMode == MeasureSpec.UNSPECIFIED) { heightMode = MeasureSpec.EXACTLY; heightSize = 300; } } else { throw new IllegalArgumentException( "DrawerLayout must be measured with MeasureSpec.EXACTLY."); } } setMeasuredDimension(widthSize, heightSize); final boolean applyInsets = mLastInsets != null && ViewCompat.getFitsSystemWindows(this); final int layoutDirection = ViewCompat.getLayoutDirection(this); // Gravity value for each drawer we've seen. Only one of each permitted. int foundDrawers = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (applyInsets) { final int cgrav = GravityCompat.getAbsoluteGravity(lp.gravity, layoutDirection); if (ViewCompat.getFitsSystemWindows(child)) { IMPL.dispatchChildInsets(child, mLastInsets, cgrav); } else { IMPL.applyMarginInsets(lp, mLastInsets, cgrav); } } if (isContentView(child)) { // Content views get measured at exactly the layout's size. final int contentWidthSpec = MeasureSpec.makeMeasureSpec( widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); final int contentHeightSpec = MeasureSpec.makeMeasureSpec( heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (isDrawerView(child)) { final int childGravity = getDrawerViewAbsoluteGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK; if ((foundDrawers & childGravity) != 0) { throw new IllegalStateException("Child drawer has absolute gravity " + gravityToString(childGravity) + " but this " + TAG + " already has a " + "drawer view along that edge"); } final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec, mMinDrawerMargin + lp.leftMargin + lp.rightMargin, lp.width); final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height); child.measure(drawerWidthSpec, drawerHeightSpec); } else { throw new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY"); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; final int width = r - l; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight()); } else { // Drawer, if it wasn't onMeasure would have thrown an exception. final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); int childLeft; final float newOffset; if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { childLeft = -childWidth + (int) (childWidth * lp.onScreen); newOffset = (float) (childWidth + childLeft) / childWidth; } else { // Right; onMeasure checked for us. childLeft = width - (int) (childWidth * lp.onScreen); newOffset = (float) (width - childLeft) / childWidth; } final boolean changeOffset = newOffset != lp.onScreen; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { default: case Gravity.TOP: { child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight); break; } case Gravity.BOTTOM: { final int height = b - t; child.layout(childLeft, height - lp.bottomMargin - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin); break; } case Gravity.CENTER_VERTICAL: { final int height = b - t; int childTop = (height - childHeight) / 2; // Offset for margins. If things don't fit right because of // bad measurement before, oh well. if (childTop < lp.topMargin) { childTop = lp.topMargin; } else if (childTop + childHeight > height - lp.bottomMargin) { childTop = height - lp.bottomMargin - childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); break; } } if (changeOffset) { setDrawerViewOffset(child, newOffset); } final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE; if (child.getVisibility() != newVisibility) { child.setVisibility(newVisibility); } } } mInLayout = false; mFirstLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override public void computeScroll() { final int childCount = getChildCount(); float scrimOpacity = 0; for (int i = 0; i < childCount; i++) { final float onscreen = ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen; scrimOpacity = Math.max(scrimOpacity, onscreen); } mScrimOpacity = scrimOpacity; // "|" used on purpose; both need to run. if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private static boolean hasOpaqueBackground(View v) { final Drawable bg = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param bg Background drawable to draw behind the status bar */ public void setStatusBarBackground(Drawable bg) { mStatusBarBackground = bg; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param resId Resource id of a background drawable to draw behind the status bar */ public void setStatusBarBackground(int resId) { mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null; } /** * Set a drawable to draw in the insets area for the status bar. * Note that this will only be activated if this DrawerLayout fitsSystemWindows. * * @param color Color to use as a background drawable to draw behind the status bar * in 0xAARRGGBB format. */ public void setStatusBarBackgroundColor(int color) { mStatusBarBackground = new ColorDrawable(color); } @Override public void onDraw(Canvas c) { super.onDraw(c); if (mDrawStatusBarBackground && mStatusBarBackground != null) { final int inset = IMPL.getTopInset(mLastInsets); if (inset > 0) { mStatusBarBackground.setBounds(0, 0, getWidth(), inset); mStatusBarBackground.draw(c); } } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final int height = getHeight(); final boolean drawingContent = isContentView(child); int clipLeft = 0, clipRight = getWidth(); final int restoreCount = canvas.save(); if (drawingContent) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); if (v == child || v.getVisibility() != VISIBLE || !hasOpaqueBackground(v) || !isDrawerView(v) || v.getHeight() < height) { continue; } if (checkDrawerViewAbsoluteGravity(v, Gravity.LEFT)) { final int vright = v.getRight(); if (vright > clipLeft) clipLeft = vright; } else { final int vleft = v.getLeft(); if (vleft < clipRight) clipRight = vleft; } } canvas.clipRect(clipLeft, 0, clipRight, getHeight()); } final boolean result = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(restoreCount); if (mScrimOpacity > 0 && drawingContent) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int imag = (int) (baseAlpha * mScrimOpacity); final int color = imag << 24 | (mScrimColor & 0xffffff); mScrimPaint.setColor(color); canvas.drawRect(clipLeft, 0, clipRight, getHeight(), mScrimPaint); } else if (mShadowLeft != null && checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { final int shadowWidth = mShadowLeft.getIntrinsicWidth(); final int childRight = child.getRight(); final int drawerPeekDistance = mLeftDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) childRight / drawerPeekDistance, 1.f)); mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom()); mShadowLeft.setAlpha((int) (0xff * alpha)); mShadowLeft.draw(canvas); } else if (mShadowRight != null && checkDrawerViewAbsoluteGravity(child, Gravity.RIGHT)) { final int shadowWidth = mShadowRight.getIntrinsicWidth(); final int childLeft = child.getLeft(); final int showing = getWidth() - childLeft; final int drawerPeekDistance = mRightDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) showing / drawerPeekDistance, 1.f)); mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); mShadowRight.setAlpha((int) (0xff * alpha)); mShadowRight.draw(canvas); } return result; } boolean isContentView(View child) { return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY; } boolean isDrawerView(View child) { final int gravity = ((LayoutParams) child.getLayoutParams()).gravity; final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(child)); return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); // "|" used deliberately here; both methods should be invoked. final boolean interceptForDrag = mLeftDragger.shouldInterceptTouchEvent(ev) | mRightDragger.shouldInterceptTouchEvent(ev); boolean interceptForTap = false; switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; if (mScrimOpacity > 0 && isContentView(mLeftDragger.findTopChildUnder((int) x, (int) y))) { interceptForTap = true; } mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_MOVE: { // If we cross the touch slop, don't perform the delayed peek for an edge touch. if (mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) { mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; } } return interceptForDrag || interceptForTap || hasPeekingDrawer() || mChildrenCanceledTouch; } @Override public boolean onTouchEvent(MotionEvent ev) { mLeftDragger.processTouchEvent(ev); mRightDragger.processTouchEvent(ev); final int action = ev.getAction(); boolean wantTouchEvents = true; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_UP: { final float x = ev.getX(); final float y = ev.getY(); boolean peekingOnly = true; final View touchedView = mLeftDragger.findTopChildUnder((int) x, (int) y); if (touchedView != null && isContentView(touchedView)) { final float dx = x - mInitialMotionX; final float dy = y - mInitialMotionY; final int slop = mLeftDragger.getTouchSlop(); if (dx * dx + dy * dy < slop * slop) { // Taps close a dimmed open drawer but only if it isn't locked open. final View openDrawer = findOpenDrawer(); if (openDrawer != null) { peekingOnly = getDrawerLockMode(openDrawer) == LOCK_MODE_LOCKED_OPEN; } } } closeDrawers(peekingOnly); mDisallowInterceptRequested = false; break; } case MotionEvent.ACTION_CANCEL: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } } return wantTouchEvents; } public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (CHILDREN_DISALLOW_INTERCEPT || (!mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) && !mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) { // If we have an edge touch we want to skip this and track it for later instead. super.requestDisallowInterceptTouchEvent(disallowIntercept); } mDisallowInterceptRequested = disallowIntercept; if (disallowIntercept) { closeDrawers(true); } } /** * Close all currently open drawer views by animating them out of view. */ public void closeDrawers() { closeDrawers(false); } void closeDrawers(boolean peekingOnly) { boolean needsInvalidate = false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!isDrawerView(child) || (peekingOnly && !lp.isPeeking)) { continue; } final int childWidth = child.getWidth(); if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { needsInvalidate |= mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop()); } else { needsInvalidate |= mRightDragger.smoothSlideViewTo(child, getWidth(), child.getTop()); } lp.isPeeking = false; } mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); if (needsInvalidate) { invalidate(); } } /** * Open the specified drawer view by animating it into view. * * @param drawerView Drawer view to open */ public void openDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 1.f; lp.knownOpen = true; View content = getChildAt(0); if (content != null) { ViewCompat.setImportantForAccessibility(content, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } ViewCompat.setImportantForAccessibility(drawerView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(), drawerView.getTop()); } } invalidate(); } /** * Open the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void openDrawer(@EdgeGravity int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } openDrawer(drawerView); } /** * Close the specified drawer view by animating it into view. * * @param drawerView Drawer view to close */ public void closeDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 0.f; lp.knownOpen = false; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop()); } } invalidate(); } /** * Close the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void closeDrawer(@EdgeGravity int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } closeDrawer(drawerView); } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. To check for partial visibility use * {@link #isDrawerVisible(android.view.View)}. * * @param drawer Drawer view to check * @return true if the given drawer view is in an open state * @see #isDrawerVisible(android.view.View) */ public boolean isDrawerOpen(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).knownOpen; } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. If there is no drawer with the given gravity this method * will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer view is in an open state */ public boolean isDrawerOpen(@EdgeGravity int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerOpen(drawerView); } return false; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * * @param drawer Drawer view to check * @return true if the given drawer is visible on-screen * @see #isDrawerOpen(android.view.View) */ public boolean isDrawerVisible(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere in between. * If there is no drawer with the given gravity this method will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer is visible on-screen */ public boolean isDrawerVisible(@EdgeGravity int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerVisible(drawerView); } return false; } private boolean hasPeekingDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); if (lp.isPeeking) { return true; } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams ? new LayoutParams((LayoutParams) p) : p instanceof ViewGroup.MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } private boolean hasVisibleDrawer() { return findVisibleDrawer() != null; } private View findVisibleDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (isDrawerView(child) && isDrawerVisible(child)) { return child; } } return null; } void cancelChildViewTouch() { // Cancel child touches if (!mChildrenCanceledTouch) { final long now = SystemClock.uptimeMillis(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); mChildrenCanceledTouch = true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && hasVisibleDrawer()) { KeyEventCompat.startTracking(event); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == LOCK_MODE_UNLOCKED) { closeDrawers(); } return visibleDrawer != null; } return super.onKeyUp(keyCode, event); } @Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.openDrawerGravity != Gravity.NO_GRAVITY) { final View toOpen = findDrawerWithGravity(ss.openDrawerGravity); if (toOpen != null) { openDrawer(toOpen); } } setDrawerLockMode(ss.lockModeLeft, Gravity.LEFT); setDrawerLockMode(ss.lockModeRight, Gravity.RIGHT); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState ss = new SavedState(superState); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (!isDrawerView(child)) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.knownOpen) { ss.openDrawerGravity = lp.gravity; // Only one drawer can be open at a time. break; } } ss.lockModeLeft = mLockModeLeft; ss.lockModeRight = mLockModeRight; return ss; } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { // Until a drawer is open, it is hidden from accessibility. if (index > 0 || (index < 0 && getChildCount() > 0)) { ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); // Also set a delegate to break the child-parent relation if the // child is hidden. For details (see incluceChildForAccessibility). ViewCompat.setAccessibilityDelegate(child, mChildAccessibilityDelegate); } else { // Initially, the content is shown for accessibility. ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } super.addView(child, index, params); } private static boolean includeChildForAccessibility(View child) { // If the child is not important for accessibility we make // sure this hides the entire subtree rooted at it as the // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDATS is not // supported on older platforms but we want to hide the entire // content and not opened drawers if a drawer is opened. return ViewCompat.getImportantForAccessibility(child) != ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS && ViewCompat.getImportantForAccessibility(child) != ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; } /** * State persisted across instances */ protected static class SavedState extends BaseSavedState { int openDrawerGravity = Gravity.NO_GRAVITY; int lockModeLeft = LOCK_MODE_UNLOCKED; int lockModeRight = LOCK_MODE_UNLOCKED; public SavedState(Parcel in) { super(in); openDrawerGravity = in.readInt(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(openDrawerGravity); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel source) { return new SavedState(source); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class ViewDragCallback extends ViewDragHelper.Callback { private final int mAbsGravity; private ViewDragHelper mDragger; private final Runnable mPeekRunnable = new Runnable() { @Override public void run() { peekDrawer(); } }; public ViewDragCallback(int gravity) { mAbsGravity = gravity; } public void setDragger(ViewDragHelper dragger) { mDragger = dragger; } public void removeCallbacks() { DrawerLayout.this.removeCallbacks(mPeekRunnable); } @Override public boolean tryCaptureView(View child, int pointerId) { // Only capture views where the gravity matches what we're looking for. // This lets us use two ViewDragHelpers, one for each side drawer. return isDrawerView(child) && checkDrawerViewAbsoluteGravity(child, mAbsGravity) && getDrawerLockMode(child) == LOCK_MODE_UNLOCKED; } @Override public void onViewDragStateChanged(int state) { updateDrawerState(mAbsGravity, state, mDragger.getCapturedView()); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { float offset; final int childWidth = changedView.getWidth(); // This reverses the positioning shown in onLayout. if (checkDrawerViewAbsoluteGravity(changedView, Gravity.LEFT)) { offset = (float) (childWidth + left) / childWidth; } else { final int width = getWidth(); offset = (float) (width - left) / childWidth; } setDrawerViewOffset(changedView, offset); changedView.setVisibility(offset == 0 ? INVISIBLE : VISIBLE); invalidate(); } @Override public void onViewCaptured(View capturedChild, int activePointerId) { final LayoutParams lp = (LayoutParams) capturedChild.getLayoutParams(); lp.isPeeking = false; closeOtherDrawer(); } private void closeOtherDrawer() { final int otherGrav = mAbsGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT; final View toClose = findDrawerWithGravity(otherGrav); if (toClose != null) { closeDrawer(toClose); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { // Offset is how open the drawer is, therefore left/right values // are reversed from one another. final float offset = getDrawerViewOffset(releasedChild); final int childWidth = releasedChild.getWidth(); int left; if (checkDrawerViewAbsoluteGravity(releasedChild, Gravity.LEFT)) { left = xvel > 0 || xvel == 0 && offset > 0.5f ? 0 : -childWidth; } else { final int width = getWidth(); left = xvel < 0 || xvel == 0 && offset > 0.5f ? width - childWidth : width; } mDragger.settleCapturedViewAt(left, releasedChild.getTop()); invalidate(); } @Override public void onEdgeTouched(int edgeFlags, int pointerId) { postDelayed(mPeekRunnable, PEEK_DELAY); } private void peekDrawer() { final View toCapture; final int childLeft; final int peekDistance = mDragger.getEdgeSize(); final boolean leftEdge = mAbsGravity == Gravity.LEFT; if (leftEdge) { toCapture = findDrawerWithGravity(Gravity.LEFT); childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance; } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); childLeft = getWidth() - peekDistance; } // Only peek if it would mean making the drawer more visible and the drawer isn't locked if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { final LayoutParams lp = (LayoutParams) toCapture.getLayoutParams(); mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop()); lp.isPeeking = true; invalidate(); closeOtherDrawer(); cancelChildViewTouch(); } } @Override public boolean onEdgeLock(int edgeFlags) { if (ALLOW_EDGE_LOCK) { final View drawer = findDrawerWithGravity(mAbsGravity); if (drawer != null && !isDrawerOpen(drawer)) { closeDrawer(drawer); } return true; } return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { final View toCapture; if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) { toCapture = findDrawerWithGravity(Gravity.LEFT); } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); } if (toCapture != null && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { mDragger.captureChildView(toCapture, pointerId); } } @Override public int getViewHorizontalDragRange(View child) { return isDrawerView(child) ? child.getWidth() : 0; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { return Math.max(-child.getWidth(), Math.min(left, 0)); } else { final int width = getWidth(); return Math.max(width - child.getWidth(), Math.min(left, width)); } } @Override public int clampViewPositionVertical(View child, int top, int dy) { return child.getTop(); } } public static class LayoutParams extends ViewGroup.MarginLayoutParams { public int gravity = Gravity.NO_GRAVITY; float onScreen; boolean isPeeking; boolean knownOpen; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS); this.gravity = a.getInt(0, Gravity.NO_GRAVITY); a.recycle(); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(int width, int height, int gravity) { this(width, height); this.gravity = gravity; } public LayoutParams(LayoutParams source) { super(source); this.gravity = source.gravity; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } } class AccessibilityDelegate extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info); super.onInitializeAccessibilityNodeInfo(host, superNode); info.setClassName(DrawerLayout.class.getName()); info.setSource(host); final ViewParent parent = ViewCompat.getParentForAccessibility(host); if (parent instanceof View) { info.setParent((View) parent); } copyNodeInfoNoChildren(info, superNode); superNode.recycle(); addChildrenForAccessibility(info, (ViewGroup) host); } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setClassName(DrawerLayout.class.getName()); } @Override public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { // Special case to handle window state change events. As far as // accessibility services are concerned, state changes from // DrawerLayout invalidate the entire contents of the screen (like // an Activity or Dialog) and they should announce the title of the // new content. if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { final List<CharSequence> eventText = event.getText(); final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null) { final int edgeGravity = getDrawerViewAbsoluteGravity(visibleDrawer); final CharSequence title = getDrawerTitle(edgeGravity); if (title != null) { eventText.add(title); } } return true; } return super.dispatchPopulateAccessibilityEvent(host, event); } private void addChildrenForAccessibility(AccessibilityNodeInfoCompat info, ViewGroup v) { final int childCount = v.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = v.getChildAt(i); if (includeChildForAccessibility(child)) { info.addChild(child); } } } @Override public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { if (includeChildForAccessibility(child)) { return super.onRequestSendAccessibilityEvent(host, child, event); } return false; } /** * This should really be in AccessibilityNodeInfoCompat, but there unfortunately * seem to be a few elements that are not easily cloneable using the underlying API. * Leave it private here as it's not general-purpose useful. */ private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) { final Rect rect = mTmpRect; src.getBoundsInParent(rect); dest.setBoundsInParent(rect); src.getBoundsInScreen(rect); dest.setBoundsInScreen(rect); dest.setVisibleToUser(src.isVisibleToUser()); dest.setPackageName(src.getPackageName()); dest.setClassName(src.getClassName()); dest.setContentDescription(src.getContentDescription()); dest.setEnabled(src.isEnabled()); dest.setClickable(src.isClickable()); dest.setFocusable(src.isFocusable()); dest.setFocused(src.isFocused()); dest.setAccessibilityFocused(src.isAccessibilityFocused()); dest.setSelected(src.isSelected()); dest.setLongClickable(src.isLongClickable()); dest.addAction(src.getActions()); } } final class ChildAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityNodeInfo(View child, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(child, info); if (!includeChildForAccessibility(child)) { // If we are ignoring the sub-tree rooted at the child, // break the connection to the rest of the node tree. // For details refer to includeChildForAccessibility. info.setParent(null); } } } }
am 62c63bed: am 99cb2bbf: Make DrawerLayout system UI flag manipulation less excitable * commit '62c63bed846de0f9097dd1c22313304788491a68': Make DrawerLayout system UI flag manipulation less excitable
v4/java/android/support/v4/widget/DrawerLayout.java
am 62c63bed: am 99cb2bbf: Make DrawerLayout system UI flag manipulation less excitable
Java
apache-2.0
0605955fa05c021e7a4f492910544fc6921f6c56
0
speedy01/Openfire,Gugli/Openfire,magnetsystems/message-openfire,akrherz/Openfire,akrherz/Openfire,magnetsystems/message-openfire,GregDThomas/Openfire,GregDThomas/Openfire,Gugli/Openfire,GregDThomas/Openfire,akrherz/Openfire,igniterealtime/Openfire,GregDThomas/Openfire,guusdk/Openfire,GregDThomas/Openfire,akrherz/Openfire,igniterealtime/Openfire,magnetsystems/message-openfire,speedy01/Openfire,igniterealtime/Openfire,igniterealtime/Openfire,Gugli/Openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,akrherz/Openfire,guusdk/Openfire,Gugli/Openfire,speedy01/Openfire,speedy01/Openfire,guusdk/Openfire,Gugli/Openfire,guusdk/Openfire,guusdk/Openfire,igniterealtime/Openfire,speedy01/Openfire
/** * $Revision $ * $Date $ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ifsoft.rayo; import org.dom4j.*; import org.jivesoftware.openfire.container.Plugin; import org.jivesoftware.openfire.container.PluginManager; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.muc.*; import org.jivesoftware.openfire.muc.spi.*; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.http.HttpBindManager; import org.jivesoftware.openfire.group.Group; import org.jivesoftware.openfire.group.GroupManager; import org.jivesoftware.openfire.group.GroupNotFoundException; import org.jivesoftware.openfire.handler.IQHandler; import org.jivesoftware.openfire.IQHandlerInfo; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.util.JiveGlobals; import org.xmpp.packet.JID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmpp.component.Component; import org.xmpp.component.ComponentException; import org.xmpp.component.ComponentManager; import org.xmpp.component.ComponentManagerFactory; import org.xmpp.component.AbstractComponent; import org.xmpp.jnodes.*; import org.xmpp.jnodes.nio.LocalIPResolver; import org.xmpp.packet.*; import java.util.*; import java.util.concurrent.*; import java.text.ParseException; import java.net.*; import com.rayo.core.*; import com.rayo.core.verb.*; import com.rayo.core.validation.*; import com.rayo.core.xml.providers.*; import com.sun.voip.server.*; import com.sun.voip.*; import org.voicebridge.*; import com.jcumulus.server.rtmfp.ServerPipelineFactory; import com.jcumulus.server.rtmfp.Sessions; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; public class RayoComponent extends AbstractComponent implements TreatmentDoneListener, CallEventListener { private static final Logger Log = LoggerFactory.getLogger(RayoComponent.class); private static final String RAYO_CORE = "urn:xmpp:rayo:1"; private static final String RAYO_RECORD = "urn:xmpp:rayo:record:1"; private static final String RAYO_SAY = "urn:xmpp:tropo:say:1"; private static final String RAYO_HANDSET = "urn:xmpp:rayo:handset:1"; private static final String HOST = "host"; private static final String LOCAL_PORT = "localport"; private static final String REMOTE_PORT = "remoteport"; private static final String ID = "id"; private static final String URI = "uri"; private static final String defaultIncomingConferenceId = "IncomingCallsConference"; public static RayoComponent self; private final RayoPlugin plugin; private RayoProvider rayoProvider = null; private RecordProvider recordProvider = null; private SayProvider sayProvider = null; private HandsetProvider handsetProvider = null; private static ConnectionlessBootstrap bootstrap = null; public static Channel channel = null; private static Sessions sessions; public RayoComponent(final RayoPlugin plugin) { self = this; this.plugin = plugin; } public void doStart() { Log.info("RayoComponent initialize " + jid); XMPPServer server = XMPPServer.getInstance(); server.getIQDiscoInfoHandler().addServerFeature(RAYO_CORE); rayoProvider = new RayoProvider(); rayoProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_RECORD); recordProvider = new RecordProvider(); recordProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_SAY); sayProvider = new SayProvider(); sayProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_HANDSET); handsetProvider = new HandsetProvider(); handsetProvider.setValidator(new Validator()); createIQHandlers(); Plugin fastpath = server.getPluginManager().getPlugin("fastpath"); if (fastpath != null) { Log.info("RayoComponent found Fastpath"); } try{ Log.info("Starting jCumulus....."); sessions = new Sessions(); ExecutorService executorservice = Executors.newCachedThreadPool(); NioDatagramChannelFactory niodatagramchannelfactory = new NioDatagramChannelFactory(executorservice); bootstrap = new ConnectionlessBootstrap(niodatagramchannelfactory); OrderedMemoryAwareThreadPoolExecutor orderedmemoryawarethreadpoolexecutor = new OrderedMemoryAwareThreadPoolExecutor(10, 0x100000L, 0x40000000L, 100L, TimeUnit.MILLISECONDS, Executors.defaultThreadFactory()); bootstrap.setPipelineFactory(new ServerPipelineFactory(sessions, orderedmemoryawarethreadpoolexecutor)); bootstrap.setOption("reuseAddress", Boolean.valueOf(true)); bootstrap.setOption("sendBufferSize", Integer.valueOf(1215)); bootstrap.setOption("receiveBufferSize", Integer.valueOf(2048)); bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(2048)); InetSocketAddress inetsocketaddress = new InetSocketAddress(JiveGlobals.getIntProperty("voicebridge.rtmfp.port", 1935)); Log.info("Listening on " + inetsocketaddress.getPort() + " port"); channel = bootstrap.bind(inetsocketaddress); } catch (Exception e) { Log.error("jCumulus startup failure"); e.printStackTrace(); } } public void doStop() { Log.info("RayoComponent shutdown "); XMPPServer server = XMPPServer.getInstance(); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_CORE); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_RECORD); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_SAY); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_HANDSET); destroyIQHandlers(); Log.info("jCumulus stopping..."); channel.close(); bootstrap.releaseExternalResources(); } public String getName() { return "rayo"; } public String getDescription() { return "XEP-0327: Rayo"; } @Override protected String[] discoInfoFeatureNamespaces() { return new String[]{RAYO_CORE}; } @Override protected String discoInfoIdentityCategoryType() { return "rayo"; } @Override protected IQ handleIQGet(IQ iq) throws Exception { Log.info("RayoComponent handleIQGet \n" + iq.toString()); final Element element = iq.getChildElement(); final String namespace = element.getNamespaceURI(); try { if (RAYO_HANDSET.equals(namespace)) { IQ reply = null; Object object = handsetProvider.fromXML(element); if (object instanceof OnHookCommand) { OnHookCommand command = (OnHookCommand) object; reply = handleOnOffHookCommand(command, iq); } else if (object instanceof OffHookCommand) { OffHookCommand command = (OffHookCommand) object; reply = handleOnOffHookCommand(command, iq); } else if (object instanceof MuteCommand) { reply = handleMuteCommand((MuteCommand) object, iq); } else if (object instanceof UnmuteCommand) { reply = handleMuteCommand((UnmuteCommand) object, iq); } else if (object instanceof HoldCommand) { reply = handleHoldCommand((HoldCommand) object, iq); } else if (object instanceof PrivateCommand) { reply = handlePrivateCommand(object, iq); } else if (object instanceof PublicCommand) { reply = handlePrivateCommand(object, iq); } return reply; } if (RAYO_RECORD.equals(namespace)) { IQ reply = null; Object object = recordProvider.fromXML(element); if (object instanceof Record) { reply = handleRecord((Record) object, iq); } else if (object instanceof PauseCommand) { reply = handlePauseRecordCommand(true, iq); } else if (object instanceof ResumeCommand) { reply = handlePauseRecordCommand(false, iq); } return reply; } if (RAYO_SAY.equals(namespace)) { IQ reply = null; Object object = sayProvider.fromXML(element); if (object instanceof Say) { reply = handleSay((Say) object, iq); } else if (object instanceof PauseCommand) { reply = handlePauseSayCommand(true, iq); } else if (object instanceof ResumeCommand) { reply = handlePauseSayCommand(false, iq); } return reply; } if (RAYO_CORE.equals(namespace)) { IQ reply = null; Object object = rayoProvider.fromXML(element); if (object instanceof JoinCommand) { reply = handleJoinCommand((JoinCommand) object, iq); } else if (object instanceof UnjoinCommand) { reply = handleUnjoinCommand((UnjoinCommand) object, iq); } else if (object instanceof AcceptCommand) { reply = handleAcceptCommand((AcceptCommand) object, iq); } else if (object instanceof AnswerCommand) { reply = handleAnswerCommand((AnswerCommand) object, iq); } else if (object instanceof HangupCommand) { reply = handleHangupCommand(iq); } else if (object instanceof RejectCommand) { // implemented as hangup on client } else if (object instanceof RedirectCommand) { RedirectCommand redirect = (RedirectCommand) object; DialCommand dial = new DialCommand(); dial.setTo(redirect.getTo()); dial.setFrom(new URI("xmpp:" + iq.getFrom())); dial.setHeaders(redirect.getHeaders()); reply = handleDialCommand((DialCommand) dial, iq, true); } else if (object instanceof DialCommand) { reply = handleDialCommand((DialCommand) object, iq, false); } else if (object instanceof StopCommand) { } else if (object instanceof DtmfCommand) { reply = handleDtmfCommand((DtmfCommand) object, iq); } else if (object instanceof DestroyMixerCommand) { } return reply; } return null; // feature not implemented. } catch (Exception e) { e.printStackTrace(); final IQ reply = IQ.createResultIQ(iq); reply.setError(PacketError.Condition.internal_server_error); return reply; } } private IQ handleHoldCommand(Object object, IQ iq) { Log.info("RayoComponent handleHoldCommand"); IQ reply = IQ.createResultIQ(iq); String callId = iq.getTo().getNode(); // far party CallHandler handler = CallHandler.findCall(callId); if (handler != null) { handler.getCallParticipant().setHeld(true); } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleMuteCommand(Object object, IQ iq) { Log.info("RayoComponent handleMuteCommand"); boolean muted = object instanceof MuteCommand; IQ reply = IQ.createResultIQ(iq); String callId = JID.escapeNode(iq.getFrom().toString()); // handset CallHandler handler = CallHandler.findCall(callId); if (handler != null) { handler.setMuted(muted); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(handler.getCallParticipant().getConferenceId()); ArrayList memberList = conferenceManager.getMemberList(); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent handleMuteCommand route event to " + target); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (muted) { MutedEvent event = new MutedEvent(); presence.getElement().add(handsetProvider.toXML(event)); } else { UnmutedEvent event = new UnmutedEvent(); presence.getElement().add(handsetProvider.toXML(event)); } sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handlePrivateCommand(Object object, IQ iq) { Log.info("RayoComponent handlePrivateCommand"); boolean privateCall = object instanceof PrivateCommand; IQ reply = IQ.createResultIQ(iq); String callId = JID.escapeNode(iq.getFrom().toString()); // handset CallHandler handler = CallHandler.findCall(callId); if (handler != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(handler.getCallParticipant().getConferenceId()); conferenceManager.setPrivateCall(privateCall); ArrayList memberList = conferenceManager.getMemberList(); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent handlePrivateCommand route event to " + target); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (privateCall) { PrivateEvent event = new PrivateEvent(); presence.getElement().add(handsetProvider.toXML(event)); } else { PublicEvent event = new PublicEvent(); presence.getElement().add(handsetProvider.toXML(event)); } sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleOnOffHookCommand(Object object, IQ iq) { Log.info("RayoComponent handleOnOffHookCommand"); IQ reply = IQ.createResultIQ(iq); String handsetId = JID.escapeNode(iq.getFrom().toString()); if (object instanceof OnHookCommand) { CallHandler handler = CallHandler.findCall(handsetId); if (handler != null) { handleOnOffHook(handsetId, object, plugin.getRelayChannel(handsetId), reply); } else { reply.setError(PacketError.Condition.item_not_found); } } else { final Handset handset = ((OffHookCommand) object).getHandset(); if (handset.sipuri == null) // webrtc handset { final RelayChannel channel = plugin.createRelayChannel(iq.getFrom(), handset); if (channel != null) { final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(HOST, LocalIPResolver.getLocalIP()); childElement.addAttribute(LOCAL_PORT, Integer.toString(channel.getPortA())); childElement.addAttribute(REMOTE_PORT, Integer.toString(channel.getPortB())); childElement.addAttribute(ID, channel.getAttachment()); childElement.addAttribute(URI, "xmpp:" + channel.getAttachment() + "@" + getDomain() + "/webrtc"); Log.debug("Created WebRTC handset channel {}:{}, {}:{}, {}:{}", new Object[]{HOST, LocalIPResolver.getLocalIP(), LOCAL_PORT, Integer.toString(channel.getPortA()), REMOTE_PORT, Integer.toString(channel.getPortB())}); handleOnOffHook(handsetId, object, channel, reply); } else { reply.setError(PacketError.Condition.internal_server_error); } } else { // SIP handset final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, handsetId); childElement.addAttribute(URI, handset.sipuri); Log.info("Created SIP handset channel " + handset.sipuri); handleOnOffHook(handsetId, object, null, reply); } } return reply; } private void handleOnOffHook(String handsetId, Object object, RelayChannel channel, IQ reply) { final boolean flag = object instanceof OnHookCommand; Log.info("RayoComponent handleOnOffHook " + flag); try { CallHandler handler = CallHandler.findCall(handsetId); if (handler != null) { handler.cancelRequest("Reseting handset to " + (flag ? "on" : "off") + "hook"); handler = null; } if (!flag) // offhook { Handset handset = ((OffHookCommand) object).getHandset(); String mediaPreference = "PCMU/8000/1"; if (handset.codec == null || "OPUS".equals(handset.codec)) mediaPreference = "PCM/48000/2"; CallParticipant cp = new CallParticipant(); cp.setCallId(handsetId); cp.setConferenceId(handset.mixer); cp.setDisplayName("rayo-handset-" + System.currentTimeMillis()); cp.setName(cp.getDisplayName()); cp.setVoiceDetection(true); cp.setCallOwner(JID.unescapeNode(handsetId)); String label = (new JID(cp.getCallOwner())).getNode(); if (handset.group != null && ! "".equals(handset.group)) { label = handset.group; } ConferenceManager cm = ConferenceManager.getConference(handset.mixer, mediaPreference, label, false); if (handset.callId != null && "".equals(handset.callId) == false) { cm.setCallId(handset.callId); // set answering far party call id for mixer } if (handset.group != null && ! "".equals(handset.group)) { cm.setGroupName(handset.group); } if (cm.isPrivateCall() == false || cm.getMemberList().size() < 2) { if (channel == null) { if (handset.sipuri.indexOf("sip:") == 0) { cp.setPhoneNumber(handset.sipuri); cp.setAutoAnswer(true); cp.setProtocol("SIP"); } else if (handset.sipuri.indexOf("rtmfp:") == 0) { String[] tokens = handset.sipuri.split(":"); if (tokens.length == 3) { cp.setProtocol("Rtmfp"); cp.setRtmfpSendStream(tokens[1]); cp.setRtmfpRecieveStream(tokens[2]); cp.setAutoAnswer(true); } else { reply.setError(PacketError.Condition.not_allowed); return; } } else { reply.setError(PacketError.Condition.not_allowed); return; } } else { cp.setMediaPreference(mediaPreference); cp.setRelayChannel(channel); cp.setProtocol("WebRtc"); } OutgoingCallHandler callHandler = new OutgoingCallHandler(this, cp); callHandler.start(); if (channel != null) { channel.setCallHandler(callHandler); } } else { reply.setError(PacketError.Condition.not_allowed); } } } catch (Exception e) { e.printStackTrace(); } } private IQ handleRecord(Record command, IQ iq) { Log.info("RayoComponent handleRecord " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); final String callId = JID.escapeNode(iq.getFrom().toString()); final String uri = command.getTo().toString(); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { try { final String fileName = uri.substring(5); // expecting file: prefix callHandler.getCallParticipant().setRecordDirectory(System.getProperty("com.sun.voip.server.Bridge.soundsDirectory", ".")); callHandler.getMemberReceiver().setRecordFromMember(true, fileName, "au"); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, fileName); childElement.addAttribute(URI, (String) uri); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handlePauseRecordCommand(boolean flag, IQ iq) { Log.info("RayoComponent handlePauseRecordCommand " + iq.getFrom() + " " + iq.getTo()); IQ reply = IQ.createResultIQ(iq); final String callId = JID.escapeNode(iq.getFrom().toString()); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { try { CallParticipant cp = callHandler.getCallParticipant(); String fileName = cp.getFromRecordingFile(); cp.setRecordDirectory(System.getProperty("com.sun.voip.server.Bridge.soundsDirectory", ".")); callHandler.getMemberReceiver().setRecordFromMember(flag, fileName, "au"); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleSay(Say command, IQ iq) { Log.info("RayoComponent handleSay " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); final String entityId = iq.getTo().getNode(); final String treatmentId = command.getPrompt().getText(); try { CallHandler callHandler = CallHandler.findCall(entityId); try { callHandler.playTreatmentToCall(treatmentId, this); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, treatmentId); childElement.addAttribute(URI, (String) "xmpp:" + entityId + "@" + getDomain() + "/" + treatmentId); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } catch (NoSuchElementException e) { // not call, lets try mixer try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(entityId); try { conferenceManager.addTreatment(treatmentId); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, treatmentId); childElement.addAttribute(URI, (String) "xmpp:" + entityId + "@" + getDomain() + "/" + treatmentId); } catch (Exception e2) { e2.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } catch (ParseException e1) { reply.setError(PacketError.Condition.item_not_found); } } return reply; } private IQ handlePauseSayCommand(boolean flag, IQ iq) { Log.info("RayoComponent handlePauseSayCommand " + iq.getFrom() + " " + iq.getTo()); IQ reply = IQ.createResultIQ(iq); final JID entityId = getJID(iq.getTo().getNode()); if (entityId != null) { final String treatmentId = entityId.getResource(); final String callId = entityId.getNode(); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { callHandler.getMember().pauseTreatment(treatmentId, flag); } else { // not call, lets try mixer try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(callId); conferenceManager.getWGManager().pauseConferenceTreatment(treatmentId, flag); } catch (ParseException e1) { reply.setError(PacketError.Condition.item_not_found); } } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleAcceptCommand(AcceptCommand command, IQ iq) { Map<String, String> headers = command.getHeaders(); String callId = iq.getTo().getNode(); // destination JID escaped String callerId = headers.get("caller_id"); // source JID String mixer = headers.get("mixer_name"); Log.info("RayoComponent handleAcceptCommand " + callerId + " " + callId + " " + mixer); IQ reply = IQ.createResultIQ(iq); JID callJID = getJID(callId); if (callJID != null) // only for XMPP calls { if (mixer != null) { headers.put("call_protocol", "XMPP"); callerId = callerId.substring(5); // remove xmpp: prefix Presence presence = new Presence(); presence.setFrom(iq.getTo()); presence.setTo(callerId); setRingingState(presence, ConferenceManager.isTransferCall(mixer), headers); sendPacket(presence); } else reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleAnswerCommand(AnswerCommand command, IQ iq) { Map<String, String> headers = command.getHeaders(); IQ reply = IQ.createResultIQ(iq); String callId = iq.getTo().getNode(); // destination JID escaped String callerId = headers.get("caller_id"); // source JID Log.info("RayoComponent AnswerCommand " + callerId + " " + callId); if (callerId != null) { JID callJID = getJID(callId); CallHandler callHandler = null; CallHandler handsetHandler = null; if (callJID != null) // XMPP call { callerId = callerId.substring(5); // remove xmpp: prefix headers.put("call_protocol", "XMPP"); headers.put("call_owner", callerId); headers.put("call_action", "join"); try { callHandler = CallHandler.findCall(callId); handsetHandler = CallHandler.findCall(JID.escapeNode(callerId)); if (handsetHandler != null) { CallParticipant hp = handsetHandler.getCallParticipant(); Presence presence1 = new Presence(); //to caller presence1.setFrom(iq.getTo()); presence1.setTo(callerId); setAnsweredState(presence1, ConferenceManager.isTransferCall(hp.getConferenceId()), headers); sendPacket(presence1); } } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); e.printStackTrace(); } } else { callHandler = CallHandler.findCall(callId); // SIP call; handsetHandler = CallHandler.findCall(JID.escapeNode(iq.getFrom().toString())); } if (callHandler != null && handsetHandler != null) { CallParticipant cp = callHandler.getCallParticipant(); CallParticipant hp = handsetHandler.getCallParticipant(); Log.info("RayoComponent handleAnswerCommand found call handlers " + cp.getCallId() + " " + hp.getCallId()); try { long start = System.currentTimeMillis(); cp.setStartTimestamp(start); cp.setHandset(hp); hp.setFarParty(cp); hp.setStartTimestamp(start); cp.setHeaders(headers); String recording = cp.getConferenceId() + "-" + cp.getStartTimestamp() + ".au"; ConferenceManager.recordConference(cp.getConferenceId(), true, recording, "au"); String destination = iq.getFrom().getNode(); String source = cp.getName(); if (callJID != null) { source = (new JID(callerId)).getNode(); Config.createCallRecord(source, recording, "xmpp:" + iq.getFrom(), cp.getStartTimestamp(), 0, "dialed") ; Config.createCallRecord(destination, recording, "xmpp:" + callerId, cp.getStartTimestamp(), 0, "received"); sendMessage(new JID(callerId), iq.getFrom(), "Call started", recording, "chat"); } else { // incoming SIP Config.createCallRecord(destination, recording, "sip:" + cp.getPhoneNumber(), cp.getStartTimestamp(), 0, "received") ; sendMessage(iq.getFrom(), new JID(cp.getCallId() + "@" + getDomain()), "Call started", recording, "chat"); } } catch (ParseException e1) { reply.setError(PacketError.Condition.internal_server_error); } } else reply.setError(PacketError.Condition.item_not_found); } else reply.setError(PacketError.Condition.item_not_found); return reply; } private IQ handleHangupCommand(IQ iq) { String callId = iq.getTo().getNode(); Log.info("RayoComponent handleHangupCommand " + iq.getFrom() + " " + callId); IQ reply = IQ.createResultIQ(iq); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { Log.info("RayoComponent handleHangupCommand found callhandler " + callId); CallParticipant cp = callHandler.getCallParticipant(); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(cp.getConferenceId()); Log.info("RayoComponent handleHangupCommand one person left, cancel call " + conferenceManager.getMemberList().size()); if (conferenceManager.getMemberList().size() <= 2) { CallHandler.hangup(callId, "User requested call termination"); } } catch (Exception e) {} } else { //reply.setError(PacketError.Condition.item_not_found); } return reply; } private JID getJID(String jid) { jid = JID.unescapeNode(jid); if (jid.indexOf("@") == -1 || jid.indexOf("/") == -1) return null; try { return new JID(jid); } catch (Exception e) { return null; } } private IQ handleDtmfCommand(DtmfCommand command, IQ iq) { Log.info("RayoComponent handleDtmfCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); try { CallHandler callHandler = CallHandler.findCall(iq.getTo().getNode()); callHandler.dtmfKeys(command.getTones()); } catch (NoSuchElementException e) { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleJoinCommand(JoinCommand command, IQ iq) { Log.info("RayoComponent handleJoinCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); String mixer = null; if (command.getType() == JoinDestinationType.CALL) { // TODO join.getTo() } else { mixer = command.getTo(); } if (mixer != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); if (CallHandler.findCall("colibri-" + mixer) == null) // other participant than colibri { attachVideobridge(mixer, iq.getFrom(), conferenceManager.getMediaInfo().toString()); if (conferenceManager.getMemberList().size() == 1) // handset already in call { String recording = mixer + "-" + System.currentTimeMillis() + ".au"; conferenceManager.recordConference(true, recording, "au"); sendMucMessage(mixer, recording, iq.getFrom(), "started voice recording"); } } sendMucMessage(mixer, null, iq.getFrom(), iq.getFrom().getNode() + " joined voice conversation"); } catch (ParseException pe) { // colibri joining as first participant try { ConferenceManager conferenceManager = ConferenceManager.getConference(mixer, "PCM/48000/2", mixer, false); String recording = mixer + "-" + System.currentTimeMillis() + ".au"; conferenceManager.recordConference(true, recording, "au"); sendMucMessage(mixer, recording, iq.getFrom(), "started voice recording"); attachVideobridge(mixer, iq.getFrom(), "PCM/48000/2"); } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } return reply; } private IQ handleUnjoinCommand(UnjoinCommand command, IQ iq) { Log.info("RayoComponent handleUnjoinCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); String mixer = null; if (command.getType() == JoinDestinationType.CALL) { // TODO join.getFrom() } else { mixer = command.getFrom(); } if (mixer != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); if (conferenceManager.getMemberList().size() == 1) { conferenceManager.recordConference(false, null, null); sendMucMessage(mixer, null, iq.getFrom(), "stopped voice recording"); detachVideobridge(mixer); } sendMucMessage(mixer, null, iq.getFrom(), iq.getFrom().getNode() + " left voice conversation"); } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } return reply; } private void attachVideobridge(String conferenceId, JID participant, String mediaPreference) { //if (XMPPServer.getInstance().getPluginManager().getPlugin("jitsivideobridge") != null) //{ Log.info("attachVideobridge Found Jitsi Videobridge, attaching.." + conferenceId); if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(conferenceId)) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(conferenceId); if (room != null) { for (MUCRole role : room.getOccupants()) { if (participant.toBareJID().equals(role.getUserAddress().toBareJID())) { Log.info("attachVideobridge Found participant " + participant.toBareJID()); try { CallParticipant vp = new CallParticipant(); vp.setCallId("colibri-" + conferenceId); vp.setCallOwner(participant.toString()); vp.setProtocol("Videobridge"); vp.setPhoneNumber(participant.getNode()); vp.setMediaPreference(mediaPreference); vp.setConferenceId(conferenceId); OutgoingCallHandler videoBridgeHandler = new OutgoingCallHandler(null, vp); videoBridgeHandler.start(); } catch (Exception e) { e.printStackTrace(); } break; } } } } //} } private void detachVideobridge(String conferenceId) { try { Log.info("Jitsi Videobridge, detaching.." + conferenceId); CallHandler callHandler = CallHandler.findCall("colibri-" + conferenceId); if (callHandler != null) { CallHandler.hangup("colibri-" + conferenceId, "Detaching from Jitsi Videobridge"); } } catch (Exception e) { e.printStackTrace(); } } private void sendMucMessage(String mixer, String recording, JID participant, String message) { if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(mixer)) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(mixer); if (room != null) { sendMessage(new JID(mixer + "@conference." + getDomain()), participant, message, recording, "groupchat"); } } } private IQ handleDialCommand(DialCommand command, IQ iq, boolean transferCall) { Log.info("RayoComponent handleHandsetDialCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); Map<String, String> headers = command.getHeaders(); String from = command.getFrom().toString(); String to = command.getTo().toString(); boolean toPhone = to.indexOf("sip:") == 0 || to.indexOf("tel:") == 0; boolean toXmpp = to.indexOf("xmpp:") == 0; String callerName = headers.get("caller_name"); String calledName = headers.get("called_name"); String handsetId = iq.getFrom().toString(); JoinCommand join = command.getJoin(); if (join != null) { if (join.getType() == JoinDestinationType.CALL) { // TODO join.getTo() } else { } reply.setError(PacketError.Condition.feature_not_implemented); } else { if (callerName == null) { callerName = iq.getFrom().getNode(); headers.put("caller_name", callerName); } if (toPhone) { if (calledName == null) { calledName = to; headers.put("called_name", calledName); } CallParticipant cp = new CallParticipant(); cp.setVoiceDetection(true); cp.setCallOwner(handsetId); cp.setProtocol("SIP"); cp.setDisplayName(callerName); cp.setPhoneNumber(to); cp.setName(calledName); cp.setHeaders(headers); reply = doPhoneAndPcCall(JID.escapeNode(handsetId), cp, reply, transferCall); } else if (toXmpp){ headers.put("call_protocol", "XMPP"); JID destination = getJID(to.substring(5)); if (destination != null) { String source = JID.escapeNode(handsetId); CallHandler handsetHandler = CallHandler.findCall(source); if (handsetHandler != null) { CallParticipant hp = handsetHandler.getCallParticipant(); headers.put("mixer_name", hp.getConferenceId()); headers.put("codec_name", "PCM/48000/2".equals(hp.getMediaPreference()) ? "OPUS" : "PCMU"); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(hp.getConferenceId()); conferenceManager.setTransferCall(transferCall); } catch (Exception e) {} if (findUser(destination.getNode()) != null) { routeXMPPCall(reply, destination, source, calledName, headers, hp.getConferenceId()); } else { int count = 0; try { Group group = GroupManager.getInstance().getGroup(destination.getNode()); for (JID memberJID : group.getMembers()) { if (iq.getFrom().toBareJID().equals(memberJID.toBareJID()) == false) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeXMPPCall(reply, session.getAddress(), source, calledName, headers, hp.getConferenceId()); count++; } } } } catch (GroupNotFoundException e) { if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(destination.getNode())) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(destination.getNode()); if (room != null) { for (MUCRole role : room.getOccupants()) { if (iq.getFrom().toBareJID().equals(role.getUserAddress().toBareJID()) == false) { routeXMPPCall(reply, role.getUserAddress(), source, calledName, headers, hp.getConferenceId()); count++; } } } } else { reply.setError(PacketError.Condition.item_not_found); } } if (count == 0) { reply.setError(PacketError.Condition.item_not_found); } } } else { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } } return reply; } private void routeXMPPCall(IQ reply, JID destination, String source, String calledName, Map<String, String> headers, String mixer) { String callId = JID.escapeNode(destination.toString()); Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(destination); OfferEvent offer = new OfferEvent(null); try { offer.setFrom(new URI("xmpp:" + JID.unescapeNode(source))); offer.setTo(new URI("xmpp:" + destination)); } catch (URISyntaxException e) { reply.setError(PacketError.Condition.feature_not_implemented); return; } if (calledName == null) { calledName = presence.getTo().getNode(); headers.put("called_name", calledName); } offer.setHeaders(headers); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(URI, (String) "xmpp:" + presence.getFrom()); childElement.addAttribute(ID, (String) callId); presence.getElement().add(rayoProvider.toXML(offer)); sendPacket(presence); } private IQ doPhoneAndPcCall(String handsetId, CallParticipant cp, IQ reply, boolean transferCall) { Log.info("RayoComponent doPhoneAndPcCall " + handsetId); CallHandler handsetHandler = CallHandler.findCall(handsetId); if (handsetHandler != null) { try { setMixer(handsetHandler, reply, cp, transferCall); OutgoingCallHandler outgoingCallHandler = new OutgoingCallHandler(this, cp); //outgoingCallHandler.setOtherCall(handsetHandler); //handsetHandler.setOtherCall(outgoingCallHandler); outgoingCallHandler.start(); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(URI, (String) "xmpp:" + cp.getCallId() + "@" + getDomain()); childElement.addAttribute(ID, (String) cp.getCallId()); } catch (Exception e) { e.printStackTrace(); reply.setError(PacketError.Condition.internal_server_error); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private void setMixer(CallHandler handsetHandler, IQ reply, CallParticipant cp, boolean transferCall) { CallParticipant hp = handsetHandler.getCallParticipant(); try { hp.setFarParty(cp); cp.setHandset(hp); long start = System.currentTimeMillis(); cp.setStartTimestamp(start); hp.setStartTimestamp(start); String mixer = hp.getConferenceId(); ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); cp.setConferenceId(mixer); cp.setCallId(mixer); cp.setMediaPreference(hp.getMediaPreference()); conferenceManager.setCallId(mixer); conferenceManager.setTransferCall(transferCall); String recording = mixer + "-" + cp.getStartTimestamp() + ".au"; conferenceManager.recordConference(true, recording, "au"); Config.createCallRecord(cp.getDisplayName(), recording, cp.getPhoneNumber(), cp.getStartTimestamp(), 0, "dialed") ; sendMessage(new JID(cp.getCallOwner()), new JID(cp.getCallId() + "@" + getDomain()), "Call started", recording, "chat"); } catch (ParseException e1) { reply.setError(PacketError.Condition.internal_server_error); } } @Override public String getDomain() { return XMPPServer.getInstance().getServerInfo().getXMPPDomain(); } public HandsetProvider getHandsetProvider() { return handsetProvider; } public void treatmentDoneNotification(TreatmentManager treatmentManager) { Log.info("RayoComponent treatmentDoneNotification " + treatmentManager.getId()); } public void callEventNotification(com.sun.voip.CallEvent callEvent) { Log.info("RayoComponent callEventNotification " + callEvent); JID from = getJID(callEvent.getCallInfo()); if (from != null) { String myEvent = com.sun.voip.CallEvent.getEventString(callEvent.getEvent()); String callState = callEvent.getCallState().toString(); try { CallHandler callHandler = CallHandler.findCall(callEvent.getCallId()); if (callHandler != null) { Log.info("RayoComponent callEventNotification found call handler " + callHandler); CallParticipant cp = callHandler.getCallParticipant(); CallParticipant hp = cp.getHandset(); if (cp != null) { Log.info("RayoComponent callEventNotification found call paticipant " + cp); Map<String, String> headers = cp.getHeaders(); headers.put("mixer_name", callEvent.getConferenceId()); headers.put("call_protocol", cp.getProtocol()); Presence presence = new Presence(); presence.setFrom(callEvent.getCallId() + "@" + getDomain()); presence.setTo(from); if ("001 STATE CHANGED".equals(myEvent)) { if ("100 INVITED".equals(callState)) { if (cp.isAutoAnswer() == false) // SIP handset, no ringing event { setRingingState(presence, ConferenceManager.isTransferCall(callEvent.getConferenceId()), headers); sendPacket(presence); } } else if ("200 ESTABLISHED".equals(callState)) { } else if ("299 ENDED".equals(callState)) { } } else if ("250 STARTED SPEAKING".equals(myEvent)) { broadcastSpeaking(true, callEvent.getCallId(), callEvent.getConferenceId(), from); } else if ("259 STOPPED SPEAKING".equals(myEvent)) { broadcastSpeaking(false, callEvent.getCallId(), callEvent.getConferenceId(), from); } else if ("269 DTMF".equals(myEvent)) { presence.getElement().add(rayoProvider.toXML(new DtmfEvent(callEvent.getCallId(), callEvent.getDtmfKey()))); sendPacket(presence); } else if ("230 TREATMENT DONE".equals(myEvent)) { presence.setFrom(callEvent.getCallId() + "@" + getDomain() + "/" + callEvent.getTreatmentId()); SayCompleteEvent complete = new SayCompleteEvent(); complete.setReason(SayCompleteEvent.Reason.valueOf("SUCCESS")); presence.getElement().add(sayProvider.toXML(complete)); sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } } private void broadcastSpeaking(Boolean startSpeaking, String callId, String conferenceId, JID from) { Log.info( "RayoComponent broadcastSpeaking " + startSpeaking + " " + callId + " " + conferenceId + " " + from); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(conferenceId); ArrayList memberList = conferenceManager.getMemberList(); sendMucMessage(conferenceId, null, from, from.getNode() + (startSpeaking ? "started" : "stopped") + " speaking"); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); if (callHandler != null) { CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent broadcastSpeaking checking " + target); if (target != null && callId.equals(cp.getCallId()) == false) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (startSpeaking) { StartedSpeakingEvent speaker = new StartedSpeakingEvent(); speaker.setSpeakerId(callId); presence.getElement().add(rayoProvider.toXML(speaker)); } else { StoppedSpeakingEvent speaker = new StoppedSpeakingEvent(); speaker.setSpeakerId(callId); presence.getElement().add(rayoProvider.toXML(speaker)); } sendPacket(presence); } } } } } catch (Exception e) { e.printStackTrace(); } } private void finishCallRecord(CallParticipant cp) { Log.info( "RayoComponent finishCallRecord " + cp.getStartTimestamp()); if (cp.getStartTimestamp() > 0) { cp.setEndTimestamp(System.currentTimeMillis()); Config.updateCallRecord(cp.getStartTimestamp(), (int)((cp.getEndTimestamp() - cp.getStartTimestamp()) / 1000)); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(cp.getConferenceId()); conferenceManager.recordConference(false, null, null); String target = cp.getCallOwner(); JID destination = getJID(conferenceManager.getCallId()); if (destination == null) { destination = new JID(conferenceManager.getCallId() + "@" + getDomain()); } if (target == null) { if (cp.getHandset() != null) { target = cp.getHandset().getCallOwner(); } } if (target != null) { try { if (target.equals(destination.toString()) == false) { sendMessage(new JID(target), destination, "Call ended", null, "chat"); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) {} cp.setStartTimestamp(0); } } private void sendMessage(JID from, JID to, String body, String fileName, String type) { Log.info( "RayoComponent sendMessage " + from + " " + to + " " + body + " " + fileName); int port = HttpBindManager.getInstance().getHttpBindUnsecurePort(); Message packet = new Message(); packet.setTo(to); packet.setFrom(from); packet.setType("chat".equals(type) ? Message.Type.chat : Message.Type.groupchat); if (fileName != null) packet.setThread("http://" + getDomain() + ":" + port + "/rayo/recordings/" + fileName); packet.setBody(body); sendPacket(packet); } public void sendPacket(Packet packet) { try { ComponentManagerFactory.getComponentManager().sendPacket(this, packet); } catch (Exception e) { Log.error("RayoComponent sendPacket " + e); e.printStackTrace(); } } public void notifyConferenceMonitors(ConferenceEvent conferenceEvent) { Log.info( "RayoComponent notifyConferenceMonitors " + conferenceEvent.toString()); if (defaultIncomingConferenceId.equals(conferenceEvent.getConferenceId())) return; ConferenceManager conferenceManager = null; try { if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) || conferenceEvent.equals(ConferenceEvent.MEMBER_JOINED)) { Log.info("RayoComponent notifyConferenceMonitors looking for call " + conferenceEvent.getCallId() + " " + conferenceEvent.getMemberCount()); try { conferenceManager = ConferenceManager.findConferenceManager(conferenceEvent.getConferenceId()); } catch (Exception e) {} if (conferenceManager != null) { String groupName = conferenceManager.getGroupName(); String callId = conferenceManager.getCallId(); if (callId == null) callId = conferenceEvent.getConferenceId(); // special case of SIP incoming CallHandler farParty = CallHandler.findCall(callId); CallHandler callHandler = CallHandler.findCall(conferenceEvent.getCallId()); if (callHandler != null) { Log.info("RayoComponent notifyConferenceMonitors found call handler " + callHandler + " " + farParty); CallParticipant callParticipant = callHandler.getCallParticipant(); ArrayList memberList = conferenceManager.getMemberList(); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) && callId.equals(conferenceEvent.getCallId())) { if (farParty != null && farParty.getCallParticipant().isHeld() == false) // far party left { synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { CallHandler participant = ((ConferenceMember) memberList.get(i)).getCallHandler(); participant.cancelRequest("Far Party has left"); } } } } int memberCount = memberList.size(); Log.info("RayoComponent notifyConferenceMonitors found owner " + callParticipant.getCallOwner() + " " + memberCount); if (groupName == null) { routeJoinEvent(callParticipant.getCallOwner(), callParticipant, conferenceEvent, memberCount, groupName, callId, farParty, conferenceManager); } else { Group group = GroupManager.getInstance().getGroup(groupName); for (JID memberJID : group.getMembers()) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeJoinEvent(session.getAddress().toString(), callParticipant, conferenceEvent, memberCount, groupName, callId, farParty, conferenceManager); } } } if (memberCount == 0 && conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { conferenceManager.recordConference(false, null, null); conferenceManager.endConference(conferenceEvent.getConferenceId()); CallParticipant heldCall = conferenceManager.getHeldCall(); if (heldCall != null) { JID target = getJID(heldCall.getCallId()); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), callParticipant.getHeaders()))); sendPacket(presence); } } } else if (memberCount == 2) { conferenceManager.setTransferCall(false); // reset after informing on redirect } } } } } catch (Exception e) { Log.error( "RayoComponent Error in notifyConferenceMonitors " + e); e.printStackTrace(); } } private void routeJoinEvent(String callee, CallParticipant callParticipant, ConferenceEvent conferenceEvent, int memberCount, String groupName, String callId, CallHandler farParty, ConferenceManager conferenceManager) { Log.info( "RayoComponent routeJoinEvent " + callee + " " + callId + " " + groupName + " " + memberCount + " " + farParty); if (callee == null) return; Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(callee); Map<String, String> headers = callParticipant.getHeaders(); headers.put("call_owner", callParticipant.getCallOwner()); headers.put("call_action", conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) ? "leave" : "join"); headers.put("call_protocol", callParticipant.getProtocol()); headers.put("mixer_name", conferenceEvent.getConferenceId()); headers.put("group_name", groupName); if (memberCount > 2) // conferencing state { Log.info( "RayoComponent routeJoinEvent conferenced state " + memberCount); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { UnjoinedEvent event = new UnjoinedEvent(null, conferenceEvent.getConferenceId(), JoinDestinationType.MIXER); presence.getElement().add(rayoProvider.toXML(event)); } else { JoinedEvent event = new JoinedEvent(null, conferenceEvent.getConferenceId(), JoinDestinationType.MIXER); presence.getElement().add(rayoProvider.toXML(event)); } sendPacket(presence); } else { if (memberCount == 2) // caller with callee only { Log.info( "RayoComponent routeJoinEvent answered state " + callId + " " + conferenceEvent.getCallId()); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) // previously conferenced { Log.info( "RayoComponent routeJoinEvent someone left "); if (callId.equals(conferenceEvent.getCallId()) == false) // handset leaving { Log.info( "RayoComponent routeJoinEvent handset leaving "); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { Log.info( "RayoComponent routeJoinEvent far party leaving "); } } else { Log.info( "RayoComponent routeJoinEvent someone joined "); if (callId.equals(conferenceEvent.getCallId())) // far party joined { Log.info( "RayoComponent routeJoinEvent far party joined "); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { // handset joined Log.info( "RayoComponent routeJoinEvent handset joined "); if (farParty != null) { CallParticipant fp = farParty.getCallParticipant(); if (fp.isHeld()) { Log.info( "RayoComponent routeJoinEvent on hold "); fp.setHeld(false); conferenceManager.setHeldCall(null); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { Log.info( "RayoComponent routeJoinEvent not held " + fp.getProtocol() + " " + fp); if ("WebRtc".equals(fp.getProtocol()) == false) { Log.info( "RayoComponent routeJoinEvent handset joing sip call"); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } } } } } } else if (memberCount == 1) { // callee or caller if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { Log.info( "RayoComponent routeJoinEvent only one person left"); if (callId.equals(conferenceEvent.getCallId()) == false) // handset leaving { if (farParty != null) { Log.info( "RayoComponent routeJoinEvent handset leaving call " + farParty.getCallParticipant()); CallParticipant fp = farParty.getCallParticipant(); if (callParticipant.isAutoAnswer()) fp.setHeld(true); // sip phone as handset hangup if (fp.isHeld()) { Log.info( "RayoComponent routeJoinEvent call held with " + callParticipant); presence.getElement().add(handsetProvider.toXML(new OnHoldEvent())); sendPacket(presence); conferenceManager.setHeldCall(callParticipant); } } } else { // far party leaving Log.info( "RayoComponent routeJoinEvent far party leaving call " + callParticipant); if (callParticipant.isHeld()) { Log.info( "RayoComponent routeJoinEvent call held with " + farParty); presence.getElement().add(handsetProvider.toXML(new OnHoldEvent())); sendPacket(presence); conferenceManager.setHeldCall(farParty.getCallParticipant()); } else { finishCallRecord(callParticipant); presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), headers))); sendPacket(presence); } } } } else { // nobody left, call ended, signal last handset presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), headers))); sendPacket(presence); finishCallRecord(callParticipant); } } } private void setAnsweredState(Presence presence, boolean isTransfer, Map<String, String> headers) { if (isTransfer) { presence.getElement().add(handsetProvider.toXML(new TransferredEvent())); } else { presence.getElement().add(rayoProvider.toXML(new AnsweredEvent(null, headers))); } } private void setRingingState(Presence presence, boolean isTransfer, Map<String, String> headers) { if (isTransfer) { presence.getElement().add(handsetProvider.toXML(new TransferringEvent())); } else { presence.getElement().add(rayoProvider.toXML(new RingingEvent(null, headers))); } } private JID findUser(String username) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); JID foundUser = null; for (ClientSession session : sessions) { try{ String userId = session.getAddress().getNode(); if (username.equals(userId)) { Log.info("Incoming SIP, findUser " + session.getAddress()); foundUser = session.getAddress(); break; } } catch (Exception e) { } } return foundUser; } public boolean routeIncomingSIP(CallParticipant cp) { boolean canRoute = false; Group group = null; JID foundUser = findUser(cp.getToPhoneNumber()); if (foundUser != null) canRoute = true; else { try { group = GroupManager.getInstance().getGroup(cp.getToPhoneNumber()); canRoute = true; } catch (GroupNotFoundException e) { } } Log.info("Incoming SIP, call route to entity " + cp.getToPhoneNumber() + " " + canRoute); if (canRoute) { String callId = "rayo-incoming-" + System.currentTimeMillis(); cp.setCallId(callId); cp.setConferenceId(callId); if (cp.getMediaPreference() == null) cp.setMediaPreference("PCMU/8000/1"); // regular phone ConferenceManager conferenceManager = ConferenceManager.getConference(callId, cp.getMediaPreference(), cp.getToPhoneNumber(), false); conferenceManager.setCallId(callId); Map<String, String> headers = cp.getHeaders(); headers.put("mixer_name", callId); headers.put("call_protocol", "SIP"); headers.put("codec_name", "PCM/48000/2".equals(cp.getMediaPreference()) ? "OPUS" : "PCMU"); headers.put("group_name", cp.getToPhoneNumber()); if (foundUser != null) // send this call to specific user { cp.setCallOwner(foundUser.toString()); routeSIPCall(foundUser, cp, callId, headers); } else { conferenceManager.setGroupName(cp.getToPhoneNumber()); for (JID memberJID : group.getMembers()) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeSIPCall(session.getAddress(), cp, callId, headers); } } } } return canRoute; } public void routeSIPCall(JID callee, CallParticipant cp, String callId, Map<String, String> headers) { Log.info("routeSIPCall to user " + callee); if (callee != null) // send this call to user { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(callee); OfferEvent offer = new OfferEvent(null); try { offer.setTo(new URI("xmpp:" + callee.toString())); offer.setFrom(new URI("sip:" + cp.getPhoneNumber())); } catch (URISyntaxException e) { Log.error("SIP phone nos not URI " + cp.getPhoneNumber() + " " + callee); } headers.put("called_name", callee.getNode()); headers.put("caller_name", cp.getName()); offer.setHeaders(headers); presence.getElement().add(rayoProvider.toXML(offer)); sendPacket(presence); } } private IQHandler onHookIQHandler = null; private IQHandler offHookIQHandler = null; private IQHandler privateIQHandler = null; private IQHandler publicIQHandler = null; private IQHandler muteIQHandler = null; private IQHandler unmuteIQHandler = null; private IQHandler holdIQHandler = null; private IQHandler sayIQHandler = null; private IQHandler pauseSayIQHandler = null; private IQHandler resumeSayIQHandler = null; private IQHandler recordIQHandler = null; private IQHandler pauseRecordIQHandler = null; private IQHandler resumeRecordIQHandler = null; private IQHandler acceptIQHandler = null; private IQHandler answerIQHandler = null; private IQHandler dialIQHandler = null; private IQHandler hangupIQHandler = null; private IQHandler redirectIQHandler = null; private IQHandler dtmfIQHandler = null; private void createIQHandlers() { XMPPServer server = XMPPServer.getInstance(); onHookIQHandler = new OnHookIQHandler(); server.getIQRouter().addHandler(onHookIQHandler); offHookIQHandler = new OffHookIQHandler(); server.getIQRouter().addHandler(offHookIQHandler); privateIQHandler = new PrivateIQHandler(); server.getIQRouter().addHandler(privateIQHandler); publicIQHandler = new PublicIQHandler(); server.getIQRouter().addHandler(publicIQHandler); muteIQHandler = new MuteIQHandler(); server.getIQRouter().addHandler(muteIQHandler); unmuteIQHandler = new UnmuteIQHandler(); server.getIQRouter().addHandler(unmuteIQHandler); holdIQHandler = new HoldIQHandler(); server.getIQRouter().addHandler(holdIQHandler); recordIQHandler = new RecordIQHandler(); server.getIQRouter().addHandler(recordIQHandler); pauseRecordIQHandler = new PauseRecordIQHandler(); server.getIQRouter().addHandler(pauseRecordIQHandler); resumeRecordIQHandler = new ResumeRecordIQHandler(); server.getIQRouter().addHandler(resumeRecordIQHandler); sayIQHandler = new SayIQHandler(); server.getIQRouter().addHandler(sayIQHandler); pauseSayIQHandler = new PauseSayIQHandler(); server.getIQRouter().addHandler(pauseSayIQHandler); resumeSayIQHandler = new ResumeSayIQHandler(); server.getIQRouter().addHandler(resumeSayIQHandler); acceptIQHandler = new AcceptIQHandler(); server.getIQRouter().addHandler(acceptIQHandler); answerIQHandler = new AnswerIQHandler(); server.getIQRouter().addHandler(answerIQHandler); dialIQHandler = new DialIQHandler(); server.getIQRouter().addHandler(dialIQHandler); hangupIQHandler = new HangupIQHandler(); server.getIQRouter().addHandler(hangupIQHandler); redirectIQHandler = new RedirectIQHandler(); server.getIQRouter().addHandler(redirectIQHandler); dtmfIQHandler = new DtmfIQHandler(); server.getIQRouter().addHandler(dtmfIQHandler); } private void destroyIQHandlers() { XMPPServer server = XMPPServer.getInstance(); if (onHookIQHandler != null) {server.getIQRouter().removeHandler(onHookIQHandler); onHookIQHandler = null;} if (offHookIQHandler != null) {server.getIQRouter().removeHandler(offHookIQHandler); offHookIQHandler = null;} if (privateIQHandler != null) {server.getIQRouter().removeHandler(privateIQHandler); privateIQHandler = null;} if (publicIQHandler != null) {server.getIQRouter().removeHandler(publicIQHandler); publicIQHandler = null;} if (muteIQHandler != null) {server.getIQRouter().removeHandler(muteIQHandler); muteIQHandler = null;} if (unmuteIQHandler != null) {server.getIQRouter().removeHandler(unmuteIQHandler); unmuteIQHandler = null;} if (holdIQHandler != null) {server.getIQRouter().removeHandler(holdIQHandler); holdIQHandler = null;} if (sayIQHandler != null) {server.getIQRouter().removeHandler(sayIQHandler); sayIQHandler = null;} if (pauseSayIQHandler != null) {server.getIQRouter().removeHandler(pauseSayIQHandler); pauseSayIQHandler = null;} if (resumeSayIQHandler != null) {server.getIQRouter().removeHandler(resumeSayIQHandler); resumeSayIQHandler = null;} if (acceptIQHandler != null) {server.getIQRouter().removeHandler(acceptIQHandler); acceptIQHandler = null;} if (answerIQHandler != null) {server.getIQRouter().removeHandler(answerIQHandler); answerIQHandler = null;} if (dialIQHandler != null) {server.getIQRouter().removeHandler(dialIQHandler); dialIQHandler = null;} if (hangupIQHandler != null) {server.getIQRouter().removeHandler(hangupIQHandler); hangupIQHandler = null;} if (redirectIQHandler != null) {server.getIQRouter().removeHandler(redirectIQHandler); redirectIQHandler = null;} if (dtmfIQHandler != null) {server.getIQRouter().removeHandler(dtmfIQHandler); dtmfIQHandler = null;} } private class OnHookIQHandler extends IQHandler { public OnHookIQHandler() { super("Rayo: XEP 0327 - Onhook");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) {return null;} } @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("onhook", RAYO_HANDSET); } } private class OffHookIQHandler extends IQHandler { public OffHookIQHandler() { super("Rayo: XEP 0327 - Offhook");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("offhook", RAYO_HANDSET); } } private class PrivateIQHandler extends IQHandler { public PrivateIQHandler() { super("Rayo: XEP 0327 - Private");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("private", RAYO_HANDSET); } } private class PublicIQHandler extends IQHandler { public PublicIQHandler() { super("Rayo: XEP 0327 - Public");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("public", RAYO_HANDSET); } } private class MuteIQHandler extends IQHandler { public MuteIQHandler() { super("Rayo: XEP 0327 - Mute");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("mute", RAYO_HANDSET); } } private class UnmuteIQHandler extends IQHandler { public UnmuteIQHandler() { super("Rayo: XEP 0327 - Unmute");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("unmute", RAYO_HANDSET); } } private class HoldIQHandler extends IQHandler { public HoldIQHandler() { super("Rayo: XEP 0327 - Hold");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("hold", RAYO_HANDSET); } } private class RecordIQHandler extends IQHandler { public RecordIQHandler() { super("Rayo: XEP 0327 - Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("record", RAYO_RECORD); } } private class PauseRecordIQHandler extends IQHandler { public PauseRecordIQHandler() { super("Rayo: XEP 0327 - Pause Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("pause", RAYO_RECORD); } } private class ResumeRecordIQHandler extends IQHandler { public ResumeRecordIQHandler() { super("Rayo: XEP 0327 - Resume Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("resume", RAYO_RECORD); } } private class SayIQHandler extends IQHandler { public SayIQHandler() { super("Rayo: XEP 0327 - Say (text to speech)");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("say", RAYO_SAY); } } private class PauseSayIQHandler extends IQHandler { public PauseSayIQHandler() { super("Rayo: XEP 0327 - Pause Say");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("pause", RAYO_SAY); } } private class ResumeSayIQHandler extends IQHandler { public ResumeSayIQHandler() { super("Rayo: XEP 0327 - Resume Say");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("resume", RAYO_SAY); } } private class AcceptIQHandler extends IQHandler { public AcceptIQHandler() { super("Rayo: XEP 0327 - Accept");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("accept", RAYO_CORE); } } private class AnswerIQHandler extends IQHandler { public AnswerIQHandler() { super("Rayo: XEP 0327 - Answer");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("answer", RAYO_CORE); } } private class DialIQHandler extends IQHandler { public DialIQHandler() { super("Rayo: XEP 0327 - Dial");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("dial", RAYO_CORE); } } private class HangupIQHandler extends IQHandler { public HangupIQHandler() { super("Rayo: XEP 0327 - Hangup");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("hangup", RAYO_CORE); } } private class RedirectIQHandler extends IQHandler { public RedirectIQHandler() { super("Rayo: XEP 0327 - Redirect");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("redirect", RAYO_CORE); } } private class DtmfIQHandler extends IQHandler { public DtmfIQHandler() { super("Rayo: XEP 0327 - DTMF");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("dtmf", RAYO_CORE); } } }
src/plugins/rayo/src/java/org/ifsoft/rayo/RayoComponent.java
/** * $Revision $ * $Date $ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ifsoft.rayo; import org.dom4j.*; import org.jivesoftware.openfire.container.Plugin; import org.jivesoftware.openfire.container.PluginManager; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.muc.*; import org.jivesoftware.openfire.muc.spi.*; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.http.HttpBindManager; import org.jivesoftware.openfire.group.Group; import org.jivesoftware.openfire.group.GroupManager; import org.jivesoftware.openfire.group.GroupNotFoundException; import org.jivesoftware.openfire.handler.IQHandler; import org.jivesoftware.openfire.IQHandlerInfo; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.util.JiveGlobals; import org.xmpp.packet.JID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmpp.component.Component; import org.xmpp.component.ComponentException; import org.xmpp.component.ComponentManager; import org.xmpp.component.ComponentManagerFactory; import org.xmpp.component.AbstractComponent; import org.xmpp.jnodes.*; import org.xmpp.jnodes.nio.LocalIPResolver; import org.xmpp.packet.*; import java.util.*; import java.util.concurrent.*; import java.text.ParseException; import java.net.*; import com.rayo.core.*; import com.rayo.core.verb.*; import com.rayo.core.validation.*; import com.rayo.core.xml.providers.*; import com.sun.voip.server.*; import com.sun.voip.*; import org.voicebridge.*; import com.jcumulus.server.rtmfp.ServerPipelineFactory; import com.jcumulus.server.rtmfp.Sessions; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; public class RayoComponent extends AbstractComponent implements TreatmentDoneListener, CallEventListener { private static final Logger Log = LoggerFactory.getLogger(RayoComponent.class); private static final String RAYO_CORE = "urn:xmpp:rayo:1"; private static final String RAYO_RECORD = "urn:xmpp:rayo:record:1"; private static final String RAYO_SAY = "urn:xmpp:tropo:say:1"; private static final String RAYO_HANDSET = "urn:xmpp:rayo:handset:1"; private static final String HOST = "host"; private static final String LOCAL_PORT = "localport"; private static final String REMOTE_PORT = "remoteport"; private static final String ID = "id"; private static final String URI = "uri"; private static final String defaultIncomingConferenceId = "IncomingCallsConference"; public static RayoComponent self; private final RayoPlugin plugin; private RayoProvider rayoProvider = null; private RecordProvider recordProvider = null; private SayProvider sayProvider = null; private HandsetProvider handsetProvider = null; private static ConnectionlessBootstrap bootstrap = null; public static Channel channel = null; private static Sessions sessions; public RayoComponent(final RayoPlugin plugin) { self = this; this.plugin = plugin; } public void doStart() { Log.info("RayoComponent initialize " + jid); XMPPServer server = XMPPServer.getInstance(); server.getIQDiscoInfoHandler().addServerFeature(RAYO_CORE); rayoProvider = new RayoProvider(); rayoProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_RECORD); recordProvider = new RecordProvider(); recordProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_SAY); sayProvider = new SayProvider(); sayProvider.setValidator(new Validator()); server.getIQDiscoInfoHandler().addServerFeature(RAYO_HANDSET); handsetProvider = new HandsetProvider(); handsetProvider.setValidator(new Validator()); createIQHandlers(); Plugin fastpath = server.getPluginManager().getPlugin("fastpath"); if (fastpath != null) { Log.info("RayoComponent found Fastpath"); } try{ Log.info("Starting jCumulus....."); sessions = new Sessions(); ExecutorService executorservice = Executors.newCachedThreadPool(); NioDatagramChannelFactory niodatagramchannelfactory = new NioDatagramChannelFactory(executorservice); bootstrap = new ConnectionlessBootstrap(niodatagramchannelfactory); OrderedMemoryAwareThreadPoolExecutor orderedmemoryawarethreadpoolexecutor = new OrderedMemoryAwareThreadPoolExecutor(10, 0x100000L, 0x40000000L, 100L, TimeUnit.MILLISECONDS, Executors.defaultThreadFactory()); bootstrap.setPipelineFactory(new ServerPipelineFactory(sessions, orderedmemoryawarethreadpoolexecutor)); bootstrap.setOption("reuseAddress", Boolean.valueOf(true)); bootstrap.setOption("sendBufferSize", Integer.valueOf(1215)); bootstrap.setOption("receiveBufferSize", Integer.valueOf(2048)); bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(2048)); InetSocketAddress inetsocketaddress = new InetSocketAddress(JiveGlobals.getIntProperty("voicebridge.rtmfp.port", 1935)); Log.info("Listening on " + inetsocketaddress.getPort() + " port"); channel = bootstrap.bind(inetsocketaddress); } catch (Exception e) { Log.error("jCumulus startup failure"); e.printStackTrace(); } } public void doStop() { Log.info("RayoComponent shutdown "); XMPPServer server = XMPPServer.getInstance(); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_CORE); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_RECORD); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_SAY); server.getIQDiscoInfoHandler().removeServerFeature(RAYO_HANDSET); destroyIQHandlers(); Log.info("jCumulus stopping..."); channel.close(); bootstrap.releaseExternalResources(); } public String getName() { return "rayo"; } public String getDescription() { return "XEP-0327: Rayo"; } @Override protected String[] discoInfoFeatureNamespaces() { return new String[]{RAYO_CORE}; } @Override protected String discoInfoIdentityCategoryType() { return "rayo"; } @Override protected IQ handleIQGet(IQ iq) throws Exception { Log.info("RayoComponent handleIQGet \n" + iq.toString()); final Element element = iq.getChildElement(); final String namespace = element.getNamespaceURI(); try { if (RAYO_HANDSET.equals(namespace)) { IQ reply = null; Object object = handsetProvider.fromXML(element); if (object instanceof OnHookCommand) { OnHookCommand command = (OnHookCommand) object; reply = handleOnOffHookCommand(command, iq); } else if (object instanceof OffHookCommand) { OffHookCommand command = (OffHookCommand) object; reply = handleOnOffHookCommand(command, iq); } else if (object instanceof MuteCommand) { reply = handleMuteCommand((MuteCommand) object, iq); } else if (object instanceof UnmuteCommand) { reply = handleMuteCommand((UnmuteCommand) object, iq); } else if (object instanceof HoldCommand) { reply = handleHoldCommand((HoldCommand) object, iq); } else if (object instanceof PrivateCommand) { reply = handlePrivateCommand(object, iq); } else if (object instanceof PublicCommand) { reply = handlePrivateCommand(object, iq); } return reply; } if (RAYO_RECORD.equals(namespace)) { IQ reply = null; Object object = recordProvider.fromXML(element); if (object instanceof Record) { reply = handleRecord((Record) object, iq); } else if (object instanceof PauseCommand) { reply = handlePauseRecordCommand(true, iq); } else if (object instanceof ResumeCommand) { reply = handlePauseRecordCommand(false, iq); } return reply; } if (RAYO_SAY.equals(namespace)) { IQ reply = null; Object object = sayProvider.fromXML(element); if (object instanceof Say) { reply = handleSay((Say) object, iq); } else if (object instanceof PauseCommand) { reply = handlePauseSayCommand(true, iq); } else if (object instanceof ResumeCommand) { reply = handlePauseSayCommand(false, iq); } return reply; } if (RAYO_CORE.equals(namespace)) { IQ reply = null; Object object = rayoProvider.fromXML(element); if (object instanceof JoinCommand) { reply = handleJoinCommand((JoinCommand) object, iq); } else if (object instanceof UnjoinCommand) { reply = handleUnjoinCommand((UnjoinCommand) object, iq); } else if (object instanceof AcceptCommand) { reply = handleAcceptCommand((AcceptCommand) object, iq); } else if (object instanceof AnswerCommand) { reply = handleAnswerCommand((AnswerCommand) object, iq); } else if (object instanceof HangupCommand) { reply = handleHangupCommand(iq); } else if (object instanceof RejectCommand) { // implemented as hangup on client } else if (object instanceof RedirectCommand) { RedirectCommand redirect = (RedirectCommand) object; DialCommand dial = new DialCommand(); dial.setTo(redirect.getTo()); dial.setFrom(new URI("xmpp:" + iq.getFrom())); dial.setHeaders(redirect.getHeaders()); reply = handleDialCommand((DialCommand) dial, iq, true); } else if (object instanceof DialCommand) { reply = handleDialCommand((DialCommand) object, iq, false); } else if (object instanceof StopCommand) { } else if (object instanceof DtmfCommand) { reply = handleDtmfCommand((DtmfCommand) object, iq); } else if (object instanceof DestroyMixerCommand) { } return reply; } return null; // feature not implemented. } catch (Exception e) { e.printStackTrace(); final IQ reply = IQ.createResultIQ(iq); reply.setError(PacketError.Condition.internal_server_error); return reply; } } private IQ handleHoldCommand(Object object, IQ iq) { Log.info("RayoComponent handleHoldCommand"); IQ reply = IQ.createResultIQ(iq); String callId = iq.getTo().getNode(); // far party CallHandler handler = CallHandler.findCall(callId); if (handler != null) { handler.getCallParticipant().setHeld(true); } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleMuteCommand(Object object, IQ iq) { Log.info("RayoComponent handleMuteCommand"); boolean muted = object instanceof MuteCommand; IQ reply = IQ.createResultIQ(iq); String callId = JID.escapeNode(iq.getFrom().toString()); // handset CallHandler handler = CallHandler.findCall(callId); if (handler != null) { handler.setMuted(muted); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(handler.getCallParticipant().getConferenceId()); ArrayList memberList = conferenceManager.getMemberList(); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent handleMuteCommand route event to " + target); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (muted) { MutedEvent event = new MutedEvent(); presence.getElement().add(handsetProvider.toXML(event)); } else { UnmutedEvent event = new UnmutedEvent(); presence.getElement().add(handsetProvider.toXML(event)); } sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handlePrivateCommand(Object object, IQ iq) { Log.info("RayoComponent handlePrivateCommand"); boolean privateCall = object instanceof PrivateCommand; IQ reply = IQ.createResultIQ(iq); String callId = JID.escapeNode(iq.getFrom().toString()); // handset CallHandler handler = CallHandler.findCall(callId); if (handler != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(handler.getCallParticipant().getConferenceId()); conferenceManager.setPrivateCall(privateCall); ArrayList memberList = conferenceManager.getMemberList(); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent handlePrivateCommand route event to " + target); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (privateCall) { PrivateEvent event = new PrivateEvent(); presence.getElement().add(handsetProvider.toXML(event)); } else { PublicEvent event = new PublicEvent(); presence.getElement().add(handsetProvider.toXML(event)); } sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleOnOffHookCommand(Object object, IQ iq) { Log.info("RayoComponent handleOnOffHookCommand"); IQ reply = IQ.createResultIQ(iq); String handsetId = JID.escapeNode(iq.getFrom().toString()); if (object instanceof OnHookCommand) { CallHandler handler = CallHandler.findCall(handsetId); if (handler != null) { handleOnOffHook(handsetId, object, plugin.getRelayChannel(handsetId), reply); } else { reply.setError(PacketError.Condition.item_not_found); } } else { final Handset handset = ((OffHookCommand) object).getHandset(); if (handset.sipuri == null) // webrtc handset { final RelayChannel channel = plugin.createRelayChannel(iq.getFrom(), handset); if (channel != null) { final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(HOST, LocalIPResolver.getLocalIP()); childElement.addAttribute(LOCAL_PORT, Integer.toString(channel.getPortA())); childElement.addAttribute(REMOTE_PORT, Integer.toString(channel.getPortB())); childElement.addAttribute(ID, channel.getAttachment()); childElement.addAttribute(URI, "xmpp:" + channel.getAttachment() + "@" + getDomain() + "/webrtc"); Log.debug("Created WebRTC handset channel {}:{}, {}:{}, {}:{}", new Object[]{HOST, LocalIPResolver.getLocalIP(), LOCAL_PORT, Integer.toString(channel.getPortA()), REMOTE_PORT, Integer.toString(channel.getPortB())}); handleOnOffHook(handsetId, object, channel, reply); } else { reply.setError(PacketError.Condition.internal_server_error); } } else { // SIP handset final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, handsetId); childElement.addAttribute(URI, handset.sipuri); Log.info("Created SIP handset channel " + handset.sipuri); handleOnOffHook(handsetId, object, null, reply); } } return reply; } private void handleOnOffHook(String handsetId, Object object, RelayChannel channel, IQ reply) { final boolean flag = object instanceof OnHookCommand; Log.info("RayoComponent handleOnOffHook " + flag); try { CallHandler handler = CallHandler.findCall(handsetId); if (handler != null) { handler.cancelRequest("Reseting handset to " + (flag ? "on" : "off") + "hook"); handler = null; } if (!flag) // offhook { Handset handset = ((OffHookCommand) object).getHandset(); String mediaPreference = "PCMU/8000/1"; if (handset.codec == null || "OPUS".equals(handset.codec)) mediaPreference = "PCM/48000/2"; CallParticipant cp = new CallParticipant(); cp.setCallId(handsetId); cp.setConferenceId(handset.mixer); cp.setDisplayName("rayo-handset-" + System.currentTimeMillis()); cp.setName(cp.getDisplayName()); cp.setVoiceDetection(true); cp.setCallOwner(JID.unescapeNode(handsetId)); String label = (new JID(cp.getCallOwner())).getNode(); if (handset.group != null && ! "".equals(handset.group)) { label = handset.group; } ConferenceManager cm = ConferenceManager.getConference(handset.mixer, mediaPreference, label, false); if (handset.callId != null && "".equals(handset.callId) == false) { cm.setCallId(handset.callId); // set answering far party call id for mixer } if (handset.group != null && ! "".equals(handset.group)) { cm.setGroupName(handset.group); } if (cm.isPrivateCall() == false || cm.getMemberList().size() < 2) { if (channel == null) { if (handset.sipuri.indexOf("sip:") == 0) { cp.setPhoneNumber(handset.sipuri); cp.setAutoAnswer(true); cp.setProtocol("SIP"); } else if (handset.sipuri.indexOf("rtmfp:") == 0) { String[] tokens = handset.sipuri.split(":"); if (tokens.length == 3) { cp.setProtocol("Rtmfp"); cp.setRtmfpSendStream(tokens[1]); cp.setRtmfpRecieveStream(tokens[2]); cp.setAutoAnswer(true); } else { reply.setError(PacketError.Condition.not_allowed); return; } } else { reply.setError(PacketError.Condition.not_allowed); return; } } else { cp.setMediaPreference(mediaPreference); cp.setRelayChannel(channel); cp.setProtocol("WebRtc"); } OutgoingCallHandler callHandler = new OutgoingCallHandler(this, cp); callHandler.start(); if (channel != null) { channel.setCallHandler(callHandler); } } else { reply.setError(PacketError.Condition.not_allowed); } } } catch (Exception e) { e.printStackTrace(); } } private IQ handleRecord(Record command, IQ iq) { Log.info("RayoComponent handleRecord " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); final String callId = JID.escapeNode(iq.getFrom().toString()); final String uri = command.getTo().toString(); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { try { final String fileName = uri.substring(5); // expecting file: prefix callHandler.getCallParticipant().setRecordDirectory(System.getProperty("com.sun.voip.server.Bridge.soundsDirectory", ".")); callHandler.getMemberReceiver().setRecordFromMember(true, fileName, "au"); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, fileName); childElement.addAttribute(URI, (String) uri); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handlePauseRecordCommand(boolean flag, IQ iq) { Log.info("RayoComponent handlePauseRecordCommand " + iq.getFrom() + " " + iq.getTo()); IQ reply = IQ.createResultIQ(iq); final String callId = JID.escapeNode(iq.getFrom().toString()); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { try { CallParticipant cp = callHandler.getCallParticipant(); String fileName = cp.getFromRecordingFile(); cp.setRecordDirectory(System.getProperty("com.sun.voip.server.Bridge.soundsDirectory", ".")); callHandler.getMemberReceiver().setRecordFromMember(flag, fileName, "au"); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleSay(Say command, IQ iq) { Log.info("RayoComponent handleSay " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); final String entityId = iq.getTo().getNode(); final String treatmentId = command.getPrompt().getText(); try { CallHandler callHandler = CallHandler.findCall(entityId); try { callHandler.playTreatmentToCall(treatmentId, this); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, treatmentId); childElement.addAttribute(URI, (String) "xmpp:" + entityId + "@" + getDomain() + "/" + treatmentId); } catch (Exception e1) { e1.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } catch (NoSuchElementException e) { // not call, lets try mixer try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(entityId); try { conferenceManager.addTreatment(treatmentId); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(ID, treatmentId); childElement.addAttribute(URI, (String) "xmpp:" + entityId + "@" + getDomain() + "/" + treatmentId); } catch (Exception e2) { e2.printStackTrace(); reply.setError(PacketError.Condition.not_allowed); } } catch (ParseException e1) { reply.setError(PacketError.Condition.item_not_found); } } return reply; } private IQ handlePauseSayCommand(boolean flag, IQ iq) { Log.info("RayoComponent handlePauseSayCommand " + iq.getFrom() + " " + iq.getTo()); IQ reply = IQ.createResultIQ(iq); final JID entityId = getJID(iq.getTo().getNode()); if (entityId != null) { final String treatmentId = entityId.getResource(); final String callId = entityId.getNode(); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { callHandler.getMember().pauseTreatment(treatmentId, flag); } else { // not call, lets try mixer try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(callId); conferenceManager.getWGManager().pauseConferenceTreatment(treatmentId, flag); } catch (ParseException e1) { reply.setError(PacketError.Condition.item_not_found); } } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleAcceptCommand(AcceptCommand command, IQ iq) { Map<String, String> headers = command.getHeaders(); String callId = iq.getTo().getNode(); // destination JID escaped String callerId = headers.get("caller_id"); // source JID String mixer = headers.get("mixer_name"); Log.info("RayoComponent handleAcceptCommand " + callerId + " " + callId + " " + mixer); IQ reply = IQ.createResultIQ(iq); JID callJID = getJID(callId); if (callJID != null) // only for XMPP calls { if (mixer != null) { headers.put("call_protocol", "XMPP"); callerId = callerId.substring(5); // remove xmpp: prefix Presence presence = new Presence(); presence.setFrom(iq.getTo()); presence.setTo(callerId); setRingingState(presence, ConferenceManager.isTransferCall(mixer), headers); sendPacket(presence); } else reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleAnswerCommand(AnswerCommand command, IQ iq) { Map<String, String> headers = command.getHeaders(); IQ reply = IQ.createResultIQ(iq); String callId = iq.getTo().getNode(); // destination JID escaped String callerId = headers.get("caller_id"); // source JID Log.info("RayoComponent AnswerCommand " + callerId + " " + callId); if (callerId != null) { JID callJID = getJID(callId); CallHandler callHandler = null; CallHandler handsetHandler = null; if (callJID != null) // XMPP call { callerId = callerId.substring(5); // remove xmpp: prefix headers.put("call_protocol", "XMPP"); headers.put("call_owner", callerId); headers.put("call_action", "join"); try { callHandler = CallHandler.findCall(callId); handsetHandler = CallHandler.findCall(JID.escapeNode(callerId)); if (handsetHandler != null) { CallParticipant hp = handsetHandler.getCallParticipant(); Presence presence1 = new Presence(); //to caller presence1.setFrom(iq.getTo()); presence1.setTo(callerId); setAnsweredState(presence1, ConferenceManager.isTransferCall(hp.getConferenceId()), headers); sendPacket(presence1); } } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); e.printStackTrace(); } } else { callHandler = CallHandler.findCall(callId); // SIP call; handsetHandler = CallHandler.findCall(JID.escapeNode(iq.getFrom().toString())); } if (callHandler != null && handsetHandler != null) { CallParticipant cp = callHandler.getCallParticipant(); CallParticipant hp = handsetHandler.getCallParticipant(); Log.info("RayoComponent handleAnswerCommand found call handlers " + cp.getCallId() + " " + hp.getCallId()); try { long start = System.currentTimeMillis(); cp.setStartTimestamp(start); cp.setHandset(hp); hp.setFarParty(cp); hp.setStartTimestamp(start); cp.setHeaders(headers); String recording = cp.getConferenceId() + "-" + cp.getStartTimestamp() + ".au"; ConferenceManager.recordConference(cp.getConferenceId(), true, recording, "au"); String destination = iq.getFrom().getNode(); String source = cp.getName(); if (callJID != null) { source = (new JID(callerId)).getNode(); Config.createCallRecord(source, recording, "xmpp:" + iq.getFrom(), cp.getStartTimestamp(), 0, "dialed") ; Config.createCallRecord(destination, recording, "xmpp:" + callerId, cp.getStartTimestamp(), 0, "received"); sendMessage(new JID(callerId), iq.getFrom(), "Call started", recording, "chat"); } else { // incoming SIP Config.createCallRecord(destination, recording, "sip:" + cp.getPhoneNumber(), cp.getStartTimestamp(), 0, "received") ; sendMessage(iq.getFrom(), new JID(cp.getCallId() + "@" + getDomain()), "Call started", recording, "chat"); } } catch (ParseException e1) { reply.setError(PacketError.Condition.internal_server_error); } } else reply.setError(PacketError.Condition.item_not_found); } else reply.setError(PacketError.Condition.item_not_found); return reply; } private IQ handleHangupCommand(IQ iq) { String callId = iq.getTo().getNode(); Log.info("RayoComponent handleHangupCommand " + iq.getFrom() + " " + callId); IQ reply = IQ.createResultIQ(iq); CallHandler callHandler = CallHandler.findCall(callId); if (callHandler != null) { Log.info("RayoComponent handleHangupCommand found callhandler " + callId); CallParticipant cp = callHandler.getCallParticipant(); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(cp.getConferenceId()); Log.info("RayoComponent handleHangupCommand one person left, cancel call " + conferenceManager.getMemberList().size()); if (conferenceManager.getMemberList().size() <= 2) { CallHandler.hangup(callId, "User requested call termination"); } } catch (Exception e) {} } else { //reply.setError(PacketError.Condition.item_not_found); } return reply; } private JID getJID(String jid) { jid = JID.unescapeNode(jid); if (jid.indexOf("@") == -1 || jid.indexOf("/") == -1) return null; try { return new JID(jid); } catch (Exception e) { return null; } } private IQ handleDtmfCommand(DtmfCommand command, IQ iq) { Log.info("RayoComponent handleDtmfCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); try { CallHandler callHandler = CallHandler.findCall(iq.getTo().getNode()); callHandler.dtmfKeys(command.getTones()); } catch (NoSuchElementException e) { reply.setError(PacketError.Condition.item_not_found); } return reply; } private IQ handleJoinCommand(JoinCommand command, IQ iq) { Log.info("RayoComponent handleJoinCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); String mixer = null; if (command.getType() == JoinDestinationType.CALL) { // TODO join.getTo() } else { mixer = command.getTo(); } if (mixer != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); if (CallHandler.findCall("colibri-" + mixer) == null) // other participant than colibri { attachVideobridge(mixer, iq.getFrom(), conferenceManager.getMediaInfo().toString()); if (conferenceManager.getMemberList().size() == 1) // handset already in call { String recording = mixer + "-" + System.currentTimeMillis() + ".au"; conferenceManager.recordConference(true, recording, "au"); sendMucMessage(mixer, recording, iq.getFrom(), "Started voice recording"); } } sendMucMessage(mixer, null, iq.getFrom(), "Joined voice conversation"); } catch (ParseException pe) { // colibri joining as first participant try { ConferenceManager conferenceManager = ConferenceManager.getConference(mixer, "PCM/48000/2", mixer, false); String recording = mixer + "-" + System.currentTimeMillis() + ".au"; conferenceManager.recordConference(true, recording, "au"); sendMucMessage(mixer, recording, iq.getFrom(), "Started voice recording"); attachVideobridge(mixer, iq.getFrom(), "PCM/48000/2"); } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } return reply; } private IQ handleUnjoinCommand(UnjoinCommand command, IQ iq) { Log.info("RayoComponent handleUnjoinCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); String mixer = null; if (command.getType() == JoinDestinationType.CALL) { // TODO join.getFrom() } else { mixer = command.getFrom(); } if (mixer != null) { try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); if (conferenceManager.getMemberList().size() == 1) { conferenceManager.recordConference(false, null, null); sendMucMessage(mixer, null, iq.getFrom(), "Stopped voice recording"); detachVideobridge(mixer); } sendMucMessage(mixer, null, iq.getFrom(), "Left voice conversation"); } catch (Exception e) { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } return reply; } private void attachVideobridge(String conferenceId, JID participant, String mediaPreference) { //if (XMPPServer.getInstance().getPluginManager().getPlugin("jitsivideobridge") != null) //{ Log.info("attachVideobridge Found Jitsi Videobridge, attaching.." + conferenceId); if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(conferenceId)) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(conferenceId); if (room != null) { for (MUCRole role : room.getOccupants()) { if (participant.toBareJID().equals(role.getUserAddress().toBareJID())) { Log.info("attachVideobridge Found participant " + participant.toBareJID()); try { CallParticipant vp = new CallParticipant(); vp.setCallId("colibri-" + conferenceId); vp.setCallOwner(participant.toString()); vp.setProtocol("Videobridge"); vp.setPhoneNumber(participant.getNode()); vp.setMediaPreference(mediaPreference); vp.setConferenceId(conferenceId); OutgoingCallHandler videoBridgeHandler = new OutgoingCallHandler(null, vp); videoBridgeHandler.start(); } catch (Exception e) { e.printStackTrace(); } break; } } } } //} } private void detachVideobridge(String conferenceId) { try { Log.info("Jitsi Videobridge, detaching.." + conferenceId); CallHandler callHandler = CallHandler.findCall("colibri-" + conferenceId); if (callHandler != null) { CallHandler.hangup("colibri-" + conferenceId, "Detaching from Jitsi Videobridge"); } } catch (Exception e) { e.printStackTrace(); } } private void sendMucMessage(String mixer, String recording, JID participant, String message) { if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(mixer)) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(mixer); if (room != null) { sendMessage(new JID(mixer + "@conference." + getDomain()), participant, message, recording, "groupchat"); } } } private IQ handleDialCommand(DialCommand command, IQ iq, boolean transferCall) { Log.info("RayoComponent handleHandsetDialCommand " + iq.getFrom()); IQ reply = IQ.createResultIQ(iq); Map<String, String> headers = command.getHeaders(); String from = command.getFrom().toString(); String to = command.getTo().toString(); boolean toPhone = to.indexOf("sip:") == 0 || to.indexOf("tel:") == 0; boolean toXmpp = to.indexOf("xmpp:") == 0; String callerName = headers.get("caller_name"); String calledName = headers.get("called_name"); String handsetId = iq.getFrom().toString(); JoinCommand join = command.getJoin(); if (join != null) { if (join.getType() == JoinDestinationType.CALL) { // TODO join.getTo() } else { } reply.setError(PacketError.Condition.feature_not_implemented); } else { if (callerName == null) { callerName = iq.getFrom().getNode(); headers.put("caller_name", callerName); } if (toPhone) { if (calledName == null) { calledName = to; headers.put("called_name", calledName); } CallParticipant cp = new CallParticipant(); cp.setVoiceDetection(true); cp.setCallOwner(handsetId); cp.setProtocol("SIP"); cp.setDisplayName(callerName); cp.setPhoneNumber(to); cp.setName(calledName); cp.setHeaders(headers); reply = doPhoneAndPcCall(JID.escapeNode(handsetId), cp, reply, transferCall); } else if (toXmpp){ headers.put("call_protocol", "XMPP"); JID destination = getJID(to.substring(5)); if (destination != null) { String source = JID.escapeNode(handsetId); CallHandler handsetHandler = CallHandler.findCall(source); if (handsetHandler != null) { CallParticipant hp = handsetHandler.getCallParticipant(); headers.put("mixer_name", hp.getConferenceId()); headers.put("codec_name", "PCM/48000/2".equals(hp.getMediaPreference()) ? "OPUS" : "PCMU"); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(hp.getConferenceId()); conferenceManager.setTransferCall(transferCall); } catch (Exception e) {} if (findUser(destination.getNode()) != null) { routeXMPPCall(reply, destination, source, calledName, headers, hp.getConferenceId()); } else { int count = 0; try { Group group = GroupManager.getInstance().getGroup(destination.getNode()); for (JID memberJID : group.getMembers()) { if (iq.getFrom().toBareJID().equals(memberJID.toBareJID()) == false) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeXMPPCall(reply, session.getAddress(), source, calledName, headers, hp.getConferenceId()); count++; } } } } catch (GroupNotFoundException e) { if (XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").hasChatRoom(destination.getNode())) { MUCRoom room = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService("conference").getChatRoom(destination.getNode()); if (room != null) { for (MUCRole role : room.getOccupants()) { if (iq.getFrom().toBareJID().equals(role.getUserAddress().toBareJID()) == false) { routeXMPPCall(reply, role.getUserAddress(), source, calledName, headers, hp.getConferenceId()); count++; } } } } else { reply.setError(PacketError.Condition.item_not_found); } } if (count == 0) { reply.setError(PacketError.Condition.item_not_found); } } } else { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.item_not_found); } } else { reply.setError(PacketError.Condition.feature_not_implemented); } } return reply; } private void routeXMPPCall(IQ reply, JID destination, String source, String calledName, Map<String, String> headers, String mixer) { String callId = JID.escapeNode(destination.toString()); Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(destination); OfferEvent offer = new OfferEvent(null); try { offer.setFrom(new URI("xmpp:" + JID.unescapeNode(source))); offer.setTo(new URI("xmpp:" + destination)); } catch (URISyntaxException e) { reply.setError(PacketError.Condition.feature_not_implemented); return; } if (calledName == null) { calledName = presence.getTo().getNode(); headers.put("called_name", calledName); } offer.setHeaders(headers); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(URI, (String) "xmpp:" + presence.getFrom()); childElement.addAttribute(ID, (String) callId); presence.getElement().add(rayoProvider.toXML(offer)); sendPacket(presence); } private IQ doPhoneAndPcCall(String handsetId, CallParticipant cp, IQ reply, boolean transferCall) { Log.info("RayoComponent doPhoneAndPcCall " + handsetId); CallHandler handsetHandler = CallHandler.findCall(handsetId); if (handsetHandler != null) { try { setMixer(handsetHandler, reply, cp, transferCall); OutgoingCallHandler outgoingCallHandler = new OutgoingCallHandler(this, cp); //outgoingCallHandler.setOtherCall(handsetHandler); //handsetHandler.setOtherCall(outgoingCallHandler); outgoingCallHandler.start(); final Element childElement = reply.setChildElement("ref", RAYO_CORE); childElement.addAttribute(URI, (String) "xmpp:" + cp.getCallId() + "@" + getDomain()); childElement.addAttribute(ID, (String) cp.getCallId()); } catch (Exception e) { e.printStackTrace(); reply.setError(PacketError.Condition.internal_server_error); } } else { reply.setError(PacketError.Condition.item_not_found); } return reply; } private void setMixer(CallHandler handsetHandler, IQ reply, CallParticipant cp, boolean transferCall) { CallParticipant hp = handsetHandler.getCallParticipant(); try { hp.setFarParty(cp); cp.setHandset(hp); long start = System.currentTimeMillis(); cp.setStartTimestamp(start); hp.setStartTimestamp(start); String mixer = hp.getConferenceId(); ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(mixer); cp.setConferenceId(mixer); cp.setCallId(mixer); cp.setMediaPreference(hp.getMediaPreference()); conferenceManager.setCallId(mixer); conferenceManager.setTransferCall(transferCall); String recording = mixer + "-" + cp.getStartTimestamp() + ".au"; conferenceManager.recordConference(true, recording, "au"); Config.createCallRecord(cp.getDisplayName(), recording, cp.getPhoneNumber(), cp.getStartTimestamp(), 0, "dialed") ; sendMessage(new JID(cp.getCallOwner()), new JID(cp.getCallId() + "@" + getDomain()), "Call started", recording, "chat"); } catch (ParseException e1) { reply.setError(PacketError.Condition.internal_server_error); } } @Override public String getDomain() { return XMPPServer.getInstance().getServerInfo().getXMPPDomain(); } public HandsetProvider getHandsetProvider() { return handsetProvider; } public void treatmentDoneNotification(TreatmentManager treatmentManager) { Log.info("RayoComponent treatmentDoneNotification " + treatmentManager.getId()); } public void callEventNotification(com.sun.voip.CallEvent callEvent) { Log.info("RayoComponent callEventNotification " + callEvent); JID from = getJID(callEvent.getCallInfo()); if (from != null) { String myEvent = com.sun.voip.CallEvent.getEventString(callEvent.getEvent()); String callState = callEvent.getCallState().toString(); try { CallHandler callHandler = CallHandler.findCall(callEvent.getCallId()); if (callHandler != null) { Log.info("RayoComponent callEventNotification found call handler " + callHandler); CallParticipant cp = callHandler.getCallParticipant(); CallParticipant hp = cp.getHandset(); if (cp != null) { Log.info("RayoComponent callEventNotification found call paticipant " + cp); Map<String, String> headers = cp.getHeaders(); headers.put("mixer_name", callEvent.getConferenceId()); headers.put("call_protocol", cp.getProtocol()); Presence presence = new Presence(); presence.setFrom(callEvent.getCallId() + "@" + getDomain()); presence.setTo(from); if ("001 STATE CHANGED".equals(myEvent)) { if ("100 INVITED".equals(callState)) { if (cp.isAutoAnswer() == false) // SIP handset, no ringing event { setRingingState(presence, ConferenceManager.isTransferCall(callEvent.getConferenceId()), headers); sendPacket(presence); } } else if ("200 ESTABLISHED".equals(callState)) { } else if ("299 ENDED".equals(callState)) { } } else if ("250 STARTED SPEAKING".equals(myEvent)) { broadcastSpeaking(true, callEvent.getCallId(), callEvent.getConferenceId(), from); } else if ("259 STOPPED SPEAKING".equals(myEvent)) { broadcastSpeaking(false, callEvent.getCallId(), callEvent.getConferenceId(), from); } else if ("269 DTMF".equals(myEvent)) { presence.getElement().add(rayoProvider.toXML(new DtmfEvent(callEvent.getCallId(), callEvent.getDtmfKey()))); sendPacket(presence); } else if ("230 TREATMENT DONE".equals(myEvent)) { presence.setFrom(callEvent.getCallId() + "@" + getDomain() + "/" + callEvent.getTreatmentId()); SayCompleteEvent complete = new SayCompleteEvent(); complete.setReason(SayCompleteEvent.Reason.valueOf("SUCCESS")); presence.getElement().add(sayProvider.toXML(complete)); sendPacket(presence); } } } } catch (Exception e) { e.printStackTrace(); } } } private void broadcastSpeaking(Boolean startSpeaking, String callId, String conferenceId, JID from) { Log.info( "RayoComponent broadcastSpeaking " + startSpeaking + " " + callId + " " + conferenceId + " " + from); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(conferenceId); ArrayList memberList = conferenceManager.getMemberList(); synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { ConferenceMember member = (ConferenceMember) memberList.get(i); CallHandler callHandler = member.getCallHandler(); if (callHandler != null) { CallParticipant cp = callHandler.getCallParticipant(); String target = cp.getCallOwner(); Log.info( "RayoComponent broadcastSpeaking checking " + target); if (target != null && callId.equals(cp.getCallId()) == false) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); if (startSpeaking) { StartedSpeakingEvent speaker = new StartedSpeakingEvent(); speaker.setSpeakerId(callId); presence.getElement().add(rayoProvider.toXML(speaker)); } else { StoppedSpeakingEvent speaker = new StoppedSpeakingEvent(); speaker.setSpeakerId(callId); presence.getElement().add(rayoProvider.toXML(speaker)); } sendPacket(presence); } } } } } catch (Exception e) { e.printStackTrace(); } } private void finishCallRecord(CallParticipant cp) { Log.info( "RayoComponent finishCallRecord " + cp.getStartTimestamp()); if (cp.getStartTimestamp() > 0) { cp.setEndTimestamp(System.currentTimeMillis()); Config.updateCallRecord(cp.getStartTimestamp(), (int)((cp.getEndTimestamp() - cp.getStartTimestamp()) / 1000)); try { ConferenceManager conferenceManager = ConferenceManager.findConferenceManager(cp.getConferenceId()); conferenceManager.recordConference(false, null, null); String target = cp.getCallOwner(); JID destination = getJID(conferenceManager.getCallId()); if (destination == null) { destination = new JID(conferenceManager.getCallId() + "@" + getDomain()); } if (target == null) { if (cp.getHandset() != null) { target = cp.getHandset().getCallOwner(); } } if (target != null) { try { if (target.equals(destination.toString()) == false) { sendMessage(new JID(target), destination, "Call ended", null, "chat"); } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) {} cp.setStartTimestamp(0); } } private void sendMessage(JID from, JID to, String body, String fileName, String type) { Log.info( "RayoComponent sendMessage " + from + " " + to + " " + body + " " + fileName); int port = HttpBindManager.getInstance().getHttpBindUnsecurePort(); Message packet = new Message(); packet.setTo(to); packet.setFrom(from); packet.setType("chat".equals(type) ? Message.Type.chat : Message.Type.groupchat); if (fileName != null) packet.setThread("http://" + getDomain() + ":" + port + "/rayo/recordings/" + fileName); packet.setBody(body); sendPacket(packet); } public void sendPacket(Packet packet) { try { ComponentManagerFactory.getComponentManager().sendPacket(this, packet); } catch (Exception e) { Log.error("RayoComponent sendPacket " + e); e.printStackTrace(); } } public void notifyConferenceMonitors(ConferenceEvent conferenceEvent) { Log.info( "RayoComponent notifyConferenceMonitors " + conferenceEvent.toString()); if (defaultIncomingConferenceId.equals(conferenceEvent.getConferenceId())) return; ConferenceManager conferenceManager = null; try { if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) || conferenceEvent.equals(ConferenceEvent.MEMBER_JOINED)) { Log.info("RayoComponent notifyConferenceMonitors looking for call " + conferenceEvent.getCallId() + " " + conferenceEvent.getMemberCount()); try { conferenceManager = ConferenceManager.findConferenceManager(conferenceEvent.getConferenceId()); } catch (Exception e) {} if (conferenceManager != null) { String groupName = conferenceManager.getGroupName(); String callId = conferenceManager.getCallId(); if (callId == null) callId = conferenceEvent.getConferenceId(); // special case of SIP incoming CallHandler farParty = CallHandler.findCall(callId); CallHandler callHandler = CallHandler.findCall(conferenceEvent.getCallId()); if (callHandler != null) { Log.info("RayoComponent notifyConferenceMonitors found call handler " + callHandler + " " + farParty); CallParticipant callParticipant = callHandler.getCallParticipant(); ArrayList memberList = conferenceManager.getMemberList(); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) && callId.equals(conferenceEvent.getCallId())) { if (farParty != null && farParty.getCallParticipant().isHeld() == false) // far party left { synchronized (memberList) { for (int i = 0; i < memberList.size(); i++) { CallHandler participant = ((ConferenceMember) memberList.get(i)).getCallHandler(); participant.cancelRequest("Far Party has left"); } } } } int memberCount = memberList.size(); Log.info("RayoComponent notifyConferenceMonitors found owner " + callParticipant.getCallOwner() + " " + memberCount); if (groupName == null) { routeJoinEvent(callParticipant.getCallOwner(), callParticipant, conferenceEvent, memberCount, groupName, callId, farParty, conferenceManager); } else { Group group = GroupManager.getInstance().getGroup(groupName); for (JID memberJID : group.getMembers()) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeJoinEvent(session.getAddress().toString(), callParticipant, conferenceEvent, memberCount, groupName, callId, farParty, conferenceManager); } } } if (memberCount == 0 && conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { conferenceManager.recordConference(false, null, null); conferenceManager.endConference(conferenceEvent.getConferenceId()); CallParticipant heldCall = conferenceManager.getHeldCall(); if (heldCall != null) { JID target = getJID(heldCall.getCallId()); if (target != null) { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(target); presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), callParticipant.getHeaders()))); sendPacket(presence); } } } else if (memberCount == 2) { conferenceManager.setTransferCall(false); // reset after informing on redirect } } } } } catch (Exception e) { Log.error( "RayoComponent Error in notifyConferenceMonitors " + e); e.printStackTrace(); } } private void routeJoinEvent(String callee, CallParticipant callParticipant, ConferenceEvent conferenceEvent, int memberCount, String groupName, String callId, CallHandler farParty, ConferenceManager conferenceManager) { Log.info( "RayoComponent routeJoinEvent " + callee + " " + callId + " " + groupName + " " + memberCount + " " + farParty); if (callee == null) return; Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(callee); Map<String, String> headers = callParticipant.getHeaders(); headers.put("call_owner", callParticipant.getCallOwner()); headers.put("call_action", conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT) ? "leave" : "join"); headers.put("call_protocol", callParticipant.getProtocol()); headers.put("mixer_name", conferenceEvent.getConferenceId()); headers.put("group_name", groupName); if (memberCount > 2) // conferencing state { Log.info( "RayoComponent routeJoinEvent conferenced state " + memberCount); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { UnjoinedEvent event = new UnjoinedEvent(null, conferenceEvent.getConferenceId(), JoinDestinationType.MIXER); presence.getElement().add(rayoProvider.toXML(event)); } else { JoinedEvent event = new JoinedEvent(null, conferenceEvent.getConferenceId(), JoinDestinationType.MIXER); presence.getElement().add(rayoProvider.toXML(event)); } sendPacket(presence); } else { if (memberCount == 2) // caller with callee only { Log.info( "RayoComponent routeJoinEvent answered state " + callId + " " + conferenceEvent.getCallId()); if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) // previously conferenced { Log.info( "RayoComponent routeJoinEvent someone left "); if (callId.equals(conferenceEvent.getCallId()) == false) // handset leaving { Log.info( "RayoComponent routeJoinEvent handset leaving "); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { Log.info( "RayoComponent routeJoinEvent far party leaving "); } } else { Log.info( "RayoComponent routeJoinEvent someone joined "); if (callId.equals(conferenceEvent.getCallId())) // far party joined { Log.info( "RayoComponent routeJoinEvent far party joined "); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { // handset joined Log.info( "RayoComponent routeJoinEvent handset joined "); if (farParty != null) { CallParticipant fp = farParty.getCallParticipant(); if (fp.isHeld()) { Log.info( "RayoComponent routeJoinEvent on hold "); fp.setHeld(false); conferenceManager.setHeldCall(null); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } else { Log.info( "RayoComponent routeJoinEvent not held " + fp.getProtocol() + " " + fp); if ("WebRtc".equals(fp.getProtocol()) == false) { Log.info( "RayoComponent routeJoinEvent handset joing sip call"); setAnsweredState(presence, conferenceManager.isTransferCall(), headers); sendPacket(presence); } } } } } } else if (memberCount == 1) { // callee or caller if (conferenceEvent.equals(ConferenceEvent.MEMBER_LEFT)) { Log.info( "RayoComponent routeJoinEvent only one person left"); if (callId.equals(conferenceEvent.getCallId()) == false) // handset leaving { if (farParty != null) { Log.info( "RayoComponent routeJoinEvent handset leaving call " + farParty.getCallParticipant()); CallParticipant fp = farParty.getCallParticipant(); if (callParticipant.isAutoAnswer()) fp.setHeld(true); // sip phone as handset hangup if (fp.isHeld()) { Log.info( "RayoComponent routeJoinEvent call held with " + callParticipant); presence.getElement().add(handsetProvider.toXML(new OnHoldEvent())); sendPacket(presence); conferenceManager.setHeldCall(callParticipant); } } } else { // far party leaving Log.info( "RayoComponent routeJoinEvent far party leaving call " + callParticipant); if (callParticipant.isHeld()) { Log.info( "RayoComponent routeJoinEvent call held with " + farParty); presence.getElement().add(handsetProvider.toXML(new OnHoldEvent())); sendPacket(presence); conferenceManager.setHeldCall(farParty.getCallParticipant()); } else { finishCallRecord(callParticipant); presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), headers))); sendPacket(presence); } } } } else { // nobody left, call ended, signal last handset presence.getElement().add(rayoProvider.toXML(new EndEvent(null, EndEvent.Reason.valueOf("HANGUP"), headers))); sendPacket(presence); finishCallRecord(callParticipant); } } } private void setAnsweredState(Presence presence, boolean isTransfer, Map<String, String> headers) { if (isTransfer) { presence.getElement().add(handsetProvider.toXML(new TransferredEvent())); } else { presence.getElement().add(rayoProvider.toXML(new AnsweredEvent(null, headers))); } } private void setRingingState(Presence presence, boolean isTransfer, Map<String, String> headers) { if (isTransfer) { presence.getElement().add(handsetProvider.toXML(new TransferringEvent())); } else { presence.getElement().add(rayoProvider.toXML(new RingingEvent(null, headers))); } } private JID findUser(String username) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(); JID foundUser = null; for (ClientSession session : sessions) { try{ String userId = session.getAddress().getNode(); if (username.equals(userId)) { Log.info("Incoming SIP, findUser " + session.getAddress()); foundUser = session.getAddress(); break; } } catch (Exception e) { } } return foundUser; } public boolean routeIncomingSIP(CallParticipant cp) { boolean canRoute = false; Group group = null; JID foundUser = findUser(cp.getToPhoneNumber()); if (foundUser != null) canRoute = true; else { try { group = GroupManager.getInstance().getGroup(cp.getToPhoneNumber()); canRoute = true; } catch (GroupNotFoundException e) { } } Log.info("Incoming SIP, call route to entity " + cp.getToPhoneNumber() + " " + canRoute); if (canRoute) { String callId = "rayo-incoming-" + System.currentTimeMillis(); cp.setCallId(callId); cp.setConferenceId(callId); if (cp.getMediaPreference() == null) cp.setMediaPreference("PCMU/8000/1"); // regular phone ConferenceManager conferenceManager = ConferenceManager.getConference(callId, cp.getMediaPreference(), cp.getToPhoneNumber(), false); conferenceManager.setCallId(callId); Map<String, String> headers = cp.getHeaders(); headers.put("mixer_name", callId); headers.put("call_protocol", "SIP"); headers.put("codec_name", "PCM/48000/2".equals(cp.getMediaPreference()) ? "OPUS" : "PCMU"); headers.put("group_name", cp.getToPhoneNumber()); if (foundUser != null) // send this call to specific user { cp.setCallOwner(foundUser.toString()); routeSIPCall(foundUser, cp, callId, headers); } else { conferenceManager.setGroupName(cp.getToPhoneNumber()); for (JID memberJID : group.getMembers()) { Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(memberJID.getNode()); for (ClientSession session : sessions) { routeSIPCall(session.getAddress(), cp, callId, headers); } } } } return canRoute; } public void routeSIPCall(JID callee, CallParticipant cp, String callId, Map<String, String> headers) { Log.info("routeSIPCall to user " + callee); if (callee != null) // send this call to user { Presence presence = new Presence(); presence.setFrom(callId + "@" + getDomain()); presence.setTo(callee); OfferEvent offer = new OfferEvent(null); try { offer.setTo(new URI("xmpp:" + callee.toString())); offer.setFrom(new URI("sip:" + cp.getPhoneNumber())); } catch (URISyntaxException e) { Log.error("SIP phone nos not URI " + cp.getPhoneNumber() + " " + callee); } headers.put("called_name", callee.getNode()); headers.put("caller_name", cp.getName()); offer.setHeaders(headers); presence.getElement().add(rayoProvider.toXML(offer)); sendPacket(presence); } } private IQHandler onHookIQHandler = null; private IQHandler offHookIQHandler = null; private IQHandler privateIQHandler = null; private IQHandler publicIQHandler = null; private IQHandler muteIQHandler = null; private IQHandler unmuteIQHandler = null; private IQHandler holdIQHandler = null; private IQHandler sayIQHandler = null; private IQHandler pauseSayIQHandler = null; private IQHandler resumeSayIQHandler = null; private IQHandler recordIQHandler = null; private IQHandler pauseRecordIQHandler = null; private IQHandler resumeRecordIQHandler = null; private IQHandler acceptIQHandler = null; private IQHandler answerIQHandler = null; private IQHandler dialIQHandler = null; private IQHandler hangupIQHandler = null; private IQHandler redirectIQHandler = null; private IQHandler dtmfIQHandler = null; private void createIQHandlers() { XMPPServer server = XMPPServer.getInstance(); onHookIQHandler = new OnHookIQHandler(); server.getIQRouter().addHandler(onHookIQHandler); offHookIQHandler = new OffHookIQHandler(); server.getIQRouter().addHandler(offHookIQHandler); privateIQHandler = new PrivateIQHandler(); server.getIQRouter().addHandler(privateIQHandler); publicIQHandler = new PublicIQHandler(); server.getIQRouter().addHandler(publicIQHandler); muteIQHandler = new MuteIQHandler(); server.getIQRouter().addHandler(muteIQHandler); unmuteIQHandler = new UnmuteIQHandler(); server.getIQRouter().addHandler(unmuteIQHandler); holdIQHandler = new HoldIQHandler(); server.getIQRouter().addHandler(holdIQHandler); recordIQHandler = new RecordIQHandler(); server.getIQRouter().addHandler(recordIQHandler); pauseRecordIQHandler = new PauseRecordIQHandler(); server.getIQRouter().addHandler(pauseRecordIQHandler); resumeRecordIQHandler = new ResumeRecordIQHandler(); server.getIQRouter().addHandler(resumeRecordIQHandler); sayIQHandler = new SayIQHandler(); server.getIQRouter().addHandler(sayIQHandler); pauseSayIQHandler = new PauseSayIQHandler(); server.getIQRouter().addHandler(pauseSayIQHandler); resumeSayIQHandler = new ResumeSayIQHandler(); server.getIQRouter().addHandler(resumeSayIQHandler); acceptIQHandler = new AcceptIQHandler(); server.getIQRouter().addHandler(acceptIQHandler); answerIQHandler = new AnswerIQHandler(); server.getIQRouter().addHandler(answerIQHandler); dialIQHandler = new DialIQHandler(); server.getIQRouter().addHandler(dialIQHandler); hangupIQHandler = new HangupIQHandler(); server.getIQRouter().addHandler(hangupIQHandler); redirectIQHandler = new RedirectIQHandler(); server.getIQRouter().addHandler(redirectIQHandler); dtmfIQHandler = new DtmfIQHandler(); server.getIQRouter().addHandler(dtmfIQHandler); } private void destroyIQHandlers() { XMPPServer server = XMPPServer.getInstance(); if (onHookIQHandler != null) {server.getIQRouter().removeHandler(onHookIQHandler); onHookIQHandler = null;} if (offHookIQHandler != null) {server.getIQRouter().removeHandler(offHookIQHandler); offHookIQHandler = null;} if (privateIQHandler != null) {server.getIQRouter().removeHandler(privateIQHandler); privateIQHandler = null;} if (publicIQHandler != null) {server.getIQRouter().removeHandler(publicIQHandler); publicIQHandler = null;} if (muteIQHandler != null) {server.getIQRouter().removeHandler(muteIQHandler); muteIQHandler = null;} if (unmuteIQHandler != null) {server.getIQRouter().removeHandler(unmuteIQHandler); unmuteIQHandler = null;} if (holdIQHandler != null) {server.getIQRouter().removeHandler(holdIQHandler); holdIQHandler = null;} if (sayIQHandler != null) {server.getIQRouter().removeHandler(sayIQHandler); sayIQHandler = null;} if (pauseSayIQHandler != null) {server.getIQRouter().removeHandler(pauseSayIQHandler); pauseSayIQHandler = null;} if (resumeSayIQHandler != null) {server.getIQRouter().removeHandler(resumeSayIQHandler); resumeSayIQHandler = null;} if (acceptIQHandler != null) {server.getIQRouter().removeHandler(acceptIQHandler); acceptIQHandler = null;} if (answerIQHandler != null) {server.getIQRouter().removeHandler(answerIQHandler); answerIQHandler = null;} if (dialIQHandler != null) {server.getIQRouter().removeHandler(dialIQHandler); dialIQHandler = null;} if (hangupIQHandler != null) {server.getIQRouter().removeHandler(hangupIQHandler); hangupIQHandler = null;} if (redirectIQHandler != null) {server.getIQRouter().removeHandler(redirectIQHandler); redirectIQHandler = null;} if (dtmfIQHandler != null) {server.getIQRouter().removeHandler(dtmfIQHandler); dtmfIQHandler = null;} } private class OnHookIQHandler extends IQHandler { public OnHookIQHandler() { super("Rayo: XEP 0327 - Onhook");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) {return null;} } @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("onhook", RAYO_HANDSET); } } private class OffHookIQHandler extends IQHandler { public OffHookIQHandler() { super("Rayo: XEP 0327 - Offhook");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("offhook", RAYO_HANDSET); } } private class PrivateIQHandler extends IQHandler { public PrivateIQHandler() { super("Rayo: XEP 0327 - Private");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("private", RAYO_HANDSET); } } private class PublicIQHandler extends IQHandler { public PublicIQHandler() { super("Rayo: XEP 0327 - Public");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("public", RAYO_HANDSET); } } private class MuteIQHandler extends IQHandler { public MuteIQHandler() { super("Rayo: XEP 0327 - Mute");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("mute", RAYO_HANDSET); } } private class UnmuteIQHandler extends IQHandler { public UnmuteIQHandler() { super("Rayo: XEP 0327 - Unmute");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("unmute", RAYO_HANDSET); } } private class HoldIQHandler extends IQHandler { public HoldIQHandler() { super("Rayo: XEP 0327 - Hold");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("hold", RAYO_HANDSET); } } private class RecordIQHandler extends IQHandler { public RecordIQHandler() { super("Rayo: XEP 0327 - Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("record", RAYO_RECORD); } } private class PauseRecordIQHandler extends IQHandler { public PauseRecordIQHandler() { super("Rayo: XEP 0327 - Pause Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("pause", RAYO_RECORD); } } private class ResumeRecordIQHandler extends IQHandler { public ResumeRecordIQHandler() { super("Rayo: XEP 0327 - Resume Record");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("resume", RAYO_RECORD); } } private class SayIQHandler extends IQHandler { public SayIQHandler() { super("Rayo: XEP 0327 - Say (text to speech)");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("say", RAYO_SAY); } } private class PauseSayIQHandler extends IQHandler { public PauseSayIQHandler() { super("Rayo: XEP 0327 - Pause Say");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("pause", RAYO_SAY); } } private class ResumeSayIQHandler extends IQHandler { public ResumeSayIQHandler() { super("Rayo: XEP 0327 - Resume Say");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("resume", RAYO_SAY); } } private class AcceptIQHandler extends IQHandler { public AcceptIQHandler() { super("Rayo: XEP 0327 - Accept");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("accept", RAYO_CORE); } } private class AnswerIQHandler extends IQHandler { public AnswerIQHandler() { super("Rayo: XEP 0327 - Answer");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("answer", RAYO_CORE); } } private class DialIQHandler extends IQHandler { public DialIQHandler() { super("Rayo: XEP 0327 - Dial");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("dial", RAYO_CORE); } } private class HangupIQHandler extends IQHandler { public HangupIQHandler() { super("Rayo: XEP 0327 - Hangup");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("hangup", RAYO_CORE); } } private class RedirectIQHandler extends IQHandler { public RedirectIQHandler() { super("Rayo: XEP 0327 - Redirect");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("redirect", RAYO_CORE); } } private class DtmfIQHandler extends IQHandler { public DtmfIQHandler() { super("Rayo: XEP 0327 - DTMF");} @Override public IQ handleIQ(IQ iq) {try {return handleIQGet(iq);} catch(Exception e) { return null;}} @Override public IQHandlerInfo getInfo() { return new IQHandlerInfo("dtmf", RAYO_CORE); } } }
Rayo plugin - Added start/stop speaking messages to MUC message thread git-svn-id: 2e83ce7f183c9abd424edb3952fab2cdab7acd7f@13870 b35dd754-fafc-0310-a699-88a17e54d16e
src/plugins/rayo/src/java/org/ifsoft/rayo/RayoComponent.java
Rayo plugin - Added start/stop speaking messages to MUC message thread
Java
apache-2.0
26e53abb41a6839abfe056972aa775cf55fbd8d1
0
dnng/SSNoC-Java,dnng/SSNoC-Java
package edu.cmu.sv.ws.ssnoc.test; import static com.eclipsesource.restfuse.Assert.assertBadRequest; import static com.eclipsesource.restfuse.Assert.assertCreated; import static com.eclipsesource.restfuse.Assert.assertOk; import java.sql.Timestamp; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.runner.RunWith; import com.eclipsesource.restfuse.Destination; import com.eclipsesource.restfuse.HttpJUnitRunner; import com.eclipsesource.restfuse.MediaType; import com.eclipsesource.restfuse.Method; import com.eclipsesource.restfuse.Response; import com.eclipsesource.restfuse.annotation.Context; import com.eclipsesource.restfuse.annotation.HttpTest; import edu.cmu.sv.ws.ssnoc.common.logging.Log; import edu.cmu.sv.ws.ssnoc.data.util.ConnectionPoolFactory; import edu.cmu.sv.ws.ssnoc.data.util.DBUtils; import edu.cmu.sv.ws.ssnoc.data.util.IConnectionPool; import edu.cmu.sv.ws.ssnoc.dto.Message; import edu.cmu.sv.ws.ssnoc.dto.User; import edu.cmu.sv.ws.ssnoc.rest.MessageService; import edu.cmu.sv.ws.ssnoc.rest.UserService; @RunWith(HttpJUnitRunner.class) public class MessageServiceIT { @Rule public Destination destination = new Destination(this, "http://localhost:4321/ssnoc"); @Context public Response response; @BeforeClass public static void initialSetUp() throws Exception { try { IConnectionPool cp = ConnectionPoolFactory.getInstance() .getH2ConnectionPool(); cp.switchConnectionToTest(); DBUtils.reinitializeDatabase(); UserService userService = new UserService(); User testuser = new User(); testuser.setUserName("testuser"); testuser.setPassword("testuser"); userService.addUser(testuser); System.out.println(">>>>>>>Created testuser<<<<<<"); Message msg = new Message(); MessageService msgService = new MessageService(); msg.setAuthor("SSNAdmin"); Timestamp postedAt = new Timestamp(1234); msg.setPostedAt(postedAt); msg.setContent("testSendPrivateMessageToAnotherUser"); msgService.postPrivateChatMessage("SSNAdmin", "testuser", msg); System.out.println(">>>>>>>Sent private message from SSNAdmin to testuser<<<<<<"); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @AfterClass public static void finalTearDown() throws Exception { try { IConnectionPool cp = ConnectionPoolFactory.getInstance() .getH2ConnectionPool(); cp.switchConnectionToLive(); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @HttpTest(method = Method.POST, path = "/user/signup", type = MediaType.APPLICATION_JSON, content = "{\"userName\":\"testuser\",\"password\":\"testuser\"}") public void createTestUser() { assertCreated(response); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingAMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/testuser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test chat message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChatMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChattingWithNonExistantUsers() { assertBadRequest(response); } @HttpTest(method = Method.POST, path = "/message/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingMessageAsANonExistantUser() { assertBadRequest(response); } // /get// @HttpTest(method = Method.GET, path = "/messages/wall") public void checkWallMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.GET, path = "/messages/SSNAdmin/testuser") public void checkChatMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.GET, path = "/message/1") public void checkMessageID() { assertOk(response); } @HttpTest(method = Method.GET, path = "/users/SSNAdmin/chatbuddies") public void checkChatBuddies() { assertOk(response); String buddies = response.getBody(); Assert.assertTrue(buddies.contains("testuser")); } }
src/it/java/edu/cmu/sv/ws/ssnoc/test/MessageServiceIT.java
package edu.cmu.sv.ws.ssnoc.test; import static com.eclipsesource.restfuse.Assert.assertBadRequest; import static com.eclipsesource.restfuse.Assert.assertCreated; import static com.eclipsesource.restfuse.Assert.assertOk; import java.sql.Timestamp; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.runner.RunWith; import com.eclipsesource.restfuse.Destination; import com.eclipsesource.restfuse.HttpJUnitRunner; import com.eclipsesource.restfuse.MediaType; import com.eclipsesource.restfuse.Method; import com.eclipsesource.restfuse.Response; import com.eclipsesource.restfuse.annotation.Context; import com.eclipsesource.restfuse.annotation.HttpTest; import edu.cmu.sv.ws.ssnoc.common.logging.Log; import edu.cmu.sv.ws.ssnoc.data.util.ConnectionPoolFactory; import edu.cmu.sv.ws.ssnoc.data.util.DBUtils; import edu.cmu.sv.ws.ssnoc.data.util.IConnectionPool; import edu.cmu.sv.ws.ssnoc.dto.Message; import edu.cmu.sv.ws.ssnoc.dto.User; import edu.cmu.sv.ws.ssnoc.rest.MessageService; import edu.cmu.sv.ws.ssnoc.rest.UserService; @RunWith(HttpJUnitRunner.class) public class MessageServiceIT { @Rule public Destination destination = new Destination(this, "http://localhost:4321/ssnoc"); @Context public Response response; @BeforeClass public static void initialSetUp() throws Exception { try { // IConnectionPool cp = ConnectionPoolFactory.getInstance() // .getH2ConnectionPool(); // cp.switchConnectionToTest(); // // DBUtils.reinitializeDatabase(); UserService userService = new UserService(); User testuser = new User(); testuser.setUserName("testuser"); testuser.setPassword("testuser"); userService.addUser(testuser); System.out.println(">>>>>>>Created testuser<<<<<<"); Message msg = new Message(); MessageService msgService = new MessageService(); msg.setAuthor("SSNAdmin"); Timestamp postedAt = new Timestamp(1234); msg.setPostedAt(postedAt); msg.setContent("testSendPrivateMessageToAnotherUser"); msgService.postPrivateChatMessage("SSNAdmin", "testuser", msg); System.out.println(">>>>>>>Sent private message from SSNAdmin to testuser<<<<<<"); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @AfterClass public static void finalTearDown() throws Exception { try { // IConnectionPool cp = ConnectionPoolFactory.getInstance() // .getH2ConnectionPool(); // cp.switchConnectionToLive(); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @HttpTest(method = Method.POST, path = "/message/SSNAdmin", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingAMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/testuser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test chat message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChatMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChattingWithNonExistantUsers() { assertBadRequest(response); } @HttpTest(method = Method.POST, path = "/message/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingMessageAsANonExistantUser() { assertBadRequest(response); } // /get// @HttpTest(method = Method.GET, path = "/messages/wall") public void checkWallMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.GET, path = "/messages/SSNAdmin/testuser") public void checkChatMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.GET, path = "/message/1") public void checkMessageID() { assertOk(response); } @HttpTest(method = Method.GET, path = "/users/SSNAdmin/chatbuddies") public void checkChatBuddies() { assertOk(response); String buddies = response.getBody(); Assert.assertTrue(buddies.contains("testuser")); } }
integration test fix
src/it/java/edu/cmu/sv/ws/ssnoc/test/MessageServiceIT.java
integration test fix
Java
apache-2.0
59cf444daf9fb4403beafc210a7364548e1f307e
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.portlet.util; import java.io.File; import java.io.FileNotFoundException; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletContext; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import org.springframework.util.Assert; import org.springframework.web.util.WebUtils; /** * Miscellaneous utilities for portlet applications. * Used by various framework classes. * * @author Juergen Hoeller * @author William G. Thompson, Jr. * @author John A. Lewis * @since 2.0 */ public abstract class PortletUtils { /** * Return the temporary directory for the current web application, * as provided by the portlet container. * @param portletContext the portlet context of the web application * @return the File representing the temporary directory * @throws IllegalArgumentException if the supplied <code>portletContext</code> is <code>null</code> */ public static File getTempDir(PortletContext portletContext) { Assert.notNull(portletContext, "PortletContext must not be null"); return (File) portletContext.getAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE); } /** * Return the real path of the given path within the web application, * as provided by the portlet container. * <p>Prepends a slash if the path does not already start with a slash, * and throws a {@link java.io.FileNotFoundException} if the path cannot * be resolved to a resource (in contrast to * {@link javax.portlet.PortletContext#getRealPath PortletContext's <code>getRealPath</code>}, * which simply returns <code>null</code>). * @param portletContext the portlet context of the web application * @param path the relative path within the web application * @return the corresponding real path * @throws FileNotFoundException if the path cannot be resolved to a resource * @throws IllegalArgumentException if the supplied <code>portletContext</code> is <code>null</code> * @throws NullPointerException if the supplied <code>path</code> is <code>null</code> * @see javax.portlet.PortletContext#getRealPath */ public static String getRealPath(PortletContext portletContext, String path) throws FileNotFoundException { Assert.notNull(portletContext, "PortletContext must not be null"); // Interpret location as relative to the web application root directory. if (!path.startsWith("/")) { path = "/" + path; } String realPath = portletContext.getRealPath(path); if (realPath == null) { throw new FileNotFoundException( "PortletContext resource [" + path + "] cannot be resolved to absolute file path - " + "web application archive not expanded?"); } return realPath; } /** * Check the given request for a session attribute of the given name under the * {@link javax.portlet.PortletSession#PORTLET_SCOPE}. * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @return the value of the session attribute, or <code>null</code> if not found * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static Object getSessionAttribute(PortletRequest request, String name) { return getSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); } /** * Check the given request for a session attribute of the given name in the given scope. * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @param scope session scope of this attribute * @return the value of the session attribute, or <code>null</code> if not found * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static Object getSessionAttribute(PortletRequest request, String name, int scope) { Assert.notNull(request, "Request must not be null"); PortletSession session = request.getPortletSession(false); return (session != null ? session.getAttribute(name, scope) : null); } /** * Check the given request for a session attribute of the given name under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}. * Throws an exception if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @return the value of the session attribute * @throws IllegalStateException if the session attribute could not be found * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static Object getRequiredSessionAttribute(PortletRequest request, String name) throws IllegalStateException { return getRequiredSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); } /** * Check the given request for a session attribute of the given name in the given scope. * Throws an exception if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @param scope session scope of this attribute * @return the value of the session attribute * @throws IllegalStateException if the session attribute could not be found * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static Object getRequiredSessionAttribute(PortletRequest request, String name, int scope) throws IllegalStateException { Object attr = getSessionAttribute(request, name, scope); if (attr == null) { throw new IllegalStateException("No session attribute '" + name + "' found"); } return attr; } /** * Set the session attribute with the given name to the given value under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}. * Removes the session attribute if value is <code>null</code>, if a session existed at all. * Does not create a new session if not necessary! * @param request current portlet request * @param name the name of the session attribute * @param value the value of the session attribute * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static void setSessionAttribute(PortletRequest request, String name, Object value) { setSessionAttribute(request, name, value, PortletSession.PORTLET_SCOPE); } /** * Set the session attribute with the given name to the given value in the given scope. * Removes the session attribute if value is <code>null</code>, if a session existed at all. * Does not create a new session if not necessary! * @param request current portlet request * @param name the name of the session attribute * @param value the value of the session attribute * @param scope session scope of this attribute * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code> */ public static void setSessionAttribute(PortletRequest request, String name, Object value, int scope) { Assert.notNull(request, "Request must not be null"); if (value != null) { request.getPortletSession().setAttribute(name, value, scope); } else { PortletSession session = request.getPortletSession(false); if (session != null) { session.removeAttribute(name, scope); } } } /** * Get the specified session attribute under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}, * creating and setting a new attribute if no existing found. The given class * needs to have a public no-arg constructor. * Useful for on-demand state objects in a web tier, like shopping carts. * @param session current portlet session * @param name the name of the session attribute * @param clazz the class to instantiate for a new attribute * @return the value of the session attribute, newly created if not found * @throws IllegalArgumentException if the session attribute could not be instantiated; or if the supplied <code>session</code> argument is <code>null</code> */ public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz) throws IllegalArgumentException { return getOrCreateSessionAttribute(session, name, clazz, PortletSession.PORTLET_SCOPE); } /** * Get the specified session attribute in the given scope, * creating and setting a new attribute if no existing found. The given class * needs to have a public no-arg constructor. * Useful for on-demand state objects in a web tier, like shopping carts. * @param session current portlet session * @param name the name of the session attribute * @param clazz the class to instantiate for a new attribute * @param scope the session scope of this attribute * @return the value of the session attribute, newly created if not found * @throws IllegalArgumentException if the session attribute could not be instantiated; or if the supplied <code>session</code> argument is <code>null</code> */ public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz, int scope) throws IllegalArgumentException { Assert.notNull(session, "Session must not be null"); Object sessionObject = session.getAttribute(name, scope); if (sessionObject == null) { Assert.notNull(clazz, "Class must not be null if attribute value is to be instantiated"); try { sessionObject = clazz.newInstance(); } catch (InstantiationException ex) { throw new IllegalArgumentException( "Could not instantiate class [" + clazz.getName() + "] for session attribute '" + name + "': " + ex.getMessage()); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Could not access default constructor of class [" + clazz.getName() + "] for session attribute '" + name + "': " + ex.getMessage()); } session.setAttribute(name, sessionObject, scope); } return sessionObject; } /** * Return the best available mutex for the given session: * that is, an object to synchronize on for the given session. * <p>Returns the session mutex attribute if available; usually, * this means that the * {@link org.springframework.web.util.HttpSessionMutexListener} * needs to be defined in <code>web.xml</code>. Falls back to the * {@link javax.portlet.PortletSession} itself if no mutex attribute found. * <p>The session mutex is guaranteed to be the same object during * the entire lifetime of the session, available under the key defined * by the {@link org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE} * constant. It serves as a safe reference to synchronize on for locking * on the current session. * <p>In many cases, the {@link javax.portlet.PortletSession} reference * itself is a safe mutex as well, since it will always be the same * object reference for the same active logical session. However, this is * not guaranteed across different servlet containers; the only 100% safe * way is a session mutex. * @param session the HttpSession to find a mutex for * @return the mutex object (never <code>null</code>) * @see org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE * @see org.springframework.web.util.HttpSessionMutexListener */ public static Object getSessionMutex(PortletSession session) { Assert.notNull(session, "Session must not be null"); Object mutex = session.getAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE); if (mutex == null) { mutex = session; } return mutex; } /** * Expose the given Map as request attributes, using the keys as attribute names * and the values as corresponding attribute values. Keys must be Strings. * @param request current portlet request * @param attributes the attributes Map * @throws IllegalArgumentException if an invalid key is found in the Map (i.e. the key is not a String); or if * either of the supplied arguments is <code>null</code> */ public static void exposeRequestAttributes(PortletRequest request, Map attributes) throws IllegalArgumentException { Assert.notNull(request, "Request must not be null"); Assert.notNull(attributes, "attributes Map must not be null"); Iterator it = attributes.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); if (!(entry.getKey() instanceof String)) { throw new IllegalArgumentException( "Invalid key [" + entry.getKey() + "] in attributes Map - only Strings allowed as attribute keys"); } request.setAttribute((String) entry.getKey(), entry.getValue()); } } /** * Check if a specific input type="submit" parameter was sent in the request, * either via a button (directly with name) or via an image (name + ".x" or * name + ".y"). * @param request current portlet request * @param name name of the parameter * @return if the parameter was sent * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES */ public static boolean hasSubmitParameter(PortletRequest request, String name) { return getSubmitParameter(request, name) != null; } /** * Return the full name of a specific input type="submit" parameter * if it was sent in the request, either via a button (directly with name) * or via an image (name + ".x" or name + ".y"). * @param request current portlet request * @param name name of the parameter * @return the actual parameter name with suffix if needed - null if not present * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES */ public static String getSubmitParameter(PortletRequest request, String name) { Assert.notNull(request, "Request must not be null"); if (request.getParameter(name) != null) { return name; } for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) { String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i]; String parameter = name + suffix; if (request.getParameter(parameter) != null) { return parameter; } } return null; } /** * Return a map containing all parameters with the given prefix. * Maps single values to String and multiple values to String array. * <p>For example, with a prefix of "spring_", "spring_param1" and * "spring_param2" result in a Map with "param1" and "param2" as keys. * <p>Similar to portlet * {@link javax.portlet.PortletRequest#getParameterMap()}, * but more flexible. * @param request portlet request in which to look for parameters * @param prefix the beginning of parameter names * (if this is <code>null</code> or the empty string, all parameters will match) * @return map containing request parameters <b>without the prefix</b>, * containing either a String or a String array as values * @see javax.portlet.PortletRequest#getParameterNames * @see javax.portlet.PortletRequest#getParameterValues * @see javax.portlet.PortletRequest#getParameterMap */ public static Map getParametersStartingWith(PortletRequest request, String prefix) { Assert.notNull(request, "Request must not be null"); Enumeration paramNames = request.getParameterNames(); Map params = new TreeMap(); if (prefix == null) { prefix = ""; } while (paramNames != null && paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if ("".equals(prefix) || paramName.startsWith(prefix)) { String unprefixed = paramName.substring(prefix.length()); String[] values = request.getParameterValues(paramName); if (values == null) { // do nothing, no values found at all } else if (values.length > 1) { params.put(unprefixed, values); } else { params.put(unprefixed, values[0]); } } } return params; } /** * Pass all the action request parameters to the render phase by putting them into * the action response object. This may not be called when the action will call * {@link javax.portlet.ActionResponse#sendRedirect sendRedirect}. * @param request the current action request * @param response the current action response * @see javax.portlet.ActionResponse#setRenderParameter */ public static void passAllParametersToRenderPhase(ActionRequest request, ActionResponse response) { try { Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String param = (String) en.nextElement(); String values[] = request.getParameterValues(param); response.setRenderParameter(param, values); } } catch (IllegalStateException ex) { // Ignore in case sendRedirect was already set. } } /** * Clear all the render parameters from the {@link javax.portlet.ActionResponse}. * This may not be called when the action will call * {@link ActionResponse#sendRedirect sendRedirect}. * @param response the current action response * @see ActionResponse#setRenderParameters */ public static void clearAllRenderParameters(ActionResponse response) { try { response.setRenderParameters(new HashMap()); } catch (IllegalStateException ex) { // Ignore in case sendRedirect was already set. } } }
src/org/springframework/web/portlet/util/PortletUtils.java
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.portlet.util; import java.io.File; import java.io.FileNotFoundException; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletContext; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import org.springframework.util.Assert; import org.springframework.web.util.WebUtils; /** * Miscellaneous utilities for portlet applications. * Used by various framework classes. * * @author Juergen Hoeller * @author William G. Thompson, Jr. * @author John A. Lewis * @since 2.0 */ public abstract class PortletUtils { /** * Return the temporary directory for the current web application, * as provided by the portlet container. * @param portletContext the portlet context of the web application * @return the File representing the temporary directory */ public static File getTempDir(PortletContext portletContext) { Assert.notNull(portletContext, "PortletContext must not be null"); return (File) portletContext.getAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE); } /** * Return the real path of the given path within the web application, * as provided by the portlet container. * <p>Prepends a slash if the path does not already start with a slash, * and throws a FileNotFoundException if the path cannot be resolved to * a resource (in contrast to PortletContext's <code>getRealPath</code>, * which returns null). * @param portletContext the portlet context of the web application * @param path the relative path within the web application * @return the corresponding real path * @throws FileNotFoundException if the path cannot be resolved to a resource * @see javax.portlet.PortletContext#getRealPath */ public static String getRealPath(PortletContext portletContext, String path) throws FileNotFoundException { Assert.notNull(portletContext, "PortletContext must not be null"); // Interpret location as relative to the web application root directory. if (!path.startsWith("/")) { path = "/" + path; } String realPath = portletContext.getRealPath(path); if (realPath == null) { throw new FileNotFoundException( "PortletContext resource [" + path + "] cannot be resolved to absolute file path - " + "web application archive not expanded?"); } return realPath; } /** * Check the given request for a session attribute of the given name under the <code>PORTLET_SCOPE</code>. * Returns null if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @return the value of the session attribute, or null if not found */ public static Object getSessionAttribute(PortletRequest request, String name) { return getSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); } /** * Check the given request for a session attribute of the given name in the given scope. * Returns null if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @param scope session scope of this attribute * @return the value of the session attribute, or null if not found */ public static Object getSessionAttribute(PortletRequest request, String name, int scope) { Assert.notNull(request, "Request must not be null"); PortletSession session = request.getPortletSession(false); return (session != null ? session.getAttribute(name, scope) : null); } /** * Check the given request for a session attribute of the given name under the <code>PORTLET_SCOPE</code>. * Throws an exception if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @return the value of the session attribute * @throws IllegalStateException if the session attribute could not be found */ public static Object getRequiredSessionAttribute(PortletRequest request, String name) throws IllegalStateException { return getRequiredSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); } /** * Check the given request for a session attribute of the given name in the given scope. * Throws an exception if there is no session or if the session has no such attribute in that scope. * Does not create a new session if none has existed before! * @param request current portlet request * @param name the name of the session attribute * @param scope session scope of this attribute * @return the value of the session attribute * @throws IllegalStateException if the session attribute could not be found */ public static Object getRequiredSessionAttribute(PortletRequest request, String name, int scope) throws IllegalStateException { Object attr = getSessionAttribute(request, name, scope); if (attr == null) throw new IllegalStateException("No session attribute '" + name + "' found"); return attr; } /** * Set the session attribute with the given name to the given value under the <code>PORTLET_SCOPE</code>. * Removes the session attribute if value is null, if a session existed at all. * Does not create a new session if not necessary! * @param request current portlet request * @param name the name of the session attribute * @param value the value of the session attribute */ public static void setSessionAttribute(PortletRequest request, String name, Object value) { setSessionAttribute(request, name, value, PortletSession.PORTLET_SCOPE); } /** * Set the session attribute with the given name to the given value in the given scope. * Removes the session attribute if value is null, if a session existed at all. * Does not create a new session if not necessary! * @param request current portlet request * @param name the name of the session attribute * @param value the value of the session attribute * @param scope session scope of this attribute */ public static void setSessionAttribute(PortletRequest request, String name, Object value, int scope) { Assert.notNull(request, "Request must not be null"); if (value != null) { request.getPortletSession().setAttribute(name, value, scope); } else { PortletSession session = request.getPortletSession(false); if (session != null) session.removeAttribute(name, scope); } } /** * Get the specified session attribute under the <code>PORTLET_SCOPE</code>, * creating and setting a new attribute if no existing found. The given class * needs to have a public no-arg constructor. * Useful for on-demand state objects in a web tier, like shopping carts. * @param session current portlet session * @param name the name of the session attribute * @param clazz the class to instantiate for a new attribute * @return the value of the session attribute, newly created if not found * @throws IllegalArgumentException if the session attribute could not be instantiated */ public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz) throws IllegalArgumentException { return getOrCreateSessionAttribute(session, name, clazz, PortletSession.PORTLET_SCOPE); } /** * Get the specified session attribute in the given scope, * creating and setting a new attribute if no existing found. The given class * needs to have a public no-arg constructor. * Useful for on-demand state objects in a web tier, like shopping carts. * @param session current portlet session * @param name the name of the session attribute * @param clazz the class to instantiate for a new attribute * @param scope the session scope of this attribute * @return the value of the session attribute, newly created if not found * @throws IllegalArgumentException if the session attribute could not be instantiated */ public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz, int scope) throws IllegalArgumentException { Assert.notNull(session, "Session must not be null"); Object sessionObject = session.getAttribute(name, scope); if (sessionObject == null) { try { sessionObject = clazz.newInstance(); } catch (InstantiationException ex) { throw new IllegalArgumentException( "Could not instantiate class [" + clazz.getName() + "] for session attribute '" + name + "': " + ex.getMessage()); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Could not access default constructor of class [" + clazz.getName() + "] for session attribute '" + name + "': " + ex.getMessage()); } session.setAttribute(name, sessionObject, scope); } return sessionObject; } /** * Return the best available mutex for the given session: * that is, an object to synchronize on for the given session. * <p>Returns the session mutex attribute if available; usually, * this means that the HttpSessionMutexListener needs to be defined * in <code>web.xml</code>. Falls back to the PortletSession itself * if no mutex attribute found. * <p>The session mutex is guaranteed to be the same object during * the entire lifetime of the session, available under the key defined * by the <code>SESSION_MUTEX_ATTRIBUTE</code> constant. It serves as a * safe reference to synchronize on for locking on the current session. * <p>In many cases, the PortletSession reference itself is a safe mutex * as well, since it will always be the same object reference for the * same active logical session. However, this is not guaranteed across * different servlet containers; the only 100% safe way is a session mutex. * @param session the HttpSession to find a mutex for * @return the mutex object (never <code>null</code>) * @see org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE * @see org.springframework.web.util.HttpSessionMutexListener */ public static Object getSessionMutex(PortletSession session) { Assert.notNull(session, "Session must not be null"); Object mutex = session.getAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE); if (mutex == null) { mutex = session; } return mutex; } /** * Expose the given Map as request attributes, using the keys as attribute names * and the values as corresponding attribute values. Keys need to be Strings. * @param request current portlet request * @param attributes the attributes Map * @throws IllegalArgumentException if an invalid key is found in the Map */ public static void exposeRequestAttributes(PortletRequest request, Map attributes) throws IllegalArgumentException { Assert.notNull(request, "Request must not be null"); Iterator it = attributes.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); if (!(entry.getKey() instanceof String)) { throw new IllegalArgumentException( "Invalid key [" + entry.getKey() + "] in attributes Map - only Strings allowed as attribute keys"); } request.setAttribute((String) entry.getKey(), entry.getValue()); } } /** * Check if a specific input type="submit" parameter was sent in the request, * either via a button (directly with name) or via an image (name + ".x" or * name + ".y"). * @param request current portlet request * @param name name of the parameter * @return if the parameter was sent * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES */ public static boolean hasSubmitParameter(PortletRequest request, String name) { Assert.notNull(request, "Request must not be null"); if (request.getParameter(name) != null) { return true; } for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) { String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i]; if (request.getParameter(name + suffix) != null) { return true; } } return false; } /** * Return the full name of a specific input type="submit" parameter * if it was sent in the request, either via a button (directly with name) * or via an image (name + ".x" or name + ".y"). * @param request current portlet request * @param name name of the parameter * @return the actual parameter name with suffix if needed - null if not present * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES */ public static String getSubmitParameter(PortletRequest request, String name) { Assert.notNull(request, "Request must not be null"); if (request.getParameter(name) != null) { return name; } for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) { String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i]; if (request.getParameter(name + suffix) != null) { return name + suffix; } } return null; } /** * Return a map containing all parameters with the given prefix. * Maps single values to String and multiple values to String array. * <p>For example, with a prefix of "spring_", "spring_param1" and * "spring_param2" result in a Map with "param1" and "param2" as keys. * <p>Similar to portlet <code>PortletRequest.getParameterMap</code>, * but more flexible. * @param request portlet request in which to look for parameters * @param prefix the beginning of parameter names * (if this is null or the empty string, all parameters will match) * @return map containing request parameters <b>without the prefix</b>, * containing either a String or a String array as values * @see javax.portlet.PortletRequest#getParameterNames * @see javax.portlet.PortletRequest#getParameterValues * @see javax.portlet.PortletRequest#getParameterMap */ public static Map getParametersStartingWith(PortletRequest request, String prefix) { Assert.notNull(request, "Request must not be null"); Enumeration paramNames = request.getParameterNames(); Map params = new TreeMap(); if (prefix == null) { prefix = ""; } while (paramNames != null && paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if ("".equals(prefix) || paramName.startsWith(prefix)) { String unprefixed = paramName.substring(prefix.length()); String[] values = request.getParameterValues(paramName); if (values == null) { // do nothing, no values found at all } else if (values.length > 1) { params.put(unprefixed, values); } else { params.put(unprefixed, values[0]); } } } return params; } /** * Pass all the action request parameters to the render phase by putting them into * the action response object. This may not be called when the action will call * {@link javax.portlet.ActionResponse#sendRedirect sendRedirect}. * @param request the current action request * @param response the current action response * @see javax.portlet.ActionResponse#setRenderParameter */ public static void passAllParametersToRenderPhase(ActionRequest request, ActionResponse response) { try { Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String param = (String) en.nextElement(); String values[] = request.getParameterValues(param); response.setRenderParameter(param, values); } } catch (IllegalStateException ex) { // Ignore in case sendRedirect was already set. } } /** * Clear all the render parameters from the ActionResponse. * This may not be called when the action will call * {@link ActionResponse#sendRedirect sendRedirect}. * @param response the current action response * @see ActionResponse#setRenderParameters */ public static void clearAllRenderParameters(ActionResponse response) { try { response.setRenderParameters(new HashMap()); } catch (IllegalStateException ex) { // Ignore in case sendRedirect was already set. } } }
Polishing - correct use of braces for single statement if statements, <code>null</code> in Javadoc, hyperlinked the Javadoc. git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@9817 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/web/portlet/util/PortletUtils.java
Polishing - correct use of braces for single statement if statements, <code>null</code> in Javadoc, hyperlinked the Javadoc.
Java
apache-2.0
0c09a63c5b9bc6c90dc827e7849704f530e1772f
0
codehaus/httpcache4j,httpcache4j/httpcache4j,httpcache4j/httpcache4j,codehaus/httpcache4j
package org.codehaus.httpcache4j.util; import org.codehaus.httpcache4j.cache.CacheItem; import org.codehaus.httpcache4j.cache.Key; import org.codehaus.httpcache4j.cache.MemoryCacheStorage; import org.codehaus.httpcache4j.cache.Vary; import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; public class InvalidateOnRemoveLRUHashMap extends LinkedHashMap<URI, Map<Vary, CacheItem>> { private static final long serialVersionUID = -8600084275381371031L; private final int capacity; private transient RemoveListener listener; public InvalidateOnRemoveLRUHashMap(final int capacity) { super(capacity); this.capacity = capacity; } public InvalidateOnRemoveLRUHashMap(InvalidateOnRemoveLRUHashMap map) { super(map); this.capacity = map.capacity; this.listener = map.listener; } public InvalidateOnRemoveLRUHashMap copy() { return new InvalidateOnRemoveLRUHashMap(this); } @Override protected boolean removeEldestEntry(Map.Entry<URI, Map<Vary, CacheItem>> eldest) { return size() > capacity; } @Override @Deprecated public Map<Vary, CacheItem> remove(Object key) { throw new IllegalArgumentException("Use remove(Key) instead"); } public CacheItem remove(Key key) { Map<Vary, CacheItem> varyCacheItemMap = super.get(key.getURI()); if (varyCacheItemMap != null) { CacheItem item = varyCacheItemMap.remove(key.getVary()); if (listener != null) { listener.onRemoveFromMap(key); } if (varyCacheItemMap.isEmpty()) { super.remove(key.getURI()); } return item; } return null; } public void remove(URI uri) { Map<Vary, CacheItem> varyCacheItemMap = super.get(uri); if (varyCacheItemMap != null) { for (Vary vary : varyCacheItemMap.keySet()) { Key key = Key.create(uri, vary); if (listener != null) { listener.onRemoveFromMap(key); } } super.remove(uri); } } public void setListener(RemoveListener listener) { this.listener = listener; } public static interface RemoveListener { public void onRemoveFromMap(Key key); } }
httpcache4j-core/src/main/java/org/codehaus/httpcache4j/util/InvalidateOnRemoveLRUHashMap.java
package org.codehaus.httpcache4j.util; import org.codehaus.httpcache4j.cache.CacheItem; import org.codehaus.httpcache4j.cache.Key; import org.codehaus.httpcache4j.cache.MemoryCacheStorage; import org.codehaus.httpcache4j.cache.Vary; import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; public class InvalidateOnRemoveLRUHashMap extends LinkedHashMap<URI, Map<Vary, CacheItem>> { private static final long serialVersionUID = -8600084275381371031L; private final int capacity; private transient RemoveListener listener; public InvalidateOnRemoveLRUHashMap(final int capacity) { super(capacity); this.capacity = capacity; } public InvalidateOnRemoveLRUHashMap(InvalidateOnRemoveLRUHashMap map) { super(map); this.capacity = map.capacity; this.listener = map.listener; } public InvalidateOnRemoveLRUHashMap copy() { return new InvalidateOnRemoveLRUHashMap(this); } @Override protected boolean removeEldestEntry(Map.Entry<URI, Map<Vary, CacheItem>> eldest) { return size() > capacity; } @Override @Deprecated public Map<Vary, CacheItem> remove(Object key) { throw new IllegalArgumentException("Use remove(Key) instead"); } public CacheItem remove(Key key) { Map<Vary, CacheItem> varyCacheItemMap = super.get(key.getURI()); if (varyCacheItemMap != null) { CacheItem item = varyCacheItemMap.remove(key.getVary()); if (listener != null) { listener.onRemoveFromMap(key); } if (varyCacheItemMap.isEmpty()) { super.remove(key.getURI()); } return item; } return null; } public CacheItem remove(URI uri) { Map<Vary, CacheItem> varyCacheItemMap = super.get(uri); if (varyCacheItemMap != null) { for (Vary vary : varyCacheItemMap.keySet()) { Key key = Key.create(uri, vary); if (listener != null) { listener.onRemoveFromMap(key); } } } return null; } public void setListener(RemoveListener listener) { this.listener = listener; } public static interface RemoveListener { public void onRemoveFromMap(Key key); } }
Actually remove entry from cache on call to remove. Update return type.
httpcache4j-core/src/main/java/org/codehaus/httpcache4j/util/InvalidateOnRemoveLRUHashMap.java
Actually remove entry from cache on call to remove. Update return type.
Java
apache-2.0
6c720a79dc64f26febc0c9235f62c4ab345a99bf
0
tapomay/gaussianescapa,tapomay/gaussianescapa,omiey/gaussianescapa,omiey/gaussianescapa
package com.t5hm.escapa.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.t5hm.escapa.game.MainEscapaGame; import com.t5hm.escapa.game.MainEscapaLightsNoGame; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "GaussianEscapa"; config.width = 720; config.height = 360; config.useGL30 = true; // new LwjglApplication(new MainEscapaGame(), config); new LwjglApplication(new MainEscapaGame(), config); } }
desktop/src/com/t5hm/escapa/game/desktop/DesktopLauncher.java
package com.t5hm.escapa.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.t5hm.escapa.game.MainEscapaGame; import com.t5hm.escapa.game.MainEscapaLightsNoGame; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "GaussianEscapa"; config.useGL30 = true; // new LwjglApplication(new MainEscapaGame(), config); new LwjglApplication(new MainEscapaGame(), config); } }
DesktopLauncher width height setting...equivalent to device size.
desktop/src/com/t5hm/escapa/game/desktop/DesktopLauncher.java
DesktopLauncher width height setting...equivalent to device size.
Java
apache-2.0
2b0e19da481dc11a1f3655c78d8aa20477e1eac3
0
kool79/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ernestp/consulo,caot/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,caot/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,da1z/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,caot/intellij-community,asedunov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,holmes/intellij-community,retomerz/intellij-community,blademainer/intellij-community,consulo/consulo,samthor/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,kool79/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,allotria/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,supersven/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,diorcety/intellij-community,kdwink/intellij-community,robovm/robovm-studio,jagguli/intellij-community,clumsy/intellij-community,adedayo/intellij-community,amith01994/intellij-community,FHannes/intellij-community,caot/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,kool79/intellij-community,retomerz/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,holmes/intellij-community,signed/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,holmes/intellij-community,ernestp/consulo,ahb0327/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,fitermay/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,signed/intellij-community,holmes/intellij-community,signed/intellij-community,fnouama/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,samthor/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,fitermay/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,hurricup/intellij-community,asedunov/intellij-community,slisson/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,caot/intellij-community,FHannes/intellij-community,holmes/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,asedunov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,blademainer/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,fitermay/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,semonte/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,semonte/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,da1z/intellij-community,caot/intellij-community,petteyg/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ibinti/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,signed/intellij-community,allotria/intellij-community,xfournet/intellij-community,slisson/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,izonder/intellij-community,izonder/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,petteyg/intellij-community,allotria/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,kdwink/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ernestp/consulo,tmpgit/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,semonte/intellij-community,akosyakov/intellij-community,supersven/intellij-community,izonder/intellij-community,fitermay/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,asedunov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,retomerz/intellij-community,xfournet/intellij-community,supersven/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kool79/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,allotria/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,jagguli/intellij-community,caot/intellij-community,samthor/intellij-community,xfournet/intellij-community,slisson/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,FHannes/intellij-community,caot/intellij-community,samthor/intellij-community,petteyg/intellij-community,kool79/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,robovm/robovm-studio,adedayo/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,FHannes/intellij-community,caot/intellij-community,da1z/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,ernestp/consulo,FHannes/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,consulo/consulo,caot/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,xfournet/intellij-community,semonte/intellij-community,izonder/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,orekyuu/intellij-community,holmes/intellij-community,kdwink/intellij-community,kool79/intellij-community,amith01994/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,signed/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,jagguli/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,izonder/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,signed/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,signed/intellij-community,ernestp/consulo,alphafoobar/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,blademainer/intellij-community,supersven/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,vladmm/intellij-community,vvv1559/intellij-community,supersven/intellij-community,kdwink/intellij-community,hurricup/intellij-community,consulo/consulo,MER-GROUP/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,allotria/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,semonte/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,semonte/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kool79/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,holmes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,fitermay/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,robovm/robovm-studio,apixandru/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,robovm/robovm-studio,amith01994/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,consulo/consulo,adedayo/intellij-community,signed/intellij-community,izonder/intellij-community,caot/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,petteyg/intellij-community,semonte/intellij-community,vladmm/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,xfournet/intellij-community,da1z/intellij-community,clumsy/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,blademainer/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community,diorcety/intellij-community,kdwink/intellij-community,samthor/intellij-community,dslomov/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,da1z/intellij-community,allotria/intellij-community,ryano144/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,xfournet/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,diorcety/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,slisson/intellij-community,semonte/intellij-community,adedayo/intellij-community,hurricup/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,consulo/consulo,ahb0327/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,samthor/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,samthor/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,slisson/intellij-community,vladmm/intellij-community,signed/intellij-community,apixandru/intellij-community,izonder/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,xfournet/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.completion.impl; import com.intellij.codeInsight.lookup.Classifier; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import java.util.*; /** * @author peter */ class LiftShorterItemsClassifier extends Classifier<LookupElement> { private final TreeSet<String> mySortedStrings; private final MultiMap<String, LookupElement> myElements; private final MultiMap<String, String> myPrefixes; private final Classifier<LookupElement> myNext; public LiftShorterItemsClassifier(Classifier<LookupElement> next) { myNext = next; mySortedStrings = new TreeSet<String>(); myElements = new MultiMap<String, LookupElement>(); myPrefixes = new MultiMap<String, String>(); } @Override public void addElement(LookupElement element) { final Set<String> strings = getAllLookupStrings(element); for (String string : strings) { if (string.length() == 0) continue; myElements.putValue(string, element); mySortedStrings.add(string); final NavigableSet<String> after = mySortedStrings.tailSet(string, false); for (String s : after) { if (!s.startsWith(string)) { break; } myPrefixes.putValue(s, string); } final char first = string.charAt(0); final SortedSet<String> before = mySortedStrings.descendingSet().tailSet(string, false); for (String s : before) { if (s.charAt(0) != first) { break; } if (string.startsWith(s)) { myPrefixes.putValue(string, s); } } } myNext.addElement(element); } @Override public Iterable<List<LookupElement>> classify(List<LookupElement> source) { return liftShorterElements(source, new HashSet<LookupElement>()); } private Iterable<List<LookupElement>> liftShorterElements(List<LookupElement> source, Set<LookupElement> lifted) { final Set<LookupElement> srcSet = new THashSet<LookupElement>(source, TObjectHashingStrategy.IDENTITY); final Iterable<List<LookupElement>> classified = myNext.classify(source); final Set<LookupElement> processed = new HashSet<LookupElement>(); final ArrayList<List<LookupElement>> result = new ArrayList<List<LookupElement>>(); for (List<LookupElement> list : classified) { final ArrayList<LookupElement> group = new ArrayList<LookupElement>(); for (LookupElement element : list) { assert srcSet.contains(element) : myNext; if (processed.add(element)) { for (String prefix : getSortedPrefixes(element)) { List<LookupElement> shorter = new SmartList<LookupElement>(); for (LookupElement shorterElement : myElements.get(prefix)) { if (srcSet.contains(shorterElement) && processed.add(shorterElement)) { shorter.add(shorterElement); } } lifted.addAll(shorter); final Iterable<List<LookupElement>> shorterClassified = myNext.classify(shorter); if (group.isEmpty()) { ContainerUtil.addAll(result, shorterClassified); } else { group.addAll(ContainerUtil.flatten(shorterClassified)); } } group.add(element); } } result.add(group); } return result; } private String[] getSortedPrefixes(LookupElement element) { final List<String> prefixes = new SmartList<String>(); for (String string : getAllLookupStrings(element)) { prefixes.addAll(myPrefixes.get(string)); } String[] result = prefixes.toArray(new String[prefixes.size()]); Arrays.sort(result); return result; } private static Set<String> getAllLookupStrings(LookupElement element) { return element.getAllLookupStrings(); } @Override public void describeItems(LinkedHashMap<LookupElement, StringBuilder> map) { final HashSet<LookupElement> lifted = new HashSet<LookupElement>(); liftShorterElements(new ArrayList<LookupElement>(map.keySet()), lifted); if (!lifted.isEmpty()) { for (LookupElement element : map.keySet()) { final StringBuilder builder = map.get(element); if (builder.length() > 0) { builder.append(", "); } builder.append("liftShorter=").append(lifted.contains(element)); } } myNext.describeItems(map); } }
platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.completion.impl; import com.intellij.codeInsight.lookup.Classifier; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import java.util.*; /** * @author peter */ class LiftShorterItemsClassifier extends Classifier<LookupElement> { private final TreeSet<String> mySortedStrings; private final MultiMap<String, LookupElement> myElements; private final MultiMap<String, String> myPrefixes; private final Classifier<LookupElement> myNext; public LiftShorterItemsClassifier(Classifier<LookupElement> next) { myNext = next; mySortedStrings = new TreeSet<String>(); myElements = new MultiMap<String, LookupElement>(); myPrefixes = new MultiMap<String, String>(); } @Override public void addElement(LookupElement element) { final Set<String> strings = getAllLookupStrings(element); for (String string : strings) { if (string.length() == 0) continue; myElements.putValue(string, element); mySortedStrings.add(string); final NavigableSet<String> after = mySortedStrings.tailSet(string, false); for (String s : after) { if (!s.startsWith(string)) { break; } myPrefixes.putValue(s, string); } final char first = string.charAt(0); final SortedSet<String> before = mySortedStrings.descendingSet().tailSet(string, false); for (String s : before) { if (s.charAt(0) != first) { break; } if (string.startsWith(s)) { myPrefixes.putValue(string, s); } } } myNext.addElement(element); } @Override public Iterable<List<LookupElement>> classify(List<LookupElement> source) { return liftShorterElements(source, new HashSet<LookupElement>()); } private Iterable<List<LookupElement>> liftShorterElements(List<LookupElement> source, Set<LookupElement> lifted) { final Set<LookupElement> srcSet = new THashSet<LookupElement>(source, TObjectHashingStrategy.IDENTITY); final Iterable<List<LookupElement>> classified = myNext.classify(source); final Set<LookupElement> processed = new HashSet<LookupElement>(); final ArrayList<List<LookupElement>> result = new ArrayList<List<LookupElement>>(); for (List<LookupElement> list : classified) { final ArrayList<LookupElement> group = new ArrayList<LookupElement>(); for (LookupElement element : list) { assert srcSet.contains(element) : myNext; if (processed.add(element)) { final List<String> prefixes = new SmartList<String>(); for (String string : getAllLookupStrings(element)) { prefixes.addAll(myPrefixes.get(string)); } Collections.sort(prefixes); for (String prefix : prefixes) { List<LookupElement> shorter = new SmartList<LookupElement>(); for (LookupElement shorterElement : myElements.get(prefix)) { if (srcSet.contains(shorterElement) && processed.add(shorterElement)) { shorter.add(shorterElement); } } lifted.addAll(shorter); final Iterable<List<LookupElement>> shorterClassified = myNext.classify(shorter); if (group.isEmpty()) { ContainerUtil.addAll(result, shorterClassified); } else { group.addAll(ContainerUtil.flatten(shorterClassified)); } } group.add(element); } } result.add(group); } return result; } private static Set<String> getAllLookupStrings(LookupElement element) { return element.getAllLookupStrings(); /*boolean empty = element.getPrefixMatcher().getPrefix().isEmpty(); HashSet<String> result = new HashSet<String>(); for (String s : element.getAllLookupStrings()) { result.add(empty ? s : StringUtil.toLowerCase(s)); } return result;*/ } @Override public void describeItems(LinkedHashMap<LookupElement, StringBuilder> map) { final HashSet<LookupElement> lifted = new HashSet<LookupElement>(); liftShorterElements(new ArrayList<LookupElement>(map.keySet()), lifted); if (!lifted.isEmpty()) { for (LookupElement element : map.keySet()) { final StringBuilder builder = map.get(element); if (builder.length() > 0) { builder.append(", "); } builder.append("liftShorter=").append(lifted.contains(element)); } } myNext.describeItems(map); } }
workaround Collections.sort bug on Apache Harmony (EA-30430)
platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java
workaround Collections.sort bug on Apache Harmony (EA-30430)
Java
apache-2.0
5d7a8f2692f0d2f0ddf264e5f13a2de63e4ebb5d
0
catholicon/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,rombert/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,mduerig/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,mduerig/jackrabbit-oak,joansmith/jackrabbit-oak,afilimonov/jackrabbit-oak,francescomari/jackrabbit-oak,rombert/jackrabbit-oak,catholicon/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,davidegiannella/jackrabbit-oak,alexkli/jackrabbit-oak,davidegiannella/jackrabbit-oak,code-distillery/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,chetanmeh/jackrabbit-oak,stillalex/jackrabbit-oak,leftouterjoin/jackrabbit-oak,kwin/jackrabbit-oak,tripodsan/jackrabbit-oak,mduerig/jackrabbit-oak,joansmith/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,bdelacretaz/jackrabbit-oak,ieb/jackrabbit-oak,alexkli/jackrabbit-oak,chetanmeh/jackrabbit-oak,tripodsan/jackrabbit-oak,alexparvulescu/jackrabbit-oak,tripodsan/jackrabbit-oak,davidegiannella/jackrabbit-oak,chetanmeh/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,bdelacretaz/jackrabbit-oak,anchela/jackrabbit-oak,joansmith/jackrabbit-oak,davidegiannella/jackrabbit-oak,yesil/jackrabbit-oak,kwin/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,ieb/jackrabbit-oak,afilimonov/jackrabbit-oak,code-distillery/jackrabbit-oak,rombert/jackrabbit-oak,leftouterjoin/jackrabbit-oak,anchela/jackrabbit-oak,code-distillery/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,ieb/jackrabbit-oak,alexparvulescu/jackrabbit-oak,meggermo/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,yesil/jackrabbit-oak,mduerig/jackrabbit-oak,tripodsan/jackrabbit-oak,meggermo/jackrabbit-oak,meggermo/jackrabbit-oak,kwin/jackrabbit-oak,stillalex/jackrabbit-oak,joansmith/jackrabbit-oak,bdelacretaz/jackrabbit-oak,afilimonov/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,catholicon/jackrabbit-oak,stillalex/jackrabbit-oak,joansmith/jackrabbit-oak,kwin/jackrabbit-oak,francescomari/jackrabbit-oak,rombert/jackrabbit-oak,ieb/jackrabbit-oak,catholicon/jackrabbit-oak,leftouterjoin/jackrabbit-oak,leftouterjoin/jackrabbit-oak,afilimonov/jackrabbit-oak,yesil/jackrabbit-oak,bdelacretaz/jackrabbit-oak,kwin/jackrabbit-oak,francescomari/jackrabbit-oak,davidegiannella/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.run; import java.io.File; import java.io.InputStream; import java.util.Properties; import java.util.UUID; import javax.jcr.Repository; import org.apache.jackrabbit.core.RepositoryContext; import org.apache.jackrabbit.core.config.RepositoryConfig; import org.apache.jackrabbit.mk.api.MicroKernel; import org.apache.jackrabbit.mk.core.MicroKernelImpl; import org.apache.jackrabbit.oak.Oak; import org.apache.jackrabbit.oak.api.ContentRepository; import org.apache.jackrabbit.oak.benchmark.BenchmarkRunner; import org.apache.jackrabbit.oak.http.OakServlet; import org.apache.jackrabbit.oak.jcr.Jcr; import org.apache.jackrabbit.oak.kernel.KernelNodeStore; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore; import org.apache.jackrabbit.oak.plugins.segment.file.FileStore; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.upgrade.RepositoryUpgrade; import org.apache.jackrabbit.webdav.jcr.JCRWebdavServerServlet; import org.apache.jackrabbit.webdav.server.AbstractWebdavServlet; import org.apache.jackrabbit.webdav.simple.SimpleWebdavServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; public class Main { public static final int PORT = 8080; public static final String URI = "http://localhost:" + PORT + "/"; private Main() { } public static void main(String[] args) throws Exception { printProductInfo(); String command = "server"; if (args.length > 0) { command = args[0]; String[] tail = new String[args.length - 1]; System.arraycopy(args, 1, tail, 0, tail.length); args = tail; } if ("mk".equals(command)) { MicroKernelServer.main(args); } else if ("benchmark".equals(command)){ BenchmarkRunner.main(args); } else if ("server".equals(command)){ new HttpServer(URI, args); } else if ("upgrade".equals(command)) { if (args.length == 2) { upgrade(args[0], args[1]); } else { System.err.println("usage: upgrade <olddir> <newdir>"); System.exit(1); } } else if ("inspect".equals(command)) { if (args.length == 0) { System.err.println("usage: inspect <path> [uuid...]"); System.exit(1); } else { File file = new File(args[0]); FileStore store = new FileStore(file, 256 * 1024 * 1024, false); try { for (int i = 1; i < args.length; i++) { UUID uuid = UUID.fromString(args[i]); System.out.println(store.readSegment(uuid)); } } finally { store.close(); } } } else { System.err.println("Unknown command: " + command); System.exit(1); } } private static void upgrade(String olddir, String newdir) throws Exception { RepositoryContext source = RepositoryContext.create( RepositoryConfig.create(new File(olddir))); NodeStore target = new SegmentNodeStore(new FileStore( new File(newdir), 256 * 1024 * 1024, false)); new RepositoryUpgrade(source, target).copy(); source.getRepository().shutdown(); } private static void printProductInfo() { String version = null; try { InputStream stream = Main.class .getResourceAsStream("/META-INF/maven/org.apache.jackrabbit/oak-run/pom.properties"); if (stream != null) { try { Properties properties = new Properties(); properties.load(stream); version = properties.getProperty("version"); } finally { stream.close(); } } } catch (Exception ignore) { } String product; if (version != null) { product = "Apache Jackrabbit Oak " + version; } else { product = "Apache Jackrabbit Oak"; } System.out.println(product); } public static class HttpServer { private final ServletContextHandler context; private final Server server; private final MicroKernel[] kernels; public HttpServer(String uri, String[] args) throws Exception { int port = java.net.URI.create(uri).getPort(); if (port == -1) { // use default port = PORT; } context = new ServletContextHandler(); context.setContextPath("/"); if (args.length == 0) { System.out.println("Starting an in-memory repository"); System.out.println(uri + " -> [memory]"); kernels = new MicroKernel[] { new MicroKernelImpl() }; addServlets(new KernelNodeStore(kernels[0]), ""); } else if (args.length == 1) { System.out.println("Starting a standalone repository"); System.out.println(uri + " -> " + args[0]); kernels = new MicroKernel[] { new MicroKernelImpl(args[0]) }; addServlets(new KernelNodeStore(kernels[0]), ""); } else { System.out.println("Starting a clustered repository"); kernels = new MicroKernel[args.length]; for (int i = 0; i < args.length; i++) { // FIXME: Use a clustered MicroKernel implementation System.out.println(uri + "/node" + i + "/ -> " + args[i]); kernels[i] = new MicroKernelImpl(args[i]); addServlets(new KernelNodeStore(kernels[i]), "/node" + i); } } server = new Server(port); server.setHandler(context); server.start(); } public void join() throws Exception { server.join(); } public void stop() throws Exception { server.stop(); } private void addServlets(NodeStore store, String path) { Oak oak = new Oak(store); Jcr jcr = new Jcr(oak); ContentRepository repository = oak.createContentRepository(); ServletHolder holder = new ServletHolder(new OakServlet(repository)); context.addServlet(holder, path + "/*"); final Repository jcrRepository = jcr.createRepository(); ServletHolder webdav = new ServletHolder(new SimpleWebdavServlet() { @Override public Repository getRepository() { return jcrRepository; } }); webdav.setInitParameter( SimpleWebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path + "/webdav"); webdav.setInitParameter( AbstractWebdavServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Basic realm=\"Oak\""); context.addServlet(webdav, path + "/webdav/*"); ServletHolder davex = new ServletHolder(new JCRWebdavServerServlet() { @Override protected Repository getRepository() { return jcrRepository; } }); davex.setInitParameter( JCRWebdavServerServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path + "/davex"); webdav.setInitParameter( AbstractWebdavServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Basic realm=\"Oak\""); context.addServlet(davex, path + "/davex/*"); } } }
oak-run/src/main/java/org/apache/jackrabbit/oak/run/Main.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.run; import java.io.File; import java.io.InputStream; import java.util.Properties; import javax.jcr.Repository; import org.apache.jackrabbit.core.RepositoryContext; import org.apache.jackrabbit.core.config.RepositoryConfig; import org.apache.jackrabbit.mk.api.MicroKernel; import org.apache.jackrabbit.mk.core.MicroKernelImpl; import org.apache.jackrabbit.oak.Oak; import org.apache.jackrabbit.oak.api.ContentRepository; import org.apache.jackrabbit.oak.benchmark.BenchmarkRunner; import org.apache.jackrabbit.oak.http.OakServlet; import org.apache.jackrabbit.oak.jcr.Jcr; import org.apache.jackrabbit.oak.kernel.KernelNodeStore; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore; import org.apache.jackrabbit.oak.plugins.segment.file.FileStore; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.upgrade.RepositoryUpgrade; import org.apache.jackrabbit.webdav.jcr.JCRWebdavServerServlet; import org.apache.jackrabbit.webdav.server.AbstractWebdavServlet; import org.apache.jackrabbit.webdav.simple.SimpleWebdavServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; public class Main { public static final int PORT = 8080; public static final String URI = "http://localhost:" + PORT + "/"; private Main() { } public static void main(String[] args) throws Exception { printProductInfo(); String command = "server"; if (args.length > 0) { command = args[0]; String[] tail = new String[args.length - 1]; System.arraycopy(args, 1, tail, 0, tail.length); args = tail; } if ("mk".equals(command)) { MicroKernelServer.main(args); } else if ("benchmark".equals(command)){ BenchmarkRunner.main(args); } else if ("server".equals(command)){ new HttpServer(URI, args); } else if ("upgrade".equals(command)) { if (args.length == 2) { upgrade(args[0], args[1]); } else { System.err.println("usage: upgrade <olddir> <newdir>"); System.exit(1); } } else { System.err.println("Unknown command: " + command); System.exit(1); } } private static void upgrade(String olddir, String newdir) throws Exception { RepositoryContext source = RepositoryContext.create( RepositoryConfig.create(new File(olddir))); NodeStore target = new SegmentNodeStore(new FileStore( new File(newdir), 256 * 1024 * 1024, false)); new RepositoryUpgrade(source, target).copy(); source.getRepository().shutdown(); } private static void printProductInfo() { String version = null; try { InputStream stream = Main.class .getResourceAsStream("/META-INF/maven/org.apache.jackrabbit/oak-run/pom.properties"); if (stream != null) { try { Properties properties = new Properties(); properties.load(stream); version = properties.getProperty("version"); } finally { stream.close(); } } } catch (Exception ignore) { } String product; if (version != null) { product = "Apache Jackrabbit Oak " + version; } else { product = "Apache Jackrabbit Oak"; } System.out.println(product); } public static class HttpServer { private final ServletContextHandler context; private final Server server; private final MicroKernel[] kernels; public HttpServer(String uri, String[] args) throws Exception { int port = java.net.URI.create(uri).getPort(); if (port == -1) { // use default port = PORT; } context = new ServletContextHandler(); context.setContextPath("/"); if (args.length == 0) { System.out.println("Starting an in-memory repository"); System.out.println(uri + " -> [memory]"); kernels = new MicroKernel[] { new MicroKernelImpl() }; addServlets(new KernelNodeStore(kernels[0]), ""); } else if (args.length == 1) { System.out.println("Starting a standalone repository"); System.out.println(uri + " -> " + args[0]); kernels = new MicroKernel[] { new MicroKernelImpl(args[0]) }; addServlets(new KernelNodeStore(kernels[0]), ""); } else { System.out.println("Starting a clustered repository"); kernels = new MicroKernel[args.length]; for (int i = 0; i < args.length; i++) { // FIXME: Use a clustered MicroKernel implementation System.out.println(uri + "/node" + i + "/ -> " + args[i]); kernels[i] = new MicroKernelImpl(args[i]); addServlets(new KernelNodeStore(kernels[i]), "/node" + i); } } server = new Server(port); server.setHandler(context); server.start(); } public void join() throws Exception { server.join(); } public void stop() throws Exception { server.stop(); } private void addServlets(NodeStore store, String path) { Oak oak = new Oak(store); Jcr jcr = new Jcr(oak); ContentRepository repository = oak.createContentRepository(); ServletHolder holder = new ServletHolder(new OakServlet(repository)); context.addServlet(holder, path + "/*"); final Repository jcrRepository = jcr.createRepository(); ServletHolder webdav = new ServletHolder(new SimpleWebdavServlet() { @Override public Repository getRepository() { return jcrRepository; } }); webdav.setInitParameter( SimpleWebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path + "/webdav"); webdav.setInitParameter( AbstractWebdavServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Basic realm=\"Oak\""); context.addServlet(webdav, path + "/webdav/*"); ServletHolder davex = new ServletHolder(new JCRWebdavServerServlet() { @Override protected Repository getRepository() { return jcrRepository; } }); davex.setInitParameter( JCRWebdavServerServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path + "/davex"); webdav.setInitParameter( AbstractWebdavServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Basic realm=\"Oak\""); context.addServlet(davex, path + "/davex/*"); } } }
OAK-1152: SegmentMK: Improved debuggability Add an "inspect" mode to oak-run, for inspecting TarMK contents git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1539825 13f79535-47bb-0310-9956-ffa450edef68
oak-run/src/main/java/org/apache/jackrabbit/oak/run/Main.java
OAK-1152: SegmentMK: Improved debuggability
Java
apache-2.0
03b0cc847990d679a8f9f45686ed88c81cadd780
0
diffplug/durian-rx,diffplug/durian-rx
/* * Copyright 2016 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.rx; import java.util.List; import java.util.function.BiPredicate; import rx.Observable; import com.diffplug.common.base.DurianPlugins; import com.diffplug.common.base.Errors; import com.diffplug.common.debug.StackDumper; import com.diffplug.common.util.concurrent.ListenableFuture; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Plugin which gets notified of every call to {@link Rx#subscribe Rx.subscribe}, allowing various kinds of tracing. * <p> * By default, no tracing is done. To enable tracing, do one of the following: * <ul> * <li>Execute this at the very beginning of your application: {@code DurianPlugins.set(RxTracingPolicy.class, new MyTracingPolicy());}</li> * <li>Set this system property: {@code durian.plugins.com.diffplug.common.rx.RxTracingPolicy=fully.qualified.name.to.MyTracingPolicy}</li> * </ul> * {@link LogSubscriptionTrace} is a useful tracing policy for debugging errors within callbacks. * @see DurianPlugins */ public interface RxTracingPolicy { /** * Given an observable, and an {@link Rx} which is about to be subscribed to this observable, * return a (possibly instrumented) {@code Rx}. * * @param observable The {@link IObservable}, {@link Observable}, or {@link ListenableFuture} which is about to be subscribed to. * @param listener The {@link Rx} which is about to be subscribed. * @return An {@link Rx} which may (or may not) be instrumented. To ensure that the program's behavior * is not changed, implementors should ensure that all method calls are delegated unchanged to the original listener eventually. */ <T> Rx<T> hook(Object observable, Rx<T> listener); /** An {@code RxTracingPolicy} which performs no tracing, and has very low overhead. */ public static final RxTracingPolicy NONE = new RxTracingPolicy() { @Override public <T> Rx<T> hook(Object observable, Rx<T> listener) { return listener; } }; /** * An {@link RxTracingPolicy} which logs the stack trace of every subscription, so * that it can decorate any exceptions with the stack trace at the time they were subscribed. * <p> * This logging is fairly expensive, so you might want to set the {@link LogSubscriptionTrace#shouldLog} field, * which determines whether a subscription is logged or passed along untouched. * <p> * By default every {@link Rx#onValue} listener will be logged, but nothing else. * <p> * To enable this tracing policy, do one of the following: * <ul> * <li>Execute this at the very beginning of your application: {@code DurianPlugins.set(RxTracingPolicy.class, new LogSubscriptionTrace());}</li> * <li>Set this system property: {@code durian.plugins.com.diffplug.common.rx.RxTracingPolicy=com.diffplug.common.rx.RxTracingPolicy$LogSubscriptionTrace}</li> * </ul> * @see <a href="https://github.com/diffplug/durian-rx/blob/master/src/com/diffplug/common/rx/RxTracingPolicy.java?ts=4">LogSubscriptionTrace source code</a> * @see DurianPlugins */ public static class LogSubscriptionTrace implements RxTracingPolicy { /** The BiPredicate which determines which subscriptions should be logged. By default, any Rx which is logging will be logged. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "This is public on purpose, and is only functional in a debug mode.") public static BiPredicate<Object, Rx<?>> shouldLog = (observable, listener) -> listener.isLogging(); @Override public <T> Rx<T> hook(Object observable, Rx<T> listener) { if (!shouldLog.test(observable, listener)) { // we're not logging, so pass the listener unchanged return listener; } else { // capture the stack at the time of the subscription List<StackTraceElement> subscriptionTrace = StackDumper.captureStackBelow(LogSubscriptionTrace.class, Rx.RxExecutor.class, Rx.class); // create a new Rx which passes values unchanged, but instruments exceptions with the subscription stack return Rx.onValueOnTerminate(listener::onNext, error -> { if (error.isPresent()) { // if there is an error, wrap it in a SubscriptionException and log it SubscriptionException subException = new SubscriptionException(error.get(), subscriptionTrace); Errors.log().accept(subException); // if the original listener was just logging exceptions, there's no need to notify it, as this would be a double-log if (!listener.isLogging()) { // the listener isn't a simple logger, so we should pass the original exception // to ensure that our logging doesn't change the program's behavior listener.onError(error.get()); } } else { // pass clean terminations unchanged listener.onCompleted(); } }); } } /** An Exception which has the stack trace of the Rx.subscription() call which created the subscription in which the cause was thrown. */ static class SubscriptionException extends Exception { private static final long serialVersionUID = -265762944158637711L; public SubscriptionException(Throwable cause, List<StackTraceElement> stack) { super(cause); setStackTrace(stack.toArray(new StackTraceElement[stack.size()])); } } } }
src/com/diffplug/common/rx/RxTracingPolicy.java
/* * Copyright 2016 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.rx; import java.util.List; import java.util.function.BiPredicate; import rx.Observable; import com.diffplug.common.base.DurianPlugins; import com.diffplug.common.base.Errors; import com.diffplug.common.base.StackDumper; import com.diffplug.common.util.concurrent.ListenableFuture; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Plugin which gets notified of every call to {@link Rx#subscribe Rx.subscribe}, allowing various kinds of tracing. * <p> * By default, no tracing is done. To enable tracing, do one of the following: * <ul> * <li>Execute this at the very beginning of your application: {@code DurianPlugins.set(RxTracingPolicy.class, new MyTracingPolicy());}</li> * <li>Set this system property: {@code durian.plugins.com.diffplug.common.rx.RxTracingPolicy=fully.qualified.name.to.MyTracingPolicy}</li> * </ul> * {@link LogSubscriptionTrace} is a useful tracing policy for debugging errors within callbacks. * @see DurianPlugins */ public interface RxTracingPolicy { /** * Given an observable, and an {@link Rx} which is about to be subscribed to this observable, * return a (possibly instrumented) {@code Rx}. * * @param observable The {@link IObservable}, {@link Observable}, or {@link ListenableFuture} which is about to be subscribed to. * @param listener The {@link Rx} which is about to be subscribed. * @return An {@link Rx} which may (or may not) be instrumented. To ensure that the program's behavior * is not changed, implementors should ensure that all method calls are delegated unchanged to the original listener eventually. */ <T> Rx<T> hook(Object observable, Rx<T> listener); /** An {@code RxTracingPolicy} which performs no tracing, and has very low overhead. */ public static final RxTracingPolicy NONE = new RxTracingPolicy() { @Override public <T> Rx<T> hook(Object observable, Rx<T> listener) { return listener; } }; /** * An {@link RxTracingPolicy} which logs the stack trace of every subscription, so * that it can decorate any exceptions with the stack trace at the time they were subscribed. * <p> * This logging is fairly expensive, so you might want to set the {@link LogSubscriptionTrace#shouldLog} field, * which determines whether a subscription is logged or passed along untouched. * <p> * By default every {@link Rx#onValue} listener will be logged, but nothing else. * <p> * To enable this tracing policy, do one of the following: * <ul> * <li>Execute this at the very beginning of your application: {@code DurianPlugins.set(RxTracingPolicy.class, new LogSubscriptionTrace());}</li> * <li>Set this system property: {@code durian.plugins.com.diffplug.common.rx.RxTracingPolicy=com.diffplug.common.rx.RxTracingPolicy$LogSubscriptionTrace}</li> * </ul> * @see <a href="https://github.com/diffplug/durian-rx/blob/master/src/com/diffplug/common/rx/RxTracingPolicy.java?ts=4">LogSubscriptionTrace source code</a> * @see DurianPlugins */ public static class LogSubscriptionTrace implements RxTracingPolicy { /** The BiPredicate which determines which subscriptions should be logged. By default, any Rx which is logging will be logged. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "This is public on purpose, and is only functional in a debug mode.") public static BiPredicate<Object, Rx<?>> shouldLog = (observable, listener) -> listener.isLogging(); @Override public <T> Rx<T> hook(Object observable, Rx<T> listener) { if (!shouldLog.test(observable, listener)) { // we're not logging, so pass the listener unchanged return listener; } else { // capture the stack at the time of the subscription List<StackTraceElement> subscriptionTrace = StackDumper.captureStackBelow(LogSubscriptionTrace.class, Rx.RxExecutor.class, Rx.class); // create a new Rx which passes values unchanged, but instruments exceptions with the subscription stack return Rx.onValueOnTerminate(listener::onNext, error -> { if (error.isPresent()) { // if there is an error, wrap it in a SubscriptionException and log it SubscriptionException subException = new SubscriptionException(error.get(), subscriptionTrace); Errors.log().accept(subException); // if the original listener was just logging exceptions, there's no need to notify it, as this would be a double-log if (!listener.isLogging()) { // the listener isn't a simple logger, so we should pass the original exception // to ensure that our logging doesn't change the program's behavior listener.onError(error.get()); } } else { // pass clean terminations unchanged listener.onCompleted(); } }); } } /** An Exception which has the stack trace of the Rx.subscription() call which created the subscription in which the cause was thrown. */ static class SubscriptionException extends Exception { private static final long serialVersionUID = -265762944158637711L; public SubscriptionException(Throwable cause, List<StackTraceElement> stack) { super(cause); setStackTrace(stack.toArray(new StackTraceElement[stack.size()])); } } } }
Moved StackDumper to durian-debug from durian-base.
src/com/diffplug/common/rx/RxTracingPolicy.java
Moved StackDumper to durian-debug from durian-base.
Java
apache-2.0
b71ba9ac275207e12dc98fed0c0f62c32fd2db09
0
LifengWang/ReportGen,LifengWang/ReportGen,LifengWang/ReportGen
package com.intel.alex.Utils; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.*; import jxl.write.Number; import java.io.*; /** * Created by root on 3/7/16. */ public class ExcelUtil { private final String logDir; public ExcelUtil(String logDir) { this.logDir = logDir; } public void createExcel() { File excFile = new File("BigBenchTimes.xls"); if (createRawDataSheet(excFile)) { createPhaseSheet(excFile); createPowerSheet(excFile); createThroughputSheet(excFile); } } private boolean createRawDataSheet(File excFile) { try { WritableWorkbook book;// book = Workbook.createWorkbook(excFile);// int num = book.getNumberOfSheets(); WritableSheet sheet = book.createSheet("BigBenchTimes", num); FileReader fileReader = new FileReader(new File(logDir + "/run-logs/BigBenchTimes.csv")); BufferedReader br = new BufferedReader(fileReader); int i = 0; String line; while ((line = br.readLine()) != null) { String s[] = line.split(";"); if (s.length > 3) { for (int j = 0; j < s.length; j++) { if (i == 0) { Label title = new Label(j, i, s[j]); sheet.addCell(title); } else if (j == 0 || j == 2 || j == 3 || j == 4 | j == 5 | j == 8) { if (s[j] != null && !s[j].equals("")) { Number ints = new Number(j, i, Long.parseLong(s[j])); sheet.addCell(ints); } else { Label label = new Label(j, i, s[j]); sheet.addCell(label); } } else if (j == 9) { Number doubles = new Number(j, i, Double.parseDouble(s[j])); sheet.addCell(doubles); } else { Label label = new Label(j, i, s[j]); sheet.addCell(label); } } } i++; } br.close(); fileReader.close(); book.write(); book.close(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } private void createPowerSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("PowerTest", num); Label queryNumber = new Label(0, 0, "QueryNumber"); Label queryTime = new Label(1, 0, "QueryTime(s)"); newSheet.addCell(queryNumber); newSheet.addCell(queryTime); int i = 1; for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(1, r).getContents().equals("POWER_TEST") && !sheet.getCell(3, r).getContents().equals("")) { Number ints = new Number(0, i, Integer.parseInt(sheet.getCell(3, r).getContents())); newSheet.addCell(ints); Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); i++; } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } private void createThroughputSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("Throughput", num); Label queryNumber = new Label(0, 0, "QueryNumber"); newSheet.addCell(queryNumber); for(int i =1 ; i<=30;i++){ Number queries = new Number(0, i, i); newSheet.addCell(queries); } for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(1, r).getContents().equals("THROUGHPUT_TEST_1") && !sheet.getCell(3, r).getContents().equals("")) { int stream = Integer.parseInt(sheet.getCell(2, r).getContents()); Label streamNumber = new Label(stream + 1, 0, "Stream" + stream); newSheet.addCell(streamNumber); Number doubles = new Number(stream + 1, Integer.parseInt(sheet.getCell(3, r).getContents()), Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } private void createPhaseSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("PhaseTime", num); Label queryNumber = new Label(0, 0, "Phase"); Label queryTime = new Label(1, 0, "ElapsedTimes(s)"); newSheet.addCell(queryNumber); newSheet.addCell(queryTime); int i = 1; for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(2, r).getContents().equals("")) { Label phase = new Label(0, i, (sheet.getCell(1, r).getContents())); newSheet.addCell(phase); Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); i++; } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } }
src/main/java/com/intel/alex/Utils/ExcelUtil.java
package com.intel.alex.Utils; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.*; import jxl.write.Number; import java.io.*; /** * Created by root on 3/7/16. */ public class ExcelUtil { private final String logDir; public ExcelUtil(String logDir) { this.logDir = logDir; } public void createExcel() { File excFile = new File("/home/BigBenchTimes.xls"); if (createRawDataSheet(excFile)) { createPhaseSheet(excFile); createPowerSheet(excFile); createThroughputSheet(excFile); } } private boolean createRawDataSheet(File excFile) { try { WritableWorkbook book;// book = Workbook.createWorkbook(excFile);// int num = book.getNumberOfSheets(); WritableSheet sheet = book.createSheet("BigBenchTimes", num); FileReader fileReader = new FileReader(new File(logDir + "/run-logs/BigBenchTimes.csv")); BufferedReader br = new BufferedReader(fileReader); int i = 0; String line; while ((line = br.readLine()) != null) { String s[] = line.split(";"); if (s.length > 3) { for (int j = 0; j < s.length; j++) { if (i == 0) { Label title = new Label(j, i, s[j]); sheet.addCell(title); } else if (j == 0 || j == 2 || j == 3 || j == 4 | j == 5 | j == 8) { if (s[j] != null && !s[j].equals("")) { Number ints = new Number(j, i, Long.parseLong(s[j])); sheet.addCell(ints); } else { Label label = new Label(j, i, s[j]); sheet.addCell(label); } } else if (j == 9) { Number doubles = new Number(j, i, Double.parseDouble(s[j])); sheet.addCell(doubles); } else { Label label = new Label(j, i, s[j]); sheet.addCell(label); } } } i++; } br.close(); fileReader.close(); book.write(); book.close(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } private void createPowerSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("PowerTest", num); Label queryNumber = new Label(0, 0, "QueryNumber"); Label queryTime = new Label(1, 0, "QueryTime(s)"); newSheet.addCell(queryNumber); newSheet.addCell(queryTime); int i = 1; for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(1, r).getContents().equals("POWER_TEST") && !sheet.getCell(3, r).getContents().equals("")) { Number ints = new Number(0, i, Integer.parseInt(sheet.getCell(3, r).getContents())); newSheet.addCell(ints); Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); i++; } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } private void createThroughputSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("Throughput", num); Label queryNumber = new Label(0, 0, "QueryNumber"); newSheet.addCell(queryNumber); for(int i =1 ; i<=30;i++){ Number queries = new Number(0, i, i); newSheet.addCell(queries); } for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(1, r).getContents().equals("THROUGHPUT_TEST_1") && !sheet.getCell(3, r).getContents().equals("")) { int stream = Integer.parseInt(sheet.getCell(2, r).getContents()); Label streamNumber = new Label(stream + 1, 0, "Stream" + stream); newSheet.addCell(streamNumber); Number doubles = new Number(stream + 1, Integer.parseInt(sheet.getCell(3, r).getContents()), Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } private void createPhaseSheet(File excFile) { try { FileInputStream fin = new FileInputStream(excFile); Workbook wb = Workbook.getWorkbook(fin); WritableWorkbook wwb = Workbook.createWorkbook(excFile, wb); int num = wwb.getNumberOfSheets(); Sheet sheet = wwb.getSheet(0); WritableSheet newSheet = wwb.createSheet("PhaseTime", num); Label queryNumber = new Label(0, 0, "Phase"); Label queryTime = new Label(1, 0, "ElapsedTimes(s)"); newSheet.addCell(queryNumber); newSheet.addCell(queryTime); int i = 1; for (int r = 0; r < sheet.getRows(); r++) { if (sheet.getCell(2, r).getContents().equals("")) { Label phase = new Label(0, i, (sheet.getCell(1, r).getContents())); newSheet.addCell(phase); Number doubles = new Number(1, i, Double.parseDouble(sheet.getCell(9, r).getContents())); newSheet.addCell(doubles); i++; } } wwb.write(); wwb.close(); } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } }
Update ExcelUtil.java to generate excel file to project folder
src/main/java/com/intel/alex/Utils/ExcelUtil.java
Update ExcelUtil.java to generate excel file to project folder
Java
apache-2.0
1c059c101759ca6804e64c1c45e67ed83dabddd9
0
stain/profilechecker
package no.s11.owlapi; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.List; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.profiles.OWL2DLProfile; import org.semanticweb.owlapi.profiles.OWL2ELProfile; import org.semanticweb.owlapi.profiles.OWL2Profile; import org.semanticweb.owlapi.profiles.OWL2QLProfile; import org.semanticweb.owlapi.profiles.OWL2RLProfile; import org.semanticweb.owlapi.profiles.OWLProfile; import org.semanticweb.owlapi.profiles.OWLProfileReport; import org.semanticweb.owlapi.profiles.OWLProfileViolation; public class ProfileChecker { OWLProfile DEFAULT_PROFILE = new OWL2Profile(); List<OWLProfile> PROFILES = Arrays.asList(new OWL2DLProfile(), new OWL2ELProfile(), new OWL2Profile(), new OWL2QLProfile(), new OWL2RLProfile()); OWLOntologyManager m = OWLManager.createOWLOntologyManager(); public static void main(String[] args) throws OWLOntologyCreationException { System.exit(new ProfileChecker().check(args)); } public int check(String[] args) throws OWLOntologyCreationException { if (args.length == 0 || args[0].equals("-h")) { System.out .println("Usage: profilechecker.jar <ontology.owl> [profile]"); System.out.println(); System.out.println("Available profiles:"); for (OWLProfile p : PROFILES) { System.out.print(p.getClass().getSimpleName()); System.out.print(" (" + p.getName() + ")"); if (p.getClass().equals(DEFAULT_PROFILE.getClass())) { System.out.print(" -default-"); } // Can't use p.getName() as it contains spaces System.out.println(); } System.out.println("--all"); return 0; } IRI documentIRI = IRI.create(args[0]); if (!documentIRI.isAbsolute()) { // Assume it's a file documentIRI = IRI.create(new File(args[0])); } OWLOntology o = m.loadOntologyFromOntologyDocument(documentIRI); OWLProfile profile = null; if (args.length > 1) { String profileName = args[1]; for (OWLProfile p : PROFILES) { if (p.getClass().getSimpleName().equals(profileName)) { profile = p; } } if (profile == null && !profileName.equals("--all")) { throw new IllegalArgumentException("Unknown profile: " + profileName); } } else { profile = DEFAULT_PROFILE; } if (profile == null) { boolean anyFailed = false; for (OWLProfile p : PROFILES) { System.out.print(p.getClass().getSimpleName() + ": "); OWLProfileReport report = p.checkOntology(o); if (report.isInProfile()) { System.out.println("OK"); } else { System.out.println(report.getViolations().size() + " violations"); anyFailed = true; } } return anyFailed ? 1 : 0; } else { OWLProfileReport report = profile.checkOntology(o); for (OWLProfileViolation v : report.getViolations()) { System.err.println(v.toString()); } if (!report.isInProfile()) { return 1; } return 0; } } }
src/main/java/no/s11/owlapi/ProfileChecker.java
package no.s11.owlapi; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.List; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.profiles.OWL2DLProfile; import org.semanticweb.owlapi.profiles.OWL2ELProfile; import org.semanticweb.owlapi.profiles.OWL2Profile; import org.semanticweb.owlapi.profiles.OWL2QLProfile; import org.semanticweb.owlapi.profiles.OWL2RLProfile; import org.semanticweb.owlapi.profiles.OWLProfile; import org.semanticweb.owlapi.profiles.OWLProfileReport; import org.semanticweb.owlapi.profiles.OWLProfileViolation; public class ProfileChecker { OWLProfile DEFAULT_PROFILE = new OWL2Profile(); List<OWLProfile> PROFILES = Arrays.asList(new OWL2DLProfile(), new OWL2ELProfile(), new OWL2Profile(), new OWL2QLProfile(), new OWL2RLProfile()); OWLOntologyManager m = OWLManager.createOWLOntologyManager(); public static void main(String[] args) throws OWLOntologyCreationException { System.exit(new ProfileChecker().check(args)); } public int check(String[] args) throws OWLOntologyCreationException { if (args.length == 0 || args[0].equals("-h")) { System.out .println("Usage: profilechecker.jar <ontology.owl> [profile]"); System.out.println(); System.out.println("Available profiles:"); for (OWLProfile p : PROFILES) { System.out.print(p.getClass().getSimpleName()); System.out.print(" (" + p.getName() + ")"); if (p.getClass().equals(DEFAULT_PROFILE.getClass())) { System.out.print(" -default-"); } // Can't use p.getName() as it contains spaces System.out.println(); } System.out.println("--all"); return 0; } IRI documentIRI = IRI.create(args[0]); if (!documentIRI.isAbsolute()) { // Assume it's a file documentIRI = IRI.create(new File(args[0])); } OWLOntology o = m.loadOntologyFromOntologyDocument(documentIRI); OWLProfile profile = null; if (args.length > 1) { String profileName = args[1]; for (OWLProfile p : PROFILES) { if (p.getClass().getSimpleName().equals(profileName)) { profile = p; } } if (profile == null && !profileName.equals("--all")) { throw new IllegalArgumentException("Unknown profile: " + profileName); } } else { profile = DEFAULT_PROFILE; } if (profile == null) { boolean anyFailed = false; for (OWLProfile p : PROFILES) { System.out.print(p.getClass().getSimpleName() + ": "); OWLProfileReport report = p.checkOntology(o); if (report.isInProfile()) { System.out.println("OK"); } else { System.out.println(report.getViolations().size() + " violations"); anyFailed = true; } } return anyFailed ? 1 : 0; } OWLProfileReport report = profile.checkOntology(o); for (OWLProfileViolation v : report.getViolations()) { System.err.println(v); } if (!report.isInProfile()) { return 1; } return 0; } }
syntax fix
src/main/java/no/s11/owlapi/ProfileChecker.java
syntax fix
Java
apache-2.0
99715647b246fa23b7670dc536981c88640ab6db
0
robbertvanginkel/buck,nguyentruongtho/buck,davido/buck,ilya-klyuchnikov/buck,romanoid/buck,vschs007/buck,shs96c/buck,SeleniumHQ/buck,darkforestzero/buck,shybovycha/buck,shs96c/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,rmaz/buck,Addepar/buck,rmaz/buck,Addepar/buck,dsyang/buck,LegNeato/buck,LegNeato/buck,robbertvanginkel/buck,brettwooldridge/buck,zhan-xiong/buck,romanoid/buck,kageiit/buck,shybovycha/buck,JoelMarcey/buck,brettwooldridge/buck,grumpyjames/buck,zhan-xiong/buck,shs96c/buck,SeleniumHQ/buck,vschs007/buck,rmaz/buck,JoelMarcey/buck,shybovycha/buck,SeleniumHQ/buck,vschs007/buck,shs96c/buck,facebook/buck,darkforestzero/buck,shybovycha/buck,brettwooldridge/buck,JoelMarcey/buck,shs96c/buck,kageiit/buck,marcinkwiatkowski/buck,davido/buck,dsyang/buck,romanoid/buck,vschs007/buck,facebook/buck,romanoid/buck,LegNeato/buck,clonetwin26/buck,robbertvanginkel/buck,romanoid/buck,ilya-klyuchnikov/buck,vschs007/buck,JoelMarcey/buck,nguyentruongtho/buck,romanoid/buck,brettwooldridge/buck,vschs007/buck,ilya-klyuchnikov/buck,k21/buck,k21/buck,brettwooldridge/buck,brettwooldridge/buck,dsyang/buck,dsyang/buck,darkforestzero/buck,marcinkwiatkowski/buck,grumpyjames/buck,robbertvanginkel/buck,JoelMarcey/buck,romanoid/buck,ilya-klyuchnikov/buck,facebook/buck,brettwooldridge/buck,grumpyjames/buck,SeleniumHQ/buck,zhan-xiong/buck,nguyentruongtho/buck,robbertvanginkel/buck,rmaz/buck,clonetwin26/buck,dsyang/buck,dsyang/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,rmaz/buck,zhan-xiong/buck,SeleniumHQ/buck,SeleniumHQ/buck,kageiit/buck,Addepar/buck,grumpyjames/buck,Addepar/buck,zpao/buck,kageiit/buck,rmaz/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,rmaz/buck,k21/buck,dsyang/buck,LegNeato/buck,facebook/buck,rmaz/buck,clonetwin26/buck,vschs007/buck,romanoid/buck,nguyentruongtho/buck,robbertvanginkel/buck,vschs007/buck,davido/buck,marcinkwiatkowski/buck,kageiit/buck,darkforestzero/buck,rmaz/buck,dsyang/buck,zpao/buck,zhan-xiong/buck,nguyentruongtho/buck,zhan-xiong/buck,zpao/buck,dsyang/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,shs96c/buck,robbertvanginkel/buck,shs96c/buck,davido/buck,clonetwin26/buck,darkforestzero/buck,ilya-klyuchnikov/buck,shs96c/buck,romanoid/buck,robbertvanginkel/buck,robbertvanginkel/buck,zhan-xiong/buck,clonetwin26/buck,vschs007/buck,zpao/buck,romanoid/buck,marcinkwiatkowski/buck,davido/buck,davido/buck,vschs007/buck,rmaz/buck,zhan-xiong/buck,k21/buck,darkforestzero/buck,vschs007/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,shybovycha/buck,marcinkwiatkowski/buck,SeleniumHQ/buck,clonetwin26/buck,grumpyjames/buck,grumpyjames/buck,SeleniumHQ/buck,darkforestzero/buck,Addepar/buck,darkforestzero/buck,brettwooldridge/buck,SeleniumHQ/buck,marcinkwiatkowski/buck,SeleniumHQ/buck,k21/buck,davido/buck,Addepar/buck,zhan-xiong/buck,Addepar/buck,davido/buck,davido/buck,shybovycha/buck,grumpyjames/buck,marcinkwiatkowski/buck,darkforestzero/buck,shybovycha/buck,davido/buck,clonetwin26/buck,clonetwin26/buck,facebook/buck,zhan-xiong/buck,SeleniumHQ/buck,JoelMarcey/buck,LegNeato/buck,romanoid/buck,clonetwin26/buck,JoelMarcey/buck,clonetwin26/buck,brettwooldridge/buck,kageiit/buck,grumpyjames/buck,k21/buck,davido/buck,brettwooldridge/buck,robbertvanginkel/buck,grumpyjames/buck,shybovycha/buck,LegNeato/buck,clonetwin26/buck,ilya-klyuchnikov/buck,LegNeato/buck,k21/buck,clonetwin26/buck,dsyang/buck,shs96c/buck,zpao/buck,zpao/buck,zhan-xiong/buck,darkforestzero/buck,shybovycha/buck,Addepar/buck,SeleniumHQ/buck,k21/buck,rmaz/buck,vschs007/buck,nguyentruongtho/buck,facebook/buck,dsyang/buck,ilya-klyuchnikov/buck,dsyang/buck,grumpyjames/buck,vschs007/buck,kageiit/buck,k21/buck,LegNeato/buck,grumpyjames/buck,Addepar/buck,JoelMarcey/buck,robbertvanginkel/buck,LegNeato/buck,brettwooldridge/buck,rmaz/buck,brettwooldridge/buck,JoelMarcey/buck,shybovycha/buck,LegNeato/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,JoelMarcey/buck,darkforestzero/buck,SeleniumHQ/buck,Addepar/buck,shs96c/buck,shs96c/buck,grumpyjames/buck,JoelMarcey/buck,Addepar/buck,zhan-xiong/buck,k21/buck,LegNeato/buck,k21/buck,zhan-xiong/buck,k21/buck,Addepar/buck,JoelMarcey/buck,shs96c/buck,marcinkwiatkowski/buck,brettwooldridge/buck,facebook/buck,ilya-klyuchnikov/buck,Addepar/buck,davido/buck,shybovycha/buck,LegNeato/buck,k21/buck,davido/buck,darkforestzero/buck,romanoid/buck,dsyang/buck,LegNeato/buck,shs96c/buck,clonetwin26/buck,zpao/buck,rmaz/buck,darkforestzero/buck,shybovycha/buck,shybovycha/buck,romanoid/buck,JoelMarcey/buck
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java.abi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.MorePaths; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.util.sha1.Sha1HashCode; import com.facebook.buck.zip.Unzip; import com.google.common.base.Joiner; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InnerClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.ParameterNode; import org.objectweb.asm.tree.TypeAnnotationNode; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.function.BiFunction; import java.util.function.Function; import java.util.jar.JarOutputStream; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import javax.annotation.processing.Processor; import javax.lang.model.SourceVersion; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; @RunWith(Parameterized.class) public class StubJarTest { // Test a stub generated by stripping a full jar private static final String MODE_JAR_BASED = "JAR_BASED"; // Test a stub generated from source private static final String MODE_SOURCE_BASED = "SOURCE_BASED"; // Test a stub generated from source, with dependencies missing private static final String MODE_SOURCE_BASED_MISSING_DEPS = "SOURCE_BASED_MISSING_DEPS"; private static final String ANNOTATION_SOURCE = Joiner.on("\n").join(ImmutableList.of( "package com.example.buck;", "import java.lang.annotation.*;", "import static java.lang.annotation.ElementType.*;", "@Retention(RetentionPolicy.RUNTIME)", "@Target(value={CONSTRUCTOR, FIELD, METHOD, PARAMETER, TYPE})", "public @interface Foo {", " int primitiveValue() default 0;", " String[] stringArrayValue() default {\"Hello\"};", " Retention annotationValue() default @Retention(RetentionPolicy.SOURCE);", " Retention[] annotationArrayValue() default {};", " RetentionPolicy enumValue () default RetentionPolicy.CLASS;", " Class typeValue() default Foo.class;", " @Target({TYPE_PARAMETER, TYPE_USE})", " @interface TypeAnnotation { }", "}" )); @Parameterized.Parameter public String testingMode; private Map<String, AbiClass> classNameToOriginal; @Parameterized.Parameters public static Object[] getParameters() { return new Object[]{MODE_JAR_BASED, MODE_SOURCE_BASED, MODE_SOURCE_BASED_MISSING_DEPS}; } private static final ImmutableSortedSet<Path> EMPTY_CLASSPATH = ImmutableSortedSet.of(); @Rule public TemporaryFolder temp = new TemporaryFolder(); private ProjectFilesystem filesystem; @Before public void createTempFilesystem() throws IOException { File out = temp.newFolder(); filesystem = new ProjectFilesystem(out.toPath()); } @Test public void emptyClass() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", "package com.example.buck; public class A {}"); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); // Verify that the stub jar works by compiling some code that depends on A. compileToJar( ImmutableSortedSet.of(paths.stubJar), Collections.emptyList(), "B.java", "package com.example.buck; public class B extends A {}", temp.newFolder()); } @Test public void emptyClassWithAnnotation() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", "package com.example.buck; @Deprecated public class A {}"); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void classWithTwoMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join(ImmutableList.of( "package com.example.buck;", "public class A {", " public String toString() { return null; }", " public void eatCake() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesThrowsClauses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public void throwSomeStuff() throws Exception, Throwable {}", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesThrowsClausesWithTypeVars() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.io.IOException;", "public class A {", " public <E extends IOException> void throwSomeStuff() throws E {}", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void genericClassSignaturesShouldBePreserved() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T get(String key) { return null; }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void elementsInStubCorrectlyInOrder() throws IOException { // Fields and methods should stub in order // Inner classes should stub in reverse JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " boolean first;", " float second;", " public void foo() { }", " public class B { }", " public class C { }", " public void bar() { }", " public class D { }", " int between;", " public class E {", " public void hello() { }", " public void test() { }", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class", "com/example/buck/A$C.class", "com/example/buck/A$D.class", "com/example/buck/A$E.class"); } @Test public void genericInterfaceSignaturesShouldBePreserved() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public interface A<T> {", " T get(String key);", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIgnorePrivateMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " private void privateMethod() {}", " void packageMethod() {}", " protected void protectedMethod() {}", " public void publicMethod() {}", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveAField() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected String protectedField;", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIgnorePrivateFields() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " private String privateField;", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveGenericTypesOnFields() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T theField;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveGenericTypesOnMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T get(String key) { return null; }", " public <X extends Comparable<T>> X compareWith(T other) { return null; }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnMethods() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " @Foo", " public void cheese(String key) {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnFields() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " @Foo", " public String name;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnParameters() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public void peynir(@Foo String very, int tasty) {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInClasses() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<@Foo.TypeAnnotation T> { }"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInMethods() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " <@Foo.TypeAnnotation T> void foo(@Foo.TypeAnnotation String s) { }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInFields() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "import java.util.List;", "public class A {", " List<@Foo.TypeAnnotation String> list;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void omitsAnnotationsWithSourceRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@SourceRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.SOURCE)", "@interface SourceRetentionAnno { }")); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/SourceRetentionAnno.class"); } @Test public void preservesAnnotationsWithClassRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@ClassRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.CLASS)", "@interface ClassRetentionAnno { }")); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/ClassRetentionAnno.class"); } @Test public void preservesAnnotationsWithRuntimeRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@RuntimeRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.RUNTIME)", "@interface RuntimeRetentionAnno { }")); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/RuntimeRetentionAnno.class"); } @Test public void preservesAnnotationsWithPrimitiveValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(primitiveValue=1)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithStringArrayValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(stringArrayValue={\"1\", \"2\"})", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithEnumValues() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Retention(RetentionPolicy.RUNTIME)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithTypeValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(typeValue=String.class)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithEnumArrayValues() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Target({ElementType.CONSTRUCTOR, ElementType.FIELD})", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithAnnotationValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Foo(annotationValue=@Retention(RetentionPolicy.RUNTIME))", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithAnnotationArrayValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Foo(annotationArrayValue=@Retention(RetentionPolicy.RUNTIME))", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithDefaultValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo()", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationPrimitiveDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly( paths, "com/example/buck/Foo.class", "com/example/buck/Foo$TypeAnnotation.class"); } @Test public void preservesAnnotationArrayDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly( paths, "com/example/buck/Foo.class", "com/example/buck/Foo$TypeAnnotation.class"); } @Test public void preservesAnnotationAnnotationDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly( paths, "com/example/buck/Foo.class", "com/example/buck/Foo$TypeAnnotation.class"); } @Test public void preservesAnnotationEnumDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly( paths, "com/example/buck/Foo.class", "com/example/buck/Foo$TypeAnnotation.class"); } @Test public void preservesAnnotationTypeDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly( paths, "com/example/buck/Foo.class", "com/example/buck/Foo$TypeAnnotation.class"); } @Test public void stubsEnums() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "public enum A {", " Value1,", " Value2", "}" )); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubsAbstractEnums() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "public enum A {", " Value1 {", " public int get() { return 1; }", " };", " public abstract int get();", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesNotStubbed(paths, "com/example/buck/A$1.class"); } @Test public void stubsInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsProtectedInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsDefaultInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsInnerEnums() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public enum B { Value }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsNestedInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public class B {", " public class C {", " public int count;", " public void foo() {}", " }", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class", "com/example/buck/A$B$C.class"); } @Test public void doesNotStubReferencesToInnerClassesOfOtherTypes() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " B.C field;", "}", "class B {", " public class C { }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/B.class", "com/example/buck/B$C.class"); } @Test public void stubsStaticMemberClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void ignoresAnonymousClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public Runnable r = new Runnable() {", " public void run() { }", " };", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesNotStubbed(paths, "com/example/buck/A$1.class"); } @Test public void ignoresLocalClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public void method() {", " class Local { };", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesNotStubbed(paths, "com/example/buck/A$1Local.class"); } @Test public void preservesThrowsClausesOnInnerClassConstructors() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public class B {", " B() throws Exception, Throwable {", " }", " }", "}" )); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void abiSafeChangesResultInTheSameOutputJar() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"hello\"; }", " Class<?> clazz;", " public int other;", "}" ))); Sha1HashCode originalHash = filesystem.computeSha1(paths.stubJar); paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"merhaba\"; }", " Class<?> clazz = String.class;", " public int other = 32;", "}" ))); Sha1HashCode secondHash = filesystem.computeSha1(paths.stubJar); assertEquals(originalHash, secondHash); } @Test public void ordersChangesResultInADifferentOutputJar() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"hello\"; }", " Class<?> clazz;", " public int other;", "}" ))); Sha1HashCode originalHash = filesystem.computeSha1(paths.stubJar); paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " Class<?> clazz;", " public String getGreeting() { return \"hello\"; }", " protected final static int count = 42;", " public int other;", "}" ))); Sha1HashCode secondHash = filesystem.computeSha1(paths.stubJar); assertNotEquals(originalHash, secondHash); } @Test public void shouldIncludeStaticFields() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static String foo;", " public final static int count = 42;", " protected static void method() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void innerClassesInStubsCanBeCompiledAgainst() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "Outer.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class Outer {", " public class Inner {", " public String getGreeting() { return \"hola\"; }", " }", "}"))); compileToJar( ImmutableSortedSet.of(paths.stubJar), Collections.emptyList(), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck2;", // Note: different package "import com.example.buck.Outer;", // Inner class becomes available "public class A {", " private Outer.Inner field;", // Reference the inner class "}")), temp.newFolder()); } @Test public void shouldPreserveSynchronizedKeywordOnMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public synchronized void doMagic() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldKeepMultipleFieldsWithSameDescValue() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static final A SEVERE = new A();", " public static final A NOT_SEVERE = new A();", " public static final A QUITE_MILD = new A();", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldNotStubClinit() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public static int i = 3;", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubJarIsEquallyAtHomeWalkingADirectoryOfClassFiles() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public String toString() { return null; }", " public void eatCake() {}", "}"))); Path classDir = temp.newFolder().toPath(); Unzip.extractZipFile(paths.fullJar, classDir, Unzip.ExistingFileMode.OVERWRITE); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIncludeBridgeMethods() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join(ImmutableList.of( "package com.example.buck;", "public class A implements Comparable<A> {", " public int compareTo(A other) {", " return 0;", " }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } private JarPaths createFullAndStubJars( ImmutableSortedSet<Path> classPath, String fileName, String source) throws IOException { File outputDir = temp.newFolder(); List<Processor> processors = Collections.emptyList(); StubJarGeneratingProcessor stubJarGenerator = null; if (testingMode != MODE_JAR_BASED) { stubJarGenerator = new StubJarGeneratingProcessor( filesystem, outputDir.toPath().resolve("sourceStub.jar"), SourceVersion.RELEASE_8); processors = Collections.singletonList(stubJarGenerator); } Path fullJar = compileToJar( testingMode != MODE_SOURCE_BASED_MISSING_DEPS ? classPath : Collections.emptySortedSet(), processors, fileName, source, outputDir); Path stubJar; if (stubJarGenerator != null) { stubJar = stubJarGenerator.getStubJarPath(); } else { stubJar = createStubJar(fullJar); } return new JarPaths(fullJar, stubJar); } private Path createStubJar(Path fullJar) throws IOException { Path stubJar = fullJar.getParent().resolve("stub.jar"); new StubJar(fullJar).writeTo(filesystem, stubJar); return stubJar; } private Path compileToJar( SortedSet<Path> classpath, List<Processor> processors, String fileName, String source, File outputDir) throws IOException { File inputs = temp.newFolder(); File file = new File(inputs, fileName); Files.write(file.toPath(), source.getBytes(StandardCharsets.UTF_8)); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> sourceObjects = fileManager.getJavaFileObjectsFromFiles(ImmutableSet.of(file)); List<String> args = Lists.newArrayList("-g", "-d", outputDir.getAbsolutePath()); if (!classpath.isEmpty()) { args.add("-classpath"); args.add(Joiner.on(File.pathSeparator).join(FluentIterable.from(classpath) .transform(filesystem::resolve))); } JavaCompiler.CompilationTask compilation = compiler.getTask(null, fileManager, null, args, null, sourceObjects); compilation.setProcessors(processors); Boolean result = compilation.call(); fileManager.close(); assertNotNull(result); assertTrue(result); File jar = new File(outputDir, "output.jar"); try ( FileOutputStream fos = new FileOutputStream(jar); final JarOutputStream os = new JarOutputStream(fos)) { SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".class")) { ZipEntry entry = new ZipEntry(MorePaths.pathWithUnixSeparators(outputDir.toPath().relativize(file))); os.putNextEntry(entry); ByteStreams.copy(Files.newInputStream(file), os); os.closeEntry(); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(outputDir.toPath(), visitor); } return jar.toPath().toAbsolutePath(); } private AbiClass readClass(Path pathToJar, String className) throws IOException { return AbiClass.extract(filesystem.getPathForRelativePath(pathToJar), className); } private JarPaths createAnnotationFullAndStubJars() throws IOException { return createFullAndStubJars( EMPTY_CLASSPATH, "Foo.java", ANNOTATION_SOURCE); } private Path createAnnotationFullJar() throws IOException { return compileToJar( EMPTY_CLASSPATH, Collections.emptyList(), "Foo.java", ANNOTATION_SOURCE, temp.newFolder()); } private void assertClassesNotStubbed( JarPaths paths, String... classFilePaths) throws IOException { for (String classFilePath : classFilePaths) { AbiClass stubbed = readClass(paths.stubJar, classFilePath); if (stubbed != null) { fail(String.format("Should not have stubbed %s", stubbed.getClassNode().name)); } } } private void assertClassesStubbedCorrectly( JarPaths paths, String... classFilePaths) throws IOException { classNameToOriginal = new HashMap<>(); for (String classFilePath : classFilePaths) { AbiClass original = readClass(paths.fullJar, classFilePath); classNameToOriginal.put(original.getClassNode().name, original); } for (String classFilePath : classFilePaths) { AbiClass original = readClass(paths.fullJar, classFilePath); AbiClass stubbed = readClass(paths.stubJar, classFilePath); assertClassStubbedCorrectly(original, stubbed); } } /** * A class is stubbed correctly if the stub is exactly the same as its full counterpart, with * the following exceptions: * <ul> * <li>No private members, &lt;clinit&gt;, synthetic members, bridge methods, or method bodies * are present</li> * </ul> */ private void assertClassStubbedCorrectly(AbiClass original, AbiClass stubbed) { if (original == null) { if (stubbed != null) { fail(String.format("Should not have stubbed %s", stubbed.getClassNode().name)); } return; } assertNotNull(String.format("Should have stubbed %s", original.getClassNode().name), stubbed); ClassNode originalNode = original.getClassNode(); ClassNode stubbedNode = stubbed.getClassNode(); assertEquals(originalNode.version, stubbedNode.version); assertEquals(originalNode.access, stubbedNode.access); assertEquals(originalNode.name, stubbedNode.name); assertEquals(originalNode.signature, stubbedNode.signature); assertEquals(originalNode.superName, stubbedNode.superName); assertThat(stubbedNode.interfaces, Matchers.equalTo(originalNode.interfaces)); assertNull(stubbedNode.sourceFile); assertNull(stubbedNode.sourceDebug); assertEquals(originalNode.outerClass, stubbedNode.outerClass); assertNull(stubbedNode.outerMethod); assertNull(stubbedNode.outerMethodDesc); assertAnnotationsEqual(originalNode.visibleAnnotations, stubbedNode.visibleAnnotations); assertAnnotationsEqual(originalNode.invisibleAnnotations, stubbedNode.invisibleAnnotations); assertTypeAnnotationsEqual( originalNode.visibleTypeAnnotations, stubbedNode.visibleTypeAnnotations); assertTypeAnnotationsEqual( originalNode.invisibleTypeAnnotations, stubbedNode.invisibleTypeAnnotations); assertEquals(originalNode.attrs, stubbedNode.attrs); assertInnerClassesStubbedCorrectly( originalNode, originalNode.innerClasses, stubbedNode.innerClasses); assertFieldsStubbedCorrectly(originalNode.fields, stubbedNode.fields); assertMethodsStubbedCorrectly(originalNode.methods, stubbedNode.methods); } private void assertInnerClassesStubbedCorrectly( ClassNode originalOuter, List<InnerClassNode> original, List<InnerClassNode> stubbed) { List<InnerClassNode> filteredOriginal = original.stream() .filter(node -> classNameToOriginal.containsKey(node.name) && (node.outerName == originalOuter.name || node.name == originalOuter.name)) .collect(Collectors.toList()); assertMembersStubbedCorrectly( filteredOriginal, stubbed, node -> node.access, StubJarTest::assertInnerClassStubbedCorrectly); } private static void assertMethodsStubbedCorrectly( List<MethodNode> original, List<MethodNode> stubbed) { assertMembersStubbedCorrectly( original, stubbed, node -> node.access, StubJarTest::assertMethodStubbedCorrectly); } private static void assertFieldsStubbedCorrectly( List<FieldNode> original, List<FieldNode> stubbed) { assertMembersStubbedCorrectly( original, stubbed, node -> node.access, StubJarTest::assertFieldStubbedCorrectly); } private static <M> void assertMembersStubbedCorrectly( List<M> original, List<M> stubbed, Function<M, Integer> getAccess, BiFunction<M, M, Void> assertMemberStubbedCorrectly) { List<M> filtered = original.stream() .filter(m -> { if (m instanceof InnerClassNode) { return true; } if (m instanceof MethodNode && ((MethodNode) m).name.equals("<clinit>") && ((MethodNode) m).desc.equals("()V")) { return false; } int access = getAccess.apply(m); // Never stub things that are private return (access & (Opcodes.ACC_PRIVATE)) == 0; }) .collect(Collectors.toList()); // We just iterate through since order of each list should match // An IndexOutOFBoundsException may be thrown if extra or missing stubs are found int max = Math.max(stubbed.size(), filtered.size()); for (int i = 0; i < max; i++) { assertMemberStubbedCorrectly.apply(filtered.get(i), stubbed.remove(0)); } } private static Void assertInnerClassStubbedCorrectly( InnerClassNode original, InnerClassNode stubbed) { assertEquals(original.name, stubbed.name); assertEquals(original.outerName, stubbed.outerName); assertEquals(original.innerName, stubbed.innerName); assertEquals(original.access, stubbed.access); return null; } private static Void assertMethodStubbedCorrectly(MethodNode original, MethodNode stubbed) { assertEquals(original.access, stubbed.access); assertEquals(original.name, stubbed.name); assertEquals(original.desc, stubbed.desc); assertEquals(original.signature, stubbed.signature); assertEquals(original.exceptions, stubbed.exceptions); assertParametersEqual(original.parameters, stubbed.parameters); assertAnnotationsEqual(original.visibleAnnotations, stubbed.visibleAnnotations); assertAnnotationsEqual(original.invisibleAnnotations, stubbed.invisibleAnnotations); assertTypeAnnotationsEqual(original.visibleTypeAnnotations, stubbed.visibleTypeAnnotations); assertTypeAnnotationsEqual(original.invisibleTypeAnnotations, stubbed.invisibleTypeAnnotations); assertAnnotationValueEquals(original.annotationDefault, stubbed.annotationDefault); assertParameterAnnotationsEqual( original.visibleParameterAnnotations, stubbed.visibleParameterAnnotations); assertParameterAnnotationsEqual( original.invisibleParameterAnnotations, stubbed.invisibleParameterAnnotations); return null; } private static Void assertFieldStubbedCorrectly(FieldNode original, FieldNode stubbed) { assertEquals(original.access, stubbed.access); assertEquals(original.name, stubbed.name); assertEquals(original.desc, stubbed.desc); assertEquals(original.signature, stubbed.signature); assertEquals(original.value, stubbed.value); assertAnnotationsEqual(original.visibleAnnotations, stubbed.visibleAnnotations); assertAnnotationsEqual(original.invisibleAnnotations, stubbed.invisibleAnnotations); assertTypeAnnotationsEqual(original.visibleTypeAnnotations, stubbed.visibleTypeAnnotations); assertTypeAnnotationsEqual(original.invisibleTypeAnnotations, stubbed.invisibleTypeAnnotations); assertEquals(original.attrs, stubbed.attrs); return null; } private static void assertParameterAnnotationsEqual( List<AnnotationNode>[] expected, List<AnnotationNode>[] seen) { if (expected == null) { assertNull(seen); return; } assertSame(expected.length, seen.length); for (int i = 0; i < expected.length; i++) { assertAnnotationsEqual(expected[i], seen[i]); } } private static void assertAnnotationsEqual( List<AnnotationNode> expected, List<AnnotationNode> seen) { assertListsEqual(expected, seen, StubJarTest::annotationToString); } private static void assertParametersEqual( List<ParameterNode> expected, List<ParameterNode> seen) { assertListsEqual(expected, seen, StubJarTest::parameterToString); } private static void assertTypeAnnotationsEqual( List<TypeAnnotationNode> expected, List<TypeAnnotationNode> seen) { assertListsEqual(expected, seen, StubJarTest::typeAnnotationToString); } private static <T> void assertListsEqual( List<T> expected, List<T> seen, Function<T, String> toString) { if (expected == null) { assertNull(seen); return; } assertNotNull(String.format( "Stubbed no %s's", expected.get(0).getClass().getSimpleName()), seen); assertEquals( expected.stream() .map(toString) .collect(Collectors.toList()), seen.stream() .map(toString) .collect(Collectors.toList())); } private static String typeAnnotationToString(TypeAnnotationNode typeAnnotationNode) { return String.format( "%d %s %s(%s)", typeAnnotationNode.typeRef, typeAnnotationNode.typePath, typeAnnotationNode.desc, annotationValuesToString(typeAnnotationNode.values)); } private static String parameterToString(ParameterNode parameter) { return String.format("0x%x %s", parameter.access, parameter.name); } private static String annotationToString(AnnotationNode annotationNode) { return String.format( "%s(%s)", annotationNode.desc, annotationValuesToString(annotationNode.values)); } private static void assertAnnotationValueEquals(Object expected, Object actual) { assertEquals(annotationValueToString(expected), annotationValueToString(actual)); } private static String annotationValueToString(Object value) { if (value instanceof AnnotationNode) { return annotationToString((AnnotationNode) value); } else if (value instanceof List) { return annotationValuesToString((List<?>) value); } else if (value instanceof String[]) { String[] valueArray = (String[]) value; return String.format("%s.%s", valueArray[0], valueArray[1]); } return String.valueOf(value); } private static String annotationValuesToString(List<?> values) { if (values == null) { return "null"; } StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append('['); for (int i = 0; i < values.size(); i++) { resultBuilder.append(annotationValueToString(values.get(i))); if (i > 0) { resultBuilder.append(", "); } } resultBuilder.append(']'); return resultBuilder.toString(); } private void notYetImplementedForMissingClasspath() { assumeThat(testingMode, Matchers.not(Matchers.equalTo(MODE_SOURCE_BASED_MISSING_DEPS))); } private void notYetImplementedForSource() { assumeThat(testingMode, Matchers.equalTo(MODE_JAR_BASED)); } private static class JarPaths { public final Path fullJar; public final Path stubJar; public JarPaths(Path fullJar, Path stubJar) { this.fullJar = fullJar; this.stubJar = stubJar; } } }
test/com/facebook/buck/jvm/java/abi/StubJarTest.java
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java.abi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import com.facebook.buck.io.MorePaths; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.util.sha1.Sha1HashCode; import com.facebook.buck.zip.Unzip; import com.google.common.base.Joiner; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InnerClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.ParameterNode; import org.objectweb.asm.tree.TypeAnnotationNode; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.function.BiFunction; import java.util.function.Function; import java.util.jar.JarOutputStream; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import javax.annotation.processing.Processor; import javax.lang.model.SourceVersion; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; @RunWith(Parameterized.class) public class StubJarTest { // Test a stub generated by stripping a full jar private static final String MODE_JAR_BASED = "JAR_BASED"; // Test a stub generated from source private static final String MODE_SOURCE_BASED = "SOURCE_BASED"; // Test a stub generated from source, with dependencies missing private static final String MODE_SOURCE_BASED_MISSING_DEPS = "SOURCE_BASED_MISSING_DEPS"; private static final String ANNOTATION_SOURCE = Joiner.on("\n").join(ImmutableList.of( "package com.example.buck;", "import java.lang.annotation.*;", "import static java.lang.annotation.ElementType.*;", "@Retention(RetentionPolicy.RUNTIME)", "@Target(value={CONSTRUCTOR, FIELD, METHOD, PARAMETER, TYPE})", "public @interface Foo {", " int primitiveValue() default 0;", " String[] stringArrayValue() default {\"Hello\"};", " Retention annotationValue() default @Retention(RetentionPolicy.SOURCE);", " Retention[] annotationArrayValue() default {};", " RetentionPolicy enumValue () default RetentionPolicy.CLASS;", " Class typeValue() default Foo.class;", " @Target({TYPE_PARAMETER, TYPE_USE})", " @interface TypeAnnotation { }", "}" )); @Parameterized.Parameter public String testingMode; @Parameterized.Parameters public static Object[] getParameters() { return new Object[]{MODE_JAR_BASED, MODE_SOURCE_BASED, MODE_SOURCE_BASED_MISSING_DEPS}; } private static final ImmutableSortedSet<Path> EMPTY_CLASSPATH = ImmutableSortedSet.of(); @Rule public TemporaryFolder temp = new TemporaryFolder(); private ProjectFilesystem filesystem; @Before public void createTempFilesystem() throws IOException { File out = temp.newFolder(); filesystem = new ProjectFilesystem(out.toPath()); } @Test public void emptyClass() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", "package com.example.buck; public class A {}"); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); // Verify that the stub jar works by compiling some code that depends on A. compileToJar( ImmutableSortedSet.of(paths.stubJar), Collections.emptyList(), "B.java", "package com.example.buck; public class B extends A {}", temp.newFolder()); } @Test public void emptyClassWithAnnotation() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", "package com.example.buck; @Deprecated public class A {}"); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void classWithTwoMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join(ImmutableList.of( "package com.example.buck;", "public class A {", " public String toString() { return null; }", " public void eatCake() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesThrowsClauses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public void throwSomeStuff() throws Exception, Throwable {}", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesThrowsClausesWithTypeVars() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.io.IOException;", "public class A {", " public <E extends IOException> void throwSomeStuff() throws E {}", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void genericClassSignaturesShouldBePreserved() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T get(String key) { return null; }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void elementsInStubCorrectlyInOrder() throws IOException { // Fields and methods should stub in order // Inner classes should stub in reverse JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " boolean first;", " float second;", " public void foo() { }", " public class B { }", " public class C { }", " public void bar() { }", " public class D { }", " int between;", " public class E {", " public void hello() { }", " public void test() { }", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class", "com/example/buck/A$C.class", "com/example/buck/A$D.class", "com/example/buck/A$E.class"); } @Test public void genericInterfaceSignaturesShouldBePreserved() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public interface A<T> {", " T get(String key);", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIgnorePrivateMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " private void privateMethod() {}", " void packageMethod() {}", " protected void protectedMethod() {}", " public void publicMethod() {}", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveAField() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected String protectedField;", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIgnorePrivateFields() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " private String privateField;", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveGenericTypesOnFields() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T theField;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldPreserveGenericTypesOnMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<T> {", " public T get(String key) { return null; }", " public <X extends Comparable<T>> X compareWith(T other) { return null; }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnMethods() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " @Foo", " public void cheese(String key) {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnFields() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " @Foo", " public String name;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsOnParameters() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public void peynir(@Foo String very, int tasty) {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInClasses() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A<@Foo.TypeAnnotation T> { }"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInMethods() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " <@Foo.TypeAnnotation T> void foo(@Foo.TypeAnnotation String s) { }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesTypeAnnotationsInFields() throws IOException { // TODO(jkeljo): It looks like annotated types are not accessible via Elements. The annotated // type gets put on the Tree object but doesn't make it to the corresponding Element. We can // work around this using Trees.getTypeMirror, but that brings in a lot of classpath challenges // that I don't want to deal with right now. notYetImplementedForSource(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "import java.util.List;", "public class A {", " List<@Foo.TypeAnnotation String> list;", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void omitsAnnotationsWithSourceRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@SourceRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.SOURCE)", "@interface SourceRetentionAnno { }")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithClassRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@ClassRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.CLASS)", "@interface ClassRetentionAnno { }")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithRuntimeRetention() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "import java.lang.annotation.*;", "@RuntimeRetentionAnno()", "public class A { }", "@Retention(RetentionPolicy.RUNTIME)", "@interface RuntimeRetentionAnno { }")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithPrimitiveValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(primitiveValue=1)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithStringArrayValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(stringArrayValue={\"1\", \"2\"})", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithEnumValues() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Retention(RetentionPolicy.RUNTIME)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithTypeValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo(typeValue=String.class)", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithEnumArrayValues() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Target({ElementType.CONSTRUCTOR, ElementType.FIELD})", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithAnnotationValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Foo(annotationValue=@Retention(RetentionPolicy.RUNTIME))", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithAnnotationArrayValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "import java.lang.annotation.*;", "@Foo(annotationArrayValue=@Retention(RetentionPolicy.RUNTIME))", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationsWithDefaultValues() throws IOException { notYetImplementedForMissingClasspath(); Path annotations = createAnnotationFullJar(); JarPaths paths = createFullAndStubJars( ImmutableSortedSet.of(annotations), "A.java", Joiner.on("\n").join( "package com.example.buck;", "@Foo()", "public @interface A {}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void preservesAnnotationPrimitiveDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly(paths, "com/example/buck/Foo.class"); } @Test public void preservesAnnotationArrayDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly(paths, "com/example/buck/Foo.class"); } @Test public void preservesAnnotationAnnotationDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly(paths, "com/example/buck/Foo.class"); } @Test public void preservesAnnotationEnumDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly(paths, "com/example/buck/Foo.class"); } @Test public void preservesAnnotationTypeDefaultValues() throws IOException { JarPaths paths = createAnnotationFullAndStubJars(); assertClassesStubbedCorrectly(paths, "com/example/buck/Foo.class"); } @Test public void stubsEnums() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "public enum A {", " Value1,", " Value2", "}" )); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubsAbstractEnums() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( "package com.example.buck;", "public enum A {", " Value1 {", " public int get() { return 1; }", " };", " public abstract int get();", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubsInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B.class"); } @Test public void stubsProtectedInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsDefaultInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$B.class"); } @Test public void stubsInnerEnums() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public enum B { Value }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B.class"); } @Test public void stubsNestedInnerClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public class B {", " public class C {", " public int count;", " public void foo() {}", " }", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B$C.class"); } @Test public void doesNotStubReferencesToInnerClassesOfOtherTypess() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " B.C field;", "}", "class B {", " public class C { }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubsStaticMemberClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static class B {", " public int count;", " public void foo() {}", " }", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B.class"); } @Test public void ignoresAnonymousClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public Runnable r = new Runnable() {", " public void run() { }", " };", "}" ))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class", "com/example/buck/A$1.class"); } @Test public void ignoresLocalClasses() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public void method() {", " class Local { };", " }", "}" ))); assertClassesStubbedCorrectly( paths, "com/example/buck/A.class", "com/example/buck/A$1Local.class"); } @Test public void preservesThrowsClausesOnInnerClassConstructors() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public class B {", " B() throws Exception, Throwable {", " }", " }", "}" )); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); assertClassesStubbedCorrectly(paths, "com/example/buck/A$B.class"); } @Test public void abiSafeChangesResultInTheSameOutputJar() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"hello\"; }", " Class<?> clazz;", " public int other;", "}" ))); Sha1HashCode originalHash = filesystem.computeSha1(paths.stubJar); paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"merhaba\"; }", " Class<?> clazz = String.class;", " public int other = 32;", "}" ))); Sha1HashCode secondHash = filesystem.computeSha1(paths.stubJar); assertEquals(originalHash, secondHash); } @Test public void ordersChangesResultInADifferentOutputJar() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " protected final static int count = 42;", " public String getGreeting() { return \"hello\"; }", " Class<?> clazz;", " public int other;", "}" ))); Sha1HashCode originalHash = filesystem.computeSha1(paths.stubJar); paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " Class<?> clazz;", " public String getGreeting() { return \"hello\"; }", " protected final static int count = 42;", " public int other;", "}" ))); Sha1HashCode secondHash = filesystem.computeSha1(paths.stubJar); assertNotEquals(originalHash, secondHash); } @Test public void shouldIncludeStaticFields() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static String foo;", " public final static int count = 42;", " protected static void method() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void innerClassesInStubsCanBeCompiledAgainst() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "Outer.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class Outer {", " public class Inner {", " public String getGreeting() { return \"hola\"; }", " }", "}"))); compileToJar( ImmutableSortedSet.of(paths.stubJar), Collections.emptyList(), "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck2;", // Note: different package "import com.example.buck.Outer;", // Inner class becomes available "public class A {", " private Outer.Inner field;", // Reference the inner class "}")), temp.newFolder()); } @Test public void shouldPreserveSynchronizedKeywordOnMethods() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public synchronized void doMagic() {}", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldKeepMultipleFieldsWithSameDescValue() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public static final A SEVERE = new A();", " public static final A NOT_SEVERE = new A();", " public static final A QUITE_MILD = new A();", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldNotStubClinit() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join( "package com.example.buck;", "public class A {", " public static int i = 3;", "}")); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void stubJarIsEquallyAtHomeWalkingADirectoryOfClassFiles() throws IOException { JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on("\n").join( ImmutableList.of( "package com.example.buck;", "public class A {", " public String toString() { return null; }", " public void eatCake() {}", "}"))); Path classDir = temp.newFolder().toPath(); Unzip.extractZipFile(paths.fullJar, classDir, Unzip.ExistingFileMode.OVERWRITE); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } @Test public void shouldIncludeBridgeMethods() throws IOException { notYetImplementedForSource(); JarPaths paths = createFullAndStubJars( EMPTY_CLASSPATH, "A.java", Joiner.on('\n').join(ImmutableList.of( "package com.example.buck;", "public class A implements Comparable<A> {", " public int compareTo(A other) {", " return 0;", " }", "}"))); assertClassesStubbedCorrectly(paths, "com/example/buck/A.class"); } private JarPaths createFullAndStubJars( ImmutableSortedSet<Path> classPath, String fileName, String source) throws IOException { File outputDir = temp.newFolder(); List<Processor> processors = Collections.emptyList(); StubJarGeneratingProcessor stubJarGenerator = null; if (testingMode != MODE_JAR_BASED) { stubJarGenerator = new StubJarGeneratingProcessor( filesystem, outputDir.toPath().resolve("sourceStub.jar"), SourceVersion.RELEASE_8); processors = Collections.singletonList(stubJarGenerator); } Path fullJar = compileToJar( testingMode != MODE_SOURCE_BASED_MISSING_DEPS ? classPath : Collections.emptySortedSet(), processors, fileName, source, outputDir); Path stubJar; if (stubJarGenerator != null) { stubJar = stubJarGenerator.getStubJarPath(); } else { stubJar = createStubJar(fullJar); } return new JarPaths(fullJar, stubJar); } private Path createStubJar(Path fullJar) throws IOException { Path stubJar = fullJar.getParent().resolve("stub.jar"); new StubJar(fullJar).writeTo(filesystem, stubJar); return stubJar; } private Path compileToJar( SortedSet<Path> classpath, List<Processor> processors, String fileName, String source, File outputDir) throws IOException { File inputs = temp.newFolder(); File file = new File(inputs, fileName); Files.write(file.toPath(), source.getBytes(StandardCharsets.UTF_8)); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> sourceObjects = fileManager.getJavaFileObjectsFromFiles(ImmutableSet.of(file)); List<String> args = Lists.newArrayList("-g", "-d", outputDir.getAbsolutePath()); if (!classpath.isEmpty()) { args.add("-classpath"); args.add(Joiner.on(File.pathSeparator).join(FluentIterable.from(classpath) .transform(filesystem::resolve))); } JavaCompiler.CompilationTask compilation = compiler.getTask(null, fileManager, null, args, null, sourceObjects); compilation.setProcessors(processors); Boolean result = compilation.call(); fileManager.close(); assertNotNull(result); assertTrue(result); File jar = new File(outputDir, "output.jar"); try ( FileOutputStream fos = new FileOutputStream(jar); final JarOutputStream os = new JarOutputStream(fos)) { SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".class")) { ZipEntry entry = new ZipEntry(MorePaths.pathWithUnixSeparators(outputDir.toPath().relativize(file))); os.putNextEntry(entry); ByteStreams.copy(Files.newInputStream(file), os); os.closeEntry(); } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(outputDir.toPath(), visitor); } return jar.toPath().toAbsolutePath(); } private AbiClass readClass(Path pathToJar, String className) throws IOException { return AbiClass.extract(filesystem.getPathForRelativePath(pathToJar), className); } private JarPaths createAnnotationFullAndStubJars() throws IOException { return createFullAndStubJars( EMPTY_CLASSPATH, "Foo.java", ANNOTATION_SOURCE); } private Path createAnnotationFullJar() throws IOException { return compileToJar( EMPTY_CLASSPATH, Collections.emptyList(), "Foo.java", ANNOTATION_SOURCE, temp.newFolder()); } private void assertClassesStubbedCorrectly( JarPaths paths, String... classNames) throws IOException { for (String className : classNames) { AbiClass original = readClass(paths.fullJar, className); AbiClass stubbed = readClass(paths.stubJar, className); if (isAnonymousOrLocalClass(original.getClassNode())) { original = null; } assertClassStubbedCorrectly(original, stubbed); } } /** * A class is stubbed correctly if the stub is exactly the same as its full counterpart, with * the following exceptions: * <ul> * <li>No private members, &lt;clinit&gt;, synthetic members, bridge methods, or method bodies * are present</li> * </ul> */ private static void assertClassStubbedCorrectly(AbiClass original, AbiClass stubbed) { if (original == null) { if (stubbed != null) { fail(String.format("Should not have stubbed %s", stubbed.getClassNode().name)); } return; } ClassNode originalNode = original.getClassNode(); ClassNode stubbedNode = stubbed.getClassNode(); assertEquals(originalNode.version, stubbedNode.version); assertEquals(originalNode.access, stubbedNode.access); assertEquals(originalNode.name, stubbedNode.name); assertEquals(originalNode.signature, stubbedNode.signature); assertEquals(originalNode.superName, stubbedNode.superName); assertThat(stubbedNode.interfaces, Matchers.equalTo(originalNode.interfaces)); assertNull(stubbedNode.sourceFile); assertNull(stubbedNode.sourceDebug); assertEquals(originalNode.outerClass, stubbedNode.outerClass); assertNull(stubbedNode.outerMethod); assertNull(stubbedNode.outerMethodDesc); assertAnnotationsEqual(originalNode.visibleAnnotations, stubbedNode.visibleAnnotations); assertAnnotationsEqual(originalNode.invisibleAnnotations, stubbedNode.invisibleAnnotations); assertTypeAnnotationsEqual( originalNode.visibleTypeAnnotations, stubbedNode.visibleTypeAnnotations); assertTypeAnnotationsEqual( originalNode.invisibleTypeAnnotations, stubbedNode.invisibleTypeAnnotations); assertEquals(originalNode.attrs, stubbedNode.attrs); assertInnerClassesStubbedCorrectly( originalNode, originalNode.innerClasses, stubbedNode.innerClasses); assertFieldsStubbedCorrectly(originalNode.fields, stubbedNode.fields); assertMethodsStubbedCorrectly(originalNode.methods, stubbedNode.methods); } private static void assertInnerClassesStubbedCorrectly( ClassNode originalOuter, List<InnerClassNode> original, List<InnerClassNode> stubbed) { List<InnerClassNode> filteredOriginal = original.stream() .filter(node -> node.name == originalOuter.name || (!isAnonymousOrLocalClass(node) && isMemberOf(node, originalOuter))) .collect(Collectors.toList()); assertMembersStubbedCorrectly( filteredOriginal, stubbed, node -> node.access, StubJarTest::assertInnerClassStubbedCorrectly); } private static boolean isAnonymousOrLocalClass(ClassNode node) { return isLocalClass(node) || isAnonymousClass(node); } private static boolean isLocalClass(ClassNode node) { return node.outerMethod != null; } private static boolean isAnonymousClass(ClassNode node) { if (node.outerClass == null) { return false; } for (InnerClassNode innerClass : node.innerClasses) { if (innerClass.name.equals(node.name) && innerClass.innerName == null) { return true; } } return false; } private static boolean isAnonymousOrLocalClass(InnerClassNode node) { return node.innerName == null || node.outerName == null; } private static boolean isMemberOf(InnerClassNode inner, ClassNode outer) { return inner.outerName.equals(outer.name); } private static void assertMethodsStubbedCorrectly( List<MethodNode> original, List<MethodNode> stubbed) { assertMembersStubbedCorrectly( original, stubbed, node -> node.access, StubJarTest::assertMethodStubbedCorrectly); } private static void assertFieldsStubbedCorrectly( List<FieldNode> original, List<FieldNode> stubbed) { assertMembersStubbedCorrectly( original, stubbed, node -> node.access, StubJarTest::assertFieldStubbedCorrectly); } private static <M> void assertMembersStubbedCorrectly( List<M> original, List<M> stubbed, Function<M, Integer> getAccess, BiFunction<M, M, Void> assertMemberStubbedCorrectly) { List<M> filtered = original.stream() .filter(m -> { if (m instanceof MethodNode && ((MethodNode) m).name.equals("<clinit>") && ((MethodNode) m).desc.equals("()V")) { return false; } int access = getAccess.apply(m); // Never stub things that are private return (access & (Opcodes.ACC_PRIVATE)) == 0; }) .collect(Collectors.toList()); // We just iterate through since order of each list should match // An IndexOutOFBoundsException may be thrown if extra or missing stubs are found int max = Math.max(stubbed.size(), filtered.size()); for (int i = 0; i < max; i++) { assertMemberStubbedCorrectly.apply(filtered.get(i), stubbed.remove(0)); } } private static Void assertInnerClassStubbedCorrectly( InnerClassNode original, InnerClassNode stubbed) { assertEquals(original.name, stubbed.name); assertEquals(original.outerName, stubbed.outerName); assertEquals(original.innerName, stubbed.innerName); assertEquals(original.access, stubbed.access); return null; } private static Void assertMethodStubbedCorrectly(MethodNode original, MethodNode stubbed) { assertEquals(original.access, stubbed.access); assertEquals(original.name, stubbed.name); assertEquals(original.desc, stubbed.desc); assertEquals(original.signature, stubbed.signature); assertEquals(original.exceptions, stubbed.exceptions); assertParametersEqual(original.parameters, stubbed.parameters); assertAnnotationsEqual(original.visibleAnnotations, stubbed.visibleAnnotations); assertAnnotationsEqual(original.invisibleAnnotations, stubbed.invisibleAnnotations); assertTypeAnnotationsEqual(original.visibleTypeAnnotations, stubbed.visibleTypeAnnotations); assertTypeAnnotationsEqual(original.invisibleTypeAnnotations, stubbed.invisibleTypeAnnotations); assertAnnotationValueEquals(original.annotationDefault, stubbed.annotationDefault); assertParameterAnnotationsEqual( original.visibleParameterAnnotations, stubbed.visibleParameterAnnotations); assertParameterAnnotationsEqual( original.invisibleParameterAnnotations, stubbed.invisibleParameterAnnotations); return null; } private static Void assertFieldStubbedCorrectly(FieldNode original, FieldNode stubbed) { assertEquals(original.access, stubbed.access); assertEquals(original.name, stubbed.name); assertEquals(original.desc, stubbed.desc); assertEquals(original.signature, stubbed.signature); assertEquals(original.value, stubbed.value); assertAnnotationsEqual(original.visibleAnnotations, stubbed.visibleAnnotations); assertAnnotationsEqual(original.invisibleAnnotations, stubbed.invisibleAnnotations); assertTypeAnnotationsEqual(original.visibleTypeAnnotations, stubbed.visibleTypeAnnotations); assertTypeAnnotationsEqual(original.invisibleTypeAnnotations, stubbed.invisibleTypeAnnotations); assertEquals(original.attrs, stubbed.attrs); return null; } private static void assertParameterAnnotationsEqual( List<AnnotationNode>[] expected, List<AnnotationNode>[] seen) { if (expected == null) { assertNull(seen); return; } assertSame(expected.length, seen.length); for (int i = 0; i < expected.length; i++) { assertAnnotationsEqual(expected[i], seen[i]); } } private static void assertAnnotationsEqual( List<AnnotationNode> expected, List<AnnotationNode> seen) { assertListsEqual(expected, seen, StubJarTest::annotationToString); } private static void assertParametersEqual( List<ParameterNode> expected, List<ParameterNode> seen) { assertListsEqual(expected, seen, StubJarTest::parameterToString); } private static void assertTypeAnnotationsEqual( List<TypeAnnotationNode> expected, List<TypeAnnotationNode> seen) { assertListsEqual(expected, seen, StubJarTest::typeAnnotationToString); } private static <T> void assertListsEqual( List<T> expected, List<T> seen, Function<T, String> toString) { if (expected == null) { assertNull(seen); return; } assertNotNull(String.format( "Stubbed no %s's", expected.get(0).getClass().getSimpleName()), seen); assertEquals( expected.stream() .map(toString) .collect(Collectors.toList()), seen.stream() .map(toString) .collect(Collectors.toList())); } private static String typeAnnotationToString(TypeAnnotationNode typeAnnotationNode) { return String.format( "%d %s %s(%s)", typeAnnotationNode.typeRef, typeAnnotationNode.typePath, typeAnnotationNode.desc, annotationValuesToString(typeAnnotationNode.values)); } private static String parameterToString(ParameterNode parameter) { return String.format("0x%x %s", parameter.access, parameter.name); } private static String annotationToString(AnnotationNode annotationNode) { return String.format( "%s(%s)", annotationNode.desc, annotationValuesToString(annotationNode.values)); } private static void assertAnnotationValueEquals(Object expected, Object actual) { assertEquals(annotationValueToString(expected), annotationValueToString(actual)); } private static String annotationValueToString(Object value) { if (value instanceof AnnotationNode) { return annotationToString((AnnotationNode) value); } else if (value instanceof List) { return annotationValuesToString((List<?>) value); } else if (value instanceof String[]) { String[] valueArray = (String[]) value; return String.format("%s.%s", valueArray[0], valueArray[1]); } return String.valueOf(value); } private static String annotationValuesToString(List<?> values) { if (values == null) { return "null"; } StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append('['); for (int i = 0; i < values.size(); i++) { resultBuilder.append(annotationValueToString(values.get(i))); if (i > 0) { resultBuilder.append(", "); } } resultBuilder.append(']'); return resultBuilder.toString(); } private void notYetImplementedForMissingClasspath() { assumeThat(testingMode, Matchers.not(Matchers.equalTo(MODE_SOURCE_BASED_MISSING_DEPS))); } private void notYetImplementedForSource() { assumeThat(testingMode, Matchers.equalTo(MODE_JAR_BASED)); } private static class JarPaths { public final Path fullJar; public final Path stubJar; public JarPaths(Path fullJar, Path stubJar) { this.fullJar = fullJar; this.stubJar = stubJar; } } }
Manually specify which classes should be stubbed in tests Summary: Previously we had some logic in `assertClassesStubbedCorrectly` that tried to figure out which classes should be stubbed. That logic largely duplicated the logic in the product code. The product code is about to get really complicated as we try to include technically `private` classes that are nonetheless part of the ABI (e.g. superclasses of public classes), so this commit changes the tests to manually specify which classes should be stubbed or not. Test Plan: Updated unit tests Reviewed By: dreiss fbshipit-source-id: c736343
test/com/facebook/buck/jvm/java/abi/StubJarTest.java
Manually specify which classes should be stubbed in tests
Java
bsd-2-clause
ce1587c273744b42a4284a83422dc2658967506b
0
sebastianscatularo/javadns,sebastianscatularo/javadns
// Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_LOCAL_COMPRESSION = 0x80; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_COMPRESSION = 0; private static final int EXT_LABEL_BITSTRING = 1; private static final int EXT_LABEL_LOCAL_COMPRESSION = 2; private Object [] name; private byte labels; private boolean qualified; /** The root name */ public static Name root = new Name(""); /** The maximum number of labels in a Name */ static final int MAXLABELS = 256; /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqalified, the origin to be appended */ public Name(String s, Name origin) { labels = 0; name = new Object[MAXLABELS]; if (s.equals("@") && origin != null) { append(origin); qualified = true; return; } try { MyStringTokenizer st = new MyStringTokenizer(s, "."); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.charAt(0) == '\\') name[labels++] = new BitString(token); else name[labels++] = token; } if (st.hasMoreDelimiters()) qualified = true; else { if (origin != null) { append(origin); qualified = true; } else { /* This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } if (e instanceof ArrayIndexOutOfBoundsException) sb.append(" has too many labels"); else if (e instanceof IOException) sb.append(" contains an invalid binary label"); else sb.append(" is invalid"); System.err.println(sb.toString()); name = null; labels = 0; } } /** * Create a new name from a string * @param s The string to be converted */ public Name(String s) { this (s, null); } /** * Create a new name from DNS wire format * @param in A stream containing the input data * @param c The compression context. This should be null unless a full * message is being parsed. */ public Name(DataByteInputStream in, Compression c) throws IOException { int len, start, pos, count = 0; Name name2; labels = 0; name = new Object[MAXLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); name[labels++] = new String(b); count++; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException("bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_COMPRESSION: pos = in.readUnsignedShort(); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException( "bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); name[labels++] = new BitString(bits, data); count++; break; case EXT_LABEL_LOCAL_COMPRESSION: throw new WireParseException( "Long local compression"); default: throw new WireParseException( "Unknown name format"); } /* switch */ break; case LABEL_LOCAL_COMPRESSION: throw new WireParseException("Local compression"); } /* switch */ } if (c != null) { pos = start; for (int i = 0; i < count; i++) { Name tname = new Name(this, i); c.add(pos, tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + pos); if (name[i] instanceof String) pos += (((String)name[i]).length() + 1); else pos += (((BitString)name[i]).bytes() + 2); } } qualified = true; } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[MAXLABELS]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first label replaced by a wildcard * @return The wildcard name */ public Name wild() { Name wild = new Name(this, 0); wild.name[0] = "*"; return wild; } /** * Is this name a wildcard? */ public boolean isWild() { return name[0].equals("*"); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ public void append(Name d) { System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; } /** * The length */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) total += (((String)name[i]).length() + 1); else total += (((BitString)name[i]).bytes() + 2); } return ++total; } /** * The number of labels */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; int i = labels, j = domain.labels; while (j > 0) if (!name[--i].equals(domain.name[--j])) return false; return true; } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { sb.append(name[i]); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { for (int i = 0; i < labels; i++) { Name tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (Options.check("verbosecompression")) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof String) out.writeString((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof String) out.writeStringCanonical((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } out.writeByte(0); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof String) { String s1 = (String) name[i]; String s2 = (String) d.name[i]; if (!s1.equalsIgnoreCase(s2)) return false; } else { /* BitString */ if (!name[i].equals(d.name[i])) return false; } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) { String s = (String) name[i]; for (int j = 0; j < s.length(); j++) code += Character.toLowerCase(s.charAt(j)); } else { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += b.data[i]; } } return code; } }
org/xbill/DNS/Name.java
// Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_LOCAL_COMPRESSION = 0x80; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_COMPRESSION = 0; private static final int EXT_LABEL_BITSTRING = 1; private static final int EXT_LABEL_LOCAL_COMPRESSION = 2; private Object [] name; private byte labels; private boolean qualified; /** The root name */ public static Name root = new Name(""); /** The maximum number of labels in a Name */ static final int MAXLABELS = 256; /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqalified, the origin to be appended */ public Name(String s, Name origin) { labels = 0; name = new Object[MAXLABELS]; if (s.equals("@") && origin != null) { append(origin); qualified = true; return; } try { MyStringTokenizer st = new MyStringTokenizer(s, "."); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.charAt(0) == '\\') name[labels++] = new BitString(token); else name[labels++] = token; } if (st.hasMoreDelimiters()) qualified = true; else { if (origin != null) { append(origin); qualified = true; } else { /* This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } if (e instanceof ArrayIndexOutOfBoundsException) sb.append(" has too many labels"); else if (e instanceof IOException) sb.append(" contains an invalid binary label"); else sb.append(" is invalid"); System.err.println(sb.toString()); name = null; labels = 0; } } /** * Create a new name from a string * @param s The string to be converted */ public Name(String s) { this (s, null); } public Name(DataByteInputStream in, Compression c) throws IOException { int len, start, pos, count = 0; Name name2; labels = 0; name = new Object[MAXLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); name[labels++] = new String(b); count++; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException("bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_COMPRESSION: pos = in.readUnsignedShort(); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException( "bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); name[labels++] = new BitString(bits, data); count++; break; case EXT_LABEL_LOCAL_COMPRESSION: throw new WireParseException( "Long local compression"); default: throw new WireParseException( "Unknown name format"); } /* switch */ break; case LABEL_LOCAL_COMPRESSION: throw new WireParseException("Local compression"); } /* switch */ } if (c != null) { pos = start; for (int i = 0; i < count; i++) { Name tname = new Name(this, i); c.add(pos, tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + pos); if (name[i] instanceof String) pos += (((String)name[i]).length() + 1); else pos += (((BitString)name[i]).bytes() + 2); } } qualified = true; } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[MAXLABELS]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first label replaced by a wildcard * @return The wildcard name */ public Name wild() { Name wild = new Name(this, 0); wild.name[0] = "*"; return wild; } /** * Is this name a wildcard? */ public boolean isWild() { return name[0].equals("*"); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ public void append(Name d) { System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; } /** * The length */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) total += (((String)name[i]).length() + 1); else total += (((BitString)name[i]).bytes() + 2); } return ++total; } /** * The number of labels */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; int i = labels, j = domain.labels; while (j > 0) if (!name[--i].equals(domain.name[--j])) return false; return true; } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { sb.append(name[i]); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { for (int i = 0; i < labels; i++) { Name tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (Options.check("verbosecompression")) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof String) out.writeString((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof String) out.writeStringCanonical((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } out.writeByte(0); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof String) { String s1 = (String) name[i]; String s2 = (String) d.name[i]; if (!s1.equalsIgnoreCase(s2)) return false; } else { /* BitString */ if (!name[i].equals(d.name[i])) return false; } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) { String s = (String) name[i]; for (int j = 0; j < s.length(); j++) code += Character.toLowerCase(s.charAt(j)); } else { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += b.data[i]; } } return code; } }
missing comment
org/xbill/DNS/Name.java
missing comment
Java
apache-2.0
cbc1498bbc96687cd9422879c46640f0c3261dbd
0
jboz/living-documentation,jboz/living-documentation,jboz/living-documentation,jboz/living-documentation,jboz/living-documentation,jboz/living-documentation
livingdoc-maven-plugin/src/main/java/ch/ifocusit/livingdoc/plugin/CommonMojoDefinition.java
/* * Living Documentation * * Copyright (C) 2017 Focus IT * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package ch.ifocusit.livingdoc.plugin; import io.github.robwin.markup.builder.asciidoc.AsciiDocBuilder; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.repository.RepositorySystem; import org.asciidoctor.Asciidoctor; import org.asciidoctor.OptionsBuilder; import org.asciidoctor.SafeMode; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * @author Julien Boz */ public abstract class CommonMojoDefinition extends AbstractMojo { public static final String GLOSSARY_ANCHOR = "glossaryid-{0}"; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @Component RepositorySystem repositorySystem; /** * Output format of the glossary (default html, others : adoc) */ @Parameter(defaultValue = "html") Format format; /** * Temple for glossary anchor. */ @Parameter(defaultValue = GLOSSARY_ANCHOR) String glossaryAnchorTemplate; /** * File to use for UbiquitousLanguage mapping. */ @Parameter File glossaryMapping; // /** // * Header of the generated asciidoc file // */ // @Parameter // private File headerAsciidoc; // // /** // * Footer of generated asciidoc file // */ // @Parameter // private File footerAsciidoc; /** * Indicate that only annotated classes/fields will be used. */ @Parameter(defaultValue = "false") boolean onlyAnnotated = false; /** * Directory where the glossary will be generated */ @Parameter(defaultValue = "${project.build.directory}/generated-docs", required = true) private File outputDirectory; /** * Output filename */ @Parameter private String outputFilename; void write(final String newContent, final File output) throws MojoExecutionException { // create output try { output.getParentFile().mkdirs(); IOUtils.write(newContent, new FileOutputStream(output), Charset.defaultCharset()); } catch (IOException e) { throw new MojoExecutionException(String.format("Unable to write output file '%s' !", output), e); } } void write(AsciiDocBuilder asciiDocBuilder) throws MojoExecutionException { outputDirectory.mkdirs(); File output = getOutput(Format.adoc); try { // write adco file asciiDocBuilder.writeToFile(outputDirectory.getAbsolutePath(), getFilenameWithoutExtension(), StandardCharsets.UTF_8); if (Format.html.equals(format)) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); asciidoctor.requireLibrary("asciidoctor-diagram"); // write html from .adoc asciidoctor.convertFile(output, OptionsBuilder.options().backend("html5").safe(SafeMode.UNSAFE).asMap()); } } catch (IOException e) { throw new MojoExecutionException(String.format("Unable to convert asciidoc file '%s' to html !", output.getAbsolutePath()), e); } } protected abstract String getDefaultFilename(); private String getFilename() { return StringUtils.defaultIfBlank(outputFilename, getDefaultFilename()); } String getFilenameWithoutExtension() { String filename = getFilename(); return filename.indexOf(".") > 0 ? filename.substring(0, filename.lastIndexOf(".")) : filename; } File getOutput(Format desiredExtension) { String filename = StringUtils.defaultIfBlank(outputFilename, getDefaultFilename()); filename = filename.endsWith("." + desiredExtension.name()) ? filename : filename + "." + desiredExtension; return new File(outputDirectory, filename); } AsciiDocBuilder createAsciiDocBuilder() { AsciiDocBuilder asciiDocBuilder = new AsciiDocBuilder(); asciiDocBuilder.textLine(":sectlinks:"); asciiDocBuilder.textLine(":sectanchors:"); return asciiDocBuilder; } public enum Format { asciidoc, adoc, html, plantuml } }
refactoring
livingdoc-maven-plugin/src/main/java/ch/ifocusit/livingdoc/plugin/CommonMojoDefinition.java
refactoring
Java
mit
e0ae65995447e09c0caa5f469455bc786c8f3ffc
0
tlanders/javase8
package java8_in_action.chapter6; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; public class PrimesCollector implements Collector<Integer, List<Integer>, List<Integer>> { @Override public BiConsumer<List<Integer>, Integer> accumulator() { return (primeList, candidate) -> { System.out.println("candidate=" + candidate); int candidateRoot = (int) Math.sqrt(candidate); List<Integer> checkList = takeWhile(primeList, i -> i <= candidateRoot); if(isPrime(checkList, candidate)) { primeList.add(candidate); } }; } /** * Continues taking list items as long as the predicate returns true. When the predicate returns * false then the search stops and the list up to the last index is returned. * @param theList * @param thePredicate * @return */ protected static List<Integer> takeWhile(List<Integer> theList, Predicate<Integer> thePredicate) { for(int i = 0; i < theList.size(); i++) { Integer currentInt = theList.get(i); if(!thePredicate.test(currentInt)) { return theList.subList(0, i); } } return theList; } protected boolean isPrime(List<Integer> primeList, Integer candidate) { return primeList.stream() .peek(i -> System.out.println(" checking i=" + i)) .noneMatch(x -> candidate % x == 0); } @Override public Set<Characteristics> characteristics() { return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); } @Override public BinaryOperator<List<Integer>> combiner() { return (l1, l2) -> { l1.addAll(l2); return l1; }; } @Override public Function<List<Integer>, List<Integer>> finisher() { return Function.identity(); } @Override public Supplier<List<Integer>> supplier() { return ArrayList::new; } }
src/java8_in_action/chapter6/PrimesCollector.java
package java8_in_action.chapter6; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; public class PrimesCollector implements Collector<Integer, List<Integer>, List<Integer>> { @Override public BiConsumer<List<Integer>, Integer> accumulator() { return (primeList, candidate) -> { if(isPrime(primeList, candidate)) { primeList.add(candidate); } // if(primeList.stream().noneMatch(i -> candidate % i == 0 )) { // primeList.add(candidate); // }; }; } protected boolean isPrime(List<Integer> primeList, Integer candidate) { return primeList.stream().noneMatch(x -> candidate % x == 0); } @Override public Set<Characteristics> characteristics() { return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); } @Override public BinaryOperator<List<Integer>> combiner() { return (l1, l2) -> { l1.addAll(l2); return l1; }; } @Override public Function<List<Integer>, List<Integer>> finisher() { return Function.identity(); } @Override public Supplier<List<Integer>> supplier() { return ArrayList::new; } }
optimized primes that are checked against the candidate
src/java8_in_action/chapter6/PrimesCollector.java
optimized primes that are checked against the candidate
Java
mit
4e4c3118e8cd4aa8c30186e4856970793fde89a5
0
classgraph/classgraph,lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner
/* * This file is part of FastClasspathScanner. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Luke Hutchison * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.github.lukehutch.fastclasspathscanner.json.Id; import io.github.lukehutch.fastclasspathscanner.scanner.AnnotationInfo.AnnotationParamValue; import io.github.lukehutch.fastclasspathscanner.scanner.ScanResult.InfoObject; import io.github.lukehutch.fastclasspathscanner.typesignature.ClassTypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.MethodTypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.TypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.TypeUtils; import io.github.lukehutch.fastclasspathscanner.utils.AdditionOrderedSet; import io.github.lukehutch.fastclasspathscanner.utils.JarUtils; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList; import io.github.lukehutch.fastclasspathscanner.utils.Parser.ParseException; /** Holds metadata about a class encountered during a scan. */ public class ClassInfo extends InfoObject implements Comparable<ClassInfo> { /** Name of the class/interface/annotation. */ @Id String className; /** Class modifier flags, e.g. Modifier.PUBLIC */ int modifiers; /** True if the classfile indicated this is an interface. */ boolean isInterface; /** True if the classfile indicated this is an annotation. */ boolean isAnnotation; /** The class type signature string. */ String typeSignatureStr; /** The class type signature, parsed. */ transient ClassTypeSignature typeSignature; /** The fully-qualified containing method name, for anonymous inner classes. */ String fullyQualifiedContainingMethodName; /** * If true, this class is only being referenced by another class' classfile as a superclass / implemented * interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a * whitelisted (non-blacklisted) package. * * If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a * whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package. */ boolean isExternalClass; /** * The classpath element file (classpath root dir or jar) that this class was found within, or null if this * class was found in a module. */ transient File classpathElementFile; /** * The package root within a jarfile (e.g. "BOOT-INF/classes"), or the empty string if this is not a jarfile, or * the package root is the classpath element path (as opposed to within a subdirectory of the classpath * element). */ transient String jarfilePackageRoot = ""; /** * The classpath element module that this class was found within, or null if this class was found within a * directory or jar. */ transient ModuleRef classpathElementModuleRef; /** The classpath element URL (classpath root dir or jar) that this class was found within. */ transient URL classpathElementURL; /** The classloaders to try to load this class with before calling a MatchProcessor. */ transient ClassLoader[] classLoaders; /** The scan spec. */ transient ScanSpec scanSpec; /** Info on class annotations, including optional annotation param values. */ List<AnnotationInfo> annotationInfo; /** Info on fields. */ List<FieldInfo> fieldInfo; /** Reverse mapping from field name to FieldInfo. */ transient Map<String, FieldInfo> fieldNameToFieldInfo; /** Info on fields. */ List<MethodInfo> methodInfo; /** Reverse mapping from method name to MethodInfo. */ transient MultiMapKeyToList<String, MethodInfo> methodNameToMethodInfo; /** For annotations, the default values of parameters. */ List<AnnotationParamValue> annotationDefaultParamValues; transient ScanResult scanResult; /** The set of classes related to this one. */ Map<RelType, Set<ClassInfo>> relatedClasses = new HashMap<>(); /** * The static constant initializer values of static final fields, if a StaticFinalFieldMatchProcessor matched a * field in this class. */ Map<String, Object> staticFinalFieldNameToConstantInitializerValue; // ------------------------------------------------------------------------------------------------------------- /** Sets back-reference to scan result after scan is complete. */ @Override void setScanResult(final ScanResult scanResult) { this.scanResult = scanResult; if (annotationInfo != null) { for (final AnnotationInfo ai : annotationInfo) { ai.setScanResult(scanResult); } } if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { fi.setScanResult(scanResult); } } if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { mi.setScanResult(scanResult); } } } /** Sets back-reference to ScanSpec after deserialization. */ void setFields(final ScanSpec scanSpec) { this.scanSpec = scanSpec; if (this.methodInfo != null) { for (final MethodInfo methodInfo : this.methodInfo) { methodInfo.classInfo = this; methodInfo.className = this.className; } } } private static final int ANNOTATION_CLASS_MODIFIER = 0x2000; // ------------------------------------------------------------------------------------------------------------- /** * Get the name of this class. * * @return The class name. */ public String getClassName() { return className; } /** * Get a class reference for this class. Calls the classloader. * * @return The class reference. * @throws IllegalArgumentException * if there were problems loading or initializing the class. (Note that class initialization on load * is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) */ public Class<?> getClassRef() { return scanResult.classNameToClassRef(className); } /** * Get a class reference for this class, casting it to the requested interface or superclass type. Calls the * classloader. * * @param classType * The class to cast the result to. * @return The class reference. * @throws IllegalArgumentException * if there were problems loading the class, initializing the class, or casting it to the requested * type. (Note that class initialization on load is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) */ public <T> Class<T> getClassRef(final Class<T> classType) { return scanResult.classNameToClassRef(className, classType); } /** * Returns true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass / * implemented interface / annotation, but is not itself a whitelisted class. */ public boolean isExternalClass() { return isExternalClass; } /** * Get the class modifier flags, e.g. Modifier.PUBLIC * * @return The class modifiers. */ public int getClassModifiers() { return modifiers; } /** * Get the field modifiers as a String, e.g. "public static final". For the modifier bits, call getModifiers(). * * @return The class modifiers, in String format. */ public String getModifiersStr() { return TypeUtils.modifiersToString(modifiers, /* isMethod = */ false); } /** * Test whether this ClassInfo corresponds to a public class. * * @return true if this ClassInfo corresponds to a public class. */ public boolean isPublic() { return (modifiers & Modifier.PUBLIC) != 0; } /** * Test whether this ClassInfo corresponds to an abstract class. * * @return true if this ClassInfo corresponds to an abstract class. */ public boolean isAbstract() { return (modifiers & 0x400) != 0; } /** * Test whether this ClassInfo corresponds to a synthetic class. * * @return true if this ClassInfo corresponds to a synthetic class. */ public boolean isSynthetic() { return (modifiers & 0x1000) != 0; } /** * Test whether this ClassInfo corresponds to a final class. * * @return true if this ClassInfo corresponds to a final class. */ public boolean isFinal() { return (modifiers & Modifier.FINAL) != 0; } /** * Test whether this ClassInfo corresponds to an annotation. * * @return true if this ClassInfo corresponds to an annotation. */ public boolean isAnnotation() { return isAnnotation; } /** * Test whether this ClassInfo corresponds to an interface. * * @return true if this ClassInfo corresponds to an interface. */ public boolean isInterface() { return isInterface; } /** * Test whether this ClassInfo corresponds to an enum. * * @return true if this ClassInfo corresponds to an enum. */ public boolean isEnum() { return (modifiers & 0x4000) != 0; } /** * Get the low-level Java type signature for the class, including generic type parameters, if available (else * returns null). * * @return The type signature, in string format */ public String getTypeSignatureStr() { return typeSignatureStr; } /** * Get the type signature for the class, if available (else returns null). * * @return The class type signature. */ public ClassTypeSignature getTypeSignature() { if (typeSignature == null) { return null; } if (typeSignature == null) { try { typeSignature = ClassTypeSignature.parse(typeSignatureStr); } catch (final ParseException e) { throw new IllegalArgumentException(e); } } return typeSignature; } /** * The classpath element URL (classpath root dir or jar) that this class was found within. This will consist of * exactly one entry, so you should call the getClasspathElementURL() method instead. * * @return The classpath element URL, stored in a set. */ @Deprecated public Set<URL> getClasspathElementURLs() { final Set<URL> urls = new HashSet<>(); urls.add(getClasspathElementURL()); return urls; } /** * The classpath element URL (for a classpath root dir, jar or module) that this class was found within. * * N.B. Classpath elements are handled as File objects internally. It is much faster to call * getClasspathElementFile() and/or getClasspathElementModule() -- the conversion of a File into a URL (via * File#toURI()#toURL()) is time consuming. * * @return The classpath element, as a URL. */ public URL getClasspathElementURL() { if (classpathElementURL == null) { try { if (classpathElementModuleRef != null) { classpathElementURL = classpathElementModuleRef.getModuleLocation().toURL(); } else { classpathElementURL = getClasspathElementFile().toURI().toURL(); } } catch (final MalformedURLException e) { // Shouldn't happen; File objects should always be able to be turned into URIs and then URLs throw new RuntimeException(e); } } return classpathElementURL; } /** * The classpath element file (classpath root dir or jar) that this class was found within, or null if this * class was found in a module. * * @return The classpath element, as a File. */ public File getClasspathElementFile() { return classpathElementFile; } /** * The classpath element module that this class was found within, or null if this class was found in a directory * or jar. * * @return The classpath element, as a ModuleRef. */ public ModuleRef getClasspathElementModuleRef() { return classpathElementModuleRef; } /** * Get the ClassLoader(s) to use when trying to load the class. Typically there will only be one. If there is * more than one, they will be listed in the order they should be called, until one is able to load the class. * * <p> * This is deprecated, because a different ClassLoader may need to be created dynamically if classloading fails * for the class (specifically to handle the case of needing to load classes from a Spring-Boot jar or similar, * when running outside that jar's own classloader -- see bug #209). If you need the classloader that loaded the * class, call {@link #getClassRef()} and then get the classloader from that class ref. * * @return The Classloader(s) to use when trying to load the class. */ @Deprecated public ClassLoader[] getClassLoaders() { return classLoaders; } /** Compare based on class name. */ @Override public int compareTo(final ClassInfo o) { return this.className.compareTo(o.className); } /** Use class name for equals(). */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ClassInfo other = (ClassInfo) obj; return className.equals(other.className); } /** Use hash code of class name. */ @Override public int hashCode() { return className != null ? className.hashCode() : 33; } @Override public String toString() { final ClassTypeSignature typeSig = getTypeSignature(); if (typeSig != null) { return typeSig.toString(modifiers, isAnnotation, isInterface, className); } else { final StringBuilder buf = new StringBuilder(); TypeUtils.modifiersToString(modifiers, /* isMethod = */ false, buf); if (buf.length() > 0) { buf.append(' '); } buf.append(isAnnotation ? "@interface " : isInterface ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class "); buf.append(className); return buf.toString(); } } // ------------------------------------------------------------------------------------------------------------- /** How classes are related. */ private static enum RelType { // Classes: /** * Superclasses of this class, if this is a regular class. * * <p> * (Should consist of only one entry, or null if superclass is java.lang.Object or unknown). */ SUPERCLASSES, /** Subclasses of this class, if this is a regular class. */ SUBCLASSES, /** Indicates that an inner class is contained within this one. */ CONTAINS_INNER_CLASS, /** Indicates that an outer class contains this one. (Should only have zero or one entries.) */ CONTAINED_WITHIN_OUTER_CLASS, // Interfaces: /** * Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an * interface. * * <p> * (May also include annotations, since annotations are interfaces, so you can implement an annotation.) */ IMPLEMENTED_INTERFACES, /** * Classes that implement this interface (including sub-interfaces), if this is an interface. */ CLASSES_IMPLEMENTING, // Class annotations: /** * Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is * an annotation. */ CLASS_ANNOTATIONS, /** Classes annotated with this annotation, if this is an annotation. */ CLASSES_WITH_CLASS_ANNOTATION, // Method annotations: /** Annotations on one or more methods of this class. */ METHOD_ANNOTATIONS, /** * Classes that have one or more methods annotated with this annotation, if this is an annotation. */ CLASSES_WITH_METHOD_ANNOTATION, // Field annotations: /** Annotations on one or more fields of this class. */ FIELD_ANNOTATIONS, /** * Classes that have one or more fields annotated with this annotation, if this is an annotation. */ CLASSES_WITH_FIELD_ANNOTATION, } ClassInfo() { } private ClassInfo(final String className, final int classModifiers, final boolean isExternalClass, final ScanSpec scanSpec) { this.className = className; if (className.endsWith(";")) { // Spot check to make sure class names were parsed from descriptors throw new RuntimeException("Bad class name"); } this.modifiers = classModifiers; this.isExternalClass = isExternalClass; this.scanSpec = scanSpec; } /** The class type to return. */ static enum ClassType { /** Get all class types. */ ALL, /** A standard class (not an interface or annotation). */ STANDARD_CLASS, /** * An interface (this is named "implemented interface" rather than just "interface" to distinguish it from * an annotation.) */ IMPLEMENTED_INTERFACE, /** An annotation. */ ANNOTATION, /** An interface or annotation (used since you can actually implement an annotation). */ INTERFACE_OR_ANNOTATION, } /** Get the classes related to this one in the specified way. */ static Set<ClassInfo> filterClassInfo(final Set<ClassInfo> classInfoSet, final boolean removeExternalClassesIfStrictWhitelist, final ScanSpec scanSpec, final ClassType... classTypes) { if (classInfoSet == null) { return Collections.emptySet(); } boolean includeAllTypes = classTypes.length == 0; boolean includeStandardClasses = false; boolean includeImplementedInterfaces = false; boolean includeAnnotations = false; for (final ClassType classType : classTypes) { switch (classType) { case ALL: includeAllTypes = true; break; case STANDARD_CLASS: includeStandardClasses = true; break; case IMPLEMENTED_INTERFACE: includeImplementedInterfaces = true; break; case ANNOTATION: includeAnnotations = true; break; case INTERFACE_OR_ANNOTATION: includeImplementedInterfaces = includeAnnotations = true; break; default: throw new RuntimeException("Unknown ClassType: " + classType); } } if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) { includeAllTypes = true; } // Do two passes with the same filter logic to avoid copying the set if nothing is filtered out final Set<ClassInfo> classInfoSetFiltered = new HashSet<>(classInfoSet.size()); for (final ClassInfo classInfo : classInfoSet) { // Check class type against requested type(s) if (includeAllTypes // || includeStandardClasses && classInfo.isStandardClass() || includeImplementedInterfaces && classInfo.isImplementedInterface() || includeAnnotations && classInfo.isAnnotation()) { // Check whether class should be visible in results final boolean isBlacklisted = scanSpec.classIsBlacklisted(classInfo.className); final boolean isSystemClass = JarUtils.isInSystemPackageOrModule(classInfo.className); final boolean includeExternalClasses = scanSpec.enableExternalClasses || !removeExternalClassesIfStrictWhitelist; final boolean notExternalOrIncludeExternal = !classInfo.isExternalClass || includeExternalClasses; if (notExternalOrIncludeExternal // // If this is a system class, ignore blacklist unless the blanket blacklisting of // all system jars or modules has been disabled, and this system class was specifically // blacklisted by name && (!isBlacklisted || (isSystemClass && scanSpec.blacklistSystemJarsOrModules))) { // Class passed filter criteria classInfoSetFiltered.add(classInfo); } } } return classInfoSetFiltered; } /** * Get the sorted list of the names of classes given a collection of {@link ClassInfo} objects. (Class names are * not deduplicated.) * * @param classInfoColl * The collection of {@link ClassInfo} objects. * @return The names of classes in the collection. */ public static List<String> getClassNames(final Collection<ClassInfo> classInfoColl) { if (classInfoColl.isEmpty()) { return Collections.emptyList(); } else { final ArrayList<String> classNames = new ArrayList<>(classInfoColl.size()); for (final ClassInfo classInfo : classInfoColl) { classNames.add(classInfo.className); } Collections.sort(classNames); return classNames; } } /** Get the classes directly related to this ClassInfo object the specified way. */ private Set<ClassInfo> getDirectlyRelatedClasses(final RelType relType) { final Set<ClassInfo> relatedClassClassInfo = relatedClasses.get(relType); return relatedClassClassInfo == null ? Collections.<ClassInfo> emptySet() : relatedClassClassInfo; } /** * Find all ClassInfo nodes reachable from this ClassInfo node over the given relationship type links (not * including this class itself). */ private Set<ClassInfo> getReachableClasses(final RelType relType) { final Set<ClassInfo> directlyRelatedClasses = this.getDirectlyRelatedClasses(relType); if (directlyRelatedClasses.isEmpty()) { return directlyRelatedClasses; } final Set<ClassInfo> reachableClasses = new HashSet<>(directlyRelatedClasses); if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) { // For method and field annotations, need to change the RelType when finding meta-annotations for (final ClassInfo annotation : directlyRelatedClasses) { reachableClasses.addAll(annotation.getReachableClasses(RelType.CLASS_ANNOTATIONS)); } } else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION || relType == RelType.CLASSES_WITH_FIELD_ANNOTATION) { // If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then // look for the methods or fields that they annotate for (final ClassInfo subAnnotation : filterClassInfo( getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION)) { reachableClasses.addAll(subAnnotation.getDirectlyRelatedClasses(relType)); } } else { // For other relationship types, the reachable type stays the same over the transitive closure. Find the // transitive closure, breaking cycles where necessary. final LinkedList<ClassInfo> queue = new LinkedList<>(); queue.addAll(directlyRelatedClasses); while (!queue.isEmpty()) { final ClassInfo head = queue.removeFirst(); for (final ClassInfo directlyReachableFromHead : head.getDirectlyRelatedClasses(relType)) { // Don't get in cycle if (reachableClasses.add(directlyReachableFromHead)) { queue.add(directlyReachableFromHead); } } } } return reachableClasses; } /** * Add a class with a given relationship type. Test whether the collection changed as a result of the call. */ private boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) { Set<ClassInfo> classInfoSet = relatedClasses.get(relType); if (classInfoSet == null) { relatedClasses.put(relType, classInfoSet = new HashSet<>(4)); } return classInfoSet.add(classInfo); } /** * Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should * only ever be constructed by a single thread. */ private static ClassInfo getOrCreateClassInfo(final String className, final int classModifiers, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo) { ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ true, scanSpec)); } return classInfo; } /** Add a superclass to this class. */ void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) { if (superclassName != null) { final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo); superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this); } } /** Add an annotation to this class. */ void addClassAnnotation(final AnnotationInfo classAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; if (this.annotationInfo == null) { this.annotationInfo = new ArrayList<>(); } this.annotationInfo.add(classAnnotationInfo); annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION classAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_CLASS_ANNOTATION, this); } /** Add a method annotation to this class. */ void addMethodAnnotation(final AnnotationInfo methodAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(methodAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION methodAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.METHOD_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_ANNOTATION, this); } /** Add a field annotation to this class. */ void addFieldAnnotation(final AnnotationInfo fieldAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION fieldAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.FIELD_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_FIELD_ANNOTATION, this); } /** Add an implemented interface to this class. */ void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, /* classModifiers = */ Modifier.INTERFACE, scanSpec, classNameToClassInfo); interfaceClassInfo.isInterface = true; interfaceClassInfo.modifiers |= Modifier.INTERFACE; this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo); interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this); } /** Add class containment info */ static void addClassContainment(final List<SimpleEntry<String, String>> classContainmentEntries, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo) { for (final SimpleEntry<String, String> ent : classContainmentEntries) { final String innerClassName = ent.getKey(); final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(innerClassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); final String outerClassName = ent.getValue(); final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(outerClassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo); outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo); } } /** Add containing method name, for anonymous inner classes */ void addFullyQualifiedContainingMethodName(final String fullyQualifiedContainingMethodName) { this.fullyQualifiedContainingMethodName = fullyQualifiedContainingMethodName; } /** Add a static final field's constant initializer value. */ void addStaticFinalFieldConstantInitializerValue(final String fieldName, final Object constValue) { if (this.staticFinalFieldNameToConstantInitializerValue == null) { this.staticFinalFieldNameToConstantInitializerValue = new HashMap<>(); } this.staticFinalFieldNameToConstantInitializerValue.put(fieldName, constValue); } /** Add field info. */ void addFieldInfo(final List<FieldInfo> fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final FieldInfo fieldInfo : fieldInfoList) { final List<AnnotationInfo> fieldAnnotationInfoList = fieldInfo.annotationInfo; if (fieldAnnotationInfoList != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldAnnotationInfoList) { final ClassInfo classInfo = getOrCreateClassInfo(fieldAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); fieldAnnotationInfo.addDefaultValues(classInfo.annotationDefaultParamValues); } } } if (this.fieldInfo == null) { this.fieldInfo = fieldInfoList; } else { this.fieldInfo.addAll(fieldInfoList); } } /** Add method info. */ void addMethodInfo(final List<MethodInfo> methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final MethodInfo methodInfo : methodInfoList) { final List<AnnotationInfo> methodAnnotationInfoList = methodInfo.annotationInfo; if (methodAnnotationInfoList != null) { for (final AnnotationInfo methodAnnotationInfo : methodAnnotationInfoList) { methodAnnotationInfo.addDefaultValues( getOrCreateClassInfo(methodAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo).annotationDefaultParamValues); } } final AnnotationInfo[][] methodParamAnnotationInfoList = methodInfo.parameterAnnotationInfo; if (methodParamAnnotationInfoList != null) { for (int i = 0; i < methodParamAnnotationInfoList.length; i++) { final AnnotationInfo[] paramAnnotationInfoArr = methodParamAnnotationInfoList[i]; if (paramAnnotationInfoArr != null) { for (int j = 0; j < paramAnnotationInfoArr.length; j++) { final AnnotationInfo paramAnnotationInfo = paramAnnotationInfoArr[j]; paramAnnotationInfo .addDefaultValues(getOrCreateClassInfo(paramAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo).annotationDefaultParamValues); } } } } // Add back-link from MethodInfo to enclosing ClassInfo instance methodInfo.classInfo = this; } if (this.methodInfo == null) { this.methodInfo = methodInfoList; } else { this.methodInfo.addAll(methodInfoList); } } /** Add the class type signature, including type params */ void addTypeSignature(final String typeSignatureStr) { if (this.typeSignatureStr == null) { this.typeSignatureStr = typeSignatureStr; } else { if (typeSignatureStr != null && !this.typeSignatureStr.equals(typeSignatureStr)) { throw new RuntimeException("Trying to merge two classes with different type signatures for class " + className + ": " + this.typeSignatureStr + " ; " + typeSignatureStr); } } } /** * Add annotation default values. (Only called in the case of annotation class definitions, when the annotation * has default parameter values.) */ void addAnnotationParamDefaultValues(final List<AnnotationParamValue> paramNamesAndValues) { if (this.annotationDefaultParamValues == null) { this.annotationDefaultParamValues = paramNamesAndValues; } else { this.annotationDefaultParamValues.addAll(paramNamesAndValues); } } /** * Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe, * should be run in single threaded context. */ static ClassInfo addScannedClass(final String className, final int classModifiers, final boolean isInterface, final boolean isAnnotation, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo, final ClasspathElement classpathElement, final LogNode log) { boolean classEncounteredMultipleTimes = false; ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { // This is the first time this class has been seen, add it classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ false, scanSpec)); } else { if (!classInfo.isExternalClass) { classEncounteredMultipleTimes = true; } } // Remember which classpath element (zipfile / classpath root directory / module) the class was found in final ModuleRef modRef = classpathElement.getClasspathElementModuleRef(); final File file = classpathElement.getClasspathElementFile(log); if ((classInfo.classpathElementModuleRef != null && modRef != null && !classInfo.classpathElementModuleRef.equals(modRef)) || (classInfo.classpathElementFile != null && file != null && !classInfo.classpathElementFile.equals(file))) { classEncounteredMultipleTimes = true; } if (classEncounteredMultipleTimes) { // The same class was encountered more than once in a single jarfile -- should not happen. However, // actually there is no restriction for paths within a zipfile to be unique (!!), and in fact // zipfiles in the wild do contain the same classfiles multiple times with the same exact path, // e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class if (log != null) { log.log("Class " + className + " is defined in multiple different classpath elements or modules -- " + "ClassInfo#getClasspathElementFile() and/or ClassInfo#getClasspathElementModuleRef " + "will only return the first of these; attempting to merge info from all copies of " + "the classfile"); } } if (classInfo.classpathElementFile == null) { // If class was found in more than one classpath element, keep the first classpath element reference classInfo.classpathElementFile = file; // Save jarfile package root, if any classInfo.jarfilePackageRoot = classpathElement.getJarfilePackageRoot(); } if (classInfo.classpathElementModuleRef == null) { // If class was found in more than one module, keep the first module reference classInfo.classpathElementModuleRef = modRef; } // Remember which classloader handles the class was found in, for classloading final ClassLoader[] classLoaders = classpathElement.getClassLoaders(); if (classInfo.classLoaders == null) { classInfo.classLoaders = classLoaders; } else if (classLoaders != null && !classInfo.classLoaders.equals(classLoaders)) { // Merge together ClassLoader list (concatenate and dedup) final AdditionOrderedSet<ClassLoader> allClassLoaders = new AdditionOrderedSet<>( classInfo.classLoaders); for (final ClassLoader classLoader : classLoaders) { allClassLoaders.add(classLoader); } final List<ClassLoader> classLoaderOrder = allClassLoaders.toList(); classInfo.classLoaders = classLoaderOrder.toArray(new ClassLoader[classLoaderOrder.size()]); } // Mark the classfile as scanned classInfo.isExternalClass = false; // Merge modifiers classInfo.modifiers |= classModifiers; classInfo.isInterface |= isInterface; classInfo.isAnnotation |= isAnnotation; return classInfo; } // ------------------------------------------------------------------------------------------------------------- /** * Get the names of any classes (other than this class itself) referenced in this class' type descriptor, or the * type descriptors of fields or methods (if field or method info is recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInAnyTypeDescriptor() { final Set<String> referencedClassNames = new HashSet<>(); if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { final MethodTypeSignature methodSig = mi.getTypeSignature(); if (methodSig != null) { methodSig.getAllReferencedClassNames(referencedClassNames); } } } if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { final TypeSignature fieldSig = fi.getTypeSignature(); if (fieldSig != null) { fieldSig.getAllReferencedClassNames(referencedClassNames); } } } final ClassTypeSignature classSig = getTypeSignature(); if (classSig != null) { classSig.getAllReferencedClassNames(referencedClassNames); } // Remove self-reference, and any reference to java.lang.Object referencedClassNames.remove(className); referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes referenced in the type descriptors of this class' methods (if method info is * recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInMethodTypeDescriptors() { final Set<String> referencedClassNames = new HashSet<>(); if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { final MethodTypeSignature methodSig = mi.getTypeSignature(); if (methodSig != null) { methodSig.getAllReferencedClassNames(referencedClassNames); } } } // Remove any reference to java.lang.Object referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes referenced in the type descriptors of this class' fields (if field info is * recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInFieldTypeDescriptors() { final Set<String> referencedClassNames = new HashSet<>(); if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { final TypeSignature fieldSig = fi.getTypeSignature(); if (fieldSig != null) { fieldSig.getAllReferencedClassNames(referencedClassNames); } } } // Remove any reference to java.lang.Object referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes (other than this class itself) referenced in the type descriptor of this class. * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInClassTypeDescriptor() { final Set<String> referencedClassNames = new HashSet<>(); final ClassTypeSignature classSig = getTypeSignature(); if (classSig != null) { classSig.getAllReferencedClassNames(referencedClassNames); } // Remove self-reference, and any reference to java.lang.Object referencedClassNames.remove(className); referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } // ------------------------------------------------------------------------------------------------------------- // Standard classes /** * Get the names of all classes, interfaces and annotations found during the scan, or the empty list if none. * * @return the sorted unique list of names of all classes, interfaces and annotations found during the scan, or * the empty list if none. */ static List<String> getNamesOfAllClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL)); } /** * Get the names of all standard (non-interface/annotation) classes found during the scan, or the empty list if * none. * * @return the sorted unique names of all standard (non-interface/annotation) classes found during the scan, or * the empty list if none. */ static List<String> getNamesOfAllStandardClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS)); } /** * Test whether this class is a standard class (not an annotation or interface). * * @return true if this class is a standard class (not an annotation or interface). */ public boolean isStandardClass() { return !(isAnnotation || isInterface); } // ------------- /** * Get the subclasses of this class. * * @return the set of subclasses of this class, or the empty set if none. */ public Set<ClassInfo> getSubclasses() { // Make an exception for querying all subclasses of java.lang.Object return filterClassInfo(getReachableClasses(RelType.SUBCLASSES), /* removeExternalClassesIfStrictWhitelist = */ !className.equals("java.lang.Object"), scanSpec, ClassType.ALL); } /** * Get the names of subclasses of this class. * * @return the sorted list of names of the subclasses of this class, or the empty list if none. */ public List<String> getNamesOfSubclasses() { return getClassNames(getSubclasses()); } /** * Test whether this class has the named class as a subclass. * * @param subclassName * The name of the subclass. * @return true if this class has the named class as a subclass. */ public boolean hasSubclass(final String subclassName) { return getNamesOfSubclasses().contains(subclassName); } // ------------- /** * Get the direct subclasses of this class. * * @return the set of direct subclasses of this class, or the empty set if none. */ public Set<ClassInfo> getDirectSubclasses() { // Make an exception for querying all direct subclasses of java.lang.Object return filterClassInfo(getDirectlyRelatedClasses(RelType.SUBCLASSES), /* removeExternalClassesIfStrictWhitelist = */ !className.equals("java.lang.Object"), scanSpec, ClassType.ALL); } /** * Get the names of direct subclasses of this class. * * @return the sorted list of names of direct subclasses of this class, or the empty list if none. */ public List<String> getNamesOfDirectSubclasses() { return getClassNames(getDirectSubclasses()); } /** * Test whether this class has the named direct subclass. * * @param directSubclassName * The name of the direct subclass. * @return true if this class has the named direct subclass. */ public boolean hasDirectSubclass(final String directSubclassName) { return getNamesOfDirectSubclasses().contains(directSubclassName); } // ------------- /** * Get all direct and indirect superclasses of this class (i.e. the direct superclass(es) of this class, and * their superclass(es), all the way up to the top of the class hierarchy). * * <p> * (Includes the union of all mixin superclass hierarchies in the case of Scala mixins.) * * @return the set of all superclasses of this class, or the empty set if none. */ public Set<ClassInfo> getSuperclasses() { return filterClassInfo(getReachableClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of all direct and indirect superclasses of this class (i.e. the direct superclass(es) of this * class, and their superclass(es), all the way up to the top of the class hierarchy). * * <p> * (Includes the union of all mixin superclass hierarchies in the case of Scala mixins.) * * @return the sorted list of names of all superclasses of this class, or the empty list if none. */ public List<String> getNamesOfSuperclasses() { return getClassNames(getSuperclasses()); } /** * Test whether this class extends the named superclass, directly or indirectly. * * @param superclassName * The name of the superclass. * @return true if this class has the named direct or indirect superclass. */ public boolean hasSuperclass(final String superclassName) { return getNamesOfSuperclasses().contains(superclassName); } /** * Returns true if this is an inner class (call isAnonymousInnerClass() to test if this is an anonymous inner * class). If true, the containing class can be determined by calling getOuterClasses() or getOuterClassNames(). * * @return True if this class is an inner class. */ public boolean isInnerClass() { return !getOuterClasses().isEmpty(); } /** * Returns the containing outer classes, for inner classes. Note that all containing outer classes are returned, * not just the innermost containing outer class. Returns the empty set if this is not an inner class. * * @return The set of containing outer classes. */ public Set<ClassInfo> getOuterClasses() { return filterClassInfo(getReachableClasses(RelType.CONTAINED_WITHIN_OUTER_CLASS), /* removeExternalClassesIfStrictWhitelist = */ false, scanSpec, ClassType.ALL); } /** * Returns the names of the containing outer classes, for inner classes. Note that all containing outer classes * are returned, not just the innermost containing outer class. Returns the empty list if this is not an inner * class. * * @return The name of containing outer classes. */ public List<String> getOuterClassName() { return getClassNames(getOuterClasses()); } /** * Returns true if this class contains inner classes. If true, the inner classes can be determined by calling * getInnerClasses() or getInnerClassNames(). * * @return True if this is an outer class. */ public boolean isOuterClass() { return !getInnerClasses().isEmpty(); } /** * Returns the inner classes contained within this class. Returns the empty set if none. * * @return The set of inner classes within this class. */ public Set<ClassInfo> getInnerClasses() { return filterClassInfo(getReachableClasses(RelType.CONTAINS_INNER_CLASS), /* removeExternalClassesIfStrictWhitelist = */ false, scanSpec, ClassType.ALL); } /** * Returns the names of inner classes contained within this class. Returns the empty list if none. * * @return The names of inner classes within this class. */ public List<String> getInnerClassNames() { return getClassNames(getInnerClasses()); } /** * Returns true if this is an anonymous inner class. If true, the name of the containing method can be obtained * by calling getFullyQualifiedContainingMethodName(). * * @return True if this is an anonymous inner class. */ public boolean isAnonymousInnerClass() { return fullyQualifiedContainingMethodName != null; } /** * Get fully-qualified containing method name (i.e. fully qualified classname, followed by dot, followed by * method name, for the containing method that creates an anonymous inner class. * * @return The fully-qualified method name of the method that this anonymous inner class was defined within. */ public String getFullyQualifiedContainingMethodName() { return fullyQualifiedContainingMethodName; } // ------------- /** * Get the direct superclasses of this class. * * <p> * Typically the returned set will contain zero or one direct superclass(es), but may contain more than one * direct superclass in the case of Scala mixins. * * @return the direct superclasses of this class, or the empty set if none. */ public Set<ClassInfo> getDirectSuperclasses() { return filterClassInfo(getDirectlyRelatedClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Convenience method for getting the single direct superclass of this class. Returns null if the class does not * have a superclass (e.g. in the case of interfaces). Throws IllegalArgumentException if there are multiple * direct superclasses (e.g. in the case of Scala mixins) -- use getDirectSuperclasses() if you need to deal * with mixins. * * @return the direct superclass of this class, or null if the class does not have a superclass. * @throws IllegalArgumentException * if there are multiple direct superclasses of this class (in the case of Scala mixins). */ public ClassInfo getDirectSuperclass() { final Set<ClassInfo> directSuperclasses = getDirectSuperclasses(); final int numDirectSuperclasses = directSuperclasses.size(); if (numDirectSuperclasses == 0) { return null; } else if (numDirectSuperclasses > 1) { throw new IllegalArgumentException("Class has multiple direct superclasses: " + directSuperclasses.toString() + " -- need to call getDirectSuperclasses() instead"); } else { return directSuperclasses.iterator().next(); } } /** * Get the names of direct superclasses of this class. * * <p> * Typically the returned list will contain zero or one direct superclass name(s), but may contain more than one * direct superclass name in the case of Scala mixins. * * @return the direct superclasses of this class, or the empty set if none. */ public List<String> getNamesOfDirectSuperclasses() { return getClassNames(getDirectSuperclasses()); } /** * Convenience method for getting the name of the single direct superclass of this class. Returns null if the * class does not have a superclass (e.g. in the case of interfaces). Throws IllegalArgumentException if there * are multiple direct superclasses (e.g. in the case of Scala mixins) -- use getNamesOfDirectSuperclasses() if * you need to deal with mixins. * * @return the name of the direct superclass of this class, or null if the class does not have a superclass. * @throws IllegalArgumentException * if there are multiple direct superclasses of this class (in the case of Scala mixins). */ public String getNameOfDirectSuperclass() { final List<String> namesOfDirectSuperclasses = getNamesOfDirectSuperclasses(); final int numDirectSuperclasses = namesOfDirectSuperclasses.size(); if (numDirectSuperclasses == 0) { return null; } else if (numDirectSuperclasses > 1) { throw new IllegalArgumentException( "Class has multiple direct superclasses: " + namesOfDirectSuperclasses.toString() + " -- need to call getNamesOfDirectSuperclasses() instead"); } else { return namesOfDirectSuperclasses.get(0); } } /** * Test whether this class directly extends the named superclass. * * <p> * If this class has multiple direct superclasses (in the case of Scala mixins), returns true if the named * superclass is one of the direct superclasses of this class. * * @param directSuperclassName * The direct superclass name to match. If null, matches classes without a direct superclass (e.g. * interfaces). Note that standard classes that do not extend another class have java.lang.Object as * their superclass. * @return true if this class has the named class as its direct superclass (or as one of its direct * superclasses, in the case of Scala mixins). */ public boolean hasDirectSuperclass(final String directSuperclassName) { final List<String> namesOfDirectSuperclasses = getNamesOfDirectSuperclasses(); if (directSuperclassName == null && namesOfDirectSuperclasses.isEmpty()) { return true; } else if (directSuperclassName == null || namesOfDirectSuperclasses.isEmpty()) { return false; } else { return namesOfDirectSuperclasses.contains(directSuperclassName); } } // ------------------------------------------------------------------------------------------------------------- // Interfaces /** * Get the names of interface classes found during the scan. * * @return the sorted list of names of interface classes found during the scan, or the empty list if none. */ static List<String> getNamesOfAllInterfaceClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE)); } /** * Test whether this class is an "implemented interface" (meaning a standard, non-annotation interface, or an * annotation that has also been implemented as an interface by some class). * * <p> * Annotations are interfaces, but you can also implement an annotation, so to we Test whether an interface * (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not * an interface but not an annotation. * * <p> * (This is named "implemented interface" rather than just "interface" to distinguish it from an annotation.) * * @return true if this class is an "implemented interface". */ public boolean isImplementedInterface() { return !getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING).isEmpty() || (isInterface && !isAnnotation); } // ------------- /** * Get the subinterfaces of this interface. * * @return the set of subinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getSubinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of subinterfaces of this interface. * * @return the sorted list of names of subinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfSubinterfaces() { return getClassNames(getSubinterfaces()); } /** * Test whether this class is has the named subinterface. * * @param subinterfaceName * The name of the subinterface. * @return true if this class is an interface and has the named subinterface. */ public boolean hasSubinterface(final String subinterfaceName) { return getNamesOfSubinterfaces().contains(subinterfaceName); } // ------------- /** * Get the direct subinterfaces of this interface. * * @return the set of direct subinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getDirectSubinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of direct subinterfaces of this interface. * * @return the sorted list of names of direct subinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfDirectSubinterfaces() { return getClassNames(getDirectSubinterfaces()); } /** * Test whether this class is and interface and has the named direct subinterface. * * @param directSubinterfaceName * The name of the direct subinterface. * @return true if this class is and interface and has the named direct subinterface. */ public boolean hasDirectSubinterface(final String directSubinterfaceName) { return getNamesOfDirectSubinterfaces().contains(directSubinterfaceName); } // ------------- /** * Get the superinterfaces of this interface. * * @return the set of superinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getSuperinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of superinterfaces of this interface. * * @return the sorted list of names of superinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfSuperinterfaces() { return getClassNames(getSuperinterfaces()); } /** * Test whether this class is an interface and has the named superinterface. * * @param superinterfaceName * The name of the superinterface. * @return true if this class is an interface and has the named superinterface. */ public boolean hasSuperinterface(final String superinterfaceName) { return getNamesOfSuperinterfaces().contains(superinterfaceName); } // ------------- /** * Get the direct superinterfaces of this interface. * * @return the set of direct superinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getDirectSuperinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of direct superinterfaces of this interface. * * @return the sorted list of names of direct superinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfDirectSuperinterfaces() { return getClassNames(getDirectSuperinterfaces()); } /** * Test whether this class is an interface and has the named direct superinterface. * * @param directSuperinterfaceName * The name of the direct superinterface. * @return true if this class is an interface and has the named direct superinterface. */ public boolean hasDirectSuperinterface(final String directSuperinterfaceName) { return getNamesOfDirectSuperinterfaces().contains(directSuperinterfaceName); } // ------------- /** * Get the interfaces implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces implemented by this standard class, or by one of its superclasses. Returns the * empty set if none. */ public Set<ClassInfo> getImplementedInterfaces() { if (!isStandardClass()) { return Collections.<ClassInfo> emptySet(); } else { final Set<ClassInfo> superclasses = filterClassInfo(getReachableClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); // Subclasses of implementing classes also implement the interface final Set<ClassInfo> allInterfaces = new HashSet<>(); allInterfaces.addAll(getReachableClasses(RelType.IMPLEMENTED_INTERFACES)); for (final ClassInfo superClass : superclasses) { allInterfaces.addAll(superClass.getReachableClasses(RelType.IMPLEMENTED_INTERFACES)); } return allInterfaces; } } /** * Get the interfaces implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces implemented by this standard class, or by one of its superclasses. Returns the * empty list if none. */ public List<String> getNamesOfImplementedInterfaces() { return getClassNames(getImplementedInterfaces()); } /** * Test whether this standard class implements the named interface, or by one of its superclasses. * * @param interfaceName * The name of the interface. * @return true this class is a standard class, and it (or one of its superclasses) implements the named * interface. */ public boolean implementsInterface(final String interfaceName) { return getNamesOfImplementedInterfaces().contains(interfaceName); } // ------------- /** * Get the interfaces directly implemented by this standard class. * * @return the set of interfaces directly implemented by this standard class. Returns the empty set if none. */ public Set<ClassInfo> getDirectlyImplementedInterfaces() { return !isStandardClass() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the interfaces directly implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces directly implemented by this standard class, or by one of its superclasses. * Returns the empty list if none. */ public List<String> getNamesOfDirectlyImplementedInterfaces() { return getClassNames(getDirectlyImplementedInterfaces()); } /** * Test whether this standard class directly implements the named interface, or by one of its superclasses. * * @param interfaceName * The name of the interface. * @return true this class is a standard class, and directly implements the named interface. */ public boolean directlyImplementsInterface(final String interfaceName) { return getNamesOfDirectlyImplementedInterfaces().contains(interfaceName); } // ------------- /** * Get the classes that implement this interface, and their subclasses. * * @return the set of classes implementing this interface, or the empty set if none. */ public Set<ClassInfo> getClassesImplementing() { if (!isImplementedInterface()) { return Collections.<ClassInfo> emptySet(); } else { final Set<ClassInfo> implementingClasses = filterClassInfo( getReachableClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); // Subclasses of implementing classes also implement the interface final Set<ClassInfo> allImplementingClasses = new HashSet<>(); for (final ClassInfo implementingClass : implementingClasses) { allImplementingClasses.add(implementingClass); allImplementingClasses.addAll(implementingClass.getReachableClasses(RelType.SUBCLASSES)); } return allImplementingClasses; } } /** * Get the names of classes that implement this interface, and the names of their subclasses. * * @return the sorted list of names of classes implementing this interface, or the empty list if none. */ public List<String> getNamesOfClassesImplementing() { return getClassNames(getClassesImplementing()); } /** * Test whether this class is implemented by the named class, or by one of its superclasses. * * @param className * The name of the class. * @return true if this class is implemented by the named class, or by one of its superclasses. */ public boolean isImplementedByClass(final String className) { return getNamesOfClassesImplementing().contains(className); } // ------------- /** * Get the classes that directly implement this interface, and their subclasses. * * @return the set of classes directly implementing this interface, or the empty set if none. */ public Set<ClassInfo> getClassesDirectlyImplementing() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); } /** * Get the names of classes that directly implement this interface, and the names of their subclasses. * * @return the sorted list of names of classes directly implementing this interface, or the empty list if none. */ public List<String> getNamesOfClassesDirectlyImplementing() { return getClassNames(getClassesDirectlyImplementing()); } /** * Test whether this class is directly implemented by the named class, or by one of its superclasses. * * @param className * The name of the class. * @return true if this class is directly implemented by the named class, or by one of its superclasses. */ public boolean isDirectlyImplementedByClass(final String className) { return getNamesOfClassesDirectlyImplementing().contains(className); } // ------------------------------------------------------------------------------------------------------------- // Annotations /** * Get the names of all annotation classes found during the scan. * * @return the sorted list of names of annotation classes found during the scan, or the empty list if none. */ static List<String> getNamesOfAllAnnotationClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION)); } // ------------- /** * Get the standard classes and non-annotation interfaces that are annotated by this annotation. * * @param direct * if true, return only directly-annotated classes. * @return the set of standard classes and non-annotation interfaces that are annotated by the annotation * corresponding to this ClassInfo class, or the empty set if none. */ private Set<ClassInfo> getClassesWithAnnotation(final boolean direct) { if (!isAnnotation()) { return Collections.<ClassInfo> emptySet(); } final Set<ClassInfo> classesWithAnnotation = filterClassInfo( direct ? getDirectlyRelatedClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION) : getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, // ClassType.STANDARD_CLASS, ClassType.IMPLEMENTED_INTERFACE); boolean isInherited = false; for (final ClassInfo metaAnnotation : getDirectlyRelatedClasses(RelType.CLASS_ANNOTATIONS)) { if (metaAnnotation.className.equals("java.lang.annotation.Inherited")) { isInherited = true; break; } } if (isInherited) { final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new HashSet<>(classesWithAnnotation); for (final ClassInfo classWithAnnotation : classesWithAnnotation) { classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses()); } return classesWithAnnotationAndTheirSubclasses; } else { return classesWithAnnotation; } } /** * Get the standard classes and non-annotation interfaces that are annotated by this annotation. * * @return the set of standard classes and non-annotation interfaces that are annotated by the annotation * corresponding to this ClassInfo class, or the empty set if none. */ public Set<ClassInfo> getClassesWithAnnotation() { return getClassesWithAnnotation(/* direct = */ false); } /** * Get the names of standard classes and non-annotation interfaces that are annotated by this annotation. . * * @return the sorted list of names of ClassInfo objects for standard classes and non-annotation interfaces that * are annotated by the annotation corresponding to this ClassInfo class, or the empty list if none. */ public List<String> getNamesOfClassesWithAnnotation() { return getClassNames(getClassesWithAnnotation()); } /** * Test whether this class annotates the named class. * * @param annotatedClassName * The name of the annotated class. * @return True if this class annotates the named class. */ public boolean annotatesClass(final String annotatedClassName) { return getNamesOfClassesWithAnnotation().contains(annotatedClassName); } // ------------- /** * Get the standard classes or non-annotation interfaces that are directly annotated with this annotation. * * @return the set of standard classes or non-annotation interfaces that are directly annotated with this * annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectAnnotation() { return getClassesWithAnnotation(/* direct = */ true); } /** * Get the names of standard classes or non-annotation interfaces that are directly annotated with this * annotation. * * @return the sorted list of names of standard classes or non-annotation interfaces that are directly annotated * with this annotation, or the empty list if none. */ public List<String> getNamesOfClassesWithDirectAnnotation() { return getClassNames(getClassesWithDirectAnnotation()); } /** * Test whether this class directly annotates the named class. * * @param directlyAnnotatedClassName * The name of the directly annotated class. * @return true if this class directly annotates the named class. */ public boolean directlyAnnotatesClass(final String directlyAnnotatedClassName) { return getNamesOfClassesWithDirectAnnotation().contains(directlyAnnotatedClassName); } // ------------- /** * Get the annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the set of annotations and meta-annotations on this class or interface, or meta-annotations if this * is an annotation. Returns the empty set if none. */ public Set<ClassInfo> getAnnotations() { return filterClassInfo(getReachableClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the sorted list of names of annotations and meta-annotations on this class or interface, or * meta-annotations if this is an annotation. Returns the empty list if none. */ public List<String> getNamesOfAnnotations() { return getClassNames(getAnnotations()); } /** * Test whether this class, interface or annotation has the named class annotation or meta-annotation. * * @param annotationName * The name of the annotation. * @return true if this class, interface or annotation has the named class annotation or meta-annotation. */ public boolean hasAnnotation(final String annotationName) { return getNamesOfAnnotations().contains(annotationName); } /** * Get a list of annotations on this method, along with any annotation parameter values, wrapped in * {@link AnnotationInfo} objects, or the empty list if none. * * @return A list of {@link AnnotationInfo} objects for the annotations on this method, or the empty list if * none. */ public List<AnnotationInfo> getAnnotationInfo() { return annotationInfo == null ? Collections.<AnnotationInfo> emptyList() : annotationInfo; } /** * Get a list of the default parameter values, if this is an annotation, and it has default parameter values. * Otherwise returns the empty list. * * @return If this is an annotation class, the list of {@link AnnotationParamValue} objects for each of the * default parameter values for this annotation, otherwise the empty list. */ public List<AnnotationParamValue> getAnnotationDefaultParamValues() { return annotationDefaultParamValues == null ? Collections.<AnnotationParamValue> emptyList() : annotationDefaultParamValues; } // ------------- /** * Get the direct annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the set of direct annotations and meta-annotations on this class, or the empty set if none. */ public Set<ClassInfo> getDirectAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of direct annotations and meta-annotations on this class. This is equivalent to the reflection * call Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the sorted list of names of direct annotations and meta-annotations on this class, or the empty list * if none. */ public List<String> getNamesOfDirectAnnotations() { return getClassNames(getDirectAnnotations()); } /** * Test whether this class has the named direct annotation or meta-annotation. (This is equivalent to the * reflection call Class#hasAnnotation(), except that it does not require calling the classloader, and it works * for meta-annotations as well as Annotatinons.) * * @param directAnnotationName * The name of the direct annotation. * @return true if this class has the named direct annotation or meta-annotation. */ public boolean hasDirectAnnotation(final String directAnnotationName) { return getNamesOfDirectAnnotations().contains(directAnnotationName); } // ------------- /** * Get the annotations and meta-annotations on this annotation class. * * @return the set of annotations and meta-annotations, if this is an annotation class, or the empty set if none * (or if this is not an annotation class). */ public Set<ClassInfo> getMetaAnnotations() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of annotations and meta-annotations on this annotation class. * * @return the set of annotations and meta-annotations, if this is an annotation class, or the empty list if * none (or if this is not an annotation class). */ public List<String> getNamesOfMetaAnnotations() { return getClassNames(getMetaAnnotations()); } /** * Test whether this is an annotation class and it has the named meta-annotation. * * @param metaAnnotationName * The meta-annotation name. * @return true if this is an annotation class and it has the named meta-annotation. */ public boolean hasMetaAnnotation(final String metaAnnotationName) { return getNamesOfMetaAnnotations().contains(metaAnnotationName); } // ------------- /** * Get the annotations that have this meta-annotation. * * @return the set of annotations that have this meta-annotation, or the empty set if none. */ public Set<ClassInfo> getAnnotationsWithMetaAnnotation() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of annotations that have this meta-annotation. * * @return the sorted list of names of annotations that have this meta-annotation, or the empty list if none. */ public List<String> getNamesOfAnnotationsWithMetaAnnotation() { return getClassNames(getAnnotationsWithMetaAnnotation()); } /** * Test whether this annotation has the named meta-annotation. * * @param annotationName * The annotation name. * @return true if this annotation has the named meta-annotation. */ public boolean metaAnnotatesAnnotation(final String annotationName) { return getNamesOfAnnotationsWithMetaAnnotation().contains(annotationName); } // ------------- /** * Get the annotations that have this direct meta-annotation. * * @return the set of annotations that have this direct meta-annotation, or the empty set if none. */ public Set<ClassInfo> getAnnotationsWithDirectMetaAnnotation() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of annotations that have this direct meta-annotation. * * @return the sorted list of names of annotations that have this direct meta-annotation, or the empty list if * none. */ public List<String> getNamesOfAnnotationsWithDirectMetaAnnotation() { return getClassNames(getAnnotationsWithDirectMetaAnnotation()); } /** * Test whether this annotation is directly meta-annotated with the named annotation. * * @param directMetaAnnotationName * The direct meta-annotation name. * @return true if this annotation is directly meta-annotated with the named annotation. */ public boolean hasDirectMetaAnnotation(final String directMetaAnnotationName) { return getNamesOfAnnotationsWithDirectMetaAnnotation().contains(directMetaAnnotationName); } // ------------------------------------------------------------------------------------------------------------- // Methods /** * Returns information on visible methods of the class that are not constructors. There may be more than one * method of a given name with different type signatures, due to overloading. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreMethodVisibility() * was called before the scan. If method visibility is ignored, the result may include a reference to a private * static class initializer block, with a method name of {@code "<clinit>"}. * * @return the list of MethodInfo objects for visible methods of this class, or the empty list if no methods * were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return Collections.<MethodInfo> emptyList(); } else { final List<MethodInfo> nonConstructorMethods = new ArrayList<>(); for (final MethodInfo mi : methodInfo) { final String methodName = mi.getMethodName(); if (!methodName.equals("<init>") && !methodName.equals("<clinit>")) { nonConstructorMethods.add(mi); } } return nonConstructorMethods; } } /** * Returns information on visible constructors of the class. Constructors have the method name of * {@code "<init>"}. There may be more than one constructor of a given name with different type signatures, due * to overloading. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public constructors, unless * FastClasspathScanner#ignoreMethodVisibility() was called before the scan. * * @return the list of MethodInfo objects for visible constructors of this class, or the empty list if no * constructors were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getConstructorInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return Collections.<MethodInfo> emptyList(); } else { final List<MethodInfo> nonConstructorMethods = new ArrayList<>(); for (final MethodInfo mi : methodInfo) { final String methodName = mi.getMethodName(); if (methodName.equals("<init>")) { nonConstructorMethods.add(mi); } } return nonConstructorMethods; } } /** * Returns information on visible methods and constructors of the class. There may be more than one method or * constructor or method of a given name with different type signatures, due to overloading. Constructors have * the method name of {@code "<init>"}. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods and constructors, unless * FastClasspathScanner#ignoreMethodVisibility() was called before the scan. If method visibility is ignored, * the result may include a reference to a private static class initializer block, with a method name of * {@code "<clinit>"}. * * @return the list of MethodInfo objects for visible methods and constructors of this class, or the empty list * if no methods or constructors were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodAndConstructorInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } return methodInfo == null ? Collections.<MethodInfo> emptyList() : methodInfo; } /** * Returns information on the method(s) of the class with the given method name. Constructors have the method * name of {@code "<init>"}. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreMethodVisibility() * was called before the scan. * * <p> * May return info for multiple methods with the same name (with different type signatures). * * @param methodName * The method name to query. * @return a list of MethodInfo objects for the method(s) with the given name, or the empty list if the method * was not found in this class (or is not visible). * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodInfo(final String methodName) { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return null; } if (methodNameToMethodInfo == null) { // Lazily build reverse mapping cache methodNameToMethodInfo = new MultiMapKeyToList<>(); for (final MethodInfo f : methodInfo) { methodNameToMethodInfo.put(f.getMethodName(), f); } } final List<MethodInfo> methodList = methodNameToMethodInfo.get(methodName); return methodList == null ? Collections.<MethodInfo> emptyList() : methodList; } // ------------------------------------------------------------------------------------------------------------- // Method annotations /** * Get the direct method direct annotations on this class. * * @return the set of method direct annotations on this class, or the empty set if none. */ public Set<ClassInfo> getMethodDirectAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.METHOD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the method annotations or meta-annotations on this class. * * @return the set of method annotations or meta-annotations on this class, or the empty set if none. */ public Set<ClassInfo> getMethodAnnotations() { return filterClassInfo(getReachableClasses(RelType.METHOD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of method direct annotations on this class. * * @return the sorted list of names of method direct annotations on this class, or the empty list if none. */ public List<String> getNamesOfMethodDirectAnnotations() { return getClassNames(getMethodDirectAnnotations()); } /** * Get the names of method annotations or meta-annotations on this class. * * @return the sorted list of names of method annotations or meta-annotations on this class, or the empty list * if none. */ public List<String> getNamesOfMethodAnnotations() { return getClassNames(getMethodAnnotations()); } /** * Test whether this class has a method with the named method direct annotation. * * @param annotationName * The annotation name. * @return true if this class has a method with the named direct annotation. */ public boolean hasMethodWithDirectAnnotation(final String annotationName) { return getNamesOfMethodDirectAnnotations().contains(annotationName); } /** * Test whether this class has a method with the named method annotation or meta-annotation. * * @param annotationName * The annotation name. * @return true if this class has a method with the named annotation or meta-annotation. */ public boolean hasMethodWithAnnotation(final String annotationName) { return getNamesOfMethodAnnotations().contains(annotationName); } // ------------- /** * Get the classes that have a method with this direct annotation. * * @return the set of classes that have a method with this direct annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectMethodAnnotation() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_METHOD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the classes that have a method with this annotation or meta-annotation. * * @return the set of classes that have a method with this annotation or meta-annotation, or the empty set if * none. */ public Set<ClassInfo> getClassesWithMethodAnnotation() { return filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_METHOD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a method with this direct annotation. * * @return the sorted list of names of classes that have a method with this direct annotation, or the empty list * if none. */ public List<String> getNamesOfClassesWithDirectMethodAnnotation() { return getClassNames(getClassesWithDirectMethodAnnotation()); } /** * Get the names of classes that have a method with this annotation. * * @return the sorted list of names of classes that have a method with this annotation, or the empty list if * none. */ public List<String> getNamesOfClassesWithMethodAnnotation() { return getClassNames(getClassesWithMethodAnnotation()); } /** * Test whether this annotation annotates or meta-annotates a method of the named class. * * @param className * The class name. * @return true if this annotation annotates a method of the named class. */ public boolean annotatesMethodOfClass(final String className) { return getNamesOfClassesWithMethodAnnotation().contains(className); } /** * Return a sorted list of classes that have a method directly annotated with the named annotation. * * @return the sorted list of names of classes that have a method with the named direct annotation, or the empty * list if none. */ static List<String> getNamesOfClassesWithDirectMethodAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedMethodAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getDirectlyRelatedClasses(RelType.METHOD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedMethodAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedMethodAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedMethodAnnotation); } return namesOfClassesWithNamedMethodAnnotation; } /** * Return a sorted list of classes that have a method with the named annotation or meta-annotation. * * @return the sorted list of names of classes that have a method with the named annotation or meta-annotation, * or the empty list if none. */ static List<String> getNamesOfClassesWithMethodAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedMethodAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getReachableClasses(RelType.METHOD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedMethodAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedMethodAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedMethodAnnotation); } return namesOfClassesWithNamedMethodAnnotation; } // ------------------------------------------------------------------------------------------------------------- // Fields /** * Get the constant initializer value for the named static final field, if present. * * @return the constant initializer value for the named static final field, if present. */ Object getStaticFinalFieldConstantInitializerValue(final String fieldName) { return staticFinalFieldNameToConstantInitializerValue == null ? null : staticFinalFieldNameToConstantInitializerValue.get(fieldName); } /** * Returns information on all visible fields of the class. * * <p> * Requires that FastClasspathScanner#enableFieldInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreFieldVisibility() * was called before the scan. * * @return the list of FieldInfo objects for visible fields of this class, or the empty list if no fields were * found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableFieldInfo() was not called prior to initiating the scan. */ public List<FieldInfo> getFieldInfo() { if (!scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Cannot get field info without calling " + "FastClasspathScanner#enableFieldInfo() before starting the scan"); } return fieldInfo == null ? Collections.<FieldInfo> emptyList() : fieldInfo; } /** * Returns information on a given visible field of the class. * * <p> * Requires that FastClasspathScanner#enableFieldInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public fields, unless FastClasspathScanner#ignoreFieldVisibility() * was called before the scan. * * @param fieldName * The field name to query. * @return the FieldInfo object for the named field, or null if the field was not found in this class (or is not * visible). * @throws IllegalArgumentException * if FastClasspathScanner#enableFieldInfo() was not called prior to initiating the scan. */ public FieldInfo getFieldInfo(final String fieldName) { if (!scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Cannot get field info without calling " + "FastClasspathScanner#enableFieldInfo() before starting the scan"); } if (fieldInfo == null) { return null; } if (fieldNameToFieldInfo == null) { // Lazily build reverse mapping cache fieldNameToFieldInfo = new HashMap<>(); for (final FieldInfo f : fieldInfo) { fieldNameToFieldInfo.put(f.getFieldName(), f); } } return fieldNameToFieldInfo.get(fieldName); } // ------------------------------------------------------------------------------------------------------------- // Field annotations /** * Get the field annotations on this class. * * @return the set of field annotations on this class, or the empty set if none. */ public Set<ClassInfo> getFieldAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.FIELD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of field annotations on this class. * * @return the sorted list of names of field annotations on this class, or the empty list if none. */ public List<String> getNamesOfFieldAnnotations() { return getClassNames(getFieldAnnotations()); } /** * Test whether this class has a field with the named field annotation. * * @param annotationName * The annotation name. * @return true if this class has a field with the named annotation. */ public boolean hasFieldWithAnnotation(final String annotationName) { return getNamesOfFieldAnnotations().contains(annotationName); } // ------------- /** * Get the classes that have a field with this annotation or meta-annotation. * * @return the set of classes that have a field with this annotation or meta-annotation, or the empty set if * none. */ public Set<ClassInfo> getClassesWithFieldAnnotation() { return filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_FIELD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a field with this annotation or meta-annotation. * * @return the sorted list of names of classes that have a field with this annotation or meta-annotation, or the * empty list if none. */ public List<String> getNamesOfClassesWithFieldAnnotation() { return getClassNames(getClassesWithFieldAnnotation()); } /** * Get the classes that have a field with this direct annotation. * * @return the set of classes that have a field with this direct annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectFieldAnnotation() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_FIELD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a field with this direct annotation. * * @return the sorted list of names of classes that have a field with thisdirect annotation, or the empty list * if none. */ public List<String> getNamesOfClassesWithDirectFieldAnnotation() { return getClassNames(getClassesWithDirectFieldAnnotation()); } /** * Test whether this annotation annotates a field of the named class. * * @param className * The class name. * @return true if this annotation annotates a field of the named class. */ public boolean annotatesFieldOfClass(final String className) { return getNamesOfClassesWithFieldAnnotation().contains(className); } /** * Return a sorted list of classes that have a field with the named annotation or meta-annotation. * * @return the sorted list of names of classes that have a field with the named annotation or meta-annotation, * or the empty list if none. */ static List<String> getNamesOfClassesWithFieldAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedFieldAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getReachableClasses(RelType.FIELD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedFieldAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedFieldAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedFieldAnnotation); } return namesOfClassesWithNamedFieldAnnotation; } /** * Return a sorted list of classes that have a field with the named annotation or direct annotation. * * @return the sorted list of names of classes that have a field with the named direct annotation, or the empty * list if none. */ static List<String> getNamesOfClassesWithDirectFieldAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedFieldAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getDirectlyRelatedClasses(RelType.FIELD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedFieldAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedFieldAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedFieldAnnotation); } return namesOfClassesWithNamedFieldAnnotation; } }
src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java
/* * This file is part of FastClasspathScanner. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Luke Hutchison * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.github.lukehutch.fastclasspathscanner.json.Id; import io.github.lukehutch.fastclasspathscanner.scanner.AnnotationInfo.AnnotationParamValue; import io.github.lukehutch.fastclasspathscanner.scanner.ScanResult.InfoObject; import io.github.lukehutch.fastclasspathscanner.typesignature.ClassTypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.MethodTypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.TypeSignature; import io.github.lukehutch.fastclasspathscanner.typesignature.TypeUtils; import io.github.lukehutch.fastclasspathscanner.utils.AdditionOrderedSet; import io.github.lukehutch.fastclasspathscanner.utils.JarUtils; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList; import io.github.lukehutch.fastclasspathscanner.utils.Parser.ParseException; /** Holds metadata about a class encountered during a scan. */ public class ClassInfo extends InfoObject implements Comparable<ClassInfo> { /** Name of the class/interface/annotation. */ @Id String className; /** Class modifier flags, e.g. Modifier.PUBLIC */ int modifiers; /** True if the classfile indicated this is an interface. */ boolean isInterface; /** True if the classfile indicated this is an annotation. */ boolean isAnnotation; /** The class type signature string. */ String typeSignatureStr; /** The class type signature, parsed. */ transient ClassTypeSignature typeSignature; /** The fully-qualified containing method name, for anonymous inner classes. */ String fullyQualifiedContainingMethodName; /** * If true, this class is only being referenced by another class' classfile as a superclass / implemented * interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a * whitelisted (non-blacklisted) package. * * If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a * whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package. */ boolean isExternalClass; /** * The classpath element file (classpath root dir or jar) that this class was found within, or null if this * class was found in a module. */ transient File classpathElementFile; /** * The package root within a jarfile (e.g. "BOOT-INF/classes"), or the empty string if this is not a jarfile, or * the package root is the classpath element path (as opposed to within a subdirectory of the classpath * element). */ transient String jarfilePackageRoot = ""; /** * The classpath element module that this class was found within, or null if this class was found within a * directory or jar. */ transient ModuleRef classpathElementModuleRef; /** The classpath element URL (classpath root dir or jar) that this class was found within. */ transient URL classpathElementURL; /** The classloaders to try to load this class with before calling a MatchProcessor. */ transient ClassLoader[] classLoaders; /** The scan spec. */ transient ScanSpec scanSpec; /** Info on class annotations, including optional annotation param values. */ List<AnnotationInfo> annotationInfo; /** Info on fields. */ List<FieldInfo> fieldInfo; /** Reverse mapping from field name to FieldInfo. */ transient Map<String, FieldInfo> fieldNameToFieldInfo; /** Info on fields. */ List<MethodInfo> methodInfo; /** Reverse mapping from method name to MethodInfo. */ transient MultiMapKeyToList<String, MethodInfo> methodNameToMethodInfo; /** For annotations, the default values of parameters. */ List<AnnotationParamValue> annotationDefaultParamValues; transient ScanResult scanResult; /** The set of classes related to this one. */ Map<RelType, Set<ClassInfo>> relatedClasses = new HashMap<>(); /** * The static constant initializer values of static final fields, if a StaticFinalFieldMatchProcessor matched a * field in this class. */ Map<String, Object> staticFinalFieldNameToConstantInitializerValue; // ------------------------------------------------------------------------------------------------------------- /** Sets back-reference to scan result after scan is complete. */ @Override void setScanResult(final ScanResult scanResult) { this.scanResult = scanResult; if (annotationInfo != null) { for (final AnnotationInfo ai : annotationInfo) { ai.setScanResult(scanResult); } } if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { fi.setScanResult(scanResult); } } if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { mi.setScanResult(scanResult); } } } /** Sets back-reference to ScanSpec after deserialization. */ void setFields(final ScanSpec scanSpec) { this.scanSpec = scanSpec; if (this.methodInfo != null) { for (final MethodInfo methodInfo : this.methodInfo) { methodInfo.classInfo = this; methodInfo.className = this.className; } } } private static final int ANNOTATION_CLASS_MODIFIER = 0x2000; // ------------------------------------------------------------------------------------------------------------- /** * Get the name of this class. * * @return The class name. */ public String getClassName() { return className; } /** * Get a class reference for this class. Calls the classloader. * * @return The class reference. * @throws IllegalArgumentException * if there were problems loading or initializing the class. (Note that class initialization on load * is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) */ public Class<?> getClassRef() { return scanResult.classNameToClassRef(className); } /** * Get a class reference for this class, casting it to the requested interface or superclass type. Calls the * classloader. * * @param classType * The class to cast the result to. * @return The class reference. * @throws IllegalArgumentException * if there were problems loading the class, initializing the class, or casting it to the requested * type. (Note that class initialization on load is disabled by default, you can enable it with * {@code FastClasspathScanner#initializeLoadedClasses(true)} .) */ public <T> Class<T> getClassRef(final Class<T> classType) { return scanResult.classNameToClassRef(className, classType); } /** * Returns true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass / * implemented interface / annotation, but is not itself a whitelisted class. */ public boolean isExternalClass() { return isExternalClass; } /** * Get the class modifier flags, e.g. Modifier.PUBLIC * * @return The class modifiers. */ public int getClassModifiers() { return modifiers; } /** * Get the field modifiers as a String, e.g. "public static final". For the modifier bits, call getModifiers(). * * @return The class modifiers, in String format. */ public String getModifiersStr() { return TypeUtils.modifiersToString(modifiers, /* isMethod = */ false); } /** * Test whether this ClassInfo corresponds to a public class. * * @return true if this ClassInfo corresponds to a public class. */ public boolean isPublic() { return (modifiers & Modifier.PUBLIC) != 0; } /** * Test whether this ClassInfo corresponds to an abstract class. * * @return true if this ClassInfo corresponds to an abstract class. */ public boolean isAbstract() { return (modifiers & 0x400) != 0; } /** * Test whether this ClassInfo corresponds to a synthetic class. * * @return true if this ClassInfo corresponds to a synthetic class. */ public boolean isSynthetic() { return (modifiers & 0x1000) != 0; } /** * Test whether this ClassInfo corresponds to a final class. * * @return true if this ClassInfo corresponds to a final class. */ public boolean isFinal() { return (modifiers & Modifier.FINAL) != 0; } /** * Test whether this ClassInfo corresponds to an annotation. * * @return true if this ClassInfo corresponds to an annotation. */ public boolean isAnnotation() { return isAnnotation; } /** * Test whether this ClassInfo corresponds to an interface. * * @return true if this ClassInfo corresponds to an interface. */ public boolean isInterface() { return isInterface; } /** * Test whether this ClassInfo corresponds to an enum. * * @return true if this ClassInfo corresponds to an enum. */ public boolean isEnum() { return (modifiers & 0x4000) != 0; } /** * Get the low-level Java type signature for the class, including generic type parameters, if available (else * returns null). * * @return The type signature, in string format */ public String getTypeSignatureStr() { return typeSignatureStr; } /** * Get the type signature for the class, if available (else returns null). * * @return The class type signature. */ public ClassTypeSignature getTypeSignature() { if (typeSignature == null) { return null; } if (typeSignature == null) { try { typeSignature = ClassTypeSignature.parse(typeSignatureStr); } catch (final ParseException e) { throw new IllegalArgumentException(e); } } return typeSignature; } /** * The classpath element URL (classpath root dir or jar) that this class was found within. This will consist of * exactly one entry, so you should call the getClasspathElementURL() method instead. * * @return The classpath element URL, stored in a set. */ @Deprecated public Set<URL> getClasspathElementURLs() { final Set<URL> urls = new HashSet<>(); urls.add(getClasspathElementURL()); return urls; } /** * The classpath element URL (for a classpath root dir, jar or module) that this class was found within. * * N.B. Classpath elements are handled as File objects internally. It is much faster to call * getClasspathElementFile() and/or getClasspathElementModule() -- the conversion of a File into a URL (via * File#toURI()#toURL()) is time consuming. * * @return The classpath element, as a URL. */ public URL getClasspathElementURL() { if (classpathElementURL == null) { try { if (classpathElementModuleRef != null) { classpathElementURL = classpathElementModuleRef.getModuleLocation().toURL(); } else { classpathElementURL = getClasspathElementFile().toURI().toURL(); } } catch (final MalformedURLException e) { // Shouldn't happen; File objects should always be able to be turned into URIs and then URLs throw new RuntimeException(e); } } return classpathElementURL; } /** * The classpath element file (classpath root dir or jar) that this class was found within, or null if this * class was found in a module. * * @return The classpath element, as a File. */ public File getClasspathElementFile() { return classpathElementFile; } /** * The classpath element module that this class was found within, or null if this class was found in a directory * or jar. * * @return The classpath element, as a ModuleRef. */ public ModuleRef getClasspathElementModuleRef() { return classpathElementModuleRef; } /** * Get the ClassLoader(s) to use when trying to load the class. Typically there will only be one. If there is * more than one, they will be listed in the order they should be called, until one is able to load the class. * * @return The Classloader(s) to use when trying to load the class. */ public ClassLoader[] getClassLoaders() { return classLoaders; } /** Compare based on class name. */ @Override public int compareTo(final ClassInfo o) { return this.className.compareTo(o.className); } /** Use class name for equals(). */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ClassInfo other = (ClassInfo) obj; return className.equals(other.className); } /** Use hash code of class name. */ @Override public int hashCode() { return className != null ? className.hashCode() : 33; } @Override public String toString() { final ClassTypeSignature typeSig = getTypeSignature(); if (typeSig != null) { return typeSig.toString(modifiers, isAnnotation, isInterface, className); } else { final StringBuilder buf = new StringBuilder(); TypeUtils.modifiersToString(modifiers, /* isMethod = */ false, buf); if (buf.length() > 0) { buf.append(' '); } buf.append(isAnnotation ? "@interface " : isInterface ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class "); buf.append(className); return buf.toString(); } } // ------------------------------------------------------------------------------------------------------------- /** How classes are related. */ private static enum RelType { // Classes: /** * Superclasses of this class, if this is a regular class. * * <p> * (Should consist of only one entry, or null if superclass is java.lang.Object or unknown). */ SUPERCLASSES, /** Subclasses of this class, if this is a regular class. */ SUBCLASSES, /** Indicates that an inner class is contained within this one. */ CONTAINS_INNER_CLASS, /** Indicates that an outer class contains this one. (Should only have zero or one entries.) */ CONTAINED_WITHIN_OUTER_CLASS, // Interfaces: /** * Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an * interface. * * <p> * (May also include annotations, since annotations are interfaces, so you can implement an annotation.) */ IMPLEMENTED_INTERFACES, /** * Classes that implement this interface (including sub-interfaces), if this is an interface. */ CLASSES_IMPLEMENTING, // Class annotations: /** * Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is * an annotation. */ CLASS_ANNOTATIONS, /** Classes annotated with this annotation, if this is an annotation. */ CLASSES_WITH_CLASS_ANNOTATION, // Method annotations: /** Annotations on one or more methods of this class. */ METHOD_ANNOTATIONS, /** * Classes that have one or more methods annotated with this annotation, if this is an annotation. */ CLASSES_WITH_METHOD_ANNOTATION, // Field annotations: /** Annotations on one or more fields of this class. */ FIELD_ANNOTATIONS, /** * Classes that have one or more fields annotated with this annotation, if this is an annotation. */ CLASSES_WITH_FIELD_ANNOTATION, } ClassInfo() { } private ClassInfo(final String className, final int classModifiers, final boolean isExternalClass, final ScanSpec scanSpec) { this.className = className; if (className.endsWith(";")) { // Spot check to make sure class names were parsed from descriptors throw new RuntimeException("Bad class name"); } this.modifiers = classModifiers; this.isExternalClass = isExternalClass; this.scanSpec = scanSpec; } /** The class type to return. */ static enum ClassType { /** Get all class types. */ ALL, /** A standard class (not an interface or annotation). */ STANDARD_CLASS, /** * An interface (this is named "implemented interface" rather than just "interface" to distinguish it from * an annotation.) */ IMPLEMENTED_INTERFACE, /** An annotation. */ ANNOTATION, /** An interface or annotation (used since you can actually implement an annotation). */ INTERFACE_OR_ANNOTATION, } /** Get the classes related to this one in the specified way. */ static Set<ClassInfo> filterClassInfo(final Set<ClassInfo> classInfoSet, final boolean removeExternalClassesIfStrictWhitelist, final ScanSpec scanSpec, final ClassType... classTypes) { if (classInfoSet == null) { return Collections.emptySet(); } boolean includeAllTypes = classTypes.length == 0; boolean includeStandardClasses = false; boolean includeImplementedInterfaces = false; boolean includeAnnotations = false; for (final ClassType classType : classTypes) { switch (classType) { case ALL: includeAllTypes = true; break; case STANDARD_CLASS: includeStandardClasses = true; break; case IMPLEMENTED_INTERFACE: includeImplementedInterfaces = true; break; case ANNOTATION: includeAnnotations = true; break; case INTERFACE_OR_ANNOTATION: includeImplementedInterfaces = includeAnnotations = true; break; default: throw new RuntimeException("Unknown ClassType: " + classType); } } if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) { includeAllTypes = true; } // Do two passes with the same filter logic to avoid copying the set if nothing is filtered out final Set<ClassInfo> classInfoSetFiltered = new HashSet<>(classInfoSet.size()); for (final ClassInfo classInfo : classInfoSet) { // Check class type against requested type(s) if (includeAllTypes // || includeStandardClasses && classInfo.isStandardClass() || includeImplementedInterfaces && classInfo.isImplementedInterface() || includeAnnotations && classInfo.isAnnotation()) { // Check whether class should be visible in results final boolean isBlacklisted = scanSpec.classIsBlacklisted(classInfo.className); final boolean isSystemClass = JarUtils.isInSystemPackageOrModule(classInfo.className); final boolean includeExternalClasses = scanSpec.enableExternalClasses || !removeExternalClassesIfStrictWhitelist; final boolean notExternalOrIncludeExternal = !classInfo.isExternalClass || includeExternalClasses; if (notExternalOrIncludeExternal // // If this is a system class, ignore blacklist unless the blanket blacklisting of // all system jars or modules has been disabled, and this system class was specifically // blacklisted by name && (!isBlacklisted || (isSystemClass && scanSpec.blacklistSystemJarsOrModules))) { // Class passed filter criteria classInfoSetFiltered.add(classInfo); } } } return classInfoSetFiltered; } /** * Get the sorted list of the names of classes given a collection of {@link ClassInfo} objects. (Class names are * not deduplicated.) * * @param classInfoColl * The collection of {@link ClassInfo} objects. * @return The names of classes in the collection. */ public static List<String> getClassNames(final Collection<ClassInfo> classInfoColl) { if (classInfoColl.isEmpty()) { return Collections.emptyList(); } else { final ArrayList<String> classNames = new ArrayList<>(classInfoColl.size()); for (final ClassInfo classInfo : classInfoColl) { classNames.add(classInfo.className); } Collections.sort(classNames); return classNames; } } /** Get the classes directly related to this ClassInfo object the specified way. */ private Set<ClassInfo> getDirectlyRelatedClasses(final RelType relType) { final Set<ClassInfo> relatedClassClassInfo = relatedClasses.get(relType); return relatedClassClassInfo == null ? Collections.<ClassInfo> emptySet() : relatedClassClassInfo; } /** * Find all ClassInfo nodes reachable from this ClassInfo node over the given relationship type links (not * including this class itself). */ private Set<ClassInfo> getReachableClasses(final RelType relType) { final Set<ClassInfo> directlyRelatedClasses = this.getDirectlyRelatedClasses(relType); if (directlyRelatedClasses.isEmpty()) { return directlyRelatedClasses; } final Set<ClassInfo> reachableClasses = new HashSet<>(directlyRelatedClasses); if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) { // For method and field annotations, need to change the RelType when finding meta-annotations for (final ClassInfo annotation : directlyRelatedClasses) { reachableClasses.addAll(annotation.getReachableClasses(RelType.CLASS_ANNOTATIONS)); } } else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION || relType == RelType.CLASSES_WITH_FIELD_ANNOTATION) { // If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then // look for the methods or fields that they annotate for (final ClassInfo subAnnotation : filterClassInfo( getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION)) { reachableClasses.addAll(subAnnotation.getDirectlyRelatedClasses(relType)); } } else { // For other relationship types, the reachable type stays the same over the transitive closure. Find the // transitive closure, breaking cycles where necessary. final LinkedList<ClassInfo> queue = new LinkedList<>(); queue.addAll(directlyRelatedClasses); while (!queue.isEmpty()) { final ClassInfo head = queue.removeFirst(); for (final ClassInfo directlyReachableFromHead : head.getDirectlyRelatedClasses(relType)) { // Don't get in cycle if (reachableClasses.add(directlyReachableFromHead)) { queue.add(directlyReachableFromHead); } } } } return reachableClasses; } /** * Add a class with a given relationship type. Test whether the collection changed as a result of the call. */ private boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) { Set<ClassInfo> classInfoSet = relatedClasses.get(relType); if (classInfoSet == null) { relatedClasses.put(relType, classInfoSet = new HashSet<>(4)); } return classInfoSet.add(classInfo); } /** * Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should * only ever be constructed by a single thread. */ private static ClassInfo getOrCreateClassInfo(final String className, final int classModifiers, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo) { ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ true, scanSpec)); } return classInfo; } /** Add a superclass to this class. */ void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) { if (superclassName != null) { final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo); superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this); } } /** Add an annotation to this class. */ void addClassAnnotation(final AnnotationInfo classAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; if (this.annotationInfo == null) { this.annotationInfo = new ArrayList<>(); } this.annotationInfo.add(classAnnotationInfo); annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION classAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_CLASS_ANNOTATION, this); } /** Add a method annotation to this class. */ void addMethodAnnotation(final AnnotationInfo methodAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(methodAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION methodAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.METHOD_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_ANNOTATION, this); } /** Add a field annotation to this class. */ void addFieldAnnotation(final AnnotationInfo fieldAnnotationInfo, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); annotationClassInfo.isAnnotation = true; annotationClassInfo.modifiers |= 0x2000; // Modifier.ANNOTATION fieldAnnotationInfo.addDefaultValues(annotationClassInfo.annotationDefaultParamValues); this.addRelatedClass(RelType.FIELD_ANNOTATIONS, annotationClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_FIELD_ANNOTATION, this); } /** Add an implemented interface to this class. */ void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) { final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, /* classModifiers = */ Modifier.INTERFACE, scanSpec, classNameToClassInfo); interfaceClassInfo.isInterface = true; interfaceClassInfo.modifiers |= Modifier.INTERFACE; this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo); interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this); } /** Add class containment info */ static void addClassContainment(final List<SimpleEntry<String, String>> classContainmentEntries, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo) { for (final SimpleEntry<String, String> ent : classContainmentEntries) { final String innerClassName = ent.getKey(); final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(innerClassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); final String outerClassName = ent.getValue(); final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(outerClassName, /* classModifiers = */ 0, scanSpec, classNameToClassInfo); innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo); outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo); } } /** Add containing method name, for anonymous inner classes */ void addFullyQualifiedContainingMethodName(final String fullyQualifiedContainingMethodName) { this.fullyQualifiedContainingMethodName = fullyQualifiedContainingMethodName; } /** Add a static final field's constant initializer value. */ void addStaticFinalFieldConstantInitializerValue(final String fieldName, final Object constValue) { if (this.staticFinalFieldNameToConstantInitializerValue == null) { this.staticFinalFieldNameToConstantInitializerValue = new HashMap<>(); } this.staticFinalFieldNameToConstantInitializerValue.put(fieldName, constValue); } /** Add field info. */ void addFieldInfo(final List<FieldInfo> fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final FieldInfo fieldInfo : fieldInfoList) { final List<AnnotationInfo> fieldAnnotationInfoList = fieldInfo.annotationInfo; if (fieldAnnotationInfoList != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldAnnotationInfoList) { final ClassInfo classInfo = getOrCreateClassInfo(fieldAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo); fieldAnnotationInfo.addDefaultValues(classInfo.annotationDefaultParamValues); } } } if (this.fieldInfo == null) { this.fieldInfo = fieldInfoList; } else { this.fieldInfo.addAll(fieldInfoList); } } /** Add method info. */ void addMethodInfo(final List<MethodInfo> methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final MethodInfo methodInfo : methodInfoList) { final List<AnnotationInfo> methodAnnotationInfoList = methodInfo.annotationInfo; if (methodAnnotationInfoList != null) { for (final AnnotationInfo methodAnnotationInfo : methodAnnotationInfoList) { methodAnnotationInfo.addDefaultValues( getOrCreateClassInfo(methodAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo).annotationDefaultParamValues); } } final AnnotationInfo[][] methodParamAnnotationInfoList = methodInfo.parameterAnnotationInfo; if (methodParamAnnotationInfoList != null) { for (int i = 0; i < methodParamAnnotationInfoList.length; i++) { final AnnotationInfo[] paramAnnotationInfoArr = methodParamAnnotationInfoList[i]; if (paramAnnotationInfoArr != null) { for (int j = 0; j < paramAnnotationInfoArr.length; j++) { final AnnotationInfo paramAnnotationInfo = paramAnnotationInfoArr[j]; paramAnnotationInfo .addDefaultValues(getOrCreateClassInfo(paramAnnotationInfo.annotationName, ANNOTATION_CLASS_MODIFIER, scanSpec, classNameToClassInfo).annotationDefaultParamValues); } } } } // Add back-link from MethodInfo to enclosing ClassInfo instance methodInfo.classInfo = this; } if (this.methodInfo == null) { this.methodInfo = methodInfoList; } else { this.methodInfo.addAll(methodInfoList); } } /** Add the class type signature, including type params */ void addTypeSignature(final String typeSignatureStr) { if (this.typeSignatureStr == null) { this.typeSignatureStr = typeSignatureStr; } else { if (typeSignatureStr != null && !this.typeSignatureStr.equals(typeSignatureStr)) { throw new RuntimeException("Trying to merge two classes with different type signatures for class " + className + ": " + this.typeSignatureStr + " ; " + typeSignatureStr); } } } /** * Add annotation default values. (Only called in the case of annotation class definitions, when the annotation * has default parameter values.) */ void addAnnotationParamDefaultValues(final List<AnnotationParamValue> paramNamesAndValues) { if (this.annotationDefaultParamValues == null) { this.annotationDefaultParamValues = paramNamesAndValues; } else { this.annotationDefaultParamValues.addAll(paramNamesAndValues); } } /** * Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe, * should be run in single threaded context. */ static ClassInfo addScannedClass(final String className, final int classModifiers, final boolean isInterface, final boolean isAnnotation, final ScanSpec scanSpec, final Map<String, ClassInfo> classNameToClassInfo, final ClasspathElement classpathElement, final LogNode log) { boolean classEncounteredMultipleTimes = false; ClassInfo classInfo = classNameToClassInfo.get(className); if (classInfo == null) { // This is the first time this class has been seen, add it classNameToClassInfo.put(className, classInfo = new ClassInfo(className, classModifiers, /* isExternalClass = */ false, scanSpec)); } else { if (!classInfo.isExternalClass) { classEncounteredMultipleTimes = true; } } // Remember which classpath element (zipfile / classpath root directory / module) the class was found in final ModuleRef modRef = classpathElement.getClasspathElementModuleRef(); final File file = classpathElement.getClasspathElementFile(log); if ((classInfo.classpathElementModuleRef != null && modRef != null && !classInfo.classpathElementModuleRef.equals(modRef)) || (classInfo.classpathElementFile != null && file != null && !classInfo.classpathElementFile.equals(file))) { classEncounteredMultipleTimes = true; } if (classEncounteredMultipleTimes) { // The same class was encountered more than once in a single jarfile -- should not happen. However, // actually there is no restriction for paths within a zipfile to be unique (!!), and in fact // zipfiles in the wild do contain the same classfiles multiple times with the same exact path, // e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class if (log != null) { log.log("Class " + className + " is defined in multiple different classpath elements or modules -- " + "ClassInfo#getClasspathElementFile() and/or ClassInfo#getClasspathElementModuleRef " + "will only return the first of these; attempting to merge info from all copies of " + "the classfile"); } } if (classInfo.classpathElementFile == null) { // If class was found in more than one classpath element, keep the first classpath element reference classInfo.classpathElementFile = file; // Save jarfile package root, if any classInfo.jarfilePackageRoot = classpathElement.getJarfilePackageRoot(); } if (classInfo.classpathElementModuleRef == null) { // If class was found in more than one module, keep the first module reference classInfo.classpathElementModuleRef = modRef; } // Remember which classloader handles the class was found in, for classloading final ClassLoader[] classLoaders = classpathElement.getClassLoaders(); if (classInfo.classLoaders == null) { classInfo.classLoaders = classLoaders; } else if (classLoaders != null && !classInfo.classLoaders.equals(classLoaders)) { // Merge together ClassLoader list (concatenate and dedup) final AdditionOrderedSet<ClassLoader> allClassLoaders = new AdditionOrderedSet<>( classInfo.classLoaders); for (final ClassLoader classLoader : classLoaders) { allClassLoaders.add(classLoader); } final List<ClassLoader> classLoaderOrder = allClassLoaders.toList(); classInfo.classLoaders = classLoaderOrder.toArray(new ClassLoader[classLoaderOrder.size()]); } // Mark the classfile as scanned classInfo.isExternalClass = false; // Merge modifiers classInfo.modifiers |= classModifiers; classInfo.isInterface |= isInterface; classInfo.isAnnotation |= isAnnotation; return classInfo; } // ------------------------------------------------------------------------------------------------------------- /** * Get the names of any classes (other than this class itself) referenced in this class' type descriptor, or the * type descriptors of fields or methods (if field or method info is recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInAnyTypeDescriptor() { final Set<String> referencedClassNames = new HashSet<>(); if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { final MethodTypeSignature methodSig = mi.getTypeSignature(); if (methodSig != null) { methodSig.getAllReferencedClassNames(referencedClassNames); } } } if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { final TypeSignature fieldSig = fi.getTypeSignature(); if (fieldSig != null) { fieldSig.getAllReferencedClassNames(referencedClassNames); } } } final ClassTypeSignature classSig = getTypeSignature(); if (classSig != null) { classSig.getAllReferencedClassNames(referencedClassNames); } // Remove self-reference, and any reference to java.lang.Object referencedClassNames.remove(className); referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes referenced in the type descriptors of this class' methods (if method info is * recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInMethodTypeDescriptors() { final Set<String> referencedClassNames = new HashSet<>(); if (methodInfo != null) { for (final MethodInfo mi : methodInfo) { final MethodTypeSignature methodSig = mi.getTypeSignature(); if (methodSig != null) { methodSig.getAllReferencedClassNames(referencedClassNames); } } } // Remove any reference to java.lang.Object referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes referenced in the type descriptors of this class' fields (if field info is * recorded). * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInFieldTypeDescriptors() { final Set<String> referencedClassNames = new HashSet<>(); if (fieldInfo != null) { for (final FieldInfo fi : fieldInfo) { final TypeSignature fieldSig = fi.getTypeSignature(); if (fieldSig != null) { fieldSig.getAllReferencedClassNames(referencedClassNames); } } } // Remove any reference to java.lang.Object referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } /** * Get the names of any classes (other than this class itself) referenced in the type descriptor of this class. * * @return The names of the referenced classes. */ public Set<String> getClassNamesReferencedInClassTypeDescriptor() { final Set<String> referencedClassNames = new HashSet<>(); final ClassTypeSignature classSig = getTypeSignature(); if (classSig != null) { classSig.getAllReferencedClassNames(referencedClassNames); } // Remove self-reference, and any reference to java.lang.Object referencedClassNames.remove(className); referencedClassNames.remove("java.lang.Object"); return referencedClassNames; } // ------------------------------------------------------------------------------------------------------------- // Standard classes /** * Get the names of all classes, interfaces and annotations found during the scan, or the empty list if none. * * @return the sorted unique list of names of all classes, interfaces and annotations found during the scan, or * the empty list if none. */ static List<String> getNamesOfAllClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL)); } /** * Get the names of all standard (non-interface/annotation) classes found during the scan, or the empty list if * none. * * @return the sorted unique names of all standard (non-interface/annotation) classes found during the scan, or * the empty list if none. */ static List<String> getNamesOfAllStandardClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS)); } /** * Test whether this class is a standard class (not an annotation or interface). * * @return true if this class is a standard class (not an annotation or interface). */ public boolean isStandardClass() { return !(isAnnotation || isInterface); } // ------------- /** * Get the subclasses of this class. * * @return the set of subclasses of this class, or the empty set if none. */ public Set<ClassInfo> getSubclasses() { // Make an exception for querying all subclasses of java.lang.Object return filterClassInfo(getReachableClasses(RelType.SUBCLASSES), /* removeExternalClassesIfStrictWhitelist = */ !className.equals("java.lang.Object"), scanSpec, ClassType.ALL); } /** * Get the names of subclasses of this class. * * @return the sorted list of names of the subclasses of this class, or the empty list if none. */ public List<String> getNamesOfSubclasses() { return getClassNames(getSubclasses()); } /** * Test whether this class has the named class as a subclass. * * @param subclassName * The name of the subclass. * @return true if this class has the named class as a subclass. */ public boolean hasSubclass(final String subclassName) { return getNamesOfSubclasses().contains(subclassName); } // ------------- /** * Get the direct subclasses of this class. * * @return the set of direct subclasses of this class, or the empty set if none. */ public Set<ClassInfo> getDirectSubclasses() { // Make an exception for querying all direct subclasses of java.lang.Object return filterClassInfo(getDirectlyRelatedClasses(RelType.SUBCLASSES), /* removeExternalClassesIfStrictWhitelist = */ !className.equals("java.lang.Object"), scanSpec, ClassType.ALL); } /** * Get the names of direct subclasses of this class. * * @return the sorted list of names of direct subclasses of this class, or the empty list if none. */ public List<String> getNamesOfDirectSubclasses() { return getClassNames(getDirectSubclasses()); } /** * Test whether this class has the named direct subclass. * * @param directSubclassName * The name of the direct subclass. * @return true if this class has the named direct subclass. */ public boolean hasDirectSubclass(final String directSubclassName) { return getNamesOfDirectSubclasses().contains(directSubclassName); } // ------------- /** * Get all direct and indirect superclasses of this class (i.e. the direct superclass(es) of this class, and * their superclass(es), all the way up to the top of the class hierarchy). * * <p> * (Includes the union of all mixin superclass hierarchies in the case of Scala mixins.) * * @return the set of all superclasses of this class, or the empty set if none. */ public Set<ClassInfo> getSuperclasses() { return filterClassInfo(getReachableClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of all direct and indirect superclasses of this class (i.e. the direct superclass(es) of this * class, and their superclass(es), all the way up to the top of the class hierarchy). * * <p> * (Includes the union of all mixin superclass hierarchies in the case of Scala mixins.) * * @return the sorted list of names of all superclasses of this class, or the empty list if none. */ public List<String> getNamesOfSuperclasses() { return getClassNames(getSuperclasses()); } /** * Test whether this class extends the named superclass, directly or indirectly. * * @param superclassName * The name of the superclass. * @return true if this class has the named direct or indirect superclass. */ public boolean hasSuperclass(final String superclassName) { return getNamesOfSuperclasses().contains(superclassName); } /** * Returns true if this is an inner class (call isAnonymousInnerClass() to test if this is an anonymous inner * class). If true, the containing class can be determined by calling getOuterClasses() or getOuterClassNames(). * * @return True if this class is an inner class. */ public boolean isInnerClass() { return !getOuterClasses().isEmpty(); } /** * Returns the containing outer classes, for inner classes. Note that all containing outer classes are returned, * not just the innermost containing outer class. Returns the empty set if this is not an inner class. * * @return The set of containing outer classes. */ public Set<ClassInfo> getOuterClasses() { return filterClassInfo(getReachableClasses(RelType.CONTAINED_WITHIN_OUTER_CLASS), /* removeExternalClassesIfStrictWhitelist = */ false, scanSpec, ClassType.ALL); } /** * Returns the names of the containing outer classes, for inner classes. Note that all containing outer classes * are returned, not just the innermost containing outer class. Returns the empty list if this is not an inner * class. * * @return The name of containing outer classes. */ public List<String> getOuterClassName() { return getClassNames(getOuterClasses()); } /** * Returns true if this class contains inner classes. If true, the inner classes can be determined by calling * getInnerClasses() or getInnerClassNames(). * * @return True if this is an outer class. */ public boolean isOuterClass() { return !getInnerClasses().isEmpty(); } /** * Returns the inner classes contained within this class. Returns the empty set if none. * * @return The set of inner classes within this class. */ public Set<ClassInfo> getInnerClasses() { return filterClassInfo(getReachableClasses(RelType.CONTAINS_INNER_CLASS), /* removeExternalClassesIfStrictWhitelist = */ false, scanSpec, ClassType.ALL); } /** * Returns the names of inner classes contained within this class. Returns the empty list if none. * * @return The names of inner classes within this class. */ public List<String> getInnerClassNames() { return getClassNames(getInnerClasses()); } /** * Returns true if this is an anonymous inner class. If true, the name of the containing method can be obtained * by calling getFullyQualifiedContainingMethodName(). * * @return True if this is an anonymous inner class. */ public boolean isAnonymousInnerClass() { return fullyQualifiedContainingMethodName != null; } /** * Get fully-qualified containing method name (i.e. fully qualified classname, followed by dot, followed by * method name, for the containing method that creates an anonymous inner class. * * @return The fully-qualified method name of the method that this anonymous inner class was defined within. */ public String getFullyQualifiedContainingMethodName() { return fullyQualifiedContainingMethodName; } // ------------- /** * Get the direct superclasses of this class. * * <p> * Typically the returned set will contain zero or one direct superclass(es), but may contain more than one * direct superclass in the case of Scala mixins. * * @return the direct superclasses of this class, or the empty set if none. */ public Set<ClassInfo> getDirectSuperclasses() { return filterClassInfo(getDirectlyRelatedClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Convenience method for getting the single direct superclass of this class. Returns null if the class does not * have a superclass (e.g. in the case of interfaces). Throws IllegalArgumentException if there are multiple * direct superclasses (e.g. in the case of Scala mixins) -- use getDirectSuperclasses() if you need to deal * with mixins. * * @return the direct superclass of this class, or null if the class does not have a superclass. * @throws IllegalArgumentException * if there are multiple direct superclasses of this class (in the case of Scala mixins). */ public ClassInfo getDirectSuperclass() { final Set<ClassInfo> directSuperclasses = getDirectSuperclasses(); final int numDirectSuperclasses = directSuperclasses.size(); if (numDirectSuperclasses == 0) { return null; } else if (numDirectSuperclasses > 1) { throw new IllegalArgumentException("Class has multiple direct superclasses: " + directSuperclasses.toString() + " -- need to call getDirectSuperclasses() instead"); } else { return directSuperclasses.iterator().next(); } } /** * Get the names of direct superclasses of this class. * * <p> * Typically the returned list will contain zero or one direct superclass name(s), but may contain more than one * direct superclass name in the case of Scala mixins. * * @return the direct superclasses of this class, or the empty set if none. */ public List<String> getNamesOfDirectSuperclasses() { return getClassNames(getDirectSuperclasses()); } /** * Convenience method for getting the name of the single direct superclass of this class. Returns null if the * class does not have a superclass (e.g. in the case of interfaces). Throws IllegalArgumentException if there * are multiple direct superclasses (e.g. in the case of Scala mixins) -- use getNamesOfDirectSuperclasses() if * you need to deal with mixins. * * @return the name of the direct superclass of this class, or null if the class does not have a superclass. * @throws IllegalArgumentException * if there are multiple direct superclasses of this class (in the case of Scala mixins). */ public String getNameOfDirectSuperclass() { final List<String> namesOfDirectSuperclasses = getNamesOfDirectSuperclasses(); final int numDirectSuperclasses = namesOfDirectSuperclasses.size(); if (numDirectSuperclasses == 0) { return null; } else if (numDirectSuperclasses > 1) { throw new IllegalArgumentException( "Class has multiple direct superclasses: " + namesOfDirectSuperclasses.toString() + " -- need to call getNamesOfDirectSuperclasses() instead"); } else { return namesOfDirectSuperclasses.get(0); } } /** * Test whether this class directly extends the named superclass. * * <p> * If this class has multiple direct superclasses (in the case of Scala mixins), returns true if the named * superclass is one of the direct superclasses of this class. * * @param directSuperclassName * The direct superclass name to match. If null, matches classes without a direct superclass (e.g. * interfaces). Note that standard classes that do not extend another class have java.lang.Object as * their superclass. * @return true if this class has the named class as its direct superclass (or as one of its direct * superclasses, in the case of Scala mixins). */ public boolean hasDirectSuperclass(final String directSuperclassName) { final List<String> namesOfDirectSuperclasses = getNamesOfDirectSuperclasses(); if (directSuperclassName == null && namesOfDirectSuperclasses.isEmpty()) { return true; } else if (directSuperclassName == null || namesOfDirectSuperclasses.isEmpty()) { return false; } else { return namesOfDirectSuperclasses.contains(directSuperclassName); } } // ------------------------------------------------------------------------------------------------------------- // Interfaces /** * Get the names of interface classes found during the scan. * * @return the sorted list of names of interface classes found during the scan, or the empty list if none. */ static List<String> getNamesOfAllInterfaceClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE)); } /** * Test whether this class is an "implemented interface" (meaning a standard, non-annotation interface, or an * annotation that has also been implemented as an interface by some class). * * <p> * Annotations are interfaces, but you can also implement an annotation, so to we Test whether an interface * (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not * an interface but not an annotation. * * <p> * (This is named "implemented interface" rather than just "interface" to distinguish it from an annotation.) * * @return true if this class is an "implemented interface". */ public boolean isImplementedInterface() { return !getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING).isEmpty() || (isInterface && !isAnnotation); } // ------------- /** * Get the subinterfaces of this interface. * * @return the set of subinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getSubinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of subinterfaces of this interface. * * @return the sorted list of names of subinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfSubinterfaces() { return getClassNames(getSubinterfaces()); } /** * Test whether this class is has the named subinterface. * * @param subinterfaceName * The name of the subinterface. * @return true if this class is an interface and has the named subinterface. */ public boolean hasSubinterface(final String subinterfaceName) { return getNamesOfSubinterfaces().contains(subinterfaceName); } // ------------- /** * Get the direct subinterfaces of this interface. * * @return the set of direct subinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getDirectSubinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of direct subinterfaces of this interface. * * @return the sorted list of names of direct subinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfDirectSubinterfaces() { return getClassNames(getDirectSubinterfaces()); } /** * Test whether this class is and interface and has the named direct subinterface. * * @param directSubinterfaceName * The name of the direct subinterface. * @return true if this class is and interface and has the named direct subinterface. */ public boolean hasDirectSubinterface(final String directSubinterfaceName) { return getNamesOfDirectSubinterfaces().contains(directSubinterfaceName); } // ------------- /** * Get the superinterfaces of this interface. * * @return the set of superinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getSuperinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of superinterfaces of this interface. * * @return the sorted list of names of superinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfSuperinterfaces() { return getClassNames(getSuperinterfaces()); } /** * Test whether this class is an interface and has the named superinterface. * * @param superinterfaceName * The name of the superinterface. * @return true if this class is an interface and has the named superinterface. */ public boolean hasSuperinterface(final String superinterfaceName) { return getNamesOfSuperinterfaces().contains(superinterfaceName); } // ------------- /** * Get the direct superinterfaces of this interface. * * @return the set of direct superinterfaces of this interface, or the empty set if none. */ public Set<ClassInfo> getDirectSuperinterfaces() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the names of direct superinterfaces of this interface. * * @return the sorted list of names of direct superinterfaces of this interface, or the empty list if none. */ public List<String> getNamesOfDirectSuperinterfaces() { return getClassNames(getDirectSuperinterfaces()); } /** * Test whether this class is an interface and has the named direct superinterface. * * @param directSuperinterfaceName * The name of the direct superinterface. * @return true if this class is an interface and has the named direct superinterface. */ public boolean hasDirectSuperinterface(final String directSuperinterfaceName) { return getNamesOfDirectSuperinterfaces().contains(directSuperinterfaceName); } // ------------- /** * Get the interfaces implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces implemented by this standard class, or by one of its superclasses. Returns the * empty set if none. */ public Set<ClassInfo> getImplementedInterfaces() { if (!isStandardClass()) { return Collections.<ClassInfo> emptySet(); } else { final Set<ClassInfo> superclasses = filterClassInfo(getReachableClasses(RelType.SUPERCLASSES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); // Subclasses of implementing classes also implement the interface final Set<ClassInfo> allInterfaces = new HashSet<>(); allInterfaces.addAll(getReachableClasses(RelType.IMPLEMENTED_INTERFACES)); for (final ClassInfo superClass : superclasses) { allInterfaces.addAll(superClass.getReachableClasses(RelType.IMPLEMENTED_INTERFACES)); } return allInterfaces; } } /** * Get the interfaces implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces implemented by this standard class, or by one of its superclasses. Returns the * empty list if none. */ public List<String> getNamesOfImplementedInterfaces() { return getClassNames(getImplementedInterfaces()); } /** * Test whether this standard class implements the named interface, or by one of its superclasses. * * @param interfaceName * The name of the interface. * @return true this class is a standard class, and it (or one of its superclasses) implements the named * interface. */ public boolean implementsInterface(final String interfaceName) { return getNamesOfImplementedInterfaces().contains(interfaceName); } // ------------- /** * Get the interfaces directly implemented by this standard class. * * @return the set of interfaces directly implemented by this standard class. Returns the empty set if none. */ public Set<ClassInfo> getDirectlyImplementedInterfaces() { return !isStandardClass() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.IMPLEMENTED_INTERFACES), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.IMPLEMENTED_INTERFACE); } /** * Get the interfaces directly implemented by this standard class, or by one of its superclasses. * * @return the set of interfaces directly implemented by this standard class, or by one of its superclasses. * Returns the empty list if none. */ public List<String> getNamesOfDirectlyImplementedInterfaces() { return getClassNames(getDirectlyImplementedInterfaces()); } /** * Test whether this standard class directly implements the named interface, or by one of its superclasses. * * @param interfaceName * The name of the interface. * @return true this class is a standard class, and directly implements the named interface. */ public boolean directlyImplementsInterface(final String interfaceName) { return getNamesOfDirectlyImplementedInterfaces().contains(interfaceName); } // ------------- /** * Get the classes that implement this interface, and their subclasses. * * @return the set of classes implementing this interface, or the empty set if none. */ public Set<ClassInfo> getClassesImplementing() { if (!isImplementedInterface()) { return Collections.<ClassInfo> emptySet(); } else { final Set<ClassInfo> implementingClasses = filterClassInfo( getReachableClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); // Subclasses of implementing classes also implement the interface final Set<ClassInfo> allImplementingClasses = new HashSet<>(); for (final ClassInfo implementingClass : implementingClasses) { allImplementingClasses.add(implementingClass); allImplementingClasses.addAll(implementingClass.getReachableClasses(RelType.SUBCLASSES)); } return allImplementingClasses; } } /** * Get the names of classes that implement this interface, and the names of their subclasses. * * @return the sorted list of names of classes implementing this interface, or the empty list if none. */ public List<String> getNamesOfClassesImplementing() { return getClassNames(getClassesImplementing()); } /** * Test whether this class is implemented by the named class, or by one of its superclasses. * * @param className * The name of the class. * @return true if this class is implemented by the named class, or by one of its superclasses. */ public boolean isImplementedByClass(final String className) { return getNamesOfClassesImplementing().contains(className); } // ------------- /** * Get the classes that directly implement this interface, and their subclasses. * * @return the set of classes directly implementing this interface, or the empty set if none. */ public Set<ClassInfo> getClassesDirectlyImplementing() { return !isImplementedInterface() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_IMPLEMENTING), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.STANDARD_CLASS); } /** * Get the names of classes that directly implement this interface, and the names of their subclasses. * * @return the sorted list of names of classes directly implementing this interface, or the empty list if none. */ public List<String> getNamesOfClassesDirectlyImplementing() { return getClassNames(getClassesDirectlyImplementing()); } /** * Test whether this class is directly implemented by the named class, or by one of its superclasses. * * @param className * The name of the class. * @return true if this class is directly implemented by the named class, or by one of its superclasses. */ public boolean isDirectlyImplementedByClass(final String className) { return getNamesOfClassesDirectlyImplementing().contains(className); } // ------------------------------------------------------------------------------------------------------------- // Annotations /** * Get the names of all annotation classes found during the scan. * * @return the sorted list of names of annotation classes found during the scan, or the empty list if none. */ static List<String> getNamesOfAllAnnotationClasses(final ScanSpec scanSpec, final Set<ClassInfo> allClassInfo) { return getClassNames(filterClassInfo(allClassInfo, /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION)); } // ------------- /** * Get the standard classes and non-annotation interfaces that are annotated by this annotation. * * @param direct * if true, return only directly-annotated classes. * @return the set of standard classes and non-annotation interfaces that are annotated by the annotation * corresponding to this ClassInfo class, or the empty set if none. */ private Set<ClassInfo> getClassesWithAnnotation(final boolean direct) { if (!isAnnotation()) { return Collections.<ClassInfo> emptySet(); } final Set<ClassInfo> classesWithAnnotation = filterClassInfo( direct ? getDirectlyRelatedClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION) : getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, // ClassType.STANDARD_CLASS, ClassType.IMPLEMENTED_INTERFACE); boolean isInherited = false; for (final ClassInfo metaAnnotation : getDirectlyRelatedClasses(RelType.CLASS_ANNOTATIONS)) { if (metaAnnotation.className.equals("java.lang.annotation.Inherited")) { isInherited = true; break; } } if (isInherited) { final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new HashSet<>(classesWithAnnotation); for (final ClassInfo classWithAnnotation : classesWithAnnotation) { classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses()); } return classesWithAnnotationAndTheirSubclasses; } else { return classesWithAnnotation; } } /** * Get the standard classes and non-annotation interfaces that are annotated by this annotation. * * @return the set of standard classes and non-annotation interfaces that are annotated by the annotation * corresponding to this ClassInfo class, or the empty set if none. */ public Set<ClassInfo> getClassesWithAnnotation() { return getClassesWithAnnotation(/* direct = */ false); } /** * Get the names of standard classes and non-annotation interfaces that are annotated by this annotation. . * * @return the sorted list of names of ClassInfo objects for standard classes and non-annotation interfaces that * are annotated by the annotation corresponding to this ClassInfo class, or the empty list if none. */ public List<String> getNamesOfClassesWithAnnotation() { return getClassNames(getClassesWithAnnotation()); } /** * Test whether this class annotates the named class. * * @param annotatedClassName * The name of the annotated class. * @return True if this class annotates the named class. */ public boolean annotatesClass(final String annotatedClassName) { return getNamesOfClassesWithAnnotation().contains(annotatedClassName); } // ------------- /** * Get the standard classes or non-annotation interfaces that are directly annotated with this annotation. * * @return the set of standard classes or non-annotation interfaces that are directly annotated with this * annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectAnnotation() { return getClassesWithAnnotation(/* direct = */ true); } /** * Get the names of standard classes or non-annotation interfaces that are directly annotated with this * annotation. * * @return the sorted list of names of standard classes or non-annotation interfaces that are directly annotated * with this annotation, or the empty list if none. */ public List<String> getNamesOfClassesWithDirectAnnotation() { return getClassNames(getClassesWithDirectAnnotation()); } /** * Test whether this class directly annotates the named class. * * @param directlyAnnotatedClassName * The name of the directly annotated class. * @return true if this class directly annotates the named class. */ public boolean directlyAnnotatesClass(final String directlyAnnotatedClassName) { return getNamesOfClassesWithDirectAnnotation().contains(directlyAnnotatedClassName); } // ------------- /** * Get the annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the set of annotations and meta-annotations on this class or interface, or meta-annotations if this * is an annotation. Returns the empty set if none. */ public Set<ClassInfo> getAnnotations() { return filterClassInfo(getReachableClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the sorted list of names of annotations and meta-annotations on this class or interface, or * meta-annotations if this is an annotation. Returns the empty list if none. */ public List<String> getNamesOfAnnotations() { return getClassNames(getAnnotations()); } /** * Test whether this class, interface or annotation has the named class annotation or meta-annotation. * * @param annotationName * The name of the annotation. * @return true if this class, interface or annotation has the named class annotation or meta-annotation. */ public boolean hasAnnotation(final String annotationName) { return getNamesOfAnnotations().contains(annotationName); } /** * Get a list of annotations on this method, along with any annotation parameter values, wrapped in * {@link AnnotationInfo} objects, or the empty list if none. * * @return A list of {@link AnnotationInfo} objects for the annotations on this method, or the empty list if * none. */ public List<AnnotationInfo> getAnnotationInfo() { return annotationInfo == null ? Collections.<AnnotationInfo> emptyList() : annotationInfo; } /** * Get a list of the default parameter values, if this is an annotation, and it has default parameter values. * Otherwise returns the empty list. * * @return If this is an annotation class, the list of {@link AnnotationParamValue} objects for each of the * default parameter values for this annotation, otherwise the empty list. */ public List<AnnotationParamValue> getAnnotationDefaultParamValues() { return annotationDefaultParamValues == null ? Collections.<AnnotationParamValue> emptyList() : annotationDefaultParamValues; } // ------------- /** * Get the direct annotations and meta-annotations on this class. This is equivalent to the reflection call * Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the set of direct annotations and meta-annotations on this class, or the empty set if none. */ public Set<ClassInfo> getDirectAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of direct annotations and meta-annotations on this class. This is equivalent to the reflection * call Class#getAnnotations(), except that it does not require calling the classloader, and it returns * meta-annotations as well as annotations. * * @return the sorted list of names of direct annotations and meta-annotations on this class, or the empty list * if none. */ public List<String> getNamesOfDirectAnnotations() { return getClassNames(getDirectAnnotations()); } /** * Test whether this class has the named direct annotation or meta-annotation. (This is equivalent to the * reflection call Class#hasAnnotation(), except that it does not require calling the classloader, and it works * for meta-annotations as well as Annotatinons.) * * @param directAnnotationName * The name of the direct annotation. * @return true if this class has the named direct annotation or meta-annotation. */ public boolean hasDirectAnnotation(final String directAnnotationName) { return getNamesOfDirectAnnotations().contains(directAnnotationName); } // ------------- /** * Get the annotations and meta-annotations on this annotation class. * * @return the set of annotations and meta-annotations, if this is an annotation class, or the empty set if none * (or if this is not an annotation class). */ public Set<ClassInfo> getMetaAnnotations() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASS_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of annotations and meta-annotations on this annotation class. * * @return the set of annotations and meta-annotations, if this is an annotation class, or the empty list if * none (or if this is not an annotation class). */ public List<String> getNamesOfMetaAnnotations() { return getClassNames(getMetaAnnotations()); } /** * Test whether this is an annotation class and it has the named meta-annotation. * * @param metaAnnotationName * The meta-annotation name. * @return true if this is an annotation class and it has the named meta-annotation. */ public boolean hasMetaAnnotation(final String metaAnnotationName) { return getNamesOfMetaAnnotations().contains(metaAnnotationName); } // ------------- /** * Get the annotations that have this meta-annotation. * * @return the set of annotations that have this meta-annotation, or the empty set if none. */ public Set<ClassInfo> getAnnotationsWithMetaAnnotation() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of annotations that have this meta-annotation. * * @return the sorted list of names of annotations that have this meta-annotation, or the empty list if none. */ public List<String> getNamesOfAnnotationsWithMetaAnnotation() { return getClassNames(getAnnotationsWithMetaAnnotation()); } /** * Test whether this annotation has the named meta-annotation. * * @param annotationName * The annotation name. * @return true if this annotation has the named meta-annotation. */ public boolean metaAnnotatesAnnotation(final String annotationName) { return getNamesOfAnnotationsWithMetaAnnotation().contains(annotationName); } // ------------- /** * Get the annotations that have this direct meta-annotation. * * @return the set of annotations that have this direct meta-annotation, or the empty set if none. */ public Set<ClassInfo> getAnnotationsWithDirectMetaAnnotation() { return !isAnnotation() ? Collections.<ClassInfo> emptySet() : filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_CLASS_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of annotations that have this direct meta-annotation. * * @return the sorted list of names of annotations that have this direct meta-annotation, or the empty list if * none. */ public List<String> getNamesOfAnnotationsWithDirectMetaAnnotation() { return getClassNames(getAnnotationsWithDirectMetaAnnotation()); } /** * Test whether this annotation is directly meta-annotated with the named annotation. * * @param directMetaAnnotationName * The direct meta-annotation name. * @return true if this annotation is directly meta-annotated with the named annotation. */ public boolean hasDirectMetaAnnotation(final String directMetaAnnotationName) { return getNamesOfAnnotationsWithDirectMetaAnnotation().contains(directMetaAnnotationName); } // ------------------------------------------------------------------------------------------------------------- // Methods /** * Returns information on visible methods of the class that are not constructors. There may be more than one * method of a given name with different type signatures, due to overloading. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreMethodVisibility() * was called before the scan. If method visibility is ignored, the result may include a reference to a private * static class initializer block, with a method name of {@code "<clinit>"}. * * @return the list of MethodInfo objects for visible methods of this class, or the empty list if no methods * were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return Collections.<MethodInfo> emptyList(); } else { final List<MethodInfo> nonConstructorMethods = new ArrayList<>(); for (final MethodInfo mi : methodInfo) { final String methodName = mi.getMethodName(); if (!methodName.equals("<init>") && !methodName.equals("<clinit>")) { nonConstructorMethods.add(mi); } } return nonConstructorMethods; } } /** * Returns information on visible constructors of the class. Constructors have the method name of * {@code "<init>"}. There may be more than one constructor of a given name with different type signatures, due * to overloading. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public constructors, unless * FastClasspathScanner#ignoreMethodVisibility() was called before the scan. * * @return the list of MethodInfo objects for visible constructors of this class, or the empty list if no * constructors were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getConstructorInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return Collections.<MethodInfo> emptyList(); } else { final List<MethodInfo> nonConstructorMethods = new ArrayList<>(); for (final MethodInfo mi : methodInfo) { final String methodName = mi.getMethodName(); if (methodName.equals("<init>")) { nonConstructorMethods.add(mi); } } return nonConstructorMethods; } } /** * Returns information on visible methods and constructors of the class. There may be more than one method or * constructor or method of a given name with different type signatures, due to overloading. Constructors have * the method name of {@code "<init>"}. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods and constructors, unless * FastClasspathScanner#ignoreMethodVisibility() was called before the scan. If method visibility is ignored, * the result may include a reference to a private static class initializer block, with a method name of * {@code "<clinit>"}. * * @return the list of MethodInfo objects for visible methods and constructors of this class, or the empty list * if no methods or constructors were found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodAndConstructorInfo() { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } return methodInfo == null ? Collections.<MethodInfo> emptyList() : methodInfo; } /** * Returns information on the method(s) of the class with the given method name. Constructors have the method * name of {@code "<init>"}. * * <p> * Requires that FastClasspathScanner#enableMethodInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreMethodVisibility() * was called before the scan. * * <p> * May return info for multiple methods with the same name (with different type signatures). * * @param methodName * The method name to query. * @return a list of MethodInfo objects for the method(s) with the given name, or the empty list if the method * was not found in this class (or is not visible). * @throws IllegalArgumentException * if FastClasspathScanner#enableMethodInfo() was not called prior to initiating the scan. */ public List<MethodInfo> getMethodInfo(final String methodName) { if (!scanSpec.enableMethodInfo) { throw new IllegalArgumentException("Cannot get method info without calling " + "FastClasspathScanner#enableMethodInfo() before starting the scan"); } if (methodInfo == null) { return null; } if (methodNameToMethodInfo == null) { // Lazily build reverse mapping cache methodNameToMethodInfo = new MultiMapKeyToList<>(); for (final MethodInfo f : methodInfo) { methodNameToMethodInfo.put(f.getMethodName(), f); } } final List<MethodInfo> methodList = methodNameToMethodInfo.get(methodName); return methodList == null ? Collections.<MethodInfo> emptyList() : methodList; } // ------------------------------------------------------------------------------------------------------------- // Method annotations /** * Get the direct method direct annotations on this class. * * @return the set of method direct annotations on this class, or the empty set if none. */ public Set<ClassInfo> getMethodDirectAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.METHOD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the method annotations or meta-annotations on this class. * * @return the set of method annotations or meta-annotations on this class, or the empty set if none. */ public Set<ClassInfo> getMethodAnnotations() { return filterClassInfo(getReachableClasses(RelType.METHOD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of method direct annotations on this class. * * @return the sorted list of names of method direct annotations on this class, or the empty list if none. */ public List<String> getNamesOfMethodDirectAnnotations() { return getClassNames(getMethodDirectAnnotations()); } /** * Get the names of method annotations or meta-annotations on this class. * * @return the sorted list of names of method annotations or meta-annotations on this class, or the empty list * if none. */ public List<String> getNamesOfMethodAnnotations() { return getClassNames(getMethodAnnotations()); } /** * Test whether this class has a method with the named method direct annotation. * * @param annotationName * The annotation name. * @return true if this class has a method with the named direct annotation. */ public boolean hasMethodWithDirectAnnotation(final String annotationName) { return getNamesOfMethodDirectAnnotations().contains(annotationName); } /** * Test whether this class has a method with the named method annotation or meta-annotation. * * @param annotationName * The annotation name. * @return true if this class has a method with the named annotation or meta-annotation. */ public boolean hasMethodWithAnnotation(final String annotationName) { return getNamesOfMethodAnnotations().contains(annotationName); } // ------------- /** * Get the classes that have a method with this direct annotation. * * @return the set of classes that have a method with this direct annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectMethodAnnotation() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_METHOD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the classes that have a method with this annotation or meta-annotation. * * @return the set of classes that have a method with this annotation or meta-annotation, or the empty set if * none. */ public Set<ClassInfo> getClassesWithMethodAnnotation() { return filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_METHOD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a method with this direct annotation. * * @return the sorted list of names of classes that have a method with this direct annotation, or the empty list * if none. */ public List<String> getNamesOfClassesWithDirectMethodAnnotation() { return getClassNames(getClassesWithDirectMethodAnnotation()); } /** * Get the names of classes that have a method with this annotation. * * @return the sorted list of names of classes that have a method with this annotation, or the empty list if * none. */ public List<String> getNamesOfClassesWithMethodAnnotation() { return getClassNames(getClassesWithMethodAnnotation()); } /** * Test whether this annotation annotates or meta-annotates a method of the named class. * * @param className * The class name. * @return true if this annotation annotates a method of the named class. */ public boolean annotatesMethodOfClass(final String className) { return getNamesOfClassesWithMethodAnnotation().contains(className); } /** * Return a sorted list of classes that have a method directly annotated with the named annotation. * * @return the sorted list of names of classes that have a method with the named direct annotation, or the empty * list if none. */ static List<String> getNamesOfClassesWithDirectMethodAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedMethodAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getDirectlyRelatedClasses(RelType.METHOD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedMethodAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedMethodAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedMethodAnnotation); } return namesOfClassesWithNamedMethodAnnotation; } /** * Return a sorted list of classes that have a method with the named annotation or meta-annotation. * * @return the sorted list of names of classes that have a method with the named annotation or meta-annotation, * or the empty list if none. */ static List<String> getNamesOfClassesWithMethodAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedMethodAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getReachableClasses(RelType.METHOD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedMethodAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedMethodAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedMethodAnnotation); } return namesOfClassesWithNamedMethodAnnotation; } // ------------------------------------------------------------------------------------------------------------- // Fields /** * Get the constant initializer value for the named static final field, if present. * * @return the constant initializer value for the named static final field, if present. */ Object getStaticFinalFieldConstantInitializerValue(final String fieldName) { return staticFinalFieldNameToConstantInitializerValue == null ? null : staticFinalFieldNameToConstantInitializerValue.get(fieldName); } /** * Returns information on all visible fields of the class. * * <p> * Requires that FastClasspathScanner#enableFieldInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public methods, unless FastClasspathScanner#ignoreFieldVisibility() * was called before the scan. * * @return the list of FieldInfo objects for visible fields of this class, or the empty list if no fields were * found or visible. * @throws IllegalArgumentException * if FastClasspathScanner#enableFieldInfo() was not called prior to initiating the scan. */ public List<FieldInfo> getFieldInfo() { if (!scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Cannot get field info without calling " + "FastClasspathScanner#enableFieldInfo() before starting the scan"); } return fieldInfo == null ? Collections.<FieldInfo> emptyList() : fieldInfo; } /** * Returns information on a given visible field of the class. * * <p> * Requires that FastClasspathScanner#enableFieldInfo() be called before scanning, otherwise throws * IllegalArgumentException. * * <p> * By default only returns information for public fields, unless FastClasspathScanner#ignoreFieldVisibility() * was called before the scan. * * @param fieldName * The field name to query. * @return the FieldInfo object for the named field, or null if the field was not found in this class (or is not * visible). * @throws IllegalArgumentException * if FastClasspathScanner#enableFieldInfo() was not called prior to initiating the scan. */ public FieldInfo getFieldInfo(final String fieldName) { if (!scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Cannot get field info without calling " + "FastClasspathScanner#enableFieldInfo() before starting the scan"); } if (fieldInfo == null) { return null; } if (fieldNameToFieldInfo == null) { // Lazily build reverse mapping cache fieldNameToFieldInfo = new HashMap<>(); for (final FieldInfo f : fieldInfo) { fieldNameToFieldInfo.put(f.getFieldName(), f); } } return fieldNameToFieldInfo.get(fieldName); } // ------------------------------------------------------------------------------------------------------------- // Field annotations /** * Get the field annotations on this class. * * @return the set of field annotations on this class, or the empty set if none. */ public Set<ClassInfo> getFieldAnnotations() { return filterClassInfo(getDirectlyRelatedClasses(RelType.FIELD_ANNOTATIONS), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ANNOTATION); } /** * Get the names of field annotations on this class. * * @return the sorted list of names of field annotations on this class, or the empty list if none. */ public List<String> getNamesOfFieldAnnotations() { return getClassNames(getFieldAnnotations()); } /** * Test whether this class has a field with the named field annotation. * * @param annotationName * The annotation name. * @return true if this class has a field with the named annotation. */ public boolean hasFieldWithAnnotation(final String annotationName) { return getNamesOfFieldAnnotations().contains(annotationName); } // ------------- /** * Get the classes that have a field with this annotation or meta-annotation. * * @return the set of classes that have a field with this annotation or meta-annotation, or the empty set if * none. */ public Set<ClassInfo> getClassesWithFieldAnnotation() { return filterClassInfo(getReachableClasses(RelType.CLASSES_WITH_FIELD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a field with this annotation or meta-annotation. * * @return the sorted list of names of classes that have a field with this annotation or meta-annotation, or the * empty list if none. */ public List<String> getNamesOfClassesWithFieldAnnotation() { return getClassNames(getClassesWithFieldAnnotation()); } /** * Get the classes that have a field with this direct annotation. * * @return the set of classes that have a field with this direct annotation, or the empty set if none. */ public Set<ClassInfo> getClassesWithDirectFieldAnnotation() { return filterClassInfo(getDirectlyRelatedClasses(RelType.CLASSES_WITH_FIELD_ANNOTATION), /* removeExternalClassesIfStrictWhitelist = */ true, scanSpec, ClassType.ALL); } /** * Get the names of classes that have a field with this direct annotation. * * @return the sorted list of names of classes that have a field with thisdirect annotation, or the empty list * if none. */ public List<String> getNamesOfClassesWithDirectFieldAnnotation() { return getClassNames(getClassesWithDirectFieldAnnotation()); } /** * Test whether this annotation annotates a field of the named class. * * @param className * The class name. * @return true if this annotation annotates a field of the named class. */ public boolean annotatesFieldOfClass(final String className) { return getNamesOfClassesWithFieldAnnotation().contains(className); } /** * Return a sorted list of classes that have a field with the named annotation or meta-annotation. * * @return the sorted list of names of classes that have a field with the named annotation or meta-annotation, * or the empty list if none. */ static List<String> getNamesOfClassesWithFieldAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedFieldAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getReachableClasses(RelType.FIELD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedFieldAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedFieldAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedFieldAnnotation); } return namesOfClassesWithNamedFieldAnnotation; } /** * Return a sorted list of classes that have a field with the named annotation or direct annotation. * * @return the sorted list of names of classes that have a field with the named direct annotation, or the empty * list if none. */ static List<String> getNamesOfClassesWithDirectFieldAnnotation(final String annotationName, final Set<ClassInfo> allClassInfo) { // This method will not likely be used for a large number of different annotation types, so perform a linear // search on each invocation, rather than building an index on classpath scan (so we don't slow down more // common methods). final ArrayList<String> namesOfClassesWithNamedFieldAnnotation = new ArrayList<>(); for (final ClassInfo classInfo : allClassInfo) { for (final ClassInfo annotationType : classInfo.getDirectlyRelatedClasses(RelType.FIELD_ANNOTATIONS)) { if (annotationType.className.equals(annotationName)) { namesOfClassesWithNamedFieldAnnotation.add(classInfo.className); break; } } } if (!namesOfClassesWithNamedFieldAnnotation.isEmpty()) { Collections.sort(namesOfClassesWithNamedFieldAnnotation); } return namesOfClassesWithNamedFieldAnnotation; } }
Deprecate ClassInfo#getClassLoaders() (#209) (A classloader may need to be created dynamically for Spring-Boot classes, when calling getClassRef())
src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClassInfo.java
Deprecate ClassInfo#getClassLoaders() (#209)
Java
mit
fbd1b673d7f1e92b2e7ce9182f26b2c06219a879
0
mainini/stiam-sender,iam-ictm/stiam-sender
/* * Copyright 2014 Pascal Mainini, Marc Kunz * Licensed under MIT license, see included file LICENSE or * http://opensource.org/licenses/MIT */ package ch.bfh.ti.ictm.iam.stiam.aa.authority; import ch.bfh.ti.ictm.iam.stiam.aa.test.TestConfiguration; import ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ExtendedAttributeQueryBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableEntryException; import java.security.cert.CertificateException; import java.util.ArrayList; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import static org.hamcrest.CoreMatchers.is; import org.junit.AfterClass; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.opensaml.xml.ConfigurationException; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.parse.XMLParserException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.signature.SignatureException; /** * Testsuite for the AttributeService * * @author Pascal Mainini * @author Marc Kunz */ public class AttributeServiceTest { //////////////////////////////////////// Fields private static StringWriter stringWriter; private static TestConfiguration testConfig; //////////////////////////////////////// Inner classes /** * A helper-class for mocking the servlet responses */ private static abstract class ServletResponseStub implements HttpServletResponse { private int statusCode = 0; @Override public int getStatus() { return statusCode; } @Override public void setStatus(int sc) { this.statusCode = sc; } } //////////////////////////////////////// Unit-tests and initialization /** * Set up some things before running the tests... */ @BeforeClass public static void setUpClass() { stringWriter = new StringWriter(); testConfig = new TestConfiguration(); } /** * Cleanup after testing... */ @AfterClass public static void tearDownClass() { try { stringWriter.close(); } catch (IOException ex) { } stringWriter = null; } /** * Test doGet() with an empty request */ @Test public void testAttributeServiceGETEmptyRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doGet(mockEmptyRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } /** * Test doPost() with an empty request */ @Test public void testAttributeServicePOSTEmptyRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doPost(mockEmptyRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(400)); } /** * Test doGet() with a mocked request */ @Test public void testAttributeServiceGETAttributeRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doGet(mockAttributeRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } /** * Test doPost() with a mocked request */ @Test public void testAttributeServicePOSTAttributeRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doPost(mockAttributeRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } //////////////////////////////////////// Helpers /** * @return a mocked-up HttpServletResponse with the ability to store status */ private HttpServletResponse mockResponse() { final HttpServletResponse res = mock(ServletResponseStub.class); try { when(res.getWriter()).thenReturn(new PrintWriter(stringWriter, true)); } catch (IOException ex) { fail("Could not initialise writer of servletResponse: " + ex.toString()); } doCallRealMethod().when(res).setStatus(anyInt()); doCallRealMethod().when(res).getStatus(); return res; } /** * @return a mocked-up HttpServletRequest with method POST and destination * AA */ private HttpServletRequest mockEmptyRequest() { final HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn("POST"); when(req.getRequestURL()).thenReturn(new StringBuffer(testConfig.getProperty("AttributeServiceTest.RequestURL", "http://localhost:8080/"))); return req; } /** * @return a mocked-up HttpServletRequest containing a full SAML extended * attribute query */ private HttpServletRequest mockAttributeRequest() { final HttpServletRequest req = mockEmptyRequest(); String[] attributeProperties = testConfig.getPropertyList("AttributeServiceTest.Attributes"); ArrayList<String[]> attributes; if (attributeProperties != null) { attributes = new ArrayList<>(attributeProperties.length); for (String attributeProperty : attributeProperties) { attributes.add(testConfig.getPropertyList(attributeProperty)); } } else { attributes = new ArrayList<>(0); } try { final ExtendedAttributeQueryBuilder builder = new ExtendedAttributeQueryBuilder(attributes); when(req.getParameter("SAMLRequest")).thenReturn( builder.buildBase64()); when(req.getInputStream()).thenReturn(new MockInputStream( new String("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Body>" + builder.build().substring(38) + "</S:Body></S:Envelope>")) // FIXME ugly substring-hack ); } catch (ConfigurationException | NoSuchAlgorithmException | IOException | KeyStoreException | CertificateException | UnrecoverableEntryException | SecurityException | MarshallingException | SignatureException | TransformerException | XMLParserException ex) { fail("Could not initialise servlet request: " + ex.toString()); } return req; } //////////////////////////////////////// Inner classes /** * A mockup of a ServletInputStream used for supporting the SOAP-binding. */ private class MockInputStream extends ServletInputStream { private final ByteArrayInputStream stream; MockInputStream(String data) { stream = new ByteArrayInputStream(data.getBytes()); } @Override public boolean isFinished() { return stream.available() > 0; } @Override public boolean isReady() { return true; } @Override public int read() throws IOException { return stream.read(); } @Override public void setReadListener(ReadListener readListener) { throw new UnsupportedOperationException(); } } }
src/test/java/ch/bfh/ti/ictm/iam/stiam/aa/authority/AttributeServiceTest.java
/* * Copyright 2014 Pascal Mainini, Marc Kunz * Licensed under MIT license, see included file LICENSE or * http://opensource.org/licenses/MIT */ package ch.bfh.ti.ictm.iam.stiam.aa.authority; import ch.bfh.ti.ictm.iam.stiam.aa.test.TestConfiguration; import ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ExtendedAttributeQueryBuilder; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableEntryException; import java.security.cert.CertificateException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import static org.hamcrest.CoreMatchers.is; import org.junit.AfterClass; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.opensaml.xml.ConfigurationException; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.parse.XMLParserException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.signature.SignatureException; /** * Testsuite for the AttributeService * * @author Pascal Mainini * @author Marc Kunz */ public class AttributeServiceTest { //////////////////////////////////////// Fields private static StringWriter stringWriter; private static TestConfiguration testConfig; //////////////////////////////////////// Inner classes /** * A helper-class for mocking the servlet responses */ private static abstract class ServletResponseStub implements HttpServletResponse { private int statusCode = 0; @Override public int getStatus() { return statusCode; } @Override public void setStatus(int sc) { this.statusCode = sc; } } //////////////////////////////////////// Unit-tests and initialization /** * Set up some things before running the tests... */ @BeforeClass public static void setUpClass() { stringWriter = new StringWriter(); testConfig = new TestConfiguration(); } /** * Cleanup after testing... */ @AfterClass public static void tearDownClass() { try { stringWriter.close(); } catch (IOException ex) { } stringWriter = null; } /** * Test doGet() with an empty request */ @Test public void testAttributeServiceGETEmptyRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doGet(mockEmptyRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } /** * Test doPost() with an empty request */ @Test public void testAttributeServicePOSTEmptyRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doPost(mockEmptyRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(400)); } /** * Test doGet() with a mocked request */ @Test public void testAttributeServiceGETAttributeRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doGet(mockAttributeRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } /** * Test doPost() with a mocked request */ @Test public void testAttributeServicePOSTAttributeRequest() { final AttributeService as = new AttributeService(); final HttpServletResponse res = mockResponse(); try { as.init(); as.doPost(mockAttributeRequest(), res); } catch (ServletException | IOException ex) { fail("Error while testing servlet: " + ex.toString()); } assertThat(res.getStatus(), is(200)); } //////////////////////////////////////// Helpers /** * @return a mocked-up HttpServletResponse with the ability to store status */ private HttpServletResponse mockResponse() { final HttpServletResponse res = mock(ServletResponseStub.class); try { when(res.getWriter()).thenReturn(new PrintWriter(stringWriter, true)); } catch (IOException ex) { fail("Could not initialise writer of servletResponse: " + ex.toString()); } doCallRealMethod().when(res).setStatus(anyInt()); doCallRealMethod().when(res).getStatus(); return res; } /** * @return a mocked-up HttpServletRequest with method POST and destination * AA */ private HttpServletRequest mockEmptyRequest() { final HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn("POST"); when(req.getRequestURL()).thenReturn(new StringBuffer(testConfig.getProperty("AttributeServiceTest.RequestURL", "http://localhost:8080/"))); return req; } /** * @return a mocked-up HttpServletRequest containing a full SAML extended * attribute query */ private HttpServletRequest mockAttributeRequest() { final HttpServletRequest req = mockEmptyRequest(); String[] attributeProperties = testConfig.getPropertyList("AttributeServiceTest.Attributes"); ArrayList<String[]> attributes; if (attributeProperties != null) { attributes = new ArrayList<>(attributeProperties.length); for (String attributeProperty : attributeProperties) { attributes.add(testConfig.getPropertyList(attributeProperty)); } } else { attributes = new ArrayList<>(0); } try { when(req.getParameter("SAMLRequest")).thenReturn( new ExtendedAttributeQueryBuilder(attributes).buildBase64()); } catch (ConfigurationException | NoSuchAlgorithmException | IOException | KeyStoreException | CertificateException | UnrecoverableEntryException | SecurityException | MarshallingException | SignatureException | TransformerException | XMLParserException ex) { fail("Could not initialise servlet request: " + ex.toString()); } return req; } }
fixed unit test
src/test/java/ch/bfh/ti/ictm/iam/stiam/aa/authority/AttributeServiceTest.java
fixed unit test
Java
mit
3dcb9bd7a8b9c27c576f9e9879a428afe78dc4cd
0
FlareBot/FlareBot,weeryan17/FlareBot,binaryoverload/FlareBot
package com.bwfcwalshy.flarebot; import com.bwfcwalshy.flarebot.commands.Command; import com.bwfcwalshy.flarebot.commands.CommandType; import com.bwfcwalshy.flarebot.util.Welcome; import sx.blah.discord.api.events.EventSubscriber; import sx.blah.discord.handle.impl.events.*; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IRole; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.RequestBuffer; import java.awt.*; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class Events { private FlareBot flareBot; private AtomicBoolean bool = new AtomicBoolean(false); private static final ThreadGroup COMMAND_THREADS = new ThreadGroup("Command Threads"); private static final ExecutorService CACHED_POOL = Executors.newCachedThreadPool(r -> new Thread(COMMAND_THREADS, r, "Command Pool-" + COMMAND_THREADS.activeCount())); public static final Map<String, AtomicInteger> COMMAND_COUNTER = new ConcurrentHashMap<>(); public Events(FlareBot bot) { this.flareBot = bot; } @EventSubscriber public void onReady(ReadyEvent e) { flareBot.run(); } @EventSubscriber public void onJoin(UserJoinEvent e) { if (flareBot.getWelcomeForGuild(e.getGuild()) != null) { Welcome welcome = flareBot.getWelcomeForGuild(e.getGuild()); IChannel channel = flareBot.getClient().getChannelByID(welcome.getChannelId()); if (channel != null) { String msg = welcome.getMessage().replace("%user%", e.getUser().getName()).replace("%guild%", e.getGuild().getName()).replace("%mention%", e.getUser().mention()); MessageUtils.sendMessage(channel, msg); } else flareBot.getWelcomes().remove(welcome); } if (flareBot.getAutoAssignRoles().containsKey(e.getGuild().getID())) { List<String> autoAssignRoles = flareBot.getAutoAssignRoles().get(e.getGuild().getID()); for (String s : autoAssignRoles) { IRole role = e.getGuild().getRoleByID(s); if (role != null) { RequestBuffer.request(() -> { try { e.getUser().addRole(role); } catch (DiscordException e1) { FlareBot.LOGGER.error("Could not auto-assign a role!", e1); } catch (MissingPermissionsException e1) { if (!e1.getErrorMessage().startsWith("Edited roles")) { MessageUtils.sendPM(e.getGuild().getOwner(), "**Could not auto assign a role!**\n" + e1.getErrorMessage()); return; } StringBuilder message = new StringBuilder(); message.append("**Hello!\nI am here to tell you that I could not give the role ``"); message.append(role.getName()).append("`` to one of your new users!\n"); message.append("Please move one of the following roles above ``").append(role.getName()) .append("`` in your server's role tab!\n```"); for (IRole i : FlareBot.getInstance().getClient().getOurUser().getRolesForGuild(role.getGuild())) { message.append(i.getName()).append('\n'); } message.append("\n```\nSo the role can be given.**"); MessageUtils.sendPM(e.getGuild().getOwner(), message); } }); } else autoAssignRoles.remove(s); } } } @EventSubscriber public void onGuildCreate(GuildCreateEvent e) { if (bool.get()) MessageUtils.sendMessage(new EmbedBuilder() .withColor(new Color(96, 230, 144)) .withThumbnail(e.getGuild().getIconURL()) .withFooterIcon(e.getGuild().getIconURL()) .withFooterText(OffsetDateTime.now() .format(DateTimeFormatter.RFC_1123_DATE_TIME) + " | " + e.getGuild().getID()) .withAuthorName(e.getGuild().getName()) .withAuthorIcon(e.getGuild().getIconURL()) .withDesc("Guild Created: `" + e.getGuild().getName() + "` :smile: :heart:\nGuild Owner: " + e.getGuild().getOwner().getName()) .build(), FlareBot.getInstance().getGuildLogChannel()); } @EventSubscriber public void onGuildDelete(GuildLeaveEvent e) { COMMAND_COUNTER.remove(e.getGuild().getID()); MessageUtils.sendMessage(new EmbedBuilder() .withColor(new Color(244, 23, 23)) .withThumbnail(e.getGuild().getIconURL()) .withFooterIcon(e.getGuild().getIconURL()) .withFooterText(OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) + " | " + e.getGuild().getID()) .withAuthorName(e.getGuild().getName()) .withAuthorIcon(e.getGuild().getIconURL()) .withDesc("Guild Deleted: `" + e.getGuild().getName() + "` L :broken_heart:\nGuild Owner: " + (e.getGuild().getOwner() != null ? e.getGuild().getOwner().getName() : "Non-existent, they had to much L")) .build(), FlareBot.getInstance().getGuildLogChannel()); } @EventSubscriber public void onVoice(UserVoiceChannelLeaveEvent e) { if (e.getChannel().getConnectedUsers().contains(e.getClient().getOurUser()) && e.getChannel().getConnectedUsers().size() < 2) { FlareBot.getInstance().getMusicManager().getPlayer(e.getChannel().getGuild().getID()).setPaused(true); e.getChannel().leave(); } } @EventSubscriber public void onMessage(MessageReceivedEvent e) { if (e.getMessage().getContent() != null && e.getMessage().getContent().startsWith(String.valueOf(FlareBot.getPrefixes().get(getGuildId(e)))) && !e.getMessage().getAuthor().isBot()) { bool.set(true); EnumSet<Permissions> perms = e.getMessage().getChannel() .getModifiedPermissions(FlareBot.getInstance().getClient().getOurUser()); if (!perms.contains(Permissions.ADMINISTRATOR)) { if (!perms.contains(Permissions.SEND_MESSAGES)) { return; } if (!perms.contains(Permissions.EMBED_LINKS)) { MessageUtils.sendMessage(e.getMessage().getChannel(), "Hey! I can't be used here." + "\nI do not have the `Embed Links` permission! Please go to your permissions and give me Embed Links." + "\nThanks :D"); return; } } String message = e.getMessage().getContent(); String command = message.substring(1); String[] args = new String[0]; if (message.contains(" ")) { command = command.substring(0, message.indexOf(" ") - 1); args = message.substring(message.indexOf(" ") + 1).split(" "); } for (Command cmd : flareBot.getCommands()) { if (cmd.getCommand().equalsIgnoreCase(command)) { if(cmd.getType() == CommandType.HIDDEN){ if (!cmd.getPermissions(e.getMessage().getChannel()).isCreator(e.getMessage().getAuthor())) { return; } } if (!cmd.getType().usableInDMs()) { if (e.getMessage().getChannel().isPrivate()) { MessageUtils.sendMessage(e.getMessage().getChannel(), String.format("**%s commands cannot be used in DM's!**", cmd.getType().formattedName())); return; } } if (cmd.getPermission() != null && cmd.getPermission().length() > 0) { if (!cmd.getPermissions(e.getMessage().getChannel()).hasPermission(e.getMessage().getAuthor(), cmd.getPermission())) { MessageUtils.sendMessage(e.getMessage().getChannel(), "You are missing the permission ``" + cmd.getPermission() + "`` which is required for use of this command!"); return; } } try { if (!e.getMessage().getChannel().isPrivate()) COMMAND_COUNTER.computeIfAbsent(e.getMessage().getChannel().getGuild().getID(), g -> new AtomicInteger()).incrementAndGet(); String[] finalArgs = args; CACHED_POOL.submit(() ->{ cmd.onCommand(e.getMessage().getAuthor(), e.getMessage().getChannel(), e.getMessage(), finalArgs); FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(finalArgs) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); }); } catch (Exception ex) { MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, e.getMessage().getChannel()); FlareBot.LOGGER.error("Exception in guild " + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator(), ex); } return; } else { for (String alias : cmd.getAliases()) { if (alias.equalsIgnoreCase(command)) { if(cmd.getType() == CommandType.HIDDEN){ if (!cmd.getPermissions(e.getMessage().getChannel()).isCreator(e.getMessage().getAuthor())) { return; } } FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); if (cmd.getType() == CommandType.MUSIC) { if (e.getMessage().getChannel().isPrivate()) { MessageUtils.sendMessage(e.getMessage().getChannel(), "**Music commands cannot be used in DM's!**"); return; } } if (cmd.getPermission() != null && cmd.getPermission().length() > 0) { if (!cmd.getPermissions(e.getMessage().getChannel()).hasPermission(e.getMessage().getAuthor(), cmd.getPermission())) { MessageUtils.sendMessage(e.getMessage().getChannel(), "You are missing the permission ``" + cmd.getPermission() + "`` which is required for use of this command!"); return; } } try { if (!e.getMessage().getChannel().isPrivate()) COMMAND_COUNTER.computeIfAbsent(e.getMessage().getChannel().getGuild().getID(), g -> new AtomicInteger()).incrementAndGet(); String[] finalArgs = args; CACHED_POOL.submit(() ->{ cmd.onCommand(e.getMessage().getAuthor(), e.getMessage().getChannel(), e.getMessage(), finalArgs); FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(finalArgs) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); }); } catch (Exception ex) { FlareBot.LOGGER.error("Exception in guild " + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator(), ex); MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, e.getMessage().getChannel()); } return; } } } } } } private void delete(MessageReceivedEvent e) { RequestBuffer.request(() -> { try { e.getMessage().delete(); } catch (DiscordException | MissingPermissionsException ignored) { } }); } private String getGuildId(MessageReceivedEvent e) { return e.getMessage().getChannel().getGuild() != null ? e.getMessage().getChannel().getGuild().getID() : null; } }
src/main/java/com/bwfcwalshy/flarebot/Events.java
package com.bwfcwalshy.flarebot; import com.bwfcwalshy.flarebot.commands.Command; import com.bwfcwalshy.flarebot.commands.CommandType; import com.bwfcwalshy.flarebot.util.Welcome; import sx.blah.discord.api.events.EventSubscriber; import sx.blah.discord.handle.impl.events.*; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IRole; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.EmbedBuilder; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.RequestBuffer; import java.awt.*; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class Events { private FlareBot flareBot; private AtomicBoolean bool = new AtomicBoolean(false); private static final ThreadGroup COMMAND_THREADS = new ThreadGroup("Command Threads"); private static final ExecutorService CACHED_POOL = Executors.newCachedThreadPool(r -> new Thread(COMMAND_THREADS, r, "Command Pool-" + COMMAND_THREADS.activeCount())); public static final Map<String, AtomicInteger> COMMAND_COUNTER = new ConcurrentHashMap<>(); public Events(FlareBot bot) { this.flareBot = bot; } @EventSubscriber public void onReady(ReadyEvent e) { flareBot.run(); } @EventSubscriber public void onJoin(UserJoinEvent e) { if (flareBot.getWelcomeForGuild(e.getGuild()) != null) { Welcome welcome = flareBot.getWelcomeForGuild(e.getGuild()); IChannel channel = flareBot.getClient().getChannelByID(welcome.getChannelId()); if (channel != null) { String msg = welcome.getMessage().replace("%user%", e.getUser().getName()).replace("%guild%", e.getGuild().getName()).replace("%mention%", e.getUser().mention()); MessageUtils.sendMessage(channel, msg); } else flareBot.getWelcomes().remove(welcome); } if (flareBot.getAutoAssignRoles().containsKey(e.getGuild().getID())) { List<String> autoAssignRoles = flareBot.getAutoAssignRoles().get(e.getGuild().getID()); for (String s : autoAssignRoles) { IRole role = e.getGuild().getRoleByID(s); if (role != null) { RequestBuffer.request(() -> { try { e.getUser().addRole(role); } catch (DiscordException e1) { FlareBot.LOGGER.error("Could not auto-assign a role!", e1); } catch (MissingPermissionsException e1) { if (!e1.getErrorMessage().startsWith("Edited roles")) { MessageUtils.sendPM(e.getGuild().getOwner(), "**Could not auto assign a role!**\n" + e1.getErrorMessage()); return; } StringBuilder message = new StringBuilder(); message.append("**Hello!\nI am here to tell you that I could not give the role ``"); message.append(role.getName()).append("`` to one of your new users!\n"); message.append("Please move one of the following roles above ``").append(role.getName()) .append("`` in your server's role tab!\n```"); for (IRole i : FlareBot.getInstance().getClient().getOurUser().getRolesForGuild(role.getGuild())) { message.append(i.getName()).append('\n'); } message.append("\n```\nSo the role can be given.**"); MessageUtils.sendPM(e.getGuild().getOwner(), message); } }); } else autoAssignRoles.remove(s); } } } @EventSubscriber public void onGuildCreate(GuildCreateEvent e) { if (bool.get()) MessageUtils.sendMessage(new EmbedBuilder() .withColor(new Color(96, 230, 144)) .withThumbnail(e.getGuild().getIconURL()) .withFooterIcon(e.getGuild().getIconURL()) .withFooterText(OffsetDateTime.now() .format(DateTimeFormatter.RFC_1123_DATE_TIME) + " | " + e.getGuild().getID()) .withAuthorName(e.getGuild().getName()) .withAuthorIcon(e.getGuild().getIconURL()) .withDesc("Guild Created: `" + e.getGuild().getName() + "` :smile: :heart:\nGuild Owner: " + e.getGuild().getOwner().getName()) .build(), FlareBot.getInstance().getGuildLogChannel()); } @EventSubscriber public void onGuildDelete(GuildLeaveEvent e) { COMMAND_COUNTER.remove(e.getGuild().getID()); MessageUtils.sendMessage(new EmbedBuilder() .withColor(new Color(244, 23, 23)) .withThumbnail(e.getGuild().getIconURL()) .withFooterIcon(e.getGuild().getIconURL()) .withFooterText(OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) + " | " + e.getGuild().getID()) .withAuthorName(e.getGuild().getName()) .withAuthorIcon(e.getGuild().getIconURL()) .withDesc("Guild Deleted: `" + e.getGuild().getName() + "` L :broken_heart:\nGuild Owner: " + (e.getGuild().getOwner() != null ? e.getGuild().getOwner().getName() : "Non-existent, they had to much L")) .build(), FlareBot.getInstance().getGuildLogChannel()); } @EventSubscriber public void onVoice(UserVoiceChannelLeaveEvent e) { if (e.getChannel().getConnectedUsers().contains(e.getClient().getOurUser()) && e.getChannel().getConnectedUsers().size() < 2) { FlareBot.getInstance().getMusicManager().getPlayer(e.getChannel().getGuild().getID()).setPaused(true); e.getChannel().leave(); } } @EventSubscriber public void onMessage(MessageReceivedEvent e) { if (e.getMessage().getContent() != null && e.getMessage().getContent().startsWith(String.valueOf(FlareBot.getPrefixes().get(getGuildId(e)))) && !e.getMessage().getAuthor().isBot()) { bool.set(true); EnumSet<Permissions> perms = e.getMessage().getChannel() .getModifiedPermissions(FlareBot.getInstance().getClient().getOurUser()); if (!perms.contains(Permissions.ADMINISTRATOR)) { if (!perms.contains(Permissions.SEND_MESSAGES)) { return; } if (!perms.contains(Permissions.EMBED_LINKS)) { MessageUtils.sendMessage(e.getMessage().getChannel(), "Hey! I can't be used here." + "\nI do not have the `Embed Links` permission! Please go to your permissions and give me Embed Links." + "\nThanks :D"); return; } } String message = e.getMessage().getContent(); String command = message.substring(1); String[] args = new String[0]; if (message.contains(" ")) { command = command.substring(0, message.indexOf(" ") - 1); args = message.substring(message.indexOf(" ") + 1).split(" "); } for (Command cmd : flareBot.getCommands()) { if (cmd.getCommand().equalsIgnoreCase(command)) { if(cmd.getType() == CommandType.HIDDEN){ if (!cmd.getPermissions(e.getMessage().getChannel()).isCreator(e.getMessage().getAuthor())) { return; } } if (!cmd.getType().usableInDMs()) { if (e.getMessage().getChannel().isPrivate()) { MessageUtils.sendMessage(e.getMessage().getChannel(), String.format("**%s commands cannot be used in DM's!**", cmd.getType().formattedName())); return; } } if (cmd.getPermission() != null && cmd.getPermission().length() > 0) { if (!cmd.getPermissions(e.getMessage().getChannel()).hasPermission(e.getMessage().getAuthor(), cmd.getPermission())) { MessageUtils.sendMessage(e.getMessage().getChannel(), "You are missing the permission ``" + cmd.getPermission() + "`` which is required for use of this command!"); return; } } try { if (!e.getMessage().getChannel().isPrivate()) COMMAND_COUNTER.computeIfAbsent(e.getMessage().getChannel().getGuild().getID(), g -> new AtomicInteger()).incrementAndGet(); String[] finalArgs = args; CACHED_POOL.submit(() ->{ cmd.onCommand(e.getMessage().getAuthor(), e.getMessage().getChannel(), e.getMessage(), finalArgs); FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(finalArgs) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); delete(e); }); } catch (Exception ex) { MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, e.getMessage().getChannel()); FlareBot.LOGGER.error("Exception in guild " + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator(), ex); } return; } else { for (String alias : cmd.getAliases()) { if (alias.equalsIgnoreCase(command)) { if(cmd.getType() == CommandType.HIDDEN){ if (!cmd.getPermissions(e.getMessage().getChannel()).isCreator(e.getMessage().getAuthor())) { return; } } FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); if (cmd.getType() == CommandType.MUSIC) { if (e.getMessage().getChannel().isPrivate()) { MessageUtils.sendMessage(e.getMessage().getChannel(), "**Music commands cannot be used in DM's!**"); return; } } if (cmd.getPermission() != null && cmd.getPermission().length() > 0) { if (!cmd.getPermissions(e.getMessage().getChannel()).hasPermission(e.getMessage().getAuthor(), cmd.getPermission())) { MessageUtils.sendMessage(e.getMessage().getChannel(), "You are missing the permission ``" + cmd.getPermission() + "`` which is required for use of this command!"); return; } } try { if (!e.getMessage().getChannel().isPrivate()) COMMAND_COUNTER.computeIfAbsent(e.getMessage().getChannel().getGuild().getID(), g -> new AtomicInteger()).incrementAndGet(); String[] finalArgs = args; CACHED_POOL.submit(() ->{ cmd.onCommand(e.getMessage().getAuthor(), e.getMessage().getChannel(), e.getMessage(), finalArgs); FlareBot.LOGGER.info( "Dispatching command '" + cmd.getCommand() + "' " + Arrays.toString(finalArgs) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator()); // delete(e); }); } catch (Exception ex) { FlareBot.LOGGER.error("Exception in guild " + "!\n" + '\'' + cmd.getCommand() + "' " + Arrays.toString(args) + " in " + e.getMessage().getChannel() + "! Sender: " + e.getMessage().getAuthor().getName() + '#' + e.getMessage().getAuthor().getDiscriminator(), ex); MessageUtils.sendException("**There was an internal error trying to execute your command**", ex, e.getMessage().getChannel()); } return; } } } } } } private void delete(MessageReceivedEvent e) { RequestBuffer.request(() -> { try { e.getMessage().delete(); } catch (DiscordException | MissingPermissionsException ignored) { } }); } private String getGuildId(MessageReceivedEvent e) { return e.getMessage().getChannel().getGuild() != null ? e.getMessage().getChannel().getGuild().getID() : null; } }
Disable message delete
src/main/java/com/bwfcwalshy/flarebot/Events.java
Disable message delete
Java
mit
1d76e5b2a31b51980a66ee26b62a47ebad2f34be
0
VijayKrishna/bookworm
package self.vpalepu.bookworm; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * BookWorm! * */ public class BookWorm { public static void main( String[] args ) { try { final String targetUrl = stripTrailingSlash(getArgument("worm.page")); Document doc = Jsoup.connect(targetUrl).get(); Elements links = doc.getElementsByTag("a"); final String extensionRegEx = getArgument("worm.extn"); ArrayList<String> fullHrefs = new ArrayList<>(); for(Element link : links) { final String href = link.attr("href"); if(href == null || href.isEmpty()) { continue; } final String fullHref = expandHref(targetUrl, href); if(shouldDownload(fullHref, extensionRegEx)) { fullHrefs.add(fullHref); } } int count = 1; final int linkCount = fullHrefs.size(); final String downloadStore = createDownloadStore(getArgument("worm.downloads")); for(String fullHref : fullHrefs) { downloadFile(fullHref, downloadStore, count, linkCount); count += 1; } } catch (IOException e) { e.printStackTrace(); } } /** * @param targetUrl * @param href * @return */ public static String expandHref(final String targetUrl, final String href) { String fullHref; if(!href.startsWith(targetUrl)) { if(href.startsWith("/") || href.startsWith("#")) { fullHref = targetUrl + href; } else { fullHref = targetUrl + '/' + href; } } else { fullHref = href; } return fullHref; } public static String getArgument(final String argName) { final String argValue = System.getProperty(argName); if(argValue == null) { System.err.println("Provide the following argument: -D" + argName); System.exit(1); } return argValue; } public static String createDownloadStore(final String downloadStoreName) { File downloadStore = new File(downloadStoreName); if(!downloadStore.exists()) { downloadStore.mkdirs(); } if(!downloadStore.exists() || !downloadStore.isDirectory()) { return null; } return stripTrailingSlash(downloadStoreName); } public static boolean shouldDownload(final String urlString, final String extension) { if(urlString == null || !urlString.matches(extension)) { return false; } return true; } public static void downloadFile(final String urlString, final String downloadStoreName, final int ith, final int total) { final String countStatus = ith + "/" + total; String[] split = urlString.split("/"); String fileName = split[split.length - 1]; try { URL url = new URL(urlString); InputStream in = url.openStream(); Files.copy(in, Paths.get(downloadStoreName + "/" + fileName), StandardCopyOption.REPLACE_EXISTING); in.close(); System.out.println(countStatus + "... Downloaded: " + urlString); } catch (IOException e) { System.out.println(countStatus + "!!! Error while downloading: " + urlString); e.printStackTrace(); } } public static String stripTrailingSlash(final String in) { if(in.endsWith("/")) { return in.substring(0, in.length() - 1); } return in; } }
src/main/java/self/vpalepu/bookworm/BookWorm.java
package self.vpalepu.bookworm; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * BookWorm! * */ public class BookWorm { public static void main( String[] args ) { final String targetUrl = stripTrailingSlash(getArgument("worm.page")); final String downloadStore = getArgument("worm.downloads"); final String extensionRegEx = getArgument("worm.extn"); try { Document doc = Jsoup.connect(targetUrl).get(); Elements links = doc.getElementsByTag("a"); final int linkCount = links.size(); int count = 1; for(Element link : links) { final String href = link.attr("href"); String fullHref; if(!href.startsWith(targetUrl)) { if(href.startsWith("/") || href.startsWith("#")) { fullHref = targetUrl + href; } else { fullHref = targetUrl + '/' + href; } } else { fullHref = href; } downloadFile(fullHref, createDownloadStore(downloadStore), extensionRegEx, count, linkCount); count += 1; } } catch (IOException e) { e.printStackTrace(); } } public static String getArgument(final String argName) { final String argValue = System.getProperty(argName); if(argValue == null) { System.err.println("Provide the following argument: -D" + argName); System.exit(1); } return argValue; } public static String createDownloadStore(final String downloadStoreName) { File downloadStore = new File(downloadStoreName); if(!downloadStore.exists()) { downloadStore.mkdirs(); } if(!downloadStore.exists() || !downloadStore.isDirectory()) { return null; } return stripTrailingSlash(downloadStoreName); } public static void downloadFile(final String urlString, final String downloadStoreName, final String extension, final int ith, final int total) { final String countStatus = ith + "/" + total; if(urlString == null || !urlString.matches(extension)) { System.out.println(countStatus + "!!! Skipping dowload: " + urlString); return; } String[] split = urlString.split("/"); String fileName = split[split.length - 1]; try { URL url = new URL(urlString); InputStream in = url.openStream(); Files.copy(in, Paths.get(downloadStoreName + "/" + fileName), StandardCopyOption.REPLACE_EXISTING); in.close(); System.out.println(countStatus + "... Downloaded: " + urlString); } catch (IOException e) { System.out.println(countStatus + "!!! Error while downloading: " + urlString); e.printStackTrace(); } } public static String stripTrailingSlash(final String in) { if(in.endsWith("/")) { return in.substring(0, in.length() - 1); } return in; } }
Displaying status for only donwloadable files.
src/main/java/self/vpalepu/bookworm/BookWorm.java
Displaying status for only donwloadable files.
Java
agpl-3.0
462cf4ebfc775dc974209d8af88762556770d01c
0
shunwang/sql-layer-1,ngaut/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.server.types.common.funcs; import com.foundationdb.server.types.LazyList; import com.foundationdb.server.types.TClass; import com.foundationdb.server.types.TCustomOverloadResult; import com.foundationdb.server.types.TExecutionContext; import com.foundationdb.server.types.TInstance; import com.foundationdb.server.types.TScalar; import com.foundationdb.server.types.TOverloadResult; import com.foundationdb.server.types.TPreptimeContext; import com.foundationdb.server.types.TPreptimeValue; import com.foundationdb.server.types.common.types.StringAttribute; import com.foundationdb.server.types.value.ValueSource; import com.foundationdb.server.types.value.ValueTarget; import com.foundationdb.server.types.texpressions.TInputSetBuilder; import com.foundationdb.server.types.texpressions.TScalarBase; import java.util.List; public abstract class Substring extends TScalarBase { public static TScalar[] create(TClass strType, TClass intType) { return new TScalar[] { new Substring(strType, intType, new int[] {1}) // 2 args: SUBSTR(<STRING>, <OFFSET>) { @Override protected Integer getLength(LazyList<? extends ValueSource> inputs) { return null; } }, new Substring(strType, intType, new int[] {1, 2}) // 3 args: SUBSTR(<STRING>, <OFFSET>, <LENGTH>) { @Override protected Integer getLength(LazyList<? extends ValueSource> inputs) { return inputs.get(2).getInt32(); } }, }; } protected abstract Integer getLength (LazyList<? extends ValueSource> inputs); private final TClass strType; private final TClass intType; private final int covering[]; private Substring(TClass strType, TClass intType, int covering[]) { this.strType = strType; this.intType = intType; this.covering = covering; } @Override protected void buildInputSets(TInputSetBuilder builder) { builder.covers(strType, 0).covers(intType, covering); } @Override protected void doEvaluate(TExecutionContext context, LazyList<? extends ValueSource> inputs, ValueTarget output) { output.putString(getSubstr(inputs.get(0).getString(), inputs.get(1).getInt32(), getLength(inputs)), null); } @Override public String displayName() { return "SUBSTRING"; } @Override public String[] registeredNames() { return new String[] {"SUBSTRING", "SUBSTR"}; } @Override public TOverloadResult resultType() { return TOverloadResult.custom(new TCustomOverloadResult() { @Override public TInstance resultInstance(List<TPreptimeValue> inputs, TPreptimeContext context) { int strLength = inputs.get(0).type().attribute(StringAttribute.MAX_LENGTH); // SUBSTR (<STRING> , <OFFSET>[, <LENGTH>] // check if <LENGTH> is available int length = strLength; ValueSource lenArg; if (inputs.size() == 3 && (lenArg = inputs.get(2).value()) != null && !lenArg.isNull()) length = lenArg.getInt32(); return strType.instance(length > strLength ? strLength : length, anyContaminatingNulls(inputs)); } }); } private static String getSubstr(String st, int from, Integer length) { // if str is empty or <from> and <length> is outside of reasonable index // // Note negative index is acceptable for <from>, but its absolute value has // to be within [1, str.length] (mysql index starts at 1) if (st.isEmpty() || from == 0 || (length != null && length <= 0)) return ""; try { if (from < 0) from = st.offsetByCodePoints(st.length(), from); else from = st.offsetByCodePoints(0, from - 1); } catch (IndexOutOfBoundsException ex) { return ""; } if (length == null) return st.substring(from); int to; try { to = st.offsetByCodePoints(from, length); } catch (IndexOutOfBoundsException ex) { to = st.length(); } return st.substring(from, to); } }
src/main/java/com/foundationdb/server/types/common/funcs/Substring.java
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.server.types.common.funcs; import com.foundationdb.server.types.LazyList; import com.foundationdb.server.types.TClass; import com.foundationdb.server.types.TCustomOverloadResult; import com.foundationdb.server.types.TExecutionContext; import com.foundationdb.server.types.TInstance; import com.foundationdb.server.types.TScalar; import com.foundationdb.server.types.TOverloadResult; import com.foundationdb.server.types.TPreptimeContext; import com.foundationdb.server.types.TPreptimeValue; import com.foundationdb.server.types.common.types.StringAttribute; import com.foundationdb.server.types.mcompat.mtypes.MString; import com.foundationdb.server.types.value.ValueSource; import com.foundationdb.server.types.value.ValueTarget; import com.foundationdb.server.types.texpressions.TInputSetBuilder; import com.foundationdb.server.types.texpressions.TScalarBase; import java.util.List; public abstract class Substring extends TScalarBase { public static TScalar[] create(TClass strType, TClass intType) { return new TScalar[] { new Substring(strType, intType, new int[] {1}) // 2 args: SUBSTR(<STRING>, <OFFSET>) { @Override protected Integer getLength(LazyList<? extends ValueSource> inputs) { return null; } }, new Substring(strType, intType, new int[] {1, 2}) // 3 args: SUBSTR(<STRING>, <OFFSET>, <LENGTH>) { @Override protected Integer getLength(LazyList<? extends ValueSource> inputs) { return inputs.get(2).getInt32(); } }, }; } protected abstract Integer getLength (LazyList<? extends ValueSource> inputs); private final TClass strType; private final TClass intType; private final int covering[]; private Substring(TClass strType, TClass intType, int covering[]) { this.strType = strType; this.intType = intType; this.covering = covering; } @Override protected void buildInputSets(TInputSetBuilder builder) { builder.covers(strType, 0).covers(intType, covering); } @Override protected void doEvaluate(TExecutionContext context, LazyList<? extends ValueSource> inputs, ValueTarget output) { output.putString(getSubstr(inputs.get(0).getString(), inputs.get(1).getInt32(), getLength(inputs)), null); } @Override public String displayName() { return "SUBSTRING"; } @Override public String[] registeredNames() { return new String[] {"SUBSTRING", "SUBSTR"}; } @Override public TOverloadResult resultType() { return TOverloadResult.custom(new TCustomOverloadResult() { @Override public TInstance resultInstance(List<TPreptimeValue> inputs, TPreptimeContext context) { int strLength = inputs.get(0).type().attribute(StringAttribute.MAX_LENGTH); // SUBSTR (<STRING> , <OFFSET>[, <LENGTH>] // check if <LENGTH> is available int length = strLength; ValueSource lenArg; if (inputs.size() == 3 && (lenArg = inputs.get(2).value()) != null && !lenArg.isNull()) length = lenArg.getInt32(); return MString.VARCHAR.instance(length > strLength ? strLength : length, anyContaminatingNulls(inputs)); } }); } private static String getSubstr(String st, int from, Integer length) { // if str is empty or <from> and <length> is outside of reasonable index // // Note negative index is acceptable for <from>, but its absolute value has // to be within [1, str.length] (mysql index starts at 1) if (st.isEmpty() || from == 0 || (length != null && length <= 0)) return ""; try { if (from < 0) from = st.offsetByCodePoints(st.length(), from); else from = st.offsetByCodePoints(0, from - 1); } catch (IndexOutOfBoundsException ex) { return ""; } if (length == null) return st.substring(from); int to; try { to = st.offsetByCodePoints(from, length); } catch (IndexOutOfBoundsException ex) { to = st.length(); } return st.substring(from, to); } }
Substring.
src/main/java/com/foundationdb/server/types/common/funcs/Substring.java
Substring.
Java
lgpl-2.1
b8e7f6ae07bea88a7e0e55118ba44dc3cf2d0660
0
xtremexp/UT4Converter
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.xtx.ut4converter.t3d; import javax.vecmath.Vector3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.UTGames; import org.xtx.ut4converter.tools.Geometry; /** * Base class for teleporters * * @author XtremeXp */ public class T3DTeleporter extends T3DSound { /** * Unreal 1 property refering to */ String url; public T3DTeleporter(MapConverter mc, String t3dClass) { super(mc, t3dClass); } @Override public boolean analyseT3DData(String line) { // UE1 -> "URL="hepburn2" if (line.contains("URL=")) { url = line.split("\\=")[1]; } else { return super.analyseT3DData(line); } return true; } @Override public String toString() { // only write if we have data about linked teleporter if (mapConverter.getOutputGame() == UTGames.UTGame.UT4) { sbf.append(IDT).append("Begin Actor Class=BP_Teleporter_New_C Name=").append(name).append("\n"); sbf.append(IDT).append("\tBegin Object Name=\"TriggerBox\"\n"); // to reset rotation of teleporter else teleporter destination // invalid is rotation set // TODO maybe make rotation the translation vector instead of doing // this this.rotation = null; writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tTriggerBox=TriggerBox\n"); if (linkedTo != null && !linkedTo.isEmpty()) { // Note UT4 only support teleporting to one possible location // unlike U1/UT99/? do support multiple destinations T3DTeleporter linkedTel = (T3DTeleporter) linkedTo.get(0); Vector3d t = Geometry.sub(linkedTel.location, this.location); linkedTel.rotation = null; sbf.append(IDT).append("\tTeleportTarget=(Translation=(X=").append(t.x).append(",Y=").append(t.y).append(",Z=").append(t.z).append("))\n"); sbf.append(IDT).append("\tRootComponent=TriggerBox\n"); writeEndActor(); linkedTo.clear(); // needs to remove linked teleporter or else loop // on writting linked teleporter return sbf.toString() + linkedTel.toString(); } else { sbf.append(IDT).append("\tRootComponent=TriggerBox\n"); writeEndActor(); return sbf.toString(); } } else { return ""; } } @Override public void convert() { // we need to retrieve the linked teleporters // at this stage the T3D level converter // may not have yet parsed data of destination teleporter if (linkedTo == null || linkedTo.isEmpty()) { T3DLevelConvertor tlc = mapConverter.getT3dLvlConvertor(); for (T3DActor actor : tlc.convertedActors) { if (actor instanceof T3DTeleporter) { if (actor.tag != null && this.url != null && this.url.equals("\"" + actor.tag + "\"")) { this.linkedTo.add(actor); actor.linkedTo.add(this); break; } } } } super.convert(); } }
src/main/java/org/xtx/ut4converter/t3d/T3DTeleporter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.xtx.ut4converter.t3d; import javax.vecmath.Vector3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.UTGames; import org.xtx.ut4converter.tools.Geometry; /** * Base class for teleporters * * @author XtremeXp */ public class T3DTeleporter extends T3DSound { /** * Unreal 1 property refering to */ String url; public T3DTeleporter(MapConverter mc, String t3dClass) { super(mc, t3dClass); } @Override public boolean analyseT3DData(String line) { // UE1 -> "URL="hepburn2" if (line.contains("URL=")) { url = line.split("\\=")[1]; } else { return super.analyseT3DData(line); } return true; } @Override public String toString() { // only write if we have data about linked teleporter if (mapConverter.getOutputGame() == UTGames.UTGame.UT4 && linkedTo != null && !linkedTo.isEmpty()) { sbf.append(IDT).append("Begin Actor Class=BP_Teleporter_New_C Name=").append(name).append("\n"); sbf.append(IDT).append("\tBegin Object Name=\"TriggerBox\"\n"); // to reset rotation of teleporter else teleporter destination // invalid is rotation set // TODO maybe make rotation the translation vector instead of doing // this this.rotation = null; writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tTriggerBox=TriggerBox\n"); // Note UT4 only support teleporting to one possible location // unlike U1/UT99/? do support multiple destinations T3DTeleporter linkedTel = (T3DTeleporter) linkedTo.get(0); Vector3d t = Geometry.sub(linkedTel.location, this.location); linkedTel.rotation = null; sbf.append(IDT).append("\tTeleportTarget=(Translation=(X=").append(t.x).append(",Y=").append(t.y).append(",Z=").append(t.z).append("))\n"); sbf.append(IDT).append("\tRootComponent=TriggerBox\n"); writeEndActor(); linkedTo.clear(); // needs to remove linked teleporter or else loop // on writting linked teleporter return sbf.toString() + linkedTel.toString(); } else { return ""; } } @Override public void convert() { // we need to retrieve the linked teleporters // at this stage the T3D level converter // may not have yet parsed data of destination teleporter if (linkedTo == null || linkedTo.isEmpty()) { T3DLevelConvertor tlc = mapConverter.getT3dLvlConvertor(); for (T3DActor actor : tlc.convertedActors) { if (actor instanceof T3DTeleporter) { if (actor.tag != null && this.url != null && this.url.equals("\"" + actor.tag + "\"")) { this.linkedTo.add(actor); actor.linkedTo.add(this); break; } } } } super.convert(); } }
write teleporter even if no linked teleporter found
src/main/java/org/xtx/ut4converter/t3d/T3DTeleporter.java
write teleporter even if no linked teleporter found
Java
lgpl-2.1
ea05382aa97eae01755fca009ca8b530154d88ef
0
threerings/nenya,threerings/nenya
// // $Id: BundledComponentRepositoryTest.java 3720 2005-10-05 01:39:45Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast.bundle; import java.awt.Component; import java.util.Iterator; import com.threerings.cast.ComponentClass; import com.threerings.media.image.ClientImageManager; import com.threerings.resource.ResourceManager; import junit.framework.Test; import junit.framework.TestCase; public class BundledComponentRepositoryTest extends TestCase { public BundledComponentRepositoryTest () { super(BundledComponentRepositoryTest.class.getName()); } @Override public void runTest () { try { ResourceManager rmgr = new ResourceManager("rsrc"); rmgr.initBundles( null, "config/resource/manager.properties", null); ClientImageManager imgr = new ClientImageManager(rmgr, (Component)null); BundledComponentRepository repo = new BundledComponentRepository(rmgr, imgr, "components"); // System.out.println("Classes: " + StringUtil.toString( // repo.enumerateComponentClasses())); // System.out.println("Actions: " + StringUtil.toString( // repo.enumerateActionSequences())); // System.out.println("Action sets: " + StringUtil.toString( // repo._actionSets.values().iterator())); Iterator iter = repo.enumerateComponentClasses(); while (iter.hasNext()) { // ComponentClass cclass = (ComponentClass) iter.next(); // System.out.println("IDs [" + cclass + "]: " + // StringUtil.toString( // repo.enumerateComponentIds(cclass))); } } catch (Exception e) { e.printStackTrace(); fail(); } } public static void main (String[] args) { BundledComponentRepositoryTest test = new BundledComponentRepositoryTest(); test.runTest(); } public static Test suite () { return new BundledComponentRepositoryTest(); } }
tests/src/java/com/threerings/cast/bundle/BundledComponentRepositoryTest.java
// // $Id: BundledComponentRepositoryTest.java 3720 2005-10-05 01:39:45Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast.bundle; import java.awt.Component; import java.util.Iterator; import com.threerings.cast.ComponentClass; import com.threerings.media.image.ClientImageManager; import com.threerings.resource.ResourceManager; import junit.framework.Test; import junit.framework.TestCase; public class BundledComponentRepositoryTest extends TestCase { public BundledComponentRepositoryTest () { super(BundledComponentRepositoryTest.class.getName()); } @Override public void runTest () { try { ResourceManager rmgr = new ResourceManager("rsrc"); rmgr.initBundles( null, "config/resource/manager.properties", null); ClientImageManager imgr = new ClientImageManager(rmgr, (Component)null); BundledComponentRepository repo = new BundledComponentRepository(rmgr, imgr, "components"); // System.out.println("Classes: " + StringUtil.toString( // repo.enumerateComponentClasses())); // System.out.println("Actions: " + StringUtil.toString( // repo.enumerateActionSequences())); // System.out.println("Action sets: " + StringUtil.toString( // repo._actionSets.values().iterator())); Iterator iter = repo.enumerateComponentClasses(); while (iter.hasNext()) { ComponentClass cclass = (ComponentClass)iter.next(); // System.out.println("IDs [" + cclass + "]: " + // StringUtil.toString( // repo.enumerateComponentIds(cclass))); } } catch (Exception e) { e.printStackTrace(); fail(); } } public static void main (String[] args) { BundledComponentRepositoryTest test = new BundledComponentRepositoryTest(); test.runTest(); } public static Test suite () { return new BundledComponentRepositoryTest(); } }
Local variable never read. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@581 ed5b42cb-e716-0410-a449-f6a68f950b19
tests/src/java/com/threerings/cast/bundle/BundledComponentRepositoryTest.java
Local variable never read.
Java
apache-2.0
a41bb778c295fdea3df1e86f4ac37662932d7891
0
TridentSDK/TridentSDK,TridentSDK/TridentSDK,TridentSDK/TridentSDK
/* * Trident - A Multithreaded Server Alternative * Copyright 2016 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.entity.meta.living.golem; import net.tridentsdk.base.BlockDirection; import net.tridentsdk.base.Vector; /** * @author TridentSDK * @since 0.5-alpha */ // TODO - documentation public interface ShulkerMeta { BlockDirection getFacingDirection(); void setFacingDirection(BlockDirection direction); Vector getAttachmentPosition(); void setAttachmentPosition(Vector position); byte getShieldHeight(); void setShieldHeight(byte height); }
src/main/java/net/tridentsdk/entity/meta/living/golem/ShulkerMeta.java
/* * Trident - A Multithreaded Server Alternative * Copyright 2016 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.entity.meta.living.golem; import net.tridentsdk.base.Direction; import net.tridentsdk.base.Vector; /** * @author TridentSDK * @since 0.5-alpha */ // TODO - documentation public interface ShulkerMeta { Direction getFacingDirection(); void setFacingDirection(Direction direction); Vector getAttachmentPosition(); void setAttachmentPosition(Vector position); byte getShieldHeight(); void setShieldHeight(byte height); }
Log version during startup Get rid of Direction use in ShulkerMeta
src/main/java/net/tridentsdk/entity/meta/living/golem/ShulkerMeta.java
Log version during startup Get rid of Direction use in ShulkerMeta
Java
apache-2.0
7c71c515ef1ee92debe740d42a29fd27eea8681c
0
BlurEngine/Blur,BlurEngine/Blur
/* * Copyright 2016 Ali Moghnieh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blurengine.blur; import com.blurengine.blur.events.players.PlayerDamagePlayerEvent; import com.blurengine.blur.events.players.PlayerMoveBlockEvent; import com.blurengine.blur.session.BlurPlayer; import com.supaham.commons.bukkit.utils.EventUtils; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerMoveEvent; /* * All events extend LOW to call Blur events at an early enough point in time that other code will be able to cancel these Bukkit events if necessary. */ class BlurListener implements Listener { private final BlurPlugin plugin; public BlurListener(BlurPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void callPlayerMoveBlockEvent(PlayerMoveEvent event) { Location from = event.getFrom(); Location to = event.getTo(); if (!from.toVector().equals(to.toVector())) { BlurPlayer blurPlayer = plugin.getBlur().getPlayer(event.getPlayer()); if (blurPlayer.getSession() != null) { EventUtils.callEvent(new PlayerMoveBlockEvent(event, blurPlayer)); } } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void callPlayerDamagePlayerEvent(EntityDamageByEntityEvent event) { LivingEntity damager = EventUtils.getLivingEntityDamager(event); if (event.getEntity() instanceof Player && damager instanceof Player) { BlurPlayer blurDamager = plugin.getBlur().getPlayer((Player) damager); BlurPlayer blurVictim = plugin.getBlur().getPlayer((Player) event.getEntity()); PlayerDamagePlayerEvent damageEvent = new PlayerDamagePlayerEvent(blurDamager, blurVictim, event); blurDamager.getSession().callEvent(damageEvent); if (damageEvent.isCancelled()) { event.setCancelled(true); } } } }
src/main/java/com/blurengine/blur/BlurListener.java
/* * Copyright 2016 Ali Moghnieh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blurengine.blur; import com.blurengine.blur.events.players.PlayerDamagePlayerEvent; import com.blurengine.blur.events.players.PlayerMoveBlockEvent; import com.blurengine.blur.session.BlurPlayer; import com.supaham.commons.bukkit.utils.EventUtils; import com.supaham.commons.bukkit.utils.LocationUtils; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerMoveEvent; /* * All events extend LOW to call Blur events at an early enough point in time that other code will be able to cancel these Bukkit events if necessary. */ class BlurListener implements Listener { private final BlurPlugin plugin; public BlurListener(BlurPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void callPlayerMoveBlockEvent(PlayerMoveEvent event) { if (!LocationUtils.isSameBlock(event.getFrom(), event.getTo())) { BlurPlayer blurPlayer = plugin.getBlur().getPlayer(event.getPlayer()); if (blurPlayer.getSession() != null) { EventUtils.callEvent(new PlayerMoveBlockEvent(event, blurPlayer)); } } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void callPlayerDamagePlayerEvent(EntityDamageByEntityEvent event) { LivingEntity damager = EventUtils.getLivingEntityDamager(event); if (event.getEntity() instanceof Player && damager instanceof Player) { BlurPlayer blurDamager = plugin.getBlur().getPlayer((Player) damager); BlurPlayer blurVictim = plugin.getBlur().getPlayer((Player) event.getEntity()); PlayerDamagePlayerEvent damageEvent = new PlayerDamagePlayerEvent(blurDamager, blurVictim, event); blurDamager.getSession().callEvent(damageEvent); if (damageEvent.isCancelled()) { event.setCancelled(true); } } } }
Make PlayerMoveBlockEvent fire more often. Change to compare double coordinates rather than integer.
src/main/java/com/blurengine/blur/BlurListener.java
Make PlayerMoveBlockEvent fire more often.
Java
apache-2.0
3fe17bb2f41d1b4c8beb6123c15bfc1545d1e92a
0
robymus/tinylog,yarish/tinylog,yarish/tinylog,robymus/tinylog
/* * Copyright 2012 Martin Winandy * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.pmw.tinylog; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Properties; import mockit.Mock; import mockit.MockUp; import org.junit.Test; import org.pmw.tinylog.labellers.CountLabeller; import org.pmw.tinylog.labellers.Labeller; import org.pmw.tinylog.labellers.TimestampLabeller; import org.pmw.tinylog.policies.DailyPolicy; import org.pmw.tinylog.policies.Policy; import org.pmw.tinylog.policies.SizePolicy; import org.pmw.tinylog.policies.StartupPolicy; import org.pmw.tinylog.util.FileHelper; import org.pmw.tinylog.util.PropertiesBuilder; import org.pmw.tinylog.writers.ConsoleWriter; import org.pmw.tinylog.writers.FileWriter; import org.pmw.tinylog.writers.RollingFileWriter; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Test properties loader. * * @see PropertiesLoader */ public class PropertiesLoaderTest extends AbstractTest { /** * Test reading logging level. */ @Test public final void testLevel() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.level", "TRACE")); assertEquals(LoggingLevel.TRACE, configuration.getLevel()); configuration = load(new PropertiesBuilder().set("tinylog.level", "error")); assertEquals(LoggingLevel.ERROR, configuration.getLevel()); configuration = load(new PropertiesBuilder().set("tinylog.level", "invalid")); assertEquals(LoggingLevel.INFO, configuration.getLevel()); } /** * Test reading special logging levels for packages. */ @Test public final void testPackageLevels() { PropertiesBuilder builder = new PropertiesBuilder().set("tinylog.level", "INFO"); Configuration configuration = load(builder.set("tinylog.level:a.b", "WARNING")); assertEquals(LoggingLevel.WARNING, configuration.getLevelOfPackage("a.b")); configuration = load(builder.set("tinylog.level:a.b.c", "TRACE")); assertEquals(LoggingLevel.TRACE, configuration.getLevelOfPackage("a.b.c")); configuration = load(builder.set("tinylog.level:org.pmw.tinylog", "ERROR")); assertEquals(LoggingLevel.ERROR, configuration.getLevelOfPackage("org.pmw.tinylog")); configuration = load(builder.set("tinylog.level:org.pmw.tinylog", "invalid")); assertEquals(LoggingLevel.INFO, configuration.getLevelOfPackage("org.pmw.tinylog")); } /** * Test reading logging format. */ @Test public final void testFormat() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.format", "My log entry: {message}")); assertEquals("My log entry: {message}", configuration.getFormatPattern()); } /** * Test reading locale for message format. */ @Test public final void testLocale() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.locale", "de")); assertEquals(Locale.GERMAN, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "de_DE")); assertEquals(Locale.GERMANY, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en")); assertEquals(Locale.ENGLISH, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_GB")); assertEquals(Locale.UK, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_US")); assertEquals(Locale.US, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_US_WIN")); assertEquals(new Locale("en", "US", "WIN"), configuration.getLocale()); } /** * Test reading stack trace limitation. */ @Test public final void testStackTrace() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "0")); assertEquals(0, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "1")); assertEquals(1, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "42")); assertEquals(42, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "-1")); assertEquals(Integer.MAX_VALUE, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "invalid")); int defaultValue = Configurator.defaultConfig().create().getMaxStackTraceElements(); assertEquals(defaultValue, configuration.getMaxStackTraceElements()); } /** * Test reading <code>null</code> as logging writer (no logging writer). */ @Test public final void testNullLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "null")); assertNull(configuration.getWriter()); } /** * Test reading console logging writer. */ @Test public final void testConsoleLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "console")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); } /** * Test reading file logging writer. * * @throws IOException * Test failed */ @Test public final void testFileLoggingWriter() throws IOException { new FileWriter(FileHelper.createTemporaryFile("log").getAbsolutePath()); File file = FileHelper.createTemporaryFile("log"); FileWriterMock fileWriterMock = new FileWriterMock(); Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "file")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "file").set("tinylog.writer.filename", file.getAbsolutePath())); assertNotNull(configuration.getWriter()); assertEquals(FileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), fileWriterMock.filename); file.delete(); } /** * Test reading rolling file logging writer. * * @throws IOException * Test failed */ @Test public final void testRollingFileLoggingWriter() throws IOException { File file = FileHelper.createTemporaryFile("log"); RollingFileWriterMock rollingFileWriterMock = new RollingFileWriterMock(); Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath())); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "1")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(1, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(CountLabeller.class, rollingFileWriterMock.labeller.getClass()); assertNotNull(rollingFileWriterMock.policies); assertEquals(1, rollingFileWriterMock.policies.length); assertEquals(StartupPolicy.class, rollingFileWriterMock.policies[0].getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "2").set("tinylog.writer.label", "timestamp: yyyy").set("tinylog.writer.policies", "size: 1")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(2, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(TimestampLabeller.class, rollingFileWriterMock.labeller.getClass()); assertEquals(new File("my." + new SimpleDateFormat("yyyy").format(new Date()) + ".log"), rollingFileWriterMock.labeller.getLogFile(new File("my.log"))); assertNotNull(rollingFileWriterMock.policies); assertEquals(1, rollingFileWriterMock.policies.length); assertEquals(SizePolicy.class, rollingFileWriterMock.policies[0].getClass()); assertTrue(rollingFileWriterMock.policies[0].check(null, "1")); assertFalse(rollingFileWriterMock.policies[0].check(null, "2")); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "3").set("tinylog.writer.label", "timestamp").set("tinylog.writer.policies", "startup, daily")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(3, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(TimestampLabeller.class, rollingFileWriterMock.labeller.getClass()); assertNotNull(rollingFileWriterMock.policies); assertEquals(2, rollingFileWriterMock.policies.length); assertEquals(StartupPolicy.class, rollingFileWriterMock.policies[0].getClass()); assertEquals(DailyPolicy.class, rollingFileWriterMock.policies[1].getClass()); file.delete(); } /** * Test reading an invalid logging writer. */ @Test public final void testInvalidLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "invalid")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); } /** * Test reading writing thread. */ @Test public final void testWritingThread() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true")); assertNotNull(configuration.getWritingThread()); assertEquals("main", configuration.getWritingThread().getNameOfThreadToObserve()); assertThat(configuration.getWritingThread().getPriority(), lessThan(Thread.NORM_PRIORITY)); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "false")); assertNull(configuration.getWritingThread()); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true").set("tinylog.writingthread.priority", "1")); assertNotNull(configuration.getWritingThread()); assertEquals("main", configuration.getWritingThread().getNameOfThreadToObserve()); assertEquals(1, configuration.getWritingThread().getPriority()); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true").set("tinylog.writingthread.observe", "null")); assertNotNull(configuration.getWritingThread()); assertNull(configuration.getWritingThread().getNameOfThreadToObserve()); assertThat(configuration.getWritingThread().getPriority(), lessThan(Thread.NORM_PRIORITY)); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "1").set("tinylog.writingthread.observe", "null") .set("tinylog.writingthread.priority", "1")); assertNotNull(configuration.getWritingThread()); assertNull(configuration.getWritingThread().getNameOfThreadToObserve()); assertEquals(1, configuration.getWritingThread().getPriority()); } private static Configuration load(final PropertiesBuilder propertiesBuilder) { return load(propertiesBuilder.create()); } private static Configuration load(final Properties properties) { return PropertiesLoader.readProperties(properties).create(); } private static final class FileWriterMock extends MockUp<FileWriter> { private String filename; @Mock public void $init(final String filename) { this.filename = filename; } } private static final class RollingFileWriterMock extends MockUp<RollingFileWriter> { private String filename; private int backups; private Labeller labeller; private Policy[] policies; @Mock public void $init(final String filename, final int backups, final Labeller labeller, final Policy... policies) { this.filename = filename; this.backups = backups; this.labeller = labeller; this.policies = policies; } } }
tests/src/org/pmw/tinylog/PropertiesLoaderTest.java
/* * Copyright 2012 Martin Winandy * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.pmw.tinylog; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Properties; import mockit.Mock; import mockit.MockUp; import org.junit.Test; import org.pmw.tinylog.labellers.CountLabeller; import org.pmw.tinylog.labellers.Labeller; import org.pmw.tinylog.labellers.TimestampLabeller; import org.pmw.tinylog.policies.DailyPolicy; import org.pmw.tinylog.policies.Policy; import org.pmw.tinylog.policies.SizePolicy; import org.pmw.tinylog.policies.StartupPolicy; import org.pmw.tinylog.util.FileHelper; import org.pmw.tinylog.util.PropertiesBuilder; import org.pmw.tinylog.writers.ConsoleWriter; import org.pmw.tinylog.writers.FileWriter; import org.pmw.tinylog.writers.RollingFileWriter; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * Test properties loader. * * @see PropertiesLoader */ public class PropertiesLoaderTest extends AbstractTest { /** * Test reading logging level. */ @Test public final void testLevel() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.level", "TRACE")); assertEquals(LoggingLevel.TRACE, configuration.getLevel()); configuration = load(new PropertiesBuilder().set("tinylog.level", "error")); assertEquals(LoggingLevel.ERROR, configuration.getLevel()); configuration = load(new PropertiesBuilder().set("tinylog.level", "invalid")); assertEquals(LoggingLevel.INFO, configuration.getLevel()); } /** * Test reading special logging levels for packages. */ @Test public final void testPackageLevels() { PropertiesBuilder builder = new PropertiesBuilder().set("tinylog.level", "INFO"); Configuration configuration = load(builder.set("tinylog.level:a.b", "WARNING")); assertEquals(LoggingLevel.WARNING, configuration.getLevelOfPackage("a.b")); configuration = load(builder.set("tinylog.level:a.b.c", "TRACE")); assertEquals(LoggingLevel.TRACE, configuration.getLevelOfPackage("a.b.c")); configuration = load(builder.set("tinylog.level:org.pmw.tinylog", "ERROR")); assertEquals(LoggingLevel.ERROR, configuration.getLevelOfPackage("org.pmw.tinylog")); configuration = load(builder.set("tinylog.level:org.pmw.tinylog", "invalid")); assertEquals(LoggingLevel.INFO, configuration.getLevelOfPackage("org.pmw.tinylog")); } /** * Test reading logging format. */ @Test public final void testFormat() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.format", "My log entry: {message}")); assertEquals("My log entry: {message}", configuration.getFormatPattern()); } /** * Test reading locale for message format. */ @Test public final void testLocale() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.locale", "de")); assertEquals(Locale.GERMAN, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "de_DE")); assertEquals(Locale.GERMANY, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en")); assertEquals(Locale.ENGLISH, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_GB")); assertEquals(Locale.UK, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_US")); assertEquals(Locale.US, configuration.getLocale()); configuration = load(new PropertiesBuilder().set("tinylog.locale", "en_US_WIN")); assertEquals(new Locale("en", "US", "WIN"), configuration.getLocale()); } /** * Test reading stack trace limitation. */ @Test public final void testStackTrace() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "0")); assertEquals(0, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "1")); assertEquals(1, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "42")); assertEquals(42, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "-1")); assertEquals(Integer.MAX_VALUE, configuration.getMaxStackTraceElements()); configuration = load(new PropertiesBuilder().set("tinylog.stacktrace", "invalid")); int defaultValue = Configurator.defaultConfig().create().getMaxStackTraceElements(); assertEquals(defaultValue, configuration.getMaxStackTraceElements()); } /** * Test reading <code>null</code> as logging writer (no logging writer). */ @Test public final void testNullLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "null")); assertNull(configuration.getWriter()); } /** * Test reading console logging writer. */ @Test public final void testConsoleLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "console")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); } /** * Test reading file logging writer. * * @throws IOException * Test failed */ @Test public final void testFileLoggingWriter() throws IOException { new FileWriter(FileHelper.createTemporaryFile("log").getAbsolutePath()); File file = FileHelper.createTemporaryFile("log"); FileWriterMock fileWriterMock = new FileWriterMock(); Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "file")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "file").set("tinylog.writer.filename", file.getAbsolutePath())); assertNotNull(configuration.getWriter()); assertEquals(FileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), fileWriterMock.filename); file.delete(); } /** * Test reading rolling file logging writer. * * @throws IOException * Test failed */ @Test public final void testRollingFileLoggingWriter() throws IOException { File file = FileHelper.createTemporaryFile("log"); RollingFileWriterMock rollingFileWriterMock = new RollingFileWriterMock(); Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath())); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "1")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(1, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(CountLabeller.class, rollingFileWriterMock.labeller.getClass()); assertNotNull(rollingFileWriterMock.policies); assertEquals(1, rollingFileWriterMock.policies.length); assertEquals(StartupPolicy.class, rollingFileWriterMock.policies[0].getClass()); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "2").set("tinylog.writer.label", "timestamp: yyyy").set("tinylog.writer.policies", "size: 1")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(2, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(TimestampLabeller.class, rollingFileWriterMock.labeller.getClass()); assertEquals(new File("my." + new SimpleDateFormat("yyyy").format(new Date()) + ".log"), rollingFileWriterMock.labeller.getLogFile(new File("my.log"))); assertNotNull(rollingFileWriterMock.policies); assertEquals(1, rollingFileWriterMock.policies.length); assertEquals(SizePolicy.class, rollingFileWriterMock.policies[0].getClass()); assertTrue(rollingFileWriterMock.policies[0].check(null, "1")); assertFalse(rollingFileWriterMock.policies[0].check(null, "2")); configuration = load(new PropertiesBuilder().set("tinylog.writer", "rollingfile").set("tinylog.writer.filename", file.getAbsolutePath()) .set("tinylog.writer.backups", "3").set("tinylog.writer.label", "timestamp").set("tinylog.writer.policies", "startup, daily")); assertNotNull(configuration.getWriter()); assertEquals(RollingFileWriter.class, configuration.getWriter().getClass()); assertEquals(file.getAbsolutePath(), rollingFileWriterMock.filename); assertEquals(3, rollingFileWriterMock.backups); assertNotNull(rollingFileWriterMock.labeller); assertEquals(TimestampLabeller.class, rollingFileWriterMock.labeller.getClass()); assertNotNull(rollingFileWriterMock.policies); assertEquals(2, rollingFileWriterMock.policies.length); assertEquals(StartupPolicy.class, rollingFileWriterMock.policies[0].getClass()); assertEquals(DailyPolicy.class, rollingFileWriterMock.policies[1].getClass()); file.delete(); } /** * Test reading an invalid logging writer. */ @Test public final void testInvalidLoggingWriter() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writer", "invalid")); assertNotNull(configuration.getWriter()); assertEquals(ConsoleWriter.class, configuration.getWriter().getClass()); } /** * Test reading writing thread. */ @Test public final void testWritingThread() { Configuration configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true")); assertNotNull(configuration.getWritingThread()); assertEquals("main", configuration.getWritingThread().getNameOfThreadToObserve()); assertThat(configuration.getWritingThread().getPriority(), lessThan(Thread.NORM_PRIORITY)); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "false")); assertNull(configuration.getWritingThread()); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true").set("tinylog.writingthread.priority", "1")); assertNotNull(configuration.getWritingThread()); assertEquals("main", configuration.getWritingThread().getNameOfThreadToObserve()); assertEquals(1, configuration.getWritingThread().getPriority()); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "true").set("tinylog.writingthread.observe", "null")); assertNotNull(configuration.getWritingThread()); assertNull(configuration.getWritingThread().getNameOfThreadToObserve()); assertThat(configuration.getWritingThread().getPriority(), lessThan(Thread.NORM_PRIORITY)); configuration = load(new PropertiesBuilder().set("tinylog.writingthread", "1").set("tinylog.writingthread.observe", "null") .set("tinylog.writingthread.priority", "1")); assertNotNull(configuration.getWritingThread()); assertNull(configuration.getWritingThread().getNameOfThreadToObserve()); assertEquals(1, configuration.getWritingThread().getPriority()); } private static Configuration load(final PropertiesBuilder propertiesBuilder) { return load(propertiesBuilder.create()); } private static Configuration load(final Properties properties) { return PropertiesLoader.readProperties(properties).create(); } private static final class FileWriterMock extends MockUp<FileWriter> { private String filename; @SuppressWarnings("unused") @Mock public void $init(final String filename) { this.filename = filename; } } private static final class RollingFileWriterMock extends MockUp<RollingFileWriter> { private String filename; private int backups; private Labeller labeller; private Policy[] policies; @SuppressWarnings("unused") @Mock public void $init(final String filename, final int backups, final Labeller labeller, final Policy... policies) { this.filename = filename; this.backups = backups; this.labeller = labeller; this.policies = policies; } } }
Removed unnecessary annotations
tests/src/org/pmw/tinylog/PropertiesLoaderTest.java
Removed unnecessary annotations
Java
apache-2.0
62efc2c4264c7ef551e67447b3b9c6e206dd8dd8
0
smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.base.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; import io.airlift.concurrent.MoreFutures; import org.gaul.modernizer_maven_annotations.SuppressModernizer; import org.testng.annotations.Test; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.trino.plugin.base.cache.CacheStatsAssertions.assertCacheStats; import static java.lang.String.format; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestEvictableCache { private static final int TEST_TIMEOUT_MILLIS = 10_000; @Test(timeOut = TEST_TIMEOUT_MILLIS) public void testLoad() throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith( CacheBuilder.newBuilder()); assertEquals(cache.get(42, () -> "abc"), "abc"); } @Test(timeOut = TEST_TIMEOUT_MILLIS) public void testLoadStats() throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith( CacheBuilder.newBuilder()); assertEquals(cache.stats(), new CacheStats(0, 0, 0, 0, 0, 0)); String value = assertCacheStats(cache) .misses(1) .loads(1) .calling(() -> cache.get(42, () -> "abc")); assertEquals(value, "abc"); value = assertCacheStats(cache) .hits(1) .calling(() -> cache.get(42, () -> "xyz")); assertEquals(value, "abc"); // with equal, but not the same key value = assertCacheStats(cache) .hits(1) .calling(() -> cache.get(newInteger(42), () -> "xyz")); assertEquals(value, "abc"); } @SuppressModernizer private static Integer newInteger(int value) { Integer integer = value; @SuppressWarnings({"UnnecessaryBoxing", "deprecation", "BoxedPrimitiveConstructor"}) Integer newInteger = new Integer(value); assertNotSame(integer, newInteger); return newInteger; } /** * Covers https://github.com/google/guava/issues/1881 */ @Test(timeOut = TEST_TIMEOUT_MILLIS, dataProviderClass = Invalidation.class, dataProvider = "invalidations") public void testInvalidateOngoingLoad(Invalidation invalidation) throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith(CacheBuilder.newBuilder()); Integer key = 42; CountDownLatch loadOngoing = new CountDownLatch(1); CountDownLatch invalidated = new CountDownLatch(1); CountDownLatch getReturned = new CountDownLatch(1); ExecutorService executor = newFixedThreadPool(2); try { // thread A Future<String> threadA = executor.submit(() -> { String value = cache.get(key, () -> { loadOngoing.countDown(); // 1 assertTrue(invalidated.await(10, SECONDS)); // 2 return "stale value"; }); getReturned.countDown(); // 3 return value; }); // thread B Future<String> threadB = executor.submit(() -> { assertTrue(loadOngoing.await(10, SECONDS)); // 1 switch (invalidation) { case INVALIDATE_KEY: cache.invalidate(key); break; case INVALIDATE_PREDEFINED_KEYS: cache.invalidateAll(List.of(key)); break; case INVALIDATE_SELECTED_KEYS: Set<Integer> keys = cache.asMap().keySet().stream() .filter(foundKey -> (int) foundKey == key) .collect(toImmutableSet()); cache.invalidateAll(keys); break; case INVALIDATE_ALL: cache.invalidateAll(); break; } invalidated.countDown(); // 2 // Cache may persist value after loader returned, but before `cache.get(...)` returned. Ensure the latter completed. assertTrue(getReturned.await(10, SECONDS)); // 3 return cache.get(key, () -> "fresh value"); }); assertEquals(threadA.get(), "stale value"); assertEquals(threadB.get(), "fresh value"); } finally { executor.shutdownNow(); executor.awaitTermination(10, SECONDS); } } /** * Covers https://github.com/google/guava/issues/1881 */ @Test(invocationCount = 10, timeOut = TEST_TIMEOUT_MILLIS, dataProviderClass = Invalidation.class, dataProvider = "invalidations") public void testInvalidateAndLoadConcurrently(Invalidation invalidation) throws Exception { int[] primes = {2, 3, 5, 7}; AtomicLong remoteState = new AtomicLong(1); Cache<Integer, Long> cache = EvictableCache.buildWith(CacheBuilder.newBuilder()); Integer key = 42; int threads = 4; CyclicBarrier barrier = new CyclicBarrier(threads); ExecutorService executor = newFixedThreadPool(threads); try { List<Future<Void>> futures = IntStream.range(0, threads) .mapToObj(threadNumber -> executor.submit(() -> { // prime the cache assertEquals((long) cache.get(key, remoteState::get), 1L); int prime = primes[threadNumber]; barrier.await(10, SECONDS); // modify underlying state remoteState.updateAndGet(current -> current * prime); // invalidate switch (invalidation) { case INVALIDATE_KEY: cache.invalidate(key); break; case INVALIDATE_PREDEFINED_KEYS: cache.invalidateAll(List.of(key)); break; case INVALIDATE_SELECTED_KEYS: Set<Integer> keys = cache.asMap().keySet().stream() .filter(foundKey -> (int) foundKey == key) .collect(toImmutableSet()); cache.invalidateAll(keys); break; case INVALIDATE_ALL: cache.invalidateAll(); break; } // read through cache long current = cache.get(key, remoteState::get); if (current % prime != 0) { fail(format("The value read through cache (%s) in thread (%s) is not divisable by (%s)", current, threadNumber, prime)); } return (Void) null; })) .collect(toImmutableList()); futures.forEach(MoreFutures::getFutureValue); assertEquals(remoteState.get(), 2 * 3 * 5 * 7); assertEquals((long) cache.get(key, remoteState::get), remoteState.get()); } finally { executor.shutdownNow(); executor.awaitTermination(10, SECONDS); } } }
lib/trino-plugin-toolkit/src/test/java/io/trino/plugin/base/cache/TestEvictableCache.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.base.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; import io.airlift.concurrent.MoreFutures; import org.gaul.modernizer_maven_annotations.SuppressModernizer; import org.testng.annotations.Test; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.trino.plugin.base.cache.CacheStatsAssertions.assertCacheStats; import static java.lang.String.format; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestEvictableCache { private static final int TEST_TIMEOUT_MILLIS = 10_000; @Test(timeOut = TEST_TIMEOUT_MILLIS) public void testLoad() throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith( CacheBuilder.newBuilder()); assertEquals(cache.get(42, () -> "abc"), "abc"); } @Test(timeOut = TEST_TIMEOUT_MILLIS) public void testLoadStats() throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith( CacheBuilder.newBuilder()); assertEquals(cache.stats(), new CacheStats(0, 0, 0, 0, 0, 0)); String value = assertCacheStats(cache) .misses(1) .loads(1) .calling(() -> cache.get(42, () -> "abc")); assertEquals(value, "abc"); value = assertCacheStats(cache) .hits(1) .calling(() -> cache.get(42, () -> "xyz")); assertEquals(value, "abc"); // with equal, but not the same key value = assertCacheStats(cache) .hits(1) .calling(() -> cache.get(newInteger(42), () -> "xyz")); assertEquals(value, "abc"); } @SuppressModernizer private static Integer newInteger(int value) { Integer integer = value; @SuppressWarnings({"UnnecessaryBoxing", "deprecation", "BoxedPrimitiveConstructor"}) Integer newInteger = new Integer(value); assertNotSame(integer, newInteger); return newInteger; } /** * Covers https://github.com/google/guava/issues/1881 */ @Test(timeOut = TEST_TIMEOUT_MILLIS, dataProviderClass = Invalidation.class, dataProvider = "invalidations") public void testInvalidateOngoingLoad(Invalidation invalidation) throws Exception { Cache<Integer, String> cache = EvictableCache.buildWith(CacheBuilder.newBuilder()); Integer key = 42; CountDownLatch loadOngoing = new CountDownLatch(1); CountDownLatch invalidated = new CountDownLatch(1); ExecutorService executor = newFixedThreadPool(2); try { // thread A Future<String> threadA = executor.submit(() -> { return cache.get(key, () -> { loadOngoing.countDown(); // 1 assertTrue(invalidated.await(10, SECONDS)); // 2 return "stale value"; }); }); // thread B Future<String> threadB = executor.submit(() -> { assertTrue(loadOngoing.await(10, SECONDS)); // 1 switch (invalidation) { case INVALIDATE_KEY: cache.invalidate(key); break; case INVALIDATE_PREDEFINED_KEYS: cache.invalidateAll(List.of(key)); break; case INVALIDATE_SELECTED_KEYS: Set<Integer> keys = cache.asMap().keySet().stream() .filter(foundKey -> (int) foundKey == key) .collect(toImmutableSet()); cache.invalidateAll(keys); break; case INVALIDATE_ALL: cache.invalidateAll(); break; } invalidated.countDown(); // 2 return cache.get(key, () -> "fresh value"); }); assertEquals(threadA.get(), "stale value"); assertEquals(threadB.get(), "fresh value"); } finally { executor.shutdownNow(); executor.awaitTermination(10, SECONDS); } } /** * Covers https://github.com/google/guava/issues/1881 */ @Test(invocationCount = 10, timeOut = TEST_TIMEOUT_MILLIS, dataProviderClass = Invalidation.class, dataProvider = "invalidations") public void testInvalidateAndLoadConcurrently(Invalidation invalidation) throws Exception { int[] primes = {2, 3, 5, 7}; AtomicLong remoteState = new AtomicLong(1); Cache<Integer, Long> cache = EvictableCache.buildWith(CacheBuilder.newBuilder()); Integer key = 42; int threads = 4; CyclicBarrier barrier = new CyclicBarrier(threads); ExecutorService executor = newFixedThreadPool(threads); try { List<Future<Void>> futures = IntStream.range(0, threads) .mapToObj(threadNumber -> executor.submit(() -> { // prime the cache assertEquals((long) cache.get(key, remoteState::get), 1L); int prime = primes[threadNumber]; barrier.await(10, SECONDS); // modify underlying state remoteState.updateAndGet(current -> current * prime); // invalidate switch (invalidation) { case INVALIDATE_KEY: cache.invalidate(key); break; case INVALIDATE_PREDEFINED_KEYS: cache.invalidateAll(List.of(key)); break; case INVALIDATE_SELECTED_KEYS: Set<Integer> keys = cache.asMap().keySet().stream() .filter(foundKey -> (int) foundKey == key) .collect(toImmutableSet()); cache.invalidateAll(keys); break; case INVALIDATE_ALL: cache.invalidateAll(); break; } // read through cache long current = cache.get(key, remoteState::get); if (current % prime != 0) { fail(format("The value read through cache (%s) in thread (%s) is not divisable by (%s)", current, threadNumber, prime)); } return (Void) null; })) .collect(toImmutableList()); futures.forEach(MoreFutures::getFutureValue); assertEquals(remoteState.get(), 2 * 3 * 5 * 7); assertEquals((long) cache.get(key, remoteState::get), remoteState.get()); } finally { executor.shutdownNow(); executor.awaitTermination(10, SECONDS); } } }
Improve test interleaving determinism
lib/trino-plugin-toolkit/src/test/java/io/trino/plugin/base/cache/TestEvictableCache.java
Improve test interleaving determinism
Java
apache-2.0
7bb833d2f2c3023203dd949c8ec3f40b91f40eea
0
christiaandejong/AxonFramework,AxonFramework/AxonFramework,krosenvold/AxonFramework,bojanv55/AxonFramework,phaas/AxonFramework,adinath/AxonFramework,BrentDouglas/AxonFramework,soulrebel/AxonFramework,Cosium/AxonFramework,oiavorskyi/AxonFramework,fpape/AxonFramework
/* * Copyright (c) 2010. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.sample.app.query; import org.axonframework.sample.app.AddressType; import org.hibernate.annotations.Type; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.UUID; /** * @author Allard Buijze */ @Entity public class AddressEntry { @Id @GeneratedValue private Long db_identifier; @Basic @Column(length = 36) @Type(type = "org.axonframework.sample.app.query.UUIDUserType") private UUID identifier; @Basic private String name; @Basic @Enumerated(EnumType.STRING) private AddressType addressType; @Basic private String streetAndNumber; @Basic private String zipCode; @Basic private String city; public UUID getIdentifier() { return identifier; } void setIdentifier(UUID identifier) { this.identifier = identifier; } public String getName() { return name; } void setName(String name) { this.name = name; } public AddressType getAddressType() { return addressType; } void setAddressType(AddressType addressType) { this.addressType = addressType; } public String getStreetAndNumber() { return streetAndNumber; } void setStreetAndNumber(String streetAndNumber) { this.streetAndNumber = streetAndNumber; } public String getZipCode() { return zipCode; } void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCity() { return city; } void setCity(String city) { this.city = city; } }
sample/addressbook/app/src/main/java/org/axonframework/sample/app/query/AddressEntry.java
/* * Copyright (c) 2010. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.sample.app.query; import org.axonframework.sample.app.AddressType; import org.hibernate.annotations.Type; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.UUID; /** * @author Allard Buijze */ @Entity public class AddressEntry { @Id @GeneratedValue private Long db_identifier; @Basic @Type(type = "org.axonframework.sample.app.query.UUIDUserType") private UUID identifier; @Basic private String name; @Basic @Enumerated(EnumType.STRING) private AddressType addressType; @Basic private String streetAndNumber; @Basic private String zipCode; @Basic private String city; public UUID getIdentifier() { return identifier; } void setIdentifier(UUID identifier) { this.identifier = identifier; } public String getName() { return name; } void setName(String name) { this.name = name; } public AddressType getAddressType() { return addressType; } void setAddressType(AddressType addressType) { this.addressType = addressType; } public String getStreetAndNumber() { return streetAndNumber; } void setStreetAndNumber(String streetAndNumber) { this.streetAndNumber = streetAndNumber; } public String getZipCode() { return zipCode; } void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCity() { return city; } void setCity(String city) { this.city = city; } }
Explicitly set column size on UUID type
sample/addressbook/app/src/main/java/org/axonframework/sample/app/query/AddressEntry.java
Explicitly set column size on UUID type
Java
apache-2.0
a998a693e76d649ff0b94bf7a4016f1372ee7f87
0
tuijldert/jitsi,mckayclarey/jitsi,tuijldert/jitsi,marclaporte/jitsi,marclaporte/jitsi,damencho/jitsi,mckayclarey/jitsi,martin7890/jitsi,dkcreinoso/jitsi,jitsi/jitsi,gpolitis/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,level7systems/jitsi,gpolitis/jitsi,level7systems/jitsi,damencho/jitsi,bhatvv/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,iant-gmbh/jitsi,procandi/jitsi,bebo/jitsi,ringdna/jitsi,tuijldert/jitsi,jibaro/jitsi,pplatek/jitsi,level7systems/jitsi,iant-gmbh/jitsi,martin7890/jitsi,marclaporte/jitsi,damencho/jitsi,mckayclarey/jitsi,jibaro/jitsi,level7systems/jitsi,pplatek/jitsi,ringdna/jitsi,iant-gmbh/jitsi,ibauersachs/jitsi,ringdna/jitsi,laborautonomo/jitsi,jitsi/jitsi,gpolitis/jitsi,jibaro/jitsi,bebo/jitsi,gpolitis/jitsi,ibauersachs/jitsi,martin7890/jitsi,cobratbq/jitsi,laborautonomo/jitsi,bhatvv/jitsi,Metaswitch/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,bebo/jitsi,cobratbq/jitsi,procandi/jitsi,dkcreinoso/jitsi,damencho/jitsi,bebo/jitsi,procandi/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,459below/jitsi,procandi/jitsi,bhatvv/jitsi,459below/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,jitsi/jitsi,jitsi/jitsi,459below/jitsi,ibauersachs/jitsi,procandi/jitsi,ringdna/jitsi,mckayclarey/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,jibaro/jitsi,marclaporte/jitsi,HelioGuilherme66/jitsi,bebo/jitsi,tuijldert/jitsi,cobratbq/jitsi,Metaswitch/jitsi,tuijldert/jitsi,pplatek/jitsi,ibauersachs/jitsi,damencho/jitsi,ringdna/jitsi,marclaporte/jitsi,laborautonomo/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,dkcreinoso/jitsi,gpolitis/jitsi,level7systems/jitsi,cobratbq/jitsi,jitsi/jitsi,martin7890/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,459below/jitsi,martin7890/jitsi,jibaro/jitsi,mckayclarey/jitsi,459below/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.customcontrols; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.keybindings.*; import java.util.*; public abstract class SIPCommFrame extends JFrame implements Observer { private Logger logger = Logger.getLogger(SIPCommFrame.class); ActionMap amap; InputMap imap; KeybindingSet bindings = null; public SIPCommFrame() { this.setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); // In order to have the same icon when using option panes JOptionPane.getRootFrame().setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); this.addWindowListener(new FrameWindowAdapter()); amap = this.getRootPane().getActionMap(); amap.put("close", new CloseAction()); imap = this.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } /** * The action invoked when user presses Escape key. */ private class CloseAction extends AbstractAction { public void actionPerformed(ActionEvent e) { saveSizeAndLocation(); close(true); } } /** * Sets the input map to utilize a given category of keybindings. The frame * is updated to reflect the new bindings when they change. This replaces * any previous bindings that have been added. * @param category set of keybindings to be utilized */ protected void setKeybindingInput(KeybindingSet.Category category) { // Removes old binding set if (this.bindings != null) { this.bindings.deleteObserver(this); resetInputMap(); } // Adds new bindings to input map KeybindingsService service = GuiActivator.getKeybindingsService(); this.bindings = service.getBindings(category); for (KeyStroke key : this.bindings.getBindings().keySet()) { String action = this.bindings.getBindings().get(key); imap.put(key, action); } this.bindings.addObserver(this); } /** * Bindings the string representation for a keybinding to the action that * will be executed. * @param binding string representation of action used by input map * @param action the action which will be executed when user presses the * given key combination */ protected void addKeybindingAction(String binding, Action action) { amap.put(binding, action); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class FrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { saveSizeAndLocation(); close(false); } } /** * Saves the size and the location of this frame through the * <tt>ConfigurationService</tt>. */ private void saveSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); try { configService.setProperty( className + ".width", new Integer(getWidth())); configService.setProperty( className + ".height", new Integer(getHeight())); configService.setProperty( className + ".x", new Integer(getX())); configService.setProperty( className + ".y", new Integer(getY())); } catch (PropertyVetoException e1) { logger.error("The proposed property change " + "represents an unacceptable value"); } } /** * Sets window size and position. */ public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); String widthString = configService.getString( className + ".width"); String heightString = configService.getString( className + ".height"); String xString = configService.getString( className + ".x"); String yString = configService.getString( className + ".y"); int width = 0; int height = 0; int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; if(widthString != null && heightString != null) { width = new Integer(widthString).intValue(); height = new Integer(heightString).intValue(); if(width > 0 && height > 0 && width <= screenWidth && height <= screenHeight) this.setSize(width, height); } int x = 0; int y = 0; if(xString != null && yString != null) { x = new Integer(xString).intValue(); y = new Integer(yString).intValue(); this.setLocation(x, y); } else { this.setCenterLocation(); } } /** * Positions this window in the center of the screen. */ private void setCenterLocation() { this.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - this.getWidth()/2, Toolkit.getDefaultToolkit().getScreenSize().height/2 - this.getHeight()/2 ); } /** * Checks whether the current component will * exceeds the screen size and if it do will set a default size */ private void ensureOnScreenLocationAndSize() { int x = this.getX(); int y = this.getY(); int width = this.getWidth(); int height = this.getHeight(); Rectangle virtualBounds = ScreenInformation.getScreenBounds(); // the default distance to the screen border final int borderDistance = 10; // in case any of the sizes exceeds the screen size // we set default one // get the left upper point of the window if (!(virtualBounds.contains(x, y))) { // top left exceeds screen bounds if (x < virtualBounds.x) { // window is too far to the left // move it to the right x = virtualBounds.x + borderDistance; } else if (x > virtualBounds.x) { // window is too far to the right // can only occour, when screen resolution is // changed or displayed are disconnected // move the window in the bounds to the very right x = virtualBounds.x + virtualBounds.width - width - borderDistance; if (x < virtualBounds.x + borderDistance) { x = virtualBounds.x + borderDistance; } } // top left exceeds screen bounds if (y < virtualBounds.y) { // window is too far to the top // move it to the bottom y = virtualBounds.y + borderDistance; } else if (y > virtualBounds.y) { // window is too far to the bottom // can only occour, when screen resolution is // changed or displayed are disconnected // move the window in the bounds to the very bottom y = virtualBounds.y + virtualBounds.height - height - borderDistance; if (y < virtualBounds.y + borderDistance) { y = virtualBounds.y + borderDistance; } } this.setLocation(x, y); } // check the lower right corder if (!(virtualBounds.contains(x + width, y + height))) { if (x + width > virtualBounds.x + virtualBounds.width) { // location of window is too far to the right, its right // border is out of bounds // calculate a new horizontal position // move the whole window to the left x = virtualBounds.x + virtualBounds.width - width - borderDistance; if (x < virtualBounds.x + borderDistance) { // window is already on left side, it is too wide. x = virtualBounds.x + borderDistance; // reduce the width, so it surely fits width = virtualBounds.width - 2 * borderDistance; } } if (y + height > virtualBounds.y + virtualBounds.height) { // location of window is too far to the bottom, its bottom // border is out of bounds // calculate a new vertical position // move the whole window to the top y = virtualBounds.y + virtualBounds.height - height - borderDistance; if (y < virtualBounds.y + borderDistance) { // window is already on top, it is too high. y = virtualBounds.y + borderDistance; // reduce the width, so it surely fits height = virtualBounds.height - 2 * borderDistance; } } this.setPreferredSize(new Dimension(width, height)); this.setSize(width, height); this.setLocation(x, y); } } /** * Overwrites the setVisible method in order to set the size and the * position of this window before showing it. */ public void setVisible(boolean isVisible) { if (isVisible) { this.pack(); this.setSizeAndLocation(); this.ensureOnScreenLocationAndSize(); } super.setVisible(isVisible); } /** * Overwrites the dispose method in order to save the size and the position * of this window before closing it. */ public void dispose() { this.saveSizeAndLocation(); /* * The keybinding service will outlive us so don't let us retain our * memory. */ if (bindings != null) bindings.deleteObserver(this); super.dispose(); } private void resetInputMap() { imap.clear(); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); } // Listens for changes in binding sets so they can be reflected in the input // map public void update(Observable obs, Object arg) { if (obs instanceof KeybindingSet) { KeybindingSet changedBindings = (KeybindingSet) obs; resetInputMap(); for (KeyStroke binding : changedBindings.getBindings().keySet()) { String action = changedBindings.getBindings().get(binding); imap.put(binding, action); } } } /** * All functions implemented in this method will be invoked when user * presses the Escape key. */ protected abstract void close(boolean isEscaped); }
src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.customcontrols; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.keybindings.*; import java.util.*; public abstract class SIPCommFrame extends JFrame implements Observer { private Logger logger = Logger.getLogger(SIPCommFrame.class); ActionMap amap; InputMap imap; KeybindingSet bindings = null; public SIPCommFrame() { this.setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); // In order to have the same icon when using option panes JOptionPane.getRootFrame().setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); this.addWindowListener(new FrameWindowAdapter()); amap = this.getRootPane().getActionMap(); amap.put("close", new CloseAction()); imap = this.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } /** * The action invoked when user presses Escape key. */ private class CloseAction extends AbstractAction { public void actionPerformed(ActionEvent e) { saveSizeAndLocation(); close(true); } } /** * Sets the input map to utilize a given category of keybindings. The frame * is updated to reflect the new bindings when they change. This replaces * any previous bindings that have been added. * @param category set of keybindings to be utilized */ protected void setKeybindingInput(KeybindingSet.Category category) { // Removes old binding set if (this.bindings != null) { this.bindings.deleteObserver(this); resetInputMap(); } // Adds new bindings to input map KeybindingsService service = GuiActivator.getKeybindingsService(); this.bindings = service.getBindings(category); for (KeyStroke key : this.bindings.getBindings().keySet()) { String action = this.bindings.getBindings().get(key); imap.put(key, action); } this.bindings.addObserver(this); } /** * Bindings the string representation for a keybinding to the action that * will be executed. * @param binding string representation of action used by input map * @param action the action which will be executed when user presses the * given key combination */ protected void addKeybindingAction(String binding, Action action) { amap.put(binding, action); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class FrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { saveSizeAndLocation(); close(false); } } /** * Saves the size and the location of this frame through the * <tt>ConfigurationService</tt>. */ private void saveSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); try { configService.setProperty( className + ".width", new Integer(getWidth())); configService.setProperty( className + ".height", new Integer(getHeight())); configService.setProperty( className + ".x", new Integer(getX())); configService.setProperty( className + ".y", new Integer(getY())); } catch (PropertyVetoException e1) { logger.error("The proposed property change " + "represents an unacceptable value"); } } /** * Sets window size and position. */ public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); String widthString = configService.getString( className + ".width"); String heightString = configService.getString( className + ".height"); String xString = configService.getString( className + ".x"); String yString = configService.getString( className + ".y"); int width = 0; int height = 0; int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; if(widthString != null && heightString != null) { width = new Integer(widthString).intValue(); height = new Integer(heightString).intValue(); if(width > 0 && height > 0 && width <= screenWidth && height <= screenHeight) this.setSize(width, height); } int x = 0; int y = 0; if(xString != null && yString != null) { x = new Integer(xString).intValue(); y = new Integer(yString).intValue(); this.setLocation(x, y); } else { this.setCenterLocation(); } } /** * Positions this window in the center of the screen. */ private void setCenterLocation() { this.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - this.getWidth()/2, Toolkit.getDefaultToolkit().getScreenSize().height/2 - this.getHeight()/2 ); } /** * Checks whether the current component will * exceeds the screen size and if it do will set a default size */ private void ensureOnScreenLocationAndSize() { int x = this.getX(); int y = this.getY(); int width = this.getWidth(); int height = this.getHeight(); Rectangle virtualBounds = ScreenInformation.getScreenBounds(); // the default distance to the screen border final int borderDistance = 10; // in case any of the sizes exceeds the screen size // we set default one // get the left upper point of the window if (!(virtualBounds.contains(x, y))) { // top left exceeds screen bounds if (x < virtualBounds.x) { // window is too far to the left // move it to the right x = virtualBounds.x + borderDistance; } else if (x > virtualBounds.x) { // window is too far to the right // can only occour, when screen resolution is // changed or displayed are disconnected // move the window in the bounds to the very right x = virtualBounds.x + virtualBounds.width - width - borderDistance; if (x < virtualBounds.x + borderDistance) { x = virtualBounds.x + borderDistance; } } // top left exceeds screen bounds if (y < virtualBounds.y) { // window is too far to the top // move it to the bottom y = virtualBounds.y + borderDistance; } else if (y > virtualBounds.y) { // window is too far to the bottom // can only occour, when screen resolution is // changed or displayed are disconnected // move the window in the bounds to the very bottom y = virtualBounds.y + virtualBounds.height - height - borderDistance; if (y < virtualBounds.y + borderDistance) { y = virtualBounds.y + borderDistance; } } this.setLocation(x, y); } // check the lower right corder if (!(virtualBounds.contains(x + width, y + height))) { if (x + width > virtualBounds.x + virtualBounds.width) { // location of window is too far to the right, its right // border is out of bounds // calculate a new horizontal position // move the whole window to the left x = virtualBounds.x + virtualBounds.width - width - borderDistance; if (x < virtualBounds.x + borderDistance) { // window is already on left side, it is too wide. x = virtualBounds.x + borderDistance; // reduce the width, so it surely fits width = virtualBounds.width - 2 * borderDistance; } } if (y + height > virtualBounds.y + virtualBounds.height) { // location of window is too far to the bottom, its bottom // border is out of bounds // calculate a new vertical position // move the whole window to the top y = virtualBounds.y + virtualBounds.height - height - borderDistance; if (y < virtualBounds.y + borderDistance) { // window is already on top, it is too high. y = virtualBounds.y + borderDistance; // reduce the width, so it surely fits height = virtualBounds.height - 2 * borderDistance; } } this.setPreferredSize(new Dimension(width, height)); this.setSize(width, height); this.setLocation(x, y); } } /** * Overwrites the setVisible method in order to set the size and the * position of this window before showing it. */ public void setVisible(boolean isVisible) { if (isVisible) { this.pack(); this.setSizeAndLocation(); this.ensureOnScreenLocationAndSize(); } super.setVisible(isVisible); } /** * Overwrites the dispose method in order to save the size and the position * of this window before closing it. */ public void dispose() { this.saveSizeAndLocation(); super.dispose(); } private void resetInputMap() { imap.clear(); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); } // Listens for changes in binding sets so they can be reflected in the input // map public void update(Observable obs, Object arg) { if (obs instanceof KeybindingSet) { KeybindingSet changedBindings = (KeybindingSet) obs; resetInputMap(); for (KeyStroke binding : changedBindings.getBindings().keySet()) { String action = changedBindings.getBindings().get(binding); imap.put(binding, action); } } } /** * All functions implemented in this method will be invoked when user * presses the Escape key. */ protected abstract void close(boolean isEscaped); }
Prevents the keybinding service from retaining SIPCommFrame (e.g. ChatWindow).
src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java
Prevents the keybinding service from retaining SIPCommFrame (e.g. ChatWindow).
Java
apache-2.0
4236bc2af55bcf5ce2e7ea4f78f054e85cdc759b
0
andsel/moquette,andsel/moquette,windbender/moquette,windbender/moquette,andsel/moquette,windbender/moquette,windbender/moquette,andsel/moquette
/* * Copyright (c) 2012-2017 The original author or authorsgetRockQuestions() * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.moquette.server; /** * Server constants keeper */ public class Constants { public static final String ATTR_CLIENTID = "ClientID"; public static final String CLEAN_SESSION = "cleanSession"; public static final String KEEP_ALIVE = "keepAlive"; public static final int MAX_MESSAGE_QUEUE = 1024; // number of messages }
broker/src/main/java/io/moquette/server/Constants.java
/* * Copyright (c) 2012-2017 The original author or authorsgetRockQuestions() * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.moquette.server; /** * Server constants keeper */ public class Constants { public static final String ATTR_CLIENTID = "ClientID"; public static final String CLEAN_SESSION = "cleanSession"; public static final String KEEP_ALIVE = "keepAlive"; public static final int MAX_MESSAGE_QUEUE = 1024; //number of messages }
broker/Constants: code formatter used
broker/src/main/java/io/moquette/server/Constants.java
broker/Constants: code formatter used
Java
apache-2.0
a1434d04604edce3973989546e40b49d60b38d65
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.example.tsp.gpx; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import java.io.Serializable; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.jenetics.util.ISeq; /** * A {@code WayPoint} represents a way-point, point of interest, or named * feature on a map. * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version !__version__! * @since !__version__! */ @XmlJavaTypeAdapter(WayPoint.Model.Adapter.class) public final class WayPoint implements Point, Serializable { private static final long serialVersionUID = 1L; private final Latitude _latitude; private final Longitude _longitude; private final Length _elevation; private final Speed _speed; private final ZonedDateTime _time; private final Degrees _magneticVariation; private final Length _geoidHeight; private final String _name; private final String _comment; private final String _description; private final String _source; private final ISeq<Link> _links; private final String _symbol; private final String _type; private final Fix _fix; private final UInt _sat; private final Double _hdop; private final Double _vdop; private final Double _pdop; private final Duration _ageOfGPSData; private final DGPSStation _dgpsID; /** * Create a new way-point with the given parameter. * * @param latitude the latitude of the point, WGS84 datum (mandatory) * @param longitude the longitude of the point, WGS84 datum (mandatory) * @param elevation the elevation (in meters) of the point (optional) * @param speed the current GPS speed (optional) * @param time creation/modification timestamp for element. Conforms to ISO * 8601 specification for date/time representation. Fractional seconds * are allowed for millisecond timing in tracklogs. (optional) * @param magneticVariation the magnetic variation at the point (optional) * @param geoidHeight height (in meters) of geoid (mean sea level) above * WGS84 earth ellipsoid. As defined in NMEA GGA message. (optional) * @param name the GPS name of the way-point. This field will be transferred * to and from the GPS. GPX does not place restrictions on the length * of this field or the characters contained in it. It is up to the * receiving application to validate the field before sending it to * the GPS. (optional) * @param comment GPS way-point comment. Sent to GPS as comment (optional) * @param description a text description of the element. Holds additional * information about the element intended for the user, not the GPS. * (optional) * @param source source of data. Included to give user some idea of * reliability and accuracy of data. "Garmin eTrex", "USGS quad * Boston North", e.g. (optional) * @param links links to additional information about the way-point. May be * empty, but not {@code null}. * @param symbol text of GPS symbol name. For interchange with other * programs, use the exact spelling of the symbol as displayed on the * GPS. If the GPS abbreviates words, spell them out. (optional) * @param type type (classification) of the way-point (optional) * @param fix type of GPX fix (optional) * @param sat number of satellites used to calculate the GPX fix (optional) * @param hdop horizontal dilution of precision (optional) * @param vdop vertical dilution of precision (optional) * @param pdop position dilution of precision. (optional) * @param ageOfGPSData number of seconds since last DGPS update (optional) * @param dgpsID ID of DGPS station used in differential correction (optional) */ private WayPoint( final Latitude latitude, final Longitude longitude, final Length elevation, final Speed speed, final ZonedDateTime time, final Degrees magneticVariation, final Length geoidHeight, final String name, final String comment, final String description, final String source, final ISeq<Link> links, final String symbol, final String type, final Fix fix, final UInt sat, final Double hdop, final Double vdop, final Double pdop, final Duration ageOfGPSData, final DGPSStation dgpsID ) { _latitude = requireNonNull(latitude); _longitude = requireNonNull(longitude); _elevation = elevation; _speed = speed; _time = time; _magneticVariation = magneticVariation; _geoidHeight = geoidHeight; _name = name; _comment = comment; _description = description; _source = source; _links = requireNonNull(links); _symbol = symbol; _type = type; _fix = fix; _sat = sat; _hdop = hdop; _vdop = vdop; _pdop = pdop; _ageOfGPSData = ageOfGPSData; _dgpsID = dgpsID; } @Override public Latitude getLatitude() { return _latitude; } @Override public Longitude getLongitude() { return _longitude; } @Override public Optional<Length> getElevation() { return Optional.ofNullable(_elevation); } /** * The current GPS speed. * * @return the current GPS speed */ public Optional<Speed> getSpeed() { return Optional.ofNullable(_speed); } @Override public Optional<ZonedDateTime> getTime() { return Optional.ofNullable(_time); } /** * The magnetic variation at the point. * * @return the magnetic variation at the point */ public Optional<Degrees> getMagneticVariation() { return Optional.ofNullable(_magneticVariation); } /** * The height (in meters) of geoid (mean sea level) above WGS84 earth * ellipsoid. As defined in NMEA GGA message. * * @return the height (in meters) of geoid (mean sea level) above WGS84 * earth ellipsoid */ public Optional<Length> getGeoidHeight() { return Optional.ofNullable(_geoidHeight); } /** * The GPS name of the way-point. This field will be transferred to and from * the GPS. GPX does not place restrictions on the length of this field or * the characters contained in it. It is up to the receiving application to * validate the field before sending it to the GPS. * * @return the GPS name of the way-point */ public Optional<String> getName() { return Optional.ofNullable(_name); } /** * The GPS way-point comment. * * @return the GPS way-point comment */ public Optional<String> getComment() { return Optional.ofNullable(_comment); } /** * Return a text description of the element. Holds additional information * about the element intended for the user, not the GPS. * * @return a text description of the element */ public Optional<String> getDescription() { return Optional.ofNullable(_description); } /** * Return the source of data. Included to give user some idea of reliability * and accuracy of data. "Garmin eTrex", "USGS quad Boston North", e.g. * * @return the source of the data */ public Optional<String> getSource() { return Optional.ofNullable(_source); } /** * Return the links to additional information about the way-point. * * @return the links to additional information about the way-point */ public ISeq<Link> getLinks() { return _links; } /** * Return the text of GPS symbol name. For interchange with other programs, * use the exact spelling of the symbol as displayed on the GPS. If the GPS * abbreviates words, spell them out. * * @return the text of GPS symbol name */ public Optional<String> getSymbol() { return Optional.ofNullable(_symbol); } /** * Return the type (classification) of the way-point. * * @return the type (classification) of the way-point */ public Optional<String> getType() { return Optional.ofNullable(_type); } /** * Return the type of GPX fix. * * @return the type of GPX fix */ public Optional<Fix> getFix() { return Optional.ofNullable(_fix); } /** * Return the number of satellites used to calculate the GPX fix. * * @return the number of satellites used to calculate the GPX fix */ public Optional<UInt> getSat() { return Optional.ofNullable(_sat); } /** * Return the horizontal dilution of precision. * * @return the horizontal dilution of precision */ public Optional<Double> getHdop() { return Optional.ofNullable(_hdop); } /** * Return the vertical dilution of precision. * * @return the vertical dilution of precision */ public Optional<Double> getVdop() { return Optional.ofNullable(_vdop); } /** * Return the position dilution of precision. * * @return the position dilution of precision */ public Optional<Double> getPdop() { return Optional.ofNullable(_pdop); } /** * Return the number of seconds since last DGPS update. * * @return number of seconds since last DGPS update */ public Optional<Duration> getAgeOfGPSData() { return Optional.ofNullable(_ageOfGPSData); } /** * Return the ID of DGPS station used in differential correction. * * @return the ID of DGPS station used in differential correction */ public Optional<DGPSStation> getDGPSID() { return Optional.ofNullable(_dgpsID); } @Override public int hashCode() { int hash = 37; hash += 17*_latitude.hashCode() + 31; hash += 17*_longitude.hashCode() + 31; hash += 17*Objects.hashCode(_elevation) + 31; hash += 17*Objects.hashCode(_speed) + 31; hash += 17*Objects.hashCode(_time) + 31; hash += 17*Objects.hashCode(_magneticVariation) + 31; hash += 17*Objects.hashCode(_geoidHeight) + 31; hash += 17*Objects.hashCode(_name) + 31; hash += 17*Objects.hashCode(_comment) + 31; hash += 17*Objects.hashCode(_description) + 31; hash += 17*Objects.hashCode(_source) + 31; hash += 17*Objects.hashCode(_links) + 31; hash += 17*Objects.hashCode(_symbol) + 31; hash += 17*Objects.hashCode(_type) + 31; hash += 17*Objects.hashCode(_fix) + 31; hash += 17*Objects.hashCode(_sat) + 31; hash += 17*Objects.hashCode(_hdop) + 31; hash += 17*Objects.hashCode(_vdop) + 31; hash += 17*Objects.hashCode(_pdop) + 31; hash += 17*Objects.hashCode(_ageOfGPSData) + 31; hash += 17*Objects.hashCode(_dgpsID) + 31; return hash; } @Override public boolean equals(final Object obj) { return obj instanceof WayPoint && ((WayPoint)obj)._latitude.equals(_latitude) && ((WayPoint)obj)._longitude.equals(_longitude) && Objects.equals(((WayPoint)obj)._elevation, _elevation) && Objects.equals(((WayPoint)obj)._speed, _speed) && Objects.equals(((WayPoint)obj)._time, _time) && Objects.equals(((WayPoint)obj)._magneticVariation, _magneticVariation) && Objects.equals(((WayPoint)obj)._geoidHeight, _geoidHeight) && Objects.equals(((WayPoint)obj)._name, _name) && Objects.equals(((WayPoint)obj)._comment, _comment) && Objects.equals(((WayPoint)obj)._description, _description) && Objects.equals(((WayPoint)obj)._source, _source) && Objects.equals(((WayPoint)obj)._links, _links) && Objects.equals(((WayPoint)obj)._symbol, _symbol) && Objects.equals(((WayPoint)obj)._type, _type) && Objects.equals(((WayPoint)obj)._fix, _fix) && Objects.equals(((WayPoint)obj)._sat, _sat) && Objects.equals(((WayPoint)obj)._hdop, _hdop) && Objects.equals(((WayPoint)obj)._vdop, _vdop) && Objects.equals(((WayPoint)obj)._pdop, _pdop) && Objects.equals(((WayPoint)obj)._ageOfGPSData, _ageOfGPSData) && Objects.equals(((WayPoint)obj)._dgpsID, _dgpsID); } @Override public String toString() { return format("[lat=%s, lon=%s]", _latitude, _latitude); } /** * Builder for creating a way-point with different parameters. */ public static final class Builder { private Length _elevation; private Speed _speed; private ZonedDateTime _time; private Degrees _magneticVariation; private Length _geoidHeight; private String _name; private String _comment; private String _description; private String _source; private ISeq<Link> _links; private String _symbol; private String _type; private Fix _fix; private UInt _sat; private Double _hdop; private Double _vdop; private Double _pdop; private Duration _ageOfDGPSData; private DGPSStation _dgpsID; /** * Set the elevation of the point. * * @param elevation the elevation of the point * @return {@code this} {@code Builder} for method chaining */ public Builder elevation(final Length elevation) { _elevation = elevation; return this; } /** * Set the elevation (in meters) of the point. * * @param meters the elevation of the point, in meters * @return {@code this} {@code Builder} for method chaining */ public Builder elevation(final double meters) { _elevation = Length.ofMeters(meters); return this; } /** * Set the current GPS speed. * * @param speed the current GPS speed * @return {@code this} {@code Builder} for method chaining */ public Builder speed(final Speed speed) { _speed = speed; return this; } /** * Set the current GPS speed. * * @param meterPerSecond the current GPS speed in m/s * @return {@code this} {@code Builder} for method chaining */ public Builder speed(final double meterPerSecond) { _speed = Speed.of(meterPerSecond); return this; } /** * Set the creation/modification timestamp for the point. * * @param time the creation/modification timestamp for the point * @return {@code this} {@code Builder} for method chaining */ public Builder time(final ZonedDateTime time) { _time = time; return this; } /** * Set the magnetic variation at the point. * * @param variation the magnetic variation * @return {@code this} {@code Builder} for method chaining */ public Builder magneticVariation(final Degrees variation) { _magneticVariation = variation; return this; } /** * Set the magnetic variation at the point. * * @param variation the magnetic variation * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the give value is not within the * range of {@code [0..360]} */ public Builder magneticVariation(final double variation) { _magneticVariation = Degrees.of(variation); return this; } /** * Set the height (in meters) of geoid (mean sea level) above WGS84 earth * ellipsoid. As defined in NMEA GGA message. * * @param geoidHeight the height (in meters) of geoid (mean sea level) * above WGS84 earth ellipsoid * @return {@code this} {@code Builder} for method chaining */ public Builder geoidHeight(final Length geoidHeight) { _geoidHeight = geoidHeight; return this; } /** * Set the GPS name of the way-point. This field will be transferred to * and from the GPS. GPX does not place restrictions on the length of * this field or the characters contained in it. It is up to the * receiving application to validate the field before sending it to the * GPS. * * @param name the GPS name of the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder name(final String name) { _name = name; return this; } /** * Set the GPS way-point comment. * * @param comment the GPS way-point comment. * @return {@code this} {@code Builder} for method chaining */ public Builder comment(final String comment) { _comment = comment; return this; } /** * Set the links to additional information about the way-point. * * @param links the links to additional information about the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder links(final ISeq<Link> links) { _links = links; return this; } /** * Set the text of GPS symbol name. For interchange with other programs, * use the exact spelling of the symbol as displayed on the GPS. If the * GPS abbreviates words, spell them out. * * @param symbol the text of GPS symbol name * @return {@code this} {@code Builder} for method chaining */ public Builder symbol(final String symbol) { _symbol = symbol; return this; } /** * Set the type (classification) of the way-point. * * @param type the type (classification) of the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder type(final String type) { _type = type; return this; } /** * Set the type of GPX fix. * * @param fix the type of GPX fix * @return {@code this} {@code Builder} for method chaining */ public Builder fix(final Fix fix) { _fix = fix; return this; } /** * Set the number of satellites used to calculate the GPX fix. * * @param sat the number of satellites used to calculate the GPX fix * @return {@code this} {@code Builder} for method chaining */ public Builder sat(final UInt sat) { _sat = sat; return this; } /** * Set the number of satellites used to calculate the GPX fix. * * @param sat the number of satellites used to calculate the GPX fix * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the given {@code value} is smaller * than zero */ public Builder sat(final int sat) { _sat = UInt.of(sat); return this; } /** * Set the horizontal dilution of precision. * * @param hdop the horizontal dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder hdop(final Double hdop) { _hdop = hdop; return this; } /** * Set the vertical dilution of precision. * * @param vdop the vertical dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder vdop(final Double vdop) { _vdop = vdop; return this; } /** * Set the position dilution of precision. * * @param pdop the position dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder pdop(final Double pdop) { _pdop = pdop; return this; } /** * Set the age since last DGPS update. * * @param age the age since last DGPS update * @return {@code this} {@code Builder} for method chaining */ public Builder ageOfDGPSAge(final Duration age) { _ageOfDGPSData = age; return this; } /** * Set the number of seconds since last DGPS update. * * @param seconds the age since last DGPS update * @return {@code this} {@code Builder} for method chaining */ public Builder ageOfDGPSAge(final double seconds) { _ageOfDGPSData = Duration.ofMillis((long)(seconds/1000.0)); return this; } /** * Set the ID of DGPS station used in differential correction. * * @param station the ID of DGPS station used in differential correction * @return {@code this} {@code Builder} for method chaining */ public Builder dgpsStation(final DGPSStation station) { _dgpsID = station; return this; } /** * Set the ID of DGPS station used in differential correction. * * @param station the ID of DGPS station used in differential correction * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the given station number is not in the * range of {@code [0..1023]} */ public Builder dgpsStation(final int station) { _dgpsID = DGPSStation.of(station); return this; } /** * Create a new way-point with the given latitude and longitude value. * * @param latitude the latitude of the way-point * @param longitude the longitude of the way-point * @return a newly created way-point */ public WayPoint build(final Latitude latitude, final Longitude longitude) { return new WayPoint( latitude, longitude, _elevation, _speed, _time, _magneticVariation, _geoidHeight, _name, _comment, _description, _source, _links != null ? _links : ISeq.empty(), _symbol, _type, _fix, _sat, _hdop, _vdop, _pdop, _ageOfDGPSData, _dgpsID ); } /** * Create a new way-point with the given latitude and longitude value. * * @param latitude the latitude of the way-point * @param longitude the longitude of the way-point * @return a newly created way-point */ public WayPoint build(final double latitude, final double longitude) { return build(Latitude.of(latitude), Longitude.of(longitude)); } } /* ************************************************************************* * Static object creation methods * ************************************************************************/ /** * Return a new {@code WayPoint} builder. * * @return a new {@code WayPoint} builder */ public static Builder builder() { return new Builder(); } /** * Create a new {@code WayPoint} with the given {@code latitude} and * {@code longitude} value. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @return a new {@code WayPoint} * @throws NullPointerException if one of the given arguments is {@code null} */ public static WayPoint of(final Latitude latitude, final Longitude longitude) { return builder().build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given parameters. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @param time the timestamp of the way-point * @return a new {@code WayPoint} * @throws NullPointerException if one of the given arguments is {@code null} */ public static WayPoint of( final Latitude latitude, final Longitude longitude, final ZonedDateTime time ) { return builder().time(time).build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given parameters. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @param elevation the elevation of the point * @param time the timestamp of the way-point * @return a new {@code WayPoint} * @throws NullPointerException if one of the given arguments is {@code null} */ public static WayPoint of( final Latitude latitude, final Longitude longitude, final Length elevation, final ZonedDateTime time ) { return builder() .elevation(elevation) .time(time) .build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given {@code latitude} and * {@code longitude} value. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @return a new {@code WayPoint} * @throws IllegalArgumentException if the given latitude or longitude is not * in the valid range. */ public static WayPoint of(final double latitude, final double longitude) { return builder().build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given parameters. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @param time the timestamp of the way-point * @return a new {@code WayPoint} * @throws IllegalArgumentException if the given latitude or longitude is not * in the valid range. */ public static WayPoint of( final double latitude, final double longitude, final ZonedDateTime time ) { return builder().time(time).build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given parameters. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @param elevation the elevation of the point * @param time the timestamp of the way-point * @return a new {@code WayPoint} * @throws IllegalArgumentException if the given latitude or longitude is not * in the valid range. */ public static WayPoint of( final double latitude, final double longitude, final double elevation, final ZonedDateTime time ) { return builder() .elevation(elevation) .time(time) .build(latitude, longitude); } /* ************************************************************************* * JAXB object serialization * ************************************************************************/ @XmlRootElement(name = "wpt") @XmlType(name = "gpx.WayPoint") @XmlAccessorType(XmlAccessType.FIELD) static final class Model { @XmlAttribute(name = "lat", required = true) public double latitude; @XmlAttribute(name = "lon", required = true) public double longitude; @XmlElement(name = "ele") public Double elevation; @XmlElement(name = "speed") public Double speed; @XmlElement(name = "time") public String time; @XmlElement(name = "magvar") public Double magvar; @XmlElement(name = "geoidheight") public Double geoidheight; @XmlElement(name = "name") public String name; @XmlElement(name = "cmt") public String cmt; @XmlElement(name = "desc") public String desc; @XmlElement(name = "src") public String src; @XmlElement(name = "link") public List<Link.Model> link; @XmlElement(name = "sym") public String sym; @XmlElement(name = "type") public String type; @XmlElement(name = "fix") public String fix; @XmlElement(name = "sat") public Integer sat; @XmlElement(name = "hdop") public Double hdop; @XmlElement(name = "vdop") public Double vdop; @XmlElement(name = "pdop") public Double pdop; @XmlElement(name = "ageofdgpsdata") public Double ageofdgpsdata; @XmlElement(name = "dgpsid") public Integer dgpsid; public static final class Adapter extends XmlAdapter<Model, WayPoint> { private static final DateTimeFormatter DTF = DateTimeFormatter.ISO_INSTANT; @Override public WayPoint.Model marshal(final WayPoint point) { final WayPoint.Model model = new WayPoint.Model(); model.latitude = point.getLatitude().doubleValue(); model.longitude = point.getLongitude().doubleValue(); model.elevation = point.getElevation() .map(Length::doubleValue) .orElse(null); model.speed = point.getSpeed() .map(Speed::doubleValue) .orElse(null); model.time = point.getTime() .map(DTF::format) .orElse(null); model.magvar = point.getMagneticVariation() .map(Degrees::doubleValue) .orElse(null); model.geoidheight = point.getGeoidHeight() .map(Length::doubleValue) .orElse(null); model.name = point.getName().orElse(null); model.cmt = point.getComment().orElse(null); model.src = point.getSource().orElse(null); model.link = point.getLinks() .map(Link.Model.ADAPTER::marshal) .asList(); model.sym = point.getSymbol().orElse(null); model.type = point.getType().orElse(null); model.fix = point.getFix() .map(Fix::getValue) .orElse(null); model.sat = point.getSat() .map(UInt::getValue) .orElse(null); model.hdop = point.getHdop().orElse(null); model.vdop = point.getVdop().orElse(null); model.pdop = point.getPdop().orElse(null); model.ageofdgpsdata = point.getAgeOfGPSData() .map(d -> d.toMillis()/1000.0) .orElse(null); model.dgpsid = point.getDGPSID() .map(DGPSStation::intValue) .orElse(null); return model; } @Override public WayPoint unmarshal(final WayPoint.Model model) { return new WayPoint( Latitude.of(model.latitude), Longitude.of(model.longitude), Optional.ofNullable(model.elevation) .map(Length::ofMeters) .orElse(null), Optional.ofNullable(model.speed) .map(Speed::of) .orElse(null), Optional.ofNullable(model.time) .map(t -> ZonedDateTime.parse(t, DTF)) .orElse(null), Optional.ofNullable(model.magvar) .map(Degrees::of) .orElse(null), Optional.ofNullable(model.geoidheight) .map(Length::ofMeters) .orElse(null), model.name, model.cmt, model.desc, model.src, model.link.stream() .map(Link.Model.ADAPTER::unmarshal) .collect(ISeq.toISeq()), model.sym, model.type, Optional.ofNullable(model.fix) .flatMap(Fix::of) .orElse(null), Optional.ofNullable(model.sat) .map(UInt::of) .orElse(null), model.hdop, model.vdop, model.pdop, Optional.ofNullable(model.ageofdgpsdata) .map(d -> Duration.ofMillis((long)(d*1000.0))) .orElse(null), Optional.ofNullable(model.dgpsid) .map(DGPSStation::of) .orElse(null) ); } } public static final Adapter ADAPTER = new Adapter(); } }
org.jenetics.example/src/main/java/org/jenetics/example/tsp/gpx/WayPoint.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.example.tsp.gpx; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import java.io.Serializable; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.jenetics.util.ISeq; /** * A {@code WayPoint} represents a way-point, point of interest, or named * feature on a map. * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @version !__version__! * @since !__version__! */ @XmlJavaTypeAdapter(WayPoint.Model.Adapter.class) public final class WayPoint implements Point, Serializable { private static final long serialVersionUID = 1L; private final Latitude _latitude; private final Longitude _longitude; private final Length _elevation; private final Speed _speed; private final ZonedDateTime _time; private final Degrees _magneticVariation; private final Length _geoidHeight; private final String _name; private final String _comment; private final String _description; private final String _source; private final ISeq<Link> _links; private final String _symbol; private final String _type; private final Fix _fix; private final UInt _sat; private final Double _hdop; private final Double _vdop; private final Double _pdop; private final Duration _ageOfGPSData; private final DGPSStation _dgpsID; /** * Create a new way-point with the given parameter. * * @param latitude the latitude of the point, WGS84 datum (mandatory) * @param longitude the longitude of the point, WGS84 datum (mandatory) * @param elevation the elevation (in meters) of the point (optional) * @param speed the current GPS speed (optional) * @param time creation/modification timestamp for element. Conforms to ISO * 8601 specification for date/time representation. Fractional seconds * are allowed for millisecond timing in tracklogs. (optional) * @param magneticVariation the magnetic variation at the point (optional) * @param geoidHeight height (in meters) of geoid (mean sea level) above * WGS84 earth ellipsoid. As defined in NMEA GGA message. (optional) * @param name the GPS name of the way-point. This field will be transferred * to and from the GPS. GPX does not place restrictions on the length * of this field or the characters contained in it. It is up to the * receiving application to validate the field before sending it to * the GPS. (optional) * @param comment GPS way-point comment. Sent to GPS as comment (optional) * @param description a text description of the element. Holds additional * information about the element intended for the user, not the GPS. * (optional) * @param source source of data. Included to give user some idea of * reliability and accuracy of data. "Garmin eTrex", "USGS quad * Boston North", e.g. (optional) * @param links links to additional information about the way-point. May be * empty, but not {@code null}. * @param symbol text of GPS symbol name. For interchange with other * programs, use the exact spelling of the symbol as displayed on the * GPS. If the GPS abbreviates words, spell them out. (optional) * @param type type (classification) of the way-point (optional) * @param fix type of GPX fix (optional) * @param sat number of satellites used to calculate the GPX fix (optional) * @param hdop horizontal dilution of precision (optional) * @param vdop vertical dilution of precision (optional) * @param pdop position dilution of precision. (optional) * @param ageOfGPSData number of seconds since last DGPS update (optional) * @param dgpsID ID of DGPS station used in differential correction (optional) */ private WayPoint( final Latitude latitude, final Longitude longitude, final Length elevation, final Speed speed, final ZonedDateTime time, final Degrees magneticVariation, final Length geoidHeight, final String name, final String comment, final String description, final String source, final ISeq<Link> links, final String symbol, final String type, final Fix fix, final UInt sat, final Double hdop, final Double vdop, final Double pdop, final Duration ageOfGPSData, final DGPSStation dgpsID ) { _latitude = requireNonNull(latitude); _longitude = requireNonNull(longitude); _elevation = elevation; _speed = speed; _time = time; _magneticVariation = magneticVariation; _geoidHeight = geoidHeight; _name = name; _comment = comment; _description = description; _source = source; _links = requireNonNull(links); _symbol = symbol; _type = type; _fix = fix; _sat = sat; _hdop = hdop; _vdop = vdop; _pdop = pdop; _ageOfGPSData = ageOfGPSData; _dgpsID = dgpsID; } @Override public Latitude getLatitude() { return _latitude; } @Override public Longitude getLongitude() { return _longitude; } @Override public Optional<Length> getElevation() { return Optional.ofNullable(_elevation); } /** * The current GPS speed. * * @return the current GPS speed */ public Optional<Speed> getSpeed() { return Optional.ofNullable(_speed); } @Override public Optional<ZonedDateTime> getTime() { return Optional.ofNullable(_time); } /** * The magnetic variation at the point. * * @return the magnetic variation at the point */ public Optional<Degrees> getMagneticVariation() { return Optional.ofNullable(_magneticVariation); } /** * The height (in meters) of geoid (mean sea level) above WGS84 earth * ellipsoid. As defined in NMEA GGA message. * * @return the height (in meters) of geoid (mean sea level) above WGS84 * earth ellipsoid */ public Optional<Length> getGeoidHeight() { return Optional.ofNullable(_geoidHeight); } /** * The GPS name of the way-point. This field will be transferred to and from * the GPS. GPX does not place restrictions on the length of this field or * the characters contained in it. It is up to the receiving application to * validate the field before sending it to the GPS. * * @return the GPS name of the way-point */ public Optional<String> getName() { return Optional.ofNullable(_name); } /** * The GPS way-point comment. * * @return the GPS way-point comment */ public Optional<String> getComment() { return Optional.ofNullable(_comment); } /** * Return a text description of the element. Holds additional information * about the element intended for the user, not the GPS. * * @return a text description of the element */ public Optional<String> getDescription() { return Optional.ofNullable(_description); } /** * Return the source of data. Included to give user some idea of reliability * and accuracy of data. "Garmin eTrex", "USGS quad Boston North", e.g. * * @return the source of the data */ public Optional<String> getSource() { return Optional.ofNullable(_source); } /** * Return the links to additional information about the way-point. * * @return the links to additional information about the way-point */ public ISeq<Link> getLinks() { return _links; } /** * Return the text of GPS symbol name. For interchange with other programs, * use the exact spelling of the symbol as displayed on the GPS. If the GPS * abbreviates words, spell them out. * * @return the text of GPS symbol name */ public Optional<String> getSymbol() { return Optional.ofNullable(_symbol); } /** * Return the type (classification) of the way-point. * * @return the type (classification) of the way-point */ public Optional<String> getType() { return Optional.ofNullable(_type); } /** * Return the type of GPX fix. * * @return the type of GPX fix */ public Optional<Fix> getFix() { return Optional.ofNullable(_fix); } /** * Return the number of satellites used to calculate the GPX fix. * * @return the number of satellites used to calculate the GPX fix */ public Optional<UInt> getSat() { return Optional.ofNullable(_sat); } /** * Return the horizontal dilution of precision. * * @return the horizontal dilution of precision */ public Optional<Double> getHdop() { return Optional.ofNullable(_hdop); } /** * Return the vertical dilution of precision. * * @return the vertical dilution of precision */ public Optional<Double> getVdop() { return Optional.ofNullable(_vdop); } /** * Return the position dilution of precision. * * @return the position dilution of precision */ public Optional<Double> getPdop() { return Optional.ofNullable(_pdop); } /** * Return the number of seconds since last DGPS update. * * @return number of seconds since last DGPS update */ public Optional<Duration> getAgeOfGPSData() { return Optional.ofNullable(_ageOfGPSData); } /** * Return the ID of DGPS station used in differential correction. * * @return the ID of DGPS station used in differential correction */ public Optional<DGPSStation> getDGPSID() { return Optional.ofNullable(_dgpsID); } @Override public int hashCode() { int hash = 37; hash += 17*_latitude.hashCode() + 31; hash += 17*_longitude.hashCode() + 31; hash += 17*Objects.hashCode(_elevation) + 31; hash += 17*Objects.hashCode(_speed) + 31; hash += 17*Objects.hashCode(_time) + 31; hash += 17*Objects.hashCode(_magneticVariation) + 31; hash += 17*Objects.hashCode(_geoidHeight) + 31; hash += 17*Objects.hashCode(_name) + 31; hash += 17*Objects.hashCode(_comment) + 31; hash += 17*Objects.hashCode(_description) + 31; hash += 17*Objects.hashCode(_source) + 31; hash += 17*Objects.hashCode(_links) + 31; hash += 17*Objects.hashCode(_symbol) + 31; hash += 17*Objects.hashCode(_type) + 31; hash += 17*Objects.hashCode(_fix) + 31; hash += 17*Objects.hashCode(_sat) + 31; hash += 17*Objects.hashCode(_hdop) + 31; hash += 17*Objects.hashCode(_vdop) + 31; hash += 17*Objects.hashCode(_pdop) + 31; hash += 17*Objects.hashCode(_ageOfGPSData) + 31; hash += 17*Objects.hashCode(_dgpsID) + 31; return hash; } @Override public boolean equals(final Object obj) { return obj instanceof WayPoint && ((WayPoint)obj)._latitude.equals(_latitude) && ((WayPoint)obj)._longitude.equals(_longitude) && Objects.equals(((WayPoint)obj)._elevation, _elevation) && Objects.equals(((WayPoint)obj)._speed, _speed) && Objects.equals(((WayPoint)obj)._time, _time) && Objects.equals(((WayPoint)obj)._magneticVariation, _magneticVariation) && Objects.equals(((WayPoint)obj)._geoidHeight, _geoidHeight) && Objects.equals(((WayPoint)obj)._name, _name) && Objects.equals(((WayPoint)obj)._comment, _comment) && Objects.equals(((WayPoint)obj)._description, _description) && Objects.equals(((WayPoint)obj)._source, _source) && Objects.equals(((WayPoint)obj)._links, _links) && Objects.equals(((WayPoint)obj)._symbol, _symbol) && Objects.equals(((WayPoint)obj)._type, _type) && Objects.equals(((WayPoint)obj)._fix, _fix) && Objects.equals(((WayPoint)obj)._sat, _sat) && Objects.equals(((WayPoint)obj)._hdop, _hdop) && Objects.equals(((WayPoint)obj)._vdop, _vdop) && Objects.equals(((WayPoint)obj)._pdop, _pdop) && Objects.equals(((WayPoint)obj)._ageOfGPSData, _ageOfGPSData) && Objects.equals(((WayPoint)obj)._dgpsID, _dgpsID); } @Override public String toString() { return format("[lat=%s, lon=%s]", _latitude, _latitude); } /** * Builder for creating a way-point with different parameters. */ public static final class Builder { private Length _elevation; private Speed _speed; private ZonedDateTime _time; private Degrees _magneticVariation; private Length _geoidHeight; private String _name; private String _comment; private String _description; private String _source; private ISeq<Link> _links; private String _symbol; private String _type; private Fix _fix; private UInt _sat; private Double _hdop; private Double _vdop; private Double _pdop; private Duration _ageOfDGPSData; private DGPSStation _dgpsID; /** * Set the elevation of the point. * * @param elevation the elevation of the point * @return {@code this} {@code Builder} for method chaining */ public Builder elevation(final Length elevation) { _elevation = elevation; return this; } /** * Set the elevation (in meters) of the point. * * @param meters the elevation of the point, in meters * @return {@code this} {@code Builder} for method chaining */ public Builder elevation(final double meters) { _elevation = Length.ofMeters(meters); return this; } /** * Set the current GPS speed. * * @param speed the current GPS speed * @return {@code this} {@code Builder} for method chaining */ public Builder speed(final Speed speed) { _speed = speed; return this; } /** * Set the current GPS speed. * * @param meterPerSecond the current GPS speed in m/s * @return {@code this} {@code Builder} for method chaining */ public Builder speed(final double meterPerSecond) { _speed = Speed.of(meterPerSecond); return this; } /** * Set the creation/modification timestamp for the point. * * @param time the creation/modification timestamp for the point * @return {@code this} {@code Builder} for method chaining */ public Builder time(final ZonedDateTime time) { _time = time; return this; } /** * Set the magnetic variation at the point. * * @param variation the magnetic variation * @return {@code this} {@code Builder} for method chaining */ public Builder magneticVariation(final Degrees variation) { _magneticVariation = variation; return this; } /** * Set the magnetic variation at the point. * * @param variation the magnetic variation * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the give value is not within the * range of {@code [0..360]} */ public Builder magneticVariation(final double variation) { _magneticVariation = Degrees.of(variation); return this; } /** * Set the height (in meters) of geoid (mean sea level) above WGS84 earth * ellipsoid. As defined in NMEA GGA message. * * @param geoidHeight the height (in meters) of geoid (mean sea level) * above WGS84 earth ellipsoid * @return {@code this} {@code Builder} for method chaining */ public Builder geoidHeight(final Length geoidHeight) { _geoidHeight = geoidHeight; return this; } /** * Set the GPS name of the way-point. This field will be transferred to * and from the GPS. GPX does not place restrictions on the length of * this field or the characters contained in it. It is up to the * receiving application to validate the field before sending it to the * GPS. * * @param name the GPS name of the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder name(final String name) { _name = name; return this; } /** * Set the GPS way-point comment. * * @param comment the GPS way-point comment. * @return {@code this} {@code Builder} for method chaining */ public Builder comment(final String comment) { _comment = comment; return this; } /** * Set the links to additional information about the way-point. * * @param links the links to additional information about the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder links(final ISeq<Link> links) { _links = links; return this; } /** * Set the text of GPS symbol name. For interchange with other programs, * use the exact spelling of the symbol as displayed on the GPS. If the * GPS abbreviates words, spell them out. * * @param symbol the text of GPS symbol name * @return {@code this} {@code Builder} for method chaining */ public Builder symbol(final String symbol) { _symbol = symbol; return this; } /** * Set the type (classification) of the way-point. * * @param type the type (classification) of the way-point * @return {@code this} {@code Builder} for method chaining */ public Builder type(final String type) { _type = type; return this; } /** * Set the type of GPX fix. * * @param fix the type of GPX fix * @return {@code this} {@code Builder} for method chaining */ public Builder fix(final Fix fix) { _fix = fix; return this; } /** * Set the number of satellites used to calculate the GPX fix. * * @param sat the number of satellites used to calculate the GPX fix * @return {@code this} {@code Builder} for method chaining */ public Builder sat(final UInt sat) { _sat = sat; return this; } /** * Set the number of satellites used to calculate the GPX fix. * * @param sat the number of satellites used to calculate the GPX fix * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the given {@code value} is smaller * than zero */ public Builder sat(final int sat) { _sat = UInt.of(sat); return this; } /** * Set the horizontal dilution of precision. * * @param hdop the horizontal dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder hdop(final Double hdop) { _hdop = hdop; return this; } /** * Set the vertical dilution of precision. * * @param vdop the vertical dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder vdop(final Double vdop) { _vdop = vdop; return this; } /** * Set the position dilution of precision. * * @param pdop the position dilution of precision * @return {@code this} {@code Builder} for method chaining */ public Builder pdop(final Double pdop) { _pdop = pdop; return this; } /** * Set the age since last DGPS update. * * @param age the age since last DGPS update * @return {@code this} {@code Builder} for method chaining */ public Builder ageOfDGPSAge(final Duration age) { _ageOfDGPSData = age; return this; } /** * Set the number of seconds since last DGPS update. * * @param seconds the age since last DGPS update * @return {@code this} {@code Builder} for method chaining */ public Builder ageOfDGPSAge(final double seconds) { _ageOfDGPSData = Duration.ofMillis((long)(seconds/1000.0)); return this; } /** * Set the ID of DGPS station used in differential correction. * * @param station the ID of DGPS station used in differential correction * @return {@code this} {@code Builder} for method chaining */ public Builder dgpsStation(final DGPSStation station) { _dgpsID = station; return this; } /** * Set the ID of DGPS station used in differential correction. * * @param station the ID of DGPS station used in differential correction * @return {@code this} {@code Builder} for method chaining * @throws IllegalArgumentException if the given station number is not in the * range of {@code [0..1023]} */ public Builder dgpsStation(final int station) { _dgpsID = DGPSStation.of(station); return this; } /** * Create a new way-point with the given latitude and longitude value. * * @param latitude the latitude of the way-point * @param longitude the longitude of the way-point * @return a newly created way-point */ public WayPoint build(final Latitude latitude, final Longitude longitude) { return new WayPoint( latitude, longitude, _elevation, _speed, _time, _magneticVariation, _geoidHeight, _name, _comment, _description, _source, _links != null ? _links : ISeq.empty(), _symbol, _type, _fix, _sat, _hdop, _vdop, _pdop, _ageOfDGPSData, _dgpsID ); } /** * Create a new way-point with the given latitude and longitude value. * * @param latitude the latitude of the way-point * @param longitude the longitude of the way-point * @return a newly created way-point */ public WayPoint build(final double latitude, final double longitude) { return build(Latitude.of(latitude), Longitude.of(longitude)); } } /* ************************************************************************* * Static object creation methods * ************************************************************************/ /** * Return a new {@code WayPoint} builder. * * @return a new {@code WayPoint} builder */ public static Builder builder() { return new Builder(); } /** * Create a new {@code WayPoint} with the given {@code latitude} and * {@code longitude} value. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @return a new {@code WayPoint} * @throws NullPointerException if one of the given arguments is {@code null} */ public static WayPoint of(final Latitude latitude, final Longitude longitude) { return builder().build(latitude, longitude); } /** * Create a new {@code WayPoint} with the given {@code latitude} and * {@code longitude} value. * * @param latitude the latitude of the point * @param longitude the longitude of the point * @return a new {@code WayPoint} * @throws IllegalArgumentException if the given latitude or longitude is not * in the valid range. */ public static WayPoint of(final double latitude, final double longitude) { return builder().build(latitude, longitude); } /* ************************************************************************* * JAXB object serialization * ************************************************************************/ @XmlRootElement(name = "wpt") @XmlType(name = "gpx.WayPoint") @XmlAccessorType(XmlAccessType.FIELD) static final class Model { @XmlAttribute(name = "lat", required = true) public double latitude; @XmlAttribute(name = "lon", required = true) public double longitude; @XmlElement(name = "ele") public Double elevation; @XmlElement(name = "speed") public Double speed; @XmlElement(name = "time") public String time; @XmlElement(name = "magvar") public Double magvar; @XmlElement(name = "geoidheight") public Double geoidheight; @XmlElement(name = "name") public String name; @XmlElement(name = "cmt") public String cmt; @XmlElement(name = "desc") public String desc; @XmlElement(name = "src") public String src; @XmlElement(name = "link") public List<Link.Model> link; @XmlElement(name = "sym") public String sym; @XmlElement(name = "type") public String type; @XmlElement(name = "fix") public String fix; @XmlElement(name = "sat") public Integer sat; @XmlElement(name = "hdop") public Double hdop; @XmlElement(name = "vdop") public Double vdop; @XmlElement(name = "pdop") public Double pdop; @XmlElement(name = "ageofdgpsdata") public Double ageofdgpsdata; @XmlElement(name = "dgpsid") public Integer dgpsid; public static final class Adapter extends XmlAdapter<Model, WayPoint> { private static final DateTimeFormatter DTF = DateTimeFormatter.ISO_INSTANT; @Override public WayPoint.Model marshal(final WayPoint point) { final WayPoint.Model model = new WayPoint.Model(); model.latitude = point.getLatitude().doubleValue(); model.longitude = point.getLongitude().doubleValue(); model.elevation = point.getElevation() .map(Length::doubleValue) .orElse(null); model.speed = point.getSpeed() .map(Speed::doubleValue) .orElse(null); model.time = point.getTime() .map(DTF::format) .orElse(null); model.magvar = point.getMagneticVariation() .map(Degrees::doubleValue) .orElse(null); model.geoidheight = point.getGeoidHeight() .map(Length::doubleValue) .orElse(null); model.name = point.getName().orElse(null); model.cmt = point.getComment().orElse(null); model.src = point.getSource().orElse(null); model.link = point.getLinks() .map(Link.Model.ADAPTER::marshal) .asList(); model.sym = point.getSymbol().orElse(null); model.type = point.getType().orElse(null); model.fix = point.getFix() .map(Fix::getValue) .orElse(null); model.sat = point.getSat() .map(UInt::getValue) .orElse(null); model.hdop = point.getHdop().orElse(null); model.vdop = point.getVdop().orElse(null); model.pdop = point.getPdop().orElse(null); model.ageofdgpsdata = point.getAgeOfGPSData() .map(d -> d.toMillis()/1000.0) .orElse(null); model.dgpsid = point.getDGPSID() .map(DGPSStation::intValue) .orElse(null); return model; } @Override public WayPoint unmarshal(final WayPoint.Model model) { return new WayPoint( Latitude.of(model.latitude), Longitude.of(model.longitude), Optional.ofNullable(model.elevation) .map(Length::ofMeters) .orElse(null), Optional.ofNullable(model.speed) .map(Speed::of) .orElse(null), Optional.ofNullable(model.time) .map(t -> ZonedDateTime.parse(t, DTF)) .orElse(null), Optional.ofNullable(model.magvar) .map(Degrees::of) .orElse(null), Optional.ofNullable(model.geoidheight) .map(Length::ofMeters) .orElse(null), model.name, model.cmt, model.desc, model.src, model.link.stream() .map(Link.Model.ADAPTER::unmarshal) .collect(ISeq.toISeq()), model.sym, model.type, Optional.ofNullable(model.fix) .flatMap(Fix::of) .orElse(null), Optional.ofNullable(model.sat) .map(UInt::of) .orElse(null), model.hdop, model.vdop, model.pdop, Optional.ofNullable(model.ageofdgpsdata) .map(d -> Duration.ofMillis((long)(d*1000.0))) .orElse(null), Optional.ofNullable(model.dgpsid) .map(DGPSStation::of) .orElse(null) ); } } public static final Adapter ADAPTER = new Adapter(); } }
Add additional factory methods.
org.jenetics.example/src/main/java/org/jenetics/example/tsp/gpx/WayPoint.java
Add additional factory methods.
Java
apache-2.0
41ad27b8be1cebc0685497fbee4040e8757c61b3
0
bladecoder/libgdx,nooone/libgdx,FyiurAmron/libgdx,codepoke/libgdx,hyvas/libgdx,stickyd/libgdx,jsjolund/libgdx,ninoalma/libgdx,antag99/libgdx,ricardorigodon/libgdx,kagehak/libgdx,alex-dorokhov/libgdx,del-sol/libgdx,stickyd/libgdx,bsmr-java/libgdx,ThiagoGarciaAlves/libgdx,petugez/libgdx,djom20/libgdx,Badazdz/libgdx,haedri/libgdx-1,1yvT0s/libgdx,MovingBlocks/libgdx,davebaol/libgdx,czyzby/libgdx,kzganesan/libgdx,Dzamir/libgdx,basherone/libgdxcn,fiesensee/libgdx,curtiszimmerman/libgdx,fiesensee/libgdx,309746069/libgdx,noelsison2/libgdx,FyiurAmron/libgdx,309746069/libgdx,tell10glu/libgdx,realitix/libgdx,Heart2009/libgdx,codepoke/libgdx,azakhary/libgdx,copystudy/libgdx,NathanSweet/libgdx,ninoalma/libgdx,thepullman/libgdx,curtiszimmerman/libgdx,MetSystem/libgdx,kotcrab/libgdx,copystudy/libgdx,gdos/libgdx,revo09/libgdx,djom20/libgdx,revo09/libgdx,jasonwee/libgdx,yangweigbh/libgdx,billgame/libgdx,sarkanyi/libgdx,mumer92/libgdx,ryoenji/libgdx,MikkelTAndersen/libgdx,del-sol/libgdx,SidneyXu/libgdx,ThiagoGarciaAlves/libgdx,copystudy/libgdx,katiepino/libgdx,bgroenks96/libgdx,azakhary/libgdx,zhimaijoy/libgdx,SidneyXu/libgdx,MetSystem/libgdx,snovak/libgdx,MovingBlocks/libgdx,yangweigbh/libgdx,GreenLightning/libgdx,jberberick/libgdx,FredGithub/libgdx,yangweigbh/libgdx,petugez/libgdx,ryoenji/libgdx,petugez/libgdx,bgroenks96/libgdx,MetSystem/libgdx,alex-dorokhov/libgdx,katiepino/libgdx,ricardorigodon/libgdx,BlueRiverInteractive/libgdx,js78/libgdx,thepullman/libgdx,katiepino/libgdx,MovingBlocks/libgdx,Zomby2D/libgdx,MovingBlocks/libgdx,nrallakis/libgdx,zhimaijoy/libgdx,nave966/libgdx,ya7lelkom/libgdx,shiweihappy/libgdx,Arcnor/libgdx,1yvT0s/libgdx,ricardorigodon/libgdx,Zonglin-Li6565/libgdx,youprofit/libgdx,MadcowD/libgdx,anserran/libgdx,xranby/libgdx,1yvT0s/libgdx,MikkelTAndersen/libgdx,Thotep/libgdx,Wisienkas/libgdx,Heart2009/libgdx,firefly2442/libgdx,srwonka/libGdx,FyiurAmron/libgdx,tommyettinger/libgdx,Xhanim/libgdx,toloudis/libgdx,saqsun/libgdx,bgroenks96/libgdx,Gliby/libgdx,revo09/libgdx,FredGithub/libgdx,309746069/libgdx,ttencate/libgdx,MadcowD/libgdx,toa5/libgdx,billgame/libgdx,SidneyXu/libgdx,UnluckyNinja/libgdx,sarkanyi/libgdx,kotcrab/libgdx,antag99/libgdx,samskivert/libgdx,alireza-hosseini/libgdx,bgroenks96/libgdx,ztv/libgdx,alireza-hosseini/libgdx,sjosegarcia/libgdx,ya7lelkom/libgdx,1yvT0s/libgdx,nelsonsilva/libgdx,toloudis/libgdx,zommuter/libgdx,firefly2442/libgdx,collinsmith/libgdx,MadcowD/libgdx,haedri/libgdx-1,ya7lelkom/libgdx,antag99/libgdx,srwonka/libGdx,sinistersnare/libgdx,stinsonga/libgdx,luischavez/libgdx,haedri/libgdx-1,snovak/libgdx,collinsmith/libgdx,yangweigbh/libgdx,del-sol/libgdx,alex-dorokhov/libgdx,petugez/libgdx,petugez/libgdx,petugez/libgdx,saqsun/libgdx,josephknight/libgdx,cypherdare/libgdx,SidneyXu/libgdx,TheAks999/libgdx,haedri/libgdx-1,anserran/libgdx,sjosegarcia/libgdx,sarkanyi/libgdx,andyvand/libgdx,stickyd/libgdx,Dzamir/libgdx,Gliby/libgdx,ricardorigodon/libgdx,junkdog/libgdx,revo09/libgdx,EsikAntony/libgdx,Dzamir/libgdx,fiesensee/libgdx,tell10glu/libgdx,petugez/libgdx,xoppa/libgdx,anserran/libgdx,stickyd/libgdx,bsmr-java/libgdx,fiesensee/libgdx,kagehak/libgdx,xpenatan/libgdx-LWJGL3,sjosegarcia/libgdx,ThiagoGarciaAlves/libgdx,Gliby/libgdx,flaiker/libgdx,saltares/libgdx,Thotep/libgdx,kotcrab/libgdx,del-sol/libgdx,gf11speed/libgdx,alex-dorokhov/libgdx,EsikAntony/libgdx,EsikAntony/libgdx,tommyettinger/libgdx,shiweihappy/libgdx,flaiker/libgdx,ryoenji/libgdx,ninoalma/libgdx,snovak/libgdx,Senth/libgdx,nudelchef/libgdx,shiweihappy/libgdx,xranby/libgdx,libgdx/libgdx,ztv/libgdx,JFixby/libgdx,kzganesan/libgdx,nave966/libgdx,Deftwun/libgdx,Zomby2D/libgdx,ricardorigodon/libgdx,lordjone/libgdx,Thotep/libgdx,firefly2442/libgdx,SidneyXu/libgdx,tommycli/libgdx,Zonglin-Li6565/libgdx,mumer92/libgdx,JFixby/libgdx,nelsonsilva/libgdx,bgroenks96/libgdx,antag99/libgdx,billgame/libgdx,thepullman/libgdx,thepullman/libgdx,zommuter/libgdx,fwolff/libgdx,309746069/libgdx,titovmaxim/libgdx,Zomby2D/libgdx,Badazdz/libgdx,nudelchef/libgdx,KrisLee/libgdx,titovmaxim/libgdx,alireza-hosseini/libgdx,czyzby/libgdx,NathanSweet/libgdx,basherone/libgdxcn,saqsun/libgdx,PedroRomanoBarbosa/libgdx,saltares/libgdx,sjosegarcia/libgdx,sarkanyi/libgdx,ThiagoGarciaAlves/libgdx,czyzby/libgdx,toloudis/libgdx,PedroRomanoBarbosa/libgdx,nooone/libgdx,saltares/libgdx,del-sol/libgdx,antag99/libgdx,fwolff/libgdx,katiepino/libgdx,codepoke/libgdx,PedroRomanoBarbosa/libgdx,tommycli/libgdx,jberberick/libgdx,nudelchef/libgdx,ttencate/libgdx,azakhary/libgdx,Wisienkas/libgdx,srwonka/libGdx,saltares/libgdx,realitix/libgdx,srwonka/libGdx,gouessej/libgdx,haedri/libgdx-1,FredGithub/libgdx,mumer92/libgdx,ztv/libgdx,toloudis/libgdx,Xhanim/libgdx,curtiszimmerman/libgdx,lordjone/libgdx,mumer92/libgdx,BlueRiverInteractive/libgdx,junkdog/libgdx,JDReutt/libgdx,toa5/libgdx,NathanSweet/libgdx,Gliby/libgdx,ThiagoGarciaAlves/libgdx,josephknight/libgdx,Thotep/libgdx,billgame/libgdx,lordjone/libgdx,gf11speed/libgdx,fiesensee/libgdx,ttencate/libgdx,GreenLightning/libgdx,tommyettinger/libgdx,Senth/libgdx,srwonka/libGdx,noelsison2/libgdx,petugez/libgdx,del-sol/libgdx,ztv/libgdx,MikkelTAndersen/libgdx,BlueRiverInteractive/libgdx,revo09/libgdx,MikkelTAndersen/libgdx,Senth/libgdx,gdos/libgdx,Arcnor/libgdx,bladecoder/libgdx,libgdx/libgdx,samskivert/libgdx,ricardorigodon/libgdx,revo09/libgdx,haedri/libgdx-1,tell10glu/libgdx,alex-dorokhov/libgdx,Badazdz/libgdx,fwolff/libgdx,copystudy/libgdx,PedroRomanoBarbosa/libgdx,KrisLee/libgdx,ttencate/libgdx,ttencate/libgdx,fiesensee/libgdx,kzganesan/libgdx,Senth/libgdx,alireza-hosseini/libgdx,stickyd/libgdx,kotcrab/libgdx,sinistersnare/libgdx,tommycli/libgdx,lordjone/libgdx,toloudis/libgdx,kzganesan/libgdx,saltares/libgdx,MetSystem/libgdx,firefly2442/libgdx,GreenLightning/libgdx,cypherdare/libgdx,Deftwun/libgdx,gouessej/libgdx,jberberick/libgdx,alireza-hosseini/libgdx,designcrumble/libgdx,nelsonsilva/libgdx,realitix/libgdx,nelsonsilva/libgdx,FredGithub/libgdx,kzganesan/libgdx,nrallakis/libgdx,designcrumble/libgdx,Deftwun/libgdx,tommyettinger/libgdx,ztv/libgdx,noelsison2/libgdx,ninoalma/libgdx,Zonglin-Li6565/libgdx,samskivert/libgdx,tell10glu/libgdx,copystudy/libgdx,xranby/libgdx,kzganesan/libgdx,junkdog/libgdx,nrallakis/libgdx,ya7lelkom/libgdx,curtiszimmerman/libgdx,MetSystem/libgdx,Gliby/libgdx,sarkanyi/libgdx,KrisLee/libgdx,xpenatan/libgdx-LWJGL3,cypherdare/libgdx,JFixby/libgdx,alex-dorokhov/libgdx,xoppa/libgdx,js78/libgdx,youprofit/libgdx,SidneyXu/libgdx,Heart2009/libgdx,hyvas/libgdx,nudelchef/libgdx,Heart2009/libgdx,libgdx/libgdx,titovmaxim/libgdx,EsikAntony/libgdx,JFixby/libgdx,shiweihappy/libgdx,tommycli/libgdx,thepullman/libgdx,nooone/libgdx,thepullman/libgdx,flaiker/libgdx,zommuter/libgdx,mumer92/libgdx,Arcnor/libgdx,xranby/libgdx,realitix/libgdx,jsjolund/libgdx,Deftwun/libgdx,xpenatan/libgdx-LWJGL3,KrisLee/libgdx,zhimaijoy/libgdx,bgroenks96/libgdx,Zonglin-Li6565/libgdx,snovak/libgdx,ztv/libgdx,andyvand/libgdx,antag99/libgdx,MathieuDuponchelle/gdx,realitix/libgdx,Badazdz/libgdx,ryoenji/libgdx,billgame/libgdx,Xhanim/libgdx,ya7lelkom/libgdx,toloudis/libgdx,xpenatan/libgdx-LWJGL3,davebaol/libgdx,kotcrab/libgdx,PedroRomanoBarbosa/libgdx,luischavez/libgdx,toa5/libgdx,ya7lelkom/libgdx,PedroRomanoBarbosa/libgdx,del-sol/libgdx,ninoalma/libgdx,nrallakis/libgdx,jasonwee/libgdx,youprofit/libgdx,noelsison2/libgdx,fwolff/libgdx,designcrumble/libgdx,JFixby/libgdx,curtiszimmerman/libgdx,Xhanim/libgdx,yangweigbh/libgdx,samskivert/libgdx,TheAks999/libgdx,Deftwun/libgdx,stickyd/libgdx,Gliby/libgdx,mumer92/libgdx,czyzby/libgdx,xoppa/libgdx,Xhanim/libgdx,stinsonga/libgdx,gouessej/libgdx,azakhary/libgdx,ricardorigodon/libgdx,Arcnor/libgdx,Senth/libgdx,djom20/libgdx,xpenatan/libgdx-LWJGL3,Deftwun/libgdx,lordjone/libgdx,revo09/libgdx,309746069/libgdx,fwolff/libgdx,czyzby/libgdx,toa5/libgdx,ThiagoGarciaAlves/libgdx,tommycli/libgdx,ttencate/libgdx,snovak/libgdx,sjosegarcia/libgdx,tell10glu/libgdx,fwolff/libgdx,basherone/libgdxcn,azakhary/libgdx,JFixby/libgdx,titovmaxim/libgdx,cypherdare/libgdx,andyvand/libgdx,shiweihappy/libgdx,alex-dorokhov/libgdx,flaiker/libgdx,saqsun/libgdx,309746069/libgdx,copystudy/libgdx,Wisienkas/libgdx,Thotep/libgdx,NathanSweet/libgdx,shiweihappy/libgdx,hyvas/libgdx,luischavez/libgdx,junkdog/libgdx,srwonka/libGdx,JDReutt/libgdx,tell10glu/libgdx,srwonka/libGdx,sarkanyi/libgdx,djom20/libgdx,Deftwun/libgdx,andyvand/libgdx,andyvand/libgdx,saltares/libgdx,srwonka/libGdx,noelsison2/libgdx,xpenatan/libgdx-LWJGL3,xoppa/libgdx,codepoke/libgdx,bgroenks96/libgdx,designcrumble/libgdx,MathieuDuponchelle/gdx,jberberick/libgdx,js78/libgdx,nelsonsilva/libgdx,samskivert/libgdx,libgdx/libgdx,thepullman/libgdx,BlueRiverInteractive/libgdx,toa5/libgdx,youprofit/libgdx,josephknight/libgdx,Zonglin-Li6565/libgdx,nudelchef/libgdx,MikkelTAndersen/libgdx,jasonwee/libgdx,hyvas/libgdx,toa5/libgdx,katiepino/libgdx,ryoenji/libgdx,fwolff/libgdx,Zonglin-Li6565/libgdx,antag99/libgdx,anserran/libgdx,BlueRiverInteractive/libgdx,samskivert/libgdx,jasonwee/libgdx,nave966/libgdx,Zomby2D/libgdx,jasonwee/libgdx,samskivert/libgdx,snovak/libgdx,gf11speed/libgdx,titovmaxim/libgdx,MathieuDuponchelle/gdx,Dzamir/libgdx,bsmr-java/libgdx,Zomby2D/libgdx,firefly2442/libgdx,FredGithub/libgdx,ztv/libgdx,kagehak/libgdx,hyvas/libgdx,bgroenks96/libgdx,jberberick/libgdx,GreenLightning/libgdx,basherone/libgdxcn,realitix/libgdx,nrallakis/libgdx,js78/libgdx,basherone/libgdxcn,flaiker/libgdx,alireza-hosseini/libgdx,nudelchef/libgdx,stickyd/libgdx,stinsonga/libgdx,sjosegarcia/libgdx,PedroRomanoBarbosa/libgdx,js78/libgdx,GreenLightning/libgdx,FredGithub/libgdx,czyzby/libgdx,1yvT0s/libgdx,stinsonga/libgdx,ricardorigodon/libgdx,UnluckyNinja/libgdx,josephknight/libgdx,MadcowD/libgdx,jsjolund/libgdx,Senth/libgdx,Gliby/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,haedri/libgdx-1,thepullman/libgdx,MetSystem/libgdx,Xhanim/libgdx,kagehak/libgdx,samskivert/libgdx,UnluckyNinja/libgdx,davebaol/libgdx,TheAks999/libgdx,alex-dorokhov/libgdx,gouessej/libgdx,Senth/libgdx,JDReutt/libgdx,KrisLee/libgdx,shiweihappy/libgdx,saltares/libgdx,MadcowD/libgdx,bsmr-java/libgdx,codepoke/libgdx,ryoenji/libgdx,Thotep/libgdx,MovingBlocks/libgdx,luischavez/libgdx,Senth/libgdx,gouessej/libgdx,ryoenji/libgdx,TheAks999/libgdx,bsmr-java/libgdx,sjosegarcia/libgdx,MathieuDuponchelle/gdx,Zonglin-Li6565/libgdx,MathieuDuponchelle/gdx,noelsison2/libgdx,ttencate/libgdx,gouessej/libgdx,copystudy/libgdx,bladecoder/libgdx,junkdog/libgdx,kotcrab/libgdx,basherone/libgdxcn,JFixby/libgdx,fwolff/libgdx,tell10glu/libgdx,EsikAntony/libgdx,cypherdare/libgdx,nave966/libgdx,MovingBlocks/libgdx,luischavez/libgdx,jsjolund/libgdx,nooone/libgdx,junkdog/libgdx,nave966/libgdx,nave966/libgdx,bsmr-java/libgdx,sinistersnare/libgdx,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,Dzamir/libgdx,anserran/libgdx,toa5/libgdx,djom20/libgdx,saqsun/libgdx,FyiurAmron/libgdx,jsjolund/libgdx,nrallakis/libgdx,Dzamir/libgdx,xoppa/libgdx,haedri/libgdx-1,davebaol/libgdx,jberberick/libgdx,curtiszimmerman/libgdx,hyvas/libgdx,lordjone/libgdx,zommuter/libgdx,revo09/libgdx,collinsmith/libgdx,jsjolund/libgdx,ninoalma/libgdx,FyiurAmron/libgdx,SidneyXu/libgdx,xpenatan/libgdx-LWJGL3,1yvT0s/libgdx,Dzamir/libgdx,Wisienkas/libgdx,FyiurAmron/libgdx,gdos/libgdx,stickyd/libgdx,MathieuDuponchelle/gdx,collinsmith/libgdx,titovmaxim/libgdx,lordjone/libgdx,Wisienkas/libgdx,xpenatan/libgdx-LWJGL3,anserran/libgdx,andyvand/libgdx,tommycli/libgdx,SidneyXu/libgdx,josephknight/libgdx,KrisLee/libgdx,ninoalma/libgdx,Dzamir/libgdx,tommyettinger/libgdx,GreenLightning/libgdx,azakhary/libgdx,codepoke/libgdx,gdos/libgdx,MikkelTAndersen/libgdx,JDReutt/libgdx,FyiurAmron/libgdx,copystudy/libgdx,Wisienkas/libgdx,hyvas/libgdx,MathieuDuponchelle/gdx,zommuter/libgdx,FredGithub/libgdx,xoppa/libgdx,GreenLightning/libgdx,nooone/libgdx,saqsun/libgdx,Heart2009/libgdx,nrallakis/libgdx,bsmr-java/libgdx,youprofit/libgdx,gf11speed/libgdx,Badazdz/libgdx,fiesensee/libgdx,Arcnor/libgdx,snovak/libgdx,curtiszimmerman/libgdx,katiepino/libgdx,Badazdz/libgdx,kotcrab/libgdx,TheAks999/libgdx,czyzby/libgdx,lordjone/libgdx,gf11speed/libgdx,zhimaijoy/libgdx,tommycli/libgdx,sarkanyi/libgdx,firefly2442/libgdx,BlueRiverInteractive/libgdx,junkdog/libgdx,309746069/libgdx,MathieuDuponchelle/gdx,zommuter/libgdx,xranby/libgdx,designcrumble/libgdx,JDReutt/libgdx,1yvT0s/libgdx,toloudis/libgdx,collinsmith/libgdx,fiesensee/libgdx,gf11speed/libgdx,Gliby/libgdx,Thotep/libgdx,xranby/libgdx,jasonwee/libgdx,yangweigbh/libgdx,codepoke/libgdx,designcrumble/libgdx,Deftwun/libgdx,xoppa/libgdx,EsikAntony/libgdx,realitix/libgdx,nave966/libgdx,saqsun/libgdx,billgame/libgdx,NathanSweet/libgdx,bladecoder/libgdx,TheAks999/libgdx,Badazdz/libgdx,Heart2009/libgdx,antag99/libgdx,djom20/libgdx,zhimaijoy/libgdx,ya7lelkom/libgdx,ya7lelkom/libgdx,noelsison2/libgdx,MovingBlocks/libgdx,firefly2442/libgdx,JDReutt/libgdx,flaiker/libgdx,davebaol/libgdx,Arcnor/libgdx,firefly2442/libgdx,codepoke/libgdx,tommycli/libgdx,yangweigbh/libgdx,UnluckyNinja/libgdx,nudelchef/libgdx,FyiurAmron/libgdx,MovingBlocks/libgdx,nooone/libgdx,UnluckyNinja/libgdx,billgame/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,Heart2009/libgdx,davebaol/libgdx,xranby/libgdx,Wisienkas/libgdx,sjosegarcia/libgdx,ztv/libgdx,junkdog/libgdx,realitix/libgdx,Thotep/libgdx,xranby/libgdx,jberberick/libgdx,luischavez/libgdx,gouessej/libgdx,yangweigbh/libgdx,kagehak/libgdx,andyvand/libgdx,shiweihappy/libgdx,309746069/libgdx,libgdx/libgdx,zhimaijoy/libgdx,sinistersnare/libgdx,MikkelTAndersen/libgdx,josephknight/libgdx,JFixby/libgdx,saltares/libgdx,djom20/libgdx,MadcowD/libgdx,snovak/libgdx,ttencate/libgdx,bsmr-java/libgdx,mumer92/libgdx,youprofit/libgdx,JDReutt/libgdx,jsjolund/libgdx,bladecoder/libgdx,MetSystem/libgdx,js78/libgdx,anserran/libgdx,kzganesan/libgdx,Wisienkas/libgdx,noelsison2/libgdx,KrisLee/libgdx,collinsmith/libgdx,Zonglin-Li6565/libgdx,ninoalma/libgdx,zhimaijoy/libgdx,josephknight/libgdx,flaiker/libgdx,jasonwee/libgdx,MathieuDuponchelle/gdx,youprofit/libgdx,andyvand/libgdx,collinsmith/libgdx,curtiszimmerman/libgdx,UnluckyNinja/libgdx,titovmaxim/libgdx,sarkanyi/libgdx,Xhanim/libgdx,alireza-hosseini/libgdx,BlueRiverInteractive/libgdx,czyzby/libgdx,katiepino/libgdx,Badazdz/libgdx,UnluckyNinja/libgdx,jsjolund/libgdx,del-sol/libgdx,zhimaijoy/libgdx,gdos/libgdx,anserran/libgdx,collinsmith/libgdx,BlueRiverInteractive/libgdx,FredGithub/libgdx,gf11speed/libgdx,jasonwee/libgdx,luischavez/libgdx,flaiker/libgdx,designcrumble/libgdx,zommuter/libgdx,jberberick/libgdx,1yvT0s/libgdx,Heart2009/libgdx,zommuter/libgdx,billgame/libgdx,GreenLightning/libgdx,nave966/libgdx,nrallakis/libgdx,gdos/libgdx,sinistersnare/libgdx,designcrumble/libgdx,gdos/libgdx,katiepino/libgdx,nudelchef/libgdx,EsikAntony/libgdx,saqsun/libgdx,kagehak/libgdx,MadcowD/libgdx,MetSystem/libgdx,gouessej/libgdx,josephknight/libgdx,js78/libgdx,hyvas/libgdx,ThiagoGarciaAlves/libgdx,PedroRomanoBarbosa/libgdx,titovmaxim/libgdx,kagehak/libgdx,xoppa/libgdx,TheAks999/libgdx,sinistersnare/libgdx,kotcrab/libgdx,tell10glu/libgdx,MadcowD/libgdx,toloudis/libgdx,stinsonga/libgdx,toa5/libgdx,MikkelTAndersen/libgdx,nelsonsilva/libgdx,gf11speed/libgdx,js78/libgdx,Xhanim/libgdx,djom20/libgdx,luischavez/libgdx,KrisLee/libgdx,kagehak/libgdx,TheAks999/libgdx,EsikAntony/libgdx,gdos/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; /** A button with text on it. * * <h2>Functionality</h2> A button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered with * the Button which will be called in case the button was clicked/touched. * * <h2>Layout</h2> The (preferred) width and height of a Button are derrived from the border patches in the background * {@link NinePatch} as well as the bounding box around the multi-line text displayed on the Button. Use * {@link Button#setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set * are to small for the contained text you will see artifacts. * * <h2>Style</h2> A Button is a {@link Widget} displaying a background {@link NinePatch} as well as multi-line text with a * specific font and color. The style is defined via an instance of {@link ButtonStyle}, which can be either done programmatically * or via a {@link Skin}.</p> * * A Button's style definition in a skin XML file should look like this: * * <pre> * {@code * <button name="styleName" * down="downNinePatch" * up="upNinePatch" * font="fontName" * fontColor="colorName"/>/> * } * </pre> * * <ul> * <li>The <code>name</code> attribute defines the name of the style which you can later use with * {@link Skin#newButton(String, String, String)}.</li> * <li>The <code>down</code> attribute references a {@link NinePatch} by name, to be used as the button's background when it is * pressed</li> * <li>The <code>up</code> attribute references a {@link NinePatch} by name, to be used as the button's background when it is not * pressed</li> * <li>The <code>font</code> attribute references a {@link BitmapFont} by name, to be used to render the text on the button</li> * <li>The <code>fontColor</code> attribute references a {@link Color} by name, to be used to render the text on the button</li> * </ul> * * @author mzechner */ public class Button extends Widget { final ButtonStyle style; String text; final TextBounds bounds = new TextBounds(); boolean isPressed = false; ClickListener listener = null; public Button (String text, Skin skin) { this(null, text, skin.getStyle(ButtonStyle.class)); } public Button (String text, ButtonStyle style) { this(null, text, style); } public Button (String name, String text, ButtonStyle style) { super(name, 0, 0); this.style = style; this.text = text; layout(); this.width = prefWidth; this.height = prefHeight; } @Override public void layout () { final BitmapFont font = style.font; final NinePatch downPatch = style.down; bounds.set(font.getMultiLineBounds(text)); prefHeight = downPatch.getTopHeight() + downPatch.getBottomHeight() + bounds.height - font.getDescent() * 2; prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } @Override public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; if (invalidated) layout(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); if (isPressed) downPatch.draw(batch, x, y, width, height); else upPatch.draw(batch, x, y, width, height); float textY = (int)(height * 0.5f) + (int)(bounds.height * 0.5f); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); if(isPressed) font.drawMultiLine(batch, text, x + (int)(width * 0.5f) + style.pressedOffsetX, y + textY + style.pressedOffsetY, 0, HAlignment.CENTER); else font.drawMultiLine(batch, text, x + (int)(width * 0.5f) + style.unpressedOffsetX, y + textY + style.unpressedOffsetY, 0, HAlignment.CENTER); } @Override public boolean touchDown (float x, float y, int pointer) { if (pointer != 0) return false; isPressed = true; return true; } @Override public void touchUp (float x, float y, int pointer) { if (listener != null && hit(x, y) != null) listener.click(this); isPressed = false; } @Override public void touchDragged (float x, float y, int pointer) { } /** Sets the multi-line label text of this button. Causes invalidation of all parents. * @param text */ public void setText (String text) { this.text = text; invalidateHierarchy(); } /** @return the label text of this button */ public String getText () { return text; } /** Sets the {@link ClickListener} of this button * @param listener the listener or null * @return this Button for chaining */ public Button setClickListener (ClickListener listener) { this.listener = listener; return this; } /** Defines a button style, see {@link Button} * @author mzechner */ static public class ButtonStyle { public NinePatch down; public NinePatch up; public BitmapFont font; public Color fontColor; public float pressedOffsetX; public float pressedOffsetY; public float unpressedOffsetX; public float unpressedOffsetY; public ButtonStyle () { } public ButtonStyle (BitmapFont font, Color fontColor, NinePatch down, NinePatch up, float pressedOffsetX, float pressedOffsetY, float unpressedOffsetX, float unpressedOffsetY) { this.font = font; this.fontColor = fontColor; this.down = down; this.up = up; this.pressedOffsetX = pressedOffsetX; this.pressedOffsetY = pressedOffsetY; this.unpressedOffsetX = unpressedOffsetX; this.unpressedOffsetY = unpressedOffsetY; } } /** Interface for listening to click events of a button. * @author mzechner */ static public interface ClickListener { public void click (Button button); } }
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; /** A button with text on it. * * <h2>Functionality</h2> A button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered with * the Button which will be called in case the button was clicked/touched. * * <h2>Layout</h2> The (preferred) width and height of a Button are derrived from the border patches in the background * {@link NinePatch} as well as the bounding box around the multi-line text displayed on the Button. Use * {@link Button#setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set * are to small for the contained text you will see artifacts. * * <h2>Style</h2> A Button is a {@link Widget} displaying a background {@link NinePatch} as well as multi-line text with a * specific font and color. The style is defined via an instance of {@link ButtonStyle}, which can be either done programmatically * or via a {@link Skin}.</p> * * A Button's style definition in a skin XML file should look like this: * * <pre> * {@code * <button name="styleName" * down="downNinePatch" * up="upNinePatch" * font="fontName" * fontColor="colorName"/>/> * } * </pre> * * <ul> * <li>The <code>name</code> attribute defines the name of the style which you can later use with * {@link Skin#newButton(String, String, String)}.</li> * <li>The <code>down</code> attribute references a {@link NinePatch} by name, to be used as the button's background when it is * pressed</li> * <li>The <code>up</code> attribute references a {@link NinePatch} by name, to be used as the button's background when it is not * pressed</li> * <li>The <code>font</code> attribute references a {@link BitmapFont} by name, to be used to render the text on the button</li> * <li>The <code>fontColor</code> attribute references a {@link Color} by name, to be used to render the text on the button</li> * </ul> * * @author mzechner */ public class Button extends Widget { final ButtonStyle style; String text; final TextBounds bounds = new TextBounds(); boolean isPressed = false; ClickListener listener = null; public Button (String text, Skin skin) { this(null, text, skin.getStyle(ButtonStyle.class)); } public Button (String text, ButtonStyle style) { this(null, text, style); } public Button (String name, String text, ButtonStyle style) { super(name, 0, 0); this.style = style; this.text = text; layout(); this.width = prefWidth; this.height = prefHeight; } @Override public void layout () { final BitmapFont font = style.font; final NinePatch downPatch = style.down; bounds.set(font.getMultiLineBounds(text)); prefHeight = downPatch.getTopHeight() + downPatch.getBottomHeight() + bounds.height - font.getDescent() * 2; prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } @Override public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; if (invalidated) layout(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); if (isPressed) downPatch.draw(batch, x, y, width, height); else upPatch.draw(batch, x, y, width, height); float textY = (int)(height * 0.5f) + (int)(bounds.height * 0.5f); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); if(isPressed) font.drawMultiLine(batch, text, x + (int)(width * 0.5f) + style.pressedOffsetX, y + textY + style.pressedOffsetY, 0, HAlignment.CENTER); else font.drawMultiLine(batch, text, x + (int)(width * 0.5f), y + textY, 0, HAlignment.CENTER); } @Override public boolean touchDown (float x, float y, int pointer) { if (pointer != 0) return false; isPressed = true; return true; } @Override public void touchUp (float x, float y, int pointer) { if (listener != null && hit(x, y) != null) listener.click(this); isPressed = false; } @Override public void touchDragged (float x, float y, int pointer) { } /** Sets the multi-line label text of this button. Causes invalidation of all parents. * @param text */ public void setText (String text) { this.text = text; invalidateHierarchy(); } /** @return the label text of this button */ public String getText () { return text; } /** Sets the {@link ClickListener} of this button * @param listener the listener or null * @return this Button for chaining */ public Button setClickListener (ClickListener listener) { this.listener = listener; return this; } /** Defines a button style, see {@link Button} * @author mzechner */ static public class ButtonStyle { public NinePatch down; public NinePatch up; public BitmapFont font; public Color fontColor; public float pressedOffsetX; public float pressedOffsetY; public ButtonStyle () { } public ButtonStyle (BitmapFont font, Color fontColor, NinePatch down, NinePatch up, float pressedOffsetX, float pressedOffsetY) { this.font = font; this.fontColor = fontColor; this.down = down; this.up = up; this.pressedOffsetX = pressedOffsetX; this.pressedOffsetY = pressedOffsetY; } } /** Interface for listening to click events of a button. * @author mzechner */ static public interface ClickListener { public void click (Button button); } }
[fixed] issue 432
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java
[fixed] issue 432
Java
apache-2.0
4ff407fa659fbfbc91c93021880690b9af0f582b
0
JNOSQL/diana-driver,JNOSQL/diana-driver
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.driver; import org.jnosql.diana.api.Value; import org.jnosql.diana.api.ValueWriter; import org.jnosql.diana.api.writer.ValueWriterDecorator; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.util.stream.Collectors.toList; /** * Utilitarian class to {@link Value} */ public final class ValueUtil { private static final ValueWriter VALUE_WRITER = ValueWriterDecorator.getInstance(); private static final Function CONVERT = o -> { if (o instanceof Value) { return convert(Value.class.cast(o)); } return getObject(o); }; private ValueUtil() { } /** * converter a {@link Value} to Object * * @param value the value * @return a object converted */ public static Object convert(Value value) { Objects.requireNonNull(value, "value is required"); Object val = value.get(); return getObject(val); } /** * Converts the {@link Value} to {@link List} * * @param value the value * @return a list object */ public static List<Object> convertToList(Value value) { Object val = value.get(); if(val instanceof Iterable) { return (List<Object>) StreamSupport.stream(Iterable.class.cast(val).spliterator(), false) .map(CONVERT).collect(toList()); } return Collections.singletonList(getObject(val)); } private static Object getObject(Object val) { if (VALUE_WRITER.isCompatible(val.getClass())) { return VALUE_WRITER.write(val); } return val; } }
diana-driver-commons/src/main/java/org/jnosql/diana/driver/ValueUtil.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.driver; import org.jnosql.diana.api.Value; import org.jnosql.diana.api.ValueWriter; import org.jnosql.diana.api.writer.ValueWriterDecorator; import java.util.List; import java.util.Objects; /** * Utilitarian class to {@link Value} */ public final class ValueUtil { private static final ValueWriter VALUE_WRITER = ValueWriterDecorator.getInstance(); private ValueUtil() { } /** * converter a {@link Value} to Object * * @param value the value * @return a object converted */ public static Object convert(Value value) { Objects.requireNonNull(value, "value is required"); Object val = value.get(); if (VALUE_WRITER.isCompatible(val.getClass())) { return VALUE_WRITER.write(val); } return val; } /** * Converts the {@link Value} to {@link List} * * @param value the value * @return a list object */ public static List<Object> convertToList(Value value) { } }
adds value util method
diana-driver-commons/src/main/java/org/jnosql/diana/driver/ValueUtil.java
adds value util method
Java
apache-2.0
139aa3660c77c3bae5574a46fea4a8bf17882dbd
0
sandrineBeauche/commons-collections,mohanaraosv/commons-collections,jankill/commons-collections,jankill/commons-collections,MuShiiii/commons-collections,gonmarques/commons-collections,sandrineBeauche/commons-collections,jankill/commons-collections,mohanaraosv/commons-collections,apache/commons-collections,gonmarques/commons-collections,mohanaraosv/commons-collections,sandrineBeauche/commons-collections,apache/commons-collections,MuShiiii/commons-collections,MuShiiii/commons-collections,apache/commons-collections
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.collections.list.UnmodifiableList; /** * An IteratorChain is an Iterator that wraps a number of Iterators. * <p> * This class makes multiple iterators look like one to the caller. When any * method from the Iterator interface is called, the IteratorChain will delegate * to a single underlying Iterator. The IteratorChain will invoke the Iterators * in sequence until all Iterators are exhausted. * <p> * Under many circumstances, linking Iterators together in this manner is more * efficient (and convenient) than reading out the contents of each Iterator * into a List and creating a new Iterator. * <p> * Calling a method that adds new Iterator <i>after a method in the Iterator * interface has been called</i> will result in an UnsupportedOperationException. * Subclasses should <i>take care</i> to not alter the underlying List of Iterators. * <p> * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In * this case the class will function as an empty iterator. * * @since 2.1 * @version $Id$ */ public class IteratorChain<E> implements Iterator<E> { /** The chain of iterators */ protected final List<Iterator<? extends E>> iteratorChain = new ArrayList<Iterator<? extends E>>(); /** The index of the current iterator */ protected int currentIteratorIndex = 0; /** The current iterator */ protected Iterator<? extends E> currentIterator = null; /** * The "last used" Iterator is the Iterator upon which next() or hasNext() * was most recently called used for the remove() operation only */ protected Iterator<? extends E> lastUsedIterator = null; /** * ComparatorChain is "locked" after the first time compare(Object,Object) * is called */ protected boolean isLocked = false; //----------------------------------------------------------------------- /** * Construct an IteratorChain with no Iterators. * <p> * You will normally use {@link #addIterator(Iterator)} to add some * iterators after using this constructor. */ public IteratorChain() { super(); } /** * Construct an IteratorChain with a single Iterator. * <p> * This method takes one iterator. The newly constructed iterator will * iterate through that iterator. Thus calling this constructor on its own * will have no effect other than decorating the input iterator. * <p> * You will normally use {@link #addIterator(Iterator)} to add some more * iterators after using this constructor. * * @param iterator the first child iterator in the IteratorChain, not null * @throws NullPointerException if the iterator is null */ public IteratorChain(final Iterator<? extends E> iterator) { super(); addIterator(iterator); } /** * Constructs a new <code>IteratorChain</code> over the two given iterators. * <p> * This method takes two iterators. The newly constructed iterator will * iterate through each one of the input iterators in turn. * * @param first the first child iterator in the IteratorChain, not null * @param second the second child iterator in the IteratorChain, not null * @throws NullPointerException if either iterator is null */ public IteratorChain(final Iterator<? extends E> first, final Iterator<? extends E> second) { super(); addIterator(first); addIterator(second); } /** * Constructs a new <code>IteratorChain</code> over the array of iterators. * <p> * This method takes an array of iterators. The newly constructed iterator * will iterate through each one of the input iterators in turn. * * @param iteratorChain the array of iterators, not null * @throws NullPointerException if iterators array is or contains null */ public IteratorChain(final Iterator<? extends E>... iteratorChain) { super(); for (final Iterator<? extends E> element : iteratorChain) { addIterator(element); } } /** * Constructs a new <code>IteratorChain</code> over the collection of * iterators. * <p> * This method takes a collection of iterators. The newly constructed * iterator will iterate through each one of the input iterators in turn. * * @param iteratorChain the collection of iterators, not null * @throws NullPointerException if iterators collection is or contains null * @throws ClassCastException if iterators collection doesn't contain an * iterator */ public IteratorChain(final Collection<Iterator<? extends E>> iteratorChain) { super(); for (final Iterator<? extends E> iterator : iteratorChain) { addIterator(iterator); } } //----------------------------------------------------------------------- /** * Add an Iterator to the end of the chain * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(final Iterator<? extends E> iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.add(iterator); } /** * Set the Iterator at the given index * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void setIterator(final int index, final Iterator<? extends E> iterator) throws IndexOutOfBoundsException { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.set(index, iterator); } /** * Get the list of Iterators (unmodifiable) * * @return the unmodifiable list of iterators added */ public List<Iterator<? extends E>> getIterators() { return UnmodifiableList.unmodifiableList(iteratorChain); } /** * Number of Iterators in the current IteratorChain. * * @return Iterator count */ public int size() { return iteratorChain.size(); } /** * Determine if modifications can still be made to the IteratorChain. * IteratorChains cannot be modified once they have executed a method from * the Iterator interface. * * @return true if IteratorChain cannot be modified, false if it can */ public boolean isLocked() { return isLocked; } /** * Checks whether the iterator chain is now locked and in use. */ private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException( "IteratorChain cannot be changed after the first use of a method from the Iterator interface"); } } /** * Lock the chain so no more iterators can be added. This must be called * from all Iterator interface methods. */ private void lockChain() { if (isLocked == false) { isLocked = true; } } /** * Updates the current iterator field to ensure that the current Iterator is * not exhausted */ protected void updateCurrentIterator() { if (currentIterator == null) { if (iteratorChain.isEmpty()) { currentIterator = EmptyIterator.<E> emptyIterator(); } else { currentIterator = iteratorChain.get(0); } // set last used iterator here, in case the user calls remove // before calling hasNext() or next() (although they shouldn't) lastUsedIterator = currentIterator; } while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) { currentIteratorIndex++; currentIterator = iteratorChain.get(currentIteratorIndex); } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the IteratorChain has a remaining element. * * @return true if elements remain */ public boolean hasNext() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next Object of the current Iterator * * @return Object from the current Iterator * @throws java.util.NoSuchElementException if all the Iterators are * exhausted */ public E next() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.next(); } /** * Removes from the underlying collection the last element returned by the * Iterator. As with next() and hasNext(), this method calls remove() on the * underlying Iterator. Therefore, this method may throw an * UnsupportedOperationException if the underlying Iterator does not support * this method. * * @throws UnsupportedOperationException if the remove operator is not * supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called, * or the remove method has already been called after the last call to the * next method. */ public void remove() { lockChain(); if (currentIterator == null) { updateCurrentIterator(); } lastUsedIterator.remove(); } }
src/main/java/org/apache/commons/collections/iterators/IteratorChain.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.collections.list.UnmodifiableList; /** * An IteratorChain is an Iterator that wraps a number of Iterators. * <p> * This class makes multiple iterators look like one to the caller When any * method from the Iterator interface is called, the IteratorChain will delegate * to a single underlying Iterator. The IteratorChain will invoke the Iterators * in sequence until all Iterators are exhausted. * <p> * Under many circumstances, linking Iterators together in this manner is more * efficient (and convenient) than reading out the contents of each Iterator * into a List and creating a new Iterator. * <p> * Calling a method that adds new Iterator<i>after a method in the Iterator * interface has been called</i> will result in an * UnsupportedOperationException. Subclasses should <i>take care</i> to not * alter the underlying List of Iterators. * <p> * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In * this case the class will function as an empty iterator. * * @since 2.1 * @version $Id$ */ public class IteratorChain<E> implements Iterator<E> { /** The chain of iterators */ protected final List<Iterator<? extends E>> iteratorChain = new ArrayList<Iterator<? extends E>>(); /** The index of the current iterator */ protected int currentIteratorIndex = 0; /** The current iterator */ protected Iterator<? extends E> currentIterator = null; /** * The "last used" Iterator is the Iterator upon which next() or hasNext() * was most recently called used for the remove() operation only */ protected Iterator<? extends E> lastUsedIterator = null; /** * ComparatorChain is "locked" after the first time compare(Object,Object) * is called */ protected boolean isLocked = false; //----------------------------------------------------------------------- /** * Construct an IteratorChain with no Iterators. * <p> * You will normally use {@link #addIterator(Iterator)} to add some * iterators after using this constructor. */ public IteratorChain() { super(); } /** * Construct an IteratorChain with a single Iterator. * <p> * This method takes one iterator. The newly constructed iterator will * iterate through that iterator. Thus calling this constructor on its own * will have no effect other than decorating the input iterator. * <p> * You will normally use {@link #addIterator(Iterator)} to add some more * iterators after using this constructor. * * @param iterator the first child iterator in the IteratorChain, not null * @throws NullPointerException if the iterator is null */ public IteratorChain(final Iterator<? extends E> iterator) { super(); addIterator(iterator); } /** * Constructs a new <code>IteratorChain</code> over the two given iterators. * <p> * This method takes two iterators. The newly constructed iterator will * iterate through each one of the input iterators in turn. * * @param first the first child iterator in the IteratorChain, not null * @param second the second child iterator in the IteratorChain, not null * @throws NullPointerException if either iterator is null */ public IteratorChain(final Iterator<? extends E> first, final Iterator<? extends E> second) { super(); addIterator(first); addIterator(second); } /** * Constructs a new <code>IteratorChain</code> over the array of iterators. * <p> * This method takes an array of iterators. The newly constructed iterator * will iterate through each one of the input iterators in turn. * * @param iteratorChain the array of iterators, not null * @throws NullPointerException if iterators array is or contains null */ public IteratorChain(final Iterator<? extends E>... iteratorChain) { super(); for (final Iterator<? extends E> element : iteratorChain) { addIterator(element); } } /** * Constructs a new <code>IteratorChain</code> over the collection of * iterators. * <p> * This method takes a collection of iterators. The newly constructed * iterator will iterate through each one of the input iterators in turn. * * @param iteratorChain the collection of iterators, not null * @throws NullPointerException if iterators collection is or contains null * @throws ClassCastException if iterators collection doesn't contain an * iterator */ public IteratorChain(final Collection<Iterator<? extends E>> iteratorChain) { super(); for (final Iterator<? extends E> iterator : iteratorChain) { addIterator(iterator); } } //----------------------------------------------------------------------- /** * Add an Iterator to the end of the chain * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(final Iterator<? extends E> iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.add(iterator); } /** * Set the Iterator at the given index * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void setIterator(final int index, final Iterator<? extends E> iterator) throws IndexOutOfBoundsException { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.set(index, iterator); } /** * Get the list of Iterators (unmodifiable) * * @return the unmodifiable list of iterators added */ public List<Iterator<? extends E>> getIterators() { return UnmodifiableList.unmodifiableList(iteratorChain); } /** * Number of Iterators in the current IteratorChain. * * @return Iterator count */ public int size() { return iteratorChain.size(); } /** * Determine if modifications can still be made to the IteratorChain. * IteratorChains cannot be modified once they have executed a method from * the Iterator interface. * * @return true if IteratorChain cannot be modified, false if it can */ public boolean isLocked() { return isLocked; } /** * Checks whether the iterator chain is now locked and in use. */ private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException( "IteratorChain cannot be changed after the first use of a method from the Iterator interface"); } } /** * Lock the chain so no more iterators can be added. This must be called * from all Iterator interface methods. */ private void lockChain() { if (isLocked == false) { isLocked = true; } } /** * Updates the current iterator field to ensure that the current Iterator is * not exhausted */ protected void updateCurrentIterator() { if (currentIterator == null) { if (iteratorChain.isEmpty()) { currentIterator = EmptyIterator.<E> emptyIterator(); } else { currentIterator = iteratorChain.get(0); } // set last used iterator here, in case the user calls remove // before calling hasNext() or next() (although they shouldn't) lastUsedIterator = currentIterator; } while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) { currentIteratorIndex++; currentIterator = iteratorChain.get(currentIteratorIndex); } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the IteratorChain has a remaining element. * * @return true if elements remain */ public boolean hasNext() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next Object of the current Iterator * * @return Object from the current Iterator * @throws java.util.NoSuchElementException if all the Iterators are * exhausted */ public E next() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.next(); } /** * Removes from the underlying collection the last element returned by the * Iterator. As with next() and hasNext(), this method calls remove() on the * underlying Iterator. Therefore, this method may throw an * UnsupportedOperationException if the underlying Iterator does not support * this method. * * @throws UnsupportedOperationException if the remove operator is not * supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called, * or the remove method has already been called after the last call to the * next method. */ public void remove() { lockChain(); if (currentIterator == null) { updateCurrentIterator(); } lastUsedIterator.remove(); } }
Javadoc fixes. git-svn-id: 53f0c1087cb9b05f99ff63ab1f4d1687a227fef1@1451209 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/collections/iterators/IteratorChain.java
Javadoc fixes.
Java
apache-2.0
c78ea6eb1506f2d70e06ee1092505e93e203ae64
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.jenetics.internal.util.Equality.eq; import java.io.Serializable; import java.util.function.Function; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.jenetics.internal.util.Equality; import org.jenetics.internal.util.Hash; import org.jenetics.internal.util.jaxb; import org.jenetics.util.Verifiable; /** * The {@code Phenotype} consists of a {@link Genotype} plus a fitness * {@link Function}, where the fitness {@link Function} represents the * environment where the {@link Genotype} lives. * This class implements the {@link Comparable} interface, to define a natural * order between two {@code Phenotype}s. The natural order of the * {@code Phenotypes} is defined by its fitness value (given by the * fitness {@link Function}. The {@code Phenotype} is immutable and therefore * can't be changed after creation. * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 1.0 * @version 3.1 */ @XmlJavaTypeAdapter(Phenotype.Model.Adapter.class) public final class Phenotype< G extends Gene<?, G>, C extends Comparable<? super C> > implements Comparable<Phenotype<G, C>>, Verifiable, Serializable, Runnable { private static final long serialVersionUID = 4L; private final Genotype<G> _genotype; private final Function<? super Genotype<G>, ? extends C> _function; private final Function<? super C, ? extends C> _scaler; private final long _generation; // Storing the fitness value for lazy evaluation. private transient volatile boolean _evaluated = false; private C _rawFitness = null; private C _fitness = null; /** * Create a new phenotype from the given arguments. * * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @param scaler the fitness scaler. * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ private Phenotype( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { _genotype = requireNonNull(genotype, "Genotype"); _function = requireNonNull(function, "Fitness function"); _scaler = requireNonNull(scaler, "Fitness scaler"); if (generation < 0) { throw new IllegalArgumentException(format( "Generation must not < 0 and was %s.", generation )); } _generation = generation; } /** * This method returns a copy of the {@code Genotype}, to guarantee a * immutable class. * * @return the cloned {@code Genotype} of this {@code Phenotype}. * @throws NullPointerException if one of the arguments is {@code null}. */ public Genotype<G> getGenotype() { return _genotype; } /** * Evaluates the (raw) fitness values and caches it so the fitness calculation * is performed only once. * * @return this phenotype, for method chaining. */ public Phenotype<G, C> evaluate() { if (!_evaluated) { eval(); } return this; } private synchronized void eval() { if (!_evaluated) { if (_rawFitness == null) _rawFitness = _function.apply(_genotype); if (_fitness == null) _fitness = _scaler.apply(_rawFitness); _evaluated = true; } } /** * This method simply calls the {@link #evaluate()} method. The purpose of * this method is to have a simple way for concurrent fitness calculation * for expensive fitness values. */ @Override public void run() { evaluate(); } /** * Return the fitness function used by this phenotype to calculate the * (raw) fitness value. * * @return the fitness function. */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _function; } /** * Return the fitness scaler used by this phenotype to scale the <i>raw</i> * fitness. * * @return the fitness scaler. */ public Function<? super C, ? extends C> getFitnessScaler() { return _scaler; } /** * Return the fitness value of this {@code Phenotype}. * * @return The fitness value of this {@code Phenotype}. */ public C getFitness() { evaluate(); return _fitness; } /** * Return the raw fitness (before scaling) of the phenotype. * * @return The raw fitness (before scaling) of the phenotype. */ public C getRawFitness() { evaluate(); return _rawFitness; } /** * Return the generation this {@link Phenotype} was created. * * @return The generation this {@link Phenotype} was created. */ public long getGeneration() { return _generation; } /** * Return the age of this phenotype depending on the given current generation. * * @param currentGeneration the current generation evaluated by the GA. * @return the age of this phenotype: * {@code currentGeneration - this.getGeneration()}. */ public long getAge(final long currentGeneration) { return currentGeneration - _generation; } /** * Test whether this phenotype is valid. The phenotype is valid if its * {@link Genotype} is valid. * * @return true if this phenotype is valid, false otherwise. */ @Override public boolean isValid() { return _genotype.isValid(); } @Override public int compareTo(final Phenotype<G, C> pt) { return getFitness().compareTo(pt.getFitness()); } @Override public int hashCode() { return Hash.of(getClass()) .and(_generation) .and(getFitness()) .and(getRawFitness()) .and(_genotype).value(); } @Override public boolean equals(final Object obj) { return Equality.of(this, obj).test(pt -> eq(getFitness(), pt.getFitness()) && eq(getRawFitness(), pt.getRawFitness()) && eq(_genotype, pt._genotype) && eq(_generation, pt._generation) ); } @Override public String toString() { return _genotype.toString() + " --> " + getFitness(); } /** * Create a new {@code Phenotype} with a different {@code Genotype} but the * same {@code generation}, fitness {@code function} and fitness * {@code scaler}. * * @since 3.1 * * @param genotype the new genotype * @return a new {@code phenotype} with replaced {@code genotype} * @throws NullPointerException if the given {@code genotype} is {@code null}. */ public Phenotype<G, C> newInstance(final Genotype<G> genotype) { return of(genotype, _generation, _function, _scaler); } /** * Factory method for creating a new {@link Phenotype} with the same * {@link Function} and age as this {@link Phenotype}. * * @param genotype the new genotype of the new phenotype. * @param generation date of birth (generation) of the new phenotype. * @return New {@link Phenotype} with the same fitness {@link Function}. * @throws NullPointerException if the {@code genotype} is {@code null}. */ Phenotype<G, C> newInstance( final Genotype<G> genotype, final long generation ) { return of(genotype, generation, _function, _scaler); } /** * Return a new phenotype with the the genotype of this and with new * fitness function, fitness scaler and generation. * * @param generation the generation of the new phenotype. * @param function the (new) fitness scaler of the created phenotype. * @param scaler the (new) fitness scaler of the created phenotype * @return a new phenotype with the given values. * @throws NullPointerException if one of the values is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return of(_genotype, generation, function, scaler); } /** * Return a new phenotype with the the genotype of this and with new * fitness function and generation. * * @param generation the generation of the new phenotype. * @param function the (new) fitness scaler of the created phenotype. * @return a new phenotype with the given values. * @throws NullPointerException if one of the values is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function ) { return of(_genotype, generation, function, a -> a); } /** * The {@code Genotype} is copied to guarantee an immutable class. Only * the age of the {@code Phenotype} can be incremented. * * @param <G> the gene type of the chromosome * @param <C> the fitness value type * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @return a new phenotype from the given parameters * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Phenotype<G, C> of( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, C> function ) { return of( genotype, generation, function, function instanceof Serializable ? (Function<? super C, ? extends C> & Serializable)a -> a : a -> a ); } /** * Create a new phenotype from the given arguments. * * @param <G> the gene type of the chromosome * @param <C> the fitness value type * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @param scaler the fitness scaler. * @return a new phenotype object * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Phenotype<G, C> of( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return new Phenotype<>( genotype, generation, function, scaler ); } /* ************************************************************************* * JAXB object serialization * ************************************************************************/ @XmlRootElement(name = "phenotype") @XmlType(name = "org.jenetics.Phenotype") @XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings({ "unchecked", "rawtypes" }) final static class Model { @XmlAttribute(name = "generation", required = true) public long generation; @XmlElement(name = "genotype", required = true, nillable = false) public Genotype.Model genotype; @XmlElement(name = "fitness", required = true, nillable = false) public Object fitness; @XmlElement(name = "raw-fitness", required = true, nillable = false) public Object rawFitness; public final static class Adapter extends XmlAdapter<Model, Phenotype> { @Override public Model marshal(final Phenotype pt) throws Exception { final Model m = new Model(); m.generation = pt.getGeneration(); m.genotype = Genotype.Model.ADAPTER.marshal(pt.getGenotype()); m.fitness = jaxb.marshal(pt.getFitness()); m.rawFitness = jaxb.marshal(pt.getRawFitness()); return m; } @Override public Phenotype unmarshal(final Model m) throws Exception { final Phenotype pt = new Phenotype( Genotype.Model.ADAPTER.unmarshal(m.genotype), m.generation, Function.identity(), Function.identity() ); pt._fitness = (Comparable)m.fitness; pt._rawFitness = (Comparable)m.rawFitness; return pt; } } } }
org.jenetics/src/main/java/org/jenetics/Phenotype.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.jenetics.internal.util.Equality.eq; import java.io.Serializable; import java.util.function.Function; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.jenetics.internal.util.Equality; import org.jenetics.internal.util.Hash; import org.jenetics.internal.util.jaxb; import org.jenetics.util.Verifiable; /** * The {@code Phenotype} consists of a {@link Genotype} plus a fitness * {@link Function}, where the fitness {@link Function} represents the * environment where the {@link Genotype} lives. * This class implements the {@link Comparable} interface, to define a natural * order between two {@code Phenotype}s. The natural order of the * {@code Phenotypes} is defined by its fitness value (given by the * fitness {@link Function}. The {@code Phenotype} is immutable and therefore * can't be changed after creation. * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 1.0 * @version 3.1 */ @XmlJavaTypeAdapter(Phenotype.Model.Adapter.class) public final class Phenotype< G extends Gene<?, G>, C extends Comparable<? super C> > implements Comparable<Phenotype<G, C>>, Verifiable, Serializable, Runnable { private static final long serialVersionUID = 4L; private final Genotype<G> _genotype; private final Function<? super Genotype<G>, ? extends C> _function; private final Function<? super C, ? extends C> _scaler; private final long _generation; // Storing the fitness value for lazy evaluation. private transient volatile boolean _evaluated = false; private C _rawFitness = null; private C _fitness = null; /** * Create a new phenotype from the given arguments. * * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @param scaler the fitness scaler. * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ private Phenotype( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { _genotype = requireNonNull(genotype, "Genotype"); _function = requireNonNull(function, "Fitness function"); _scaler = requireNonNull(scaler, "Fitness scaler"); if (generation < 0) { throw new IllegalArgumentException(format( "Generation must not < 0 and was %s.", generation )); } _generation = generation; } /** * This method returns a copy of the {@code Genotype}, to guarantee a * immutable class. * * @return the cloned {@code Genotype} of this {@code Phenotype}. * @throws NullPointerException if one of the arguments is {@code null}. */ public Genotype<G> getGenotype() { return _genotype; } /** * Evaluates the (raw) fitness values and caches it so the fitness calculation * is performed only once. * * @return this phenotype, for method chaining. */ public Phenotype<G, C> evaluate() { if (!_evaluated) { eval(); } return this; } private synchronized void eval() { if (!_evaluated) { if (_rawFitness == null) _rawFitness = _function.apply(_genotype); if (_fitness == null) _fitness = _scaler.apply(_rawFitness); _evaluated = true; } } /** * This method simply calls the {@link #evaluate()} method. The purpose of * this method is to have a simple way for concurrent fitness calculation * for expensive fitness values. */ @Override public void run() { evaluate(); } /** * Return the fitness function used by this phenotype to calculate the * (raw) fitness value. * * @return the fitness function. */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _function; } /** * Return the fitness scaler used by this phenotype to scale the <i>raw</i> * fitness. * * @return the fitness scaler. */ public Function<? super C, ? extends C> getFitnessScaler() { return _scaler; } /** * Return the fitness value of this {@code Phenotype}. * * @return The fitness value of this {@code Phenotype}. */ public C getFitness() { evaluate(); return _fitness; } /** * Return the raw fitness (before scaling) of the phenotype. * * @return The raw fitness (before scaling) of the phenotype. */ public C getRawFitness() { evaluate(); return _rawFitness; } /** * Return the generation this {@link Phenotype} was created. * * @return The generation this {@link Phenotype} was created. */ public long getGeneration() { return _generation; } /** * Return the age of this phenotype depending on the given current generation. * * @param currentGeneration the current generation evaluated by the GA. * @return the age of this phenotype: * {@code currentGeneration - this.getGeneration()}. */ public long getAge(final long currentGeneration) { return currentGeneration - _generation; } /** * Test whether this phenotype is valid. The phenotype is valid if its * {@link Genotype} is valid. * * @return true if this phenotype is valid, false otherwise. */ @Override public boolean isValid() { return _genotype.isValid(); } @Override public int compareTo(final Phenotype<G, C> pt) { return getFitness().compareTo(pt.getFitness()); } @Override public int hashCode() { return Hash.of(getClass()) .and(_generation) .and(getFitness()) .and(getRawFitness()) .and(_genotype).value(); } @Override public boolean equals(final Object obj) { return Equality.of(this, obj).test(pt -> eq(getFitness(), pt.getFitness()) && eq(getRawFitness(), pt.getRawFitness()) && eq(_genotype, pt._genotype) && eq(_generation, pt._generation) ); } @Override public String toString() { return _genotype.toString() + " --> " + getFitness(); } /** * Create a new {@code Phenotype} with a different {@code Genotype} but the * same {@code generation}, fitness {@code function} and fitness * {@code scaler}. * * @since 3.1 * * @param genotype the new genotype * @return a new {@code phenotype} with replaced {@code genotype} * @throws NullPointerException if the given {@code genotype} is {@code null}. */ public Phenotype<G, C> newInstance(final Genotype<G> genotype) { return of(genotype, _generation, _function, _scaler); } /** * Factory method for creating a new {@link Phenotype} with the same * {@link Function} and age as this {@link Phenotype}. * * @param genotype the new genotype of the new phenotype. * @param generation date of birth (generation) of the new phenotype. * @return New {@link Phenotype} with the same fitness {@link Function}. * @throws NullPointerException if the {@code genotype} is {@code null}. */ Phenotype<G, C> newInstance( final Genotype<G> genotype, final long generation ) { return of(genotype, generation, _function, _scaler); } /** * Return a new phenotype with the the genotype of this and with new * fitness function, fitness scaler and generation. * * @param generation the generation of the new phenotype. * @param function the (new) fitness scaler of the created phenotype. * @param scaler the (new) fitness scaler of the created phenotype * @return a new phenotype with the given values. * @throws NullPointerException if one of the values is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return of(_genotype, generation, function, scaler); } /** * Return a new phenotype with the the genotype of this and with new * fitness function and generation. * * @param generation the generation of the new phenotype. * @param function the (new) fitness scaler of the created phenotype. * @return a new phenotype with the given values. * @throws NullPointerException if one of the values is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public Phenotype<G, C> newInstance( final long generation, final Function<? super Genotype<G>, ? extends C> function ) { return of(_genotype, generation, function, a -> a); } /** * The {@code Genotype} is copied to guarantee an immutable class. Only * the age of the {@code Phenotype} can be incremented. * * @param <G> the gene type of the chromosome * @param <C> the fitness value type * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @return a new phenotype from the given parameters * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Phenotype<G, C> of( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, C> function ) { return of( genotype, generation, function, function instanceof Serializable ? (Function<? super C, ? extends C> & Serializable)a -> a : a -> a ); } /** * Create a new phenotype from the given arguments. * * @param <G> the gene type of the chromosome * @param <C> the fitness value type * @param genotype the genotype of this phenotype. * @param generation the current generation of the generated phenotype. * @param function the fitness function of this phenotype. * @param scaler the fitness scaler. * @return a new phenotype object * @throws NullPointerException if one of the arguments is {@code null}. * @throws IllegalArgumentException if the given {@code generation} is * {@code < 0}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Phenotype<G, C> of( final Genotype<G> genotype, final long generation, final Function<? super Genotype<G>, ? extends C> function, final Function<? super C, ? extends C> scaler ) { return new Phenotype<>( genotype, generation, function, scaler ); } /* ************************************************************************* * JAXB object serialization * ************************************************************************/ @XmlRootElement(name = "phenotype") @XmlType(name = "org.jenetics.Phenotype") @XmlAccessorType(XmlAccessType.FIELD) @SuppressWarnings({ "unchecked", "rawtypes" }) final static class Model { @XmlAttribute(name = "generation", required = true) public long generation; @XmlElement(name = "genotype", required = true, nillable = false) public Genotype.Model genotype; @XmlElement(name = "fitness", required = true, nillable = false) public Object fitness; @XmlElement(name = "raw-fitness", required = true, nillable = false) public Object rawFitness; public final static class Adapter extends XmlAdapter<Model, Phenotype> { @Override public Model marshal(final Phenotype pt) throws Exception { final Model m = new Model(); m.generation = pt.getGeneration(); m.genotype = Genotype.Model.ADAPTER.marshal(pt.getGenotype()); m.fitness = jaxb.marshal(pt.getFitness()); m.rawFitness = jaxb.marshal(pt.getRawFitness()); return m; } @Override public Phenotype unmarshal(final Model m) throws Exception { final Phenotype pt = new Phenotype( Genotype.Model.ADAPTER.unmarshal(m.genotype), m.generation, Function.identity(), Function.identity() ); pt._fitness = (Comparable)m.fitness; pt._rawFitness = (Comparable)m.rawFitness; return pt; } } } }
Minor code reformatting.
org.jenetics/src/main/java/org/jenetics/Phenotype.java
Minor code reformatting.
Java
apache-2.0
080477d36902396e71aea52c3f4326d1fc76f817
0
Cantara/Java-Auto-Update,Cantara/Java-Auto-Update
package no.cantara.jau; import com.sun.jna.Pointer; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinNT; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Makes sure any running managed service is killed if JAU should restart */ public class DuplicateProcessHandler { private static final Logger log = LoggerFactory.getLogger(DuplicateProcessHandler.class); public static final String RUNNING_PROCESS_FILENAME = "last-running-process.txt"; public static boolean killExistingProcessIfRunning() { String pid = getRunningProcessPidFromFile(); if (pid != null) { if (isValidPid(pid)) { if (processIsRunning(pid)) { log.info("Last recorded running managed process pid={} is running", pid); return killRunningProcessBasedOnOS(pid); } } } else { log.info("{} not found. Assuming no existing managed process is running.", RUNNING_PROCESS_FILENAME); } return false; } private static String findWindowsProcessId(Process process) { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handleNumber = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handleNumber)); int pid = kernel.GetProcessId(handle); log.debug("Found pid for managed process: {}", pid); return pid + ""; } catch (Throwable e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); } } return null; } public static void findRunningManagedProcessPidAndWriteToFile(Process managedProcess) { String pid = null; if (isWindows()) { pid = findWindowsProcessId(managedProcess); } else { pid = findUnixProcessId(managedProcess); } if (pid != null) { writePidToFile(pid); } } private static String findUnixProcessId(Process managedProcess) { String pid; Field pidField = null; try { pidField = managedProcess.getClass().getDeclaredField("pid"); } catch (NoSuchFieldException e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); return null; } try { pidField.setAccessible(true); pid = Long.toString(pidField.getLong(managedProcess)); } catch (IllegalAccessException e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); return null; } return pid; } private static void writePidToFile(String pid) { Path filePath = Paths.get(RUNNING_PROCESS_FILENAME); try { if (!Files.exists(filePath)) { Files.createFile(Paths.get(RUNNING_PROCESS_FILENAME)); } } catch (IOException e) { log.error("Could not create file to managed process pid={}", pid, e); return; } try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(RUNNING_PROCESS_FILENAME), "utf-8"))) { writer.write(pid); log.debug("Wrote pid={} to file={}", pid, RUNNING_PROCESS_FILENAME); } catch (FileNotFoundException e) { log.error("File '{}' to write managed process pid={} not found", RUNNING_PROCESS_FILENAME,pid, e); } catch (UnsupportedEncodingException e) { log.error("Encoding error while writing to {}", RUNNING_PROCESS_FILENAME, e); } catch (IOException e) { log.error("Could not write to file '{}'", RUNNING_PROCESS_FILENAME); } } private static String getRunningProcessPidFromFile() { Path file = Paths.get(RUNNING_PROCESS_FILENAME); String pid = null; if (Files.exists(file)) { try { pid = new String(Files.readAllBytes(Paths.get(RUNNING_PROCESS_FILENAME))); } catch (IOException e) { log.warn("Could not read file={}. Possible multiple processes!", RUNNING_PROCESS_FILENAME); } } return pid; } private static boolean processIsRunning(String pid) { ProcessBuilder processBuilder; if (isWindows()) { //tasklist exit code is always 0. Parse output //findstr exit code 0 if found pid, 1 if it doesn't processBuilder = new ProcessBuilder("cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\""); } else { processBuilder = new ProcessBuilder("ps", "-p", pid); } boolean processIsRunning = executeProcessRunningCheck(pid, processBuilder); return processIsRunning; } private static boolean executeProcessRunningCheck(String pid, ProcessBuilder processBuilder) { boolean processIsRunning = executeProcess(pid, processBuilder); if (processIsRunning) { log.info("Found pid={} of last recorded running managed process", pid); return true; } else { log.info("Last recorded running managed process pid={} is not running", pid); return false; } } private static boolean isValidPid(String pid) { // TODO: Is this check of valid PID too naive? try { Long.parseLong(pid); return true; } catch (NumberFormatException e) { log.warn("PID is not valid number. Got: '{}' {}", pid, e); return false; } } private static boolean killRunningProcessBasedOnOS(String pid) { log.info("Killing existing managed process with pid={}", pid); ProcessBuilder processBuilder; if (isWindows()) { processBuilder = new ProcessBuilder("taskkill", pid); } else { //unix processBuilder = new ProcessBuilder("kill", "-9", pid); } boolean processWasKilled = executeProcess(pid, processBuilder); if (processWasKilled) { log.info("Successfully killed existing running managed process pid={}", pid); return true; } else { log.error("Could not kill existing running managed process pid={}. Possible multiple processes!", pid); return false; } } private static boolean executeProcess(String pid, ProcessBuilder processBuilder) { try { Process p = processBuilder.start(); try { p.waitFor(); if (p.exitValue() == 0) { return true; } else { printErrorCommandFromProcess(p); } } catch (InterruptedException e) { log.warn("Interrupted execution of process", e); } } catch (IOException e) { log.warn("IOException with execution of process", e); } return false; } private static void printErrorCommandFromProcess(Process p) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } String result = builder.toString(); if (!result.isEmpty()) { log.error("Error output from kill command: '{}'", result); } } private static boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("windows"); } }
src/main/java/no/cantara/jau/DuplicateProcessHandler.java
package no.cantara.jau; import com.sun.jna.Pointer; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinNT; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Makes sure any running managed service is killed if JAU should restart */ public class DuplicateProcessHandler { private static final Logger log = LoggerFactory.getLogger(DuplicateProcessHandler.class); public static final String RUNNING_PROCESS_FILENAME = "last-running-process.txt"; public static boolean killExistingProcessIfRunning() { String pid = getRunningProcessPidFromFile(); if (pid != null) { if (isValidPid(pid)) { if (processIsRunning(pid)) { log.info("Last recorded running managed process pid={} is running", pid); return killRunningProcessBasedOnOS(pid); } } } else { log.info("{} not found. Assuming no existing managed process is running.", RUNNING_PROCESS_FILENAME); } return false; } private static String findWindowsProcessId(Process process) { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handleNumber = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handleNumber)); int pid = kernel.GetProcessId(handle); log.debug("Detected pid: {}", pid); return pid + ""; } catch (Throwable e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); } } return null; } public static void findRunningManagedProcessPidAndWriteToFile(Process managedProcess) { String pid = null; if (isWindows()) { pid = findWindowsProcessId(managedProcess); } else { pid = findUnixProcessId(managedProcess); } if (pid != null) { writePidToFile(pid); } } private static String findUnixProcessId(Process managedProcess) { String pid; Field pidField = null; try { pidField = managedProcess.getClass().getDeclaredField("pid"); } catch (NoSuchFieldException e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); return null; } try { pidField.setAccessible(true); pid = Long.toString(pidField.getLong(managedProcess)); } catch (IllegalAccessException e) { log.error("Could not get PID of managed process. This could lead to duplicate managed processes!", e); return null; } return pid; } private static void writePidToFile(String pid) { Path filePath = Paths.get(RUNNING_PROCESS_FILENAME); try { if (!Files.exists(filePath)) { Files.createFile(Paths.get(RUNNING_PROCESS_FILENAME)); } } catch (IOException e) { log.error("Could not create file to managed process pid={}", pid, e); return; } try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(RUNNING_PROCESS_FILENAME), "utf-8"))) { writer.write(pid); log.debug("Wrote pid={} to file={}", pid, RUNNING_PROCESS_FILENAME); } catch (FileNotFoundException e) { log.error("File '{}' to write managed process pid={} not found", RUNNING_PROCESS_FILENAME,pid, e); } catch (UnsupportedEncodingException e) { log.error("Encoding error while writing to {}", RUNNING_PROCESS_FILENAME, e); } catch (IOException e) { log.error("Could not write to file '{}'", RUNNING_PROCESS_FILENAME); } } private static String getRunningProcessPidFromFile() { Path file = Paths.get(RUNNING_PROCESS_FILENAME); String pid = null; if (Files.exists(file)) { try { pid = new String(Files.readAllBytes(Paths.get(RUNNING_PROCESS_FILENAME))); } catch (IOException e) { log.warn("Could not read file={}. Possible multiple processes!", RUNNING_PROCESS_FILENAME); } } return pid; } public static boolean processIsRunning(String pid) { ProcessBuilder processBuilder; if (isWindows()) { //tasklist exit code is always 0. Parse output //findstr exit code 0 if found pid, 1 if it doesn't processBuilder = new ProcessBuilder("cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\""); } else { processBuilder = new ProcessBuilder("ps", "-p", pid); } boolean processIsRunning = executeProcessRunningCheck(pid, processBuilder); return processIsRunning; } private static boolean executeProcessRunningCheck(String pid, ProcessBuilder processBuilder) { boolean processIsRunning = executeProcess(pid, processBuilder); if (processIsRunning) { log.info("Found pid={} of last recorded running managed process", pid); return true; } else { log.info("Last recorded running managed process pid={} is not running", pid); return false; } } private static boolean isValidPid(String pid) { // TODO: Is this check of valid PID too naive? try { Long.parseLong(pid); return true; } catch (NumberFormatException e) { log.warn("PID is not valid number. Got: '{}' {}", pid, e); return false; } } private static boolean killRunningProcessBasedOnOS(String pid) { log.info("Killing existing managed process with pid={}", pid); ProcessBuilder processBuilder; if (isWindows()) { processBuilder = new ProcessBuilder("taskkill", pid); } else { //unix processBuilder = new ProcessBuilder("kill", "-9", pid); } boolean processWasKilled = executeProcess(pid, processBuilder); if (processWasKilled) { log.info("Successfully killed existing running managed process pid={}", pid); return true; } else { log.error("Could not kill existing running managed process pid={}. Possible multiple processes!", pid); return false; } } public static boolean executeProcess(String pid, ProcessBuilder processBuilder) { try { Process p = processBuilder.start(); try { p.waitFor(); if (p.exitValue() == 0) { return true; } else { printErrorCommandFromProcess(p); } } catch (InterruptedException e) { log.warn("Interrupted execution of process", e); } } catch (IOException e) { log.warn("IOException with execution of process", e); } return false; } private static void printErrorCommandFromProcess(Process p) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } String result = builder.toString(); if (!result.isEmpty()) { log.error("Error output from kill command: '{}'", result); } } private static boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("windows"); } }
Restrict scope for methods not requiring public
src/main/java/no/cantara/jau/DuplicateProcessHandler.java
Restrict scope for methods not requiring public
Java
apache-2.0
4f59ad85cc803d7c28d25d13de84dc847d7d72b1
0
greese/dasein-persist,Sylistron/dasein-persist
/** * Copyright (C) 1998-2011 enStratusNetworks LLC * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ /* $Id: Transaction.java,v 1.14 2009/07/02 01:36:20 greese Exp $ */ /* Copyright (c) 2002-2004 Valtira Corporation, All Rights Reserved */ package org.dasein.persist; // J2SE imports import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.EmptyStackException; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; // J2EE imports import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; // Apache imports import org.apache.log4j.Logger; /** * Represents a database transaction to applications managing their * own transactions. To use this class, call <code>getInstance()</code> * to get a transaction and pass that transaction to all * <code>Execution</code> objects that need to execute in the same * transaction context. * <br/> * Last modified: $Date: 2009/07/02 01:36:20 $ * @version $Revision: 1.14 $ * @author George Reese */ public class Transaction { static private final Logger logger = Logger.getLogger(Transaction.class); /** * A count of open connections. */ static private final AtomicInteger connections = new AtomicInteger(0); /** * The most transactions ever open at a single time. */ static private final AtomicInteger highPoint = new AtomicInteger(0); /** * The next transaction ID to use. */ static private final AtomicInteger nextTransactionId = new AtomicInteger(0); /** * A list of open transactions. */ static private final Map<Number,Transaction> transactions = new ConcurrentHashMap<Number, Transaction>(8, 0.9f, 1); /** * Cache of Execution objects to minimize dynamically created SQL */ static private final Map<String,Stack<Execution>> eventCache = new ConcurrentHashMap<String, Stack<Execution>>(8, 0.9f, 1); static private final AtomicBoolean maidLaunched = new AtomicBoolean(false); /** * Cleans up transactions that somehow never got cleaned up. */ static private void clean() { while( true ) { ArrayList<Transaction> closing; int count; if( logger.isInfoEnabled() ) { logger.info("There are " + connections.get() + " open connections right now (high point: " + highPoint.get() + ")."); } try { Thread.sleep(1000L); } catch( InterruptedException ignore ) { /* ignore me */ } count = transactions.size(); if( count < 1 ) { continue; } if( logger.isInfoEnabled() ) { logger.info("Running the maid service on " + count + " transactions."); } closing = new ArrayList<Transaction>(); long now = System.currentTimeMillis(); // ConcurrentHashMap provides a weakly-consistent view for this iterator for( Transaction xaction : transactions.values() ) { long diff = (now - xaction.openTime)/1000L; if( diff > 10 ) { Thread t = xaction.executionThread; logger.warn("Open transaction " + xaction.transactionId + " has been open for " + diff + " seconds."); logger.warn("Transaction " + xaction.transactionId + " state: " + xaction.state); if( t== null ) { logger.warn("Thread: no execution thread active"); } else { logger.warn("Thread " + t.getName() + " (" + t.getState() + "):"); for( StackTraceElement elem : t.getStackTrace() ) { logger.warn("\t" + elem.toString()); } } } if( diff > 600 ) { closing.add(xaction); } } for( Transaction xaction: closing ) { logger.warn("Encountered a stale transaction (" + xaction.transactionId + "), forcing a close: " + xaction.state); xaction.logStackTrace(); xaction.close(); } } } /** * Provides a new transaction instance to manage your transaction * context. * @return the transaction for your new transaction context */ static public Transaction getInstance() { return getInstance(false); } static public Transaction getInstance(boolean readOnly) { Transaction xaction; final int xid = nextTransactionId.incrementAndGet(); if( xid == Integer.MAX_VALUE ) { nextTransactionId.set(0); } xaction = new Transaction(xid, readOnly); if (maidLaunched.compareAndSet(false, true)) { final Thread maid = new Thread() { public void run() { clean(); } }; maid.setName("Transaction Maid"); maid.setDaemon(true); maid.setPriority(Thread.MIN_PRIORITY + 1); maid.start(); } return xaction; } static public void report() { MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); StringBuilder sb = new StringBuilder(); sb.append("Dasein Connection Report (" + new Date() + "):"); sb.append("Open connections: " + connections); sb.append(", High connections: " + highPoint); sb.append(", Transaction cache size: " + transactions.size()); sb.append(", Event cache size: " + eventCache.size()); sb.append(", Heap memory usage: " + bean.getHeapMemoryUsage()); sb.append(", Non-heap memory usage: " + bean.getNonHeapMemoryUsage()); sb.append(", Free memory: " + (Runtime.getRuntime().freeMemory() / 1024000L) + "MB"); sb.append(", Total memory: " + (Runtime.getRuntime().totalMemory() / 1024000L) + "MB"); sb.append(", Max memory: " + (Runtime.getRuntime().maxMemory() / 1024000L) + "MB"); logger.info(sb.toString()); } /** * A connection object for this transaction. */ private volatile Connection connection = null; /** * Marks the transaction as dirty and no longer able to be used. */ private volatile boolean dirty = false; private volatile Thread executionThread = null; /** * A stack of events that are part of this transaction. */ private final Stack<Execution> events = new Stack<Execution>(); private final Stack<String> statements = new Stack<String>(); /** * Marks the time the transaction was opened so it can be closed. */ private long openTime = 0L; /** * Defines this transaction as being a read-only transaction. */ private boolean readOnly = false; /** * A state tracker for debugging purposes. */ private String state = "NEW"; /** * A unique transaction identifier. */ private int transactionId; private StackTraceElement[] stackTrace; /** * Constructs a transaction object having the specified transaction ID. * @param xid the transaction ID that identifies the transaction * @param readOnly true if the transaction is just for reading. */ private Transaction(int xid, boolean readOnly) { super(); transactionId = xid; this.readOnly = readOnly; } /** * Closes the transaction. If the transaction has not been committed, * it is rolled back. */ public void close() { logger.debug("enter - close()"); try { state = "CLOSING"; if( connection != null ) { logger.warn("Connection not committed, rolling back."); rollback(); } logger.debug("Closing all open events."); if( !events.empty() ) { state = "CLOSING EVENTS"; do { Execution exec = (Execution)events.pop(); try { Stack<Execution> stack; exec.close(); stack = eventCache.get(exec.getClass().getName()); if( stack != null ) { stack.push(exec); } } catch( Throwable t ) { logger.error(t.getMessage(), t); } } while( !events.empty() ); } state = "CLOSED"; logger.debug("return - close()"); } finally { if( logger.isDebugEnabled() ) { logger.debug("Removing transaction: " + transactionId); } transactions.remove(new Integer(transactionId)); logger.debug("exit - close()"); events.clear(); statements.clear(); stackTrace = null; } } /** * Commits the transaction to the database and closes the transaction. * The transaction should not be used or referenced after calling * this method. * @throws org.dasein.persist.PersistenceException either you are trying * to commit to a used up transaction or a database error occurred * during the commit */ public void commit() throws PersistenceException { logger.debug("enter - commit()"); try { if( connection == null ) { if( dirty ) { throw new PersistenceException("Attempt to commit a committed or aborted transaction."); } logger.debug("return as no-op - commit()"); return; } state = "COMMITTING"; try { if( logger.isDebugEnabled() ) { logger.debug("Committing: " + transactionId); } connection.commit(); state = "CLOSING CONNECTIONS"; connection.close(); connection = null; final int numConnections = connections.decrementAndGet(); if( logger.isInfoEnabled() ) { logger.info("Reduced the number of connections from " + (numConnections+1) + " due to commit."); } if( logger.isDebugEnabled() ) { logger.debug("Releasing: " + transactionId); } close(); logger.debug("return - commit()"); } catch( SQLException e ) { throw new PersistenceException(e.getMessage()); } finally { if( connection != null ) { logger.warn("Commit failed: " + transactionId); rollback(); } dirty = true; } } finally { logger.debug("exit - commit()"); } } public Map<String,Object> execute(Class<? extends Execution> cls, Map<String,Object> args) throws PersistenceException { return execute(cls, args, null); } public Map<String,Object> execute(Class<? extends Execution> cls, Map<String,Object> args, String dsn) throws PersistenceException { logger.debug("enter - execute(Class,Map)"); try { StringBuilder holder = new StringBuilder(); boolean success = false; executionThread = Thread.currentThread(); state = "PREPARING"; try { Execution event = getEvent(cls); Map<String,Object> res; if( connection == null ) { if( logger.isDebugEnabled() ) { logger.debug("New connection: " + transactionId); } open(event, dsn); } /* stateargs = event.loadStatement(connection, args); if( stateargs == null ) { state = "EXECUTING"; } else { state = "EXECUTING:\n" + stateargs; } */ state = "EXECUTING " + event.getClass().getName(); stackTrace = Thread.currentThread().getStackTrace(); res = event.executeEvent(this, args, holder); events.push(event); statements.push(holder.toString()); success = true; logger.debug("return - execute(Execution, Map)"); state = "AWAITING COMMIT: " + holder.toString(); return res; } catch( SQLException e ) { String err = "SQLException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.warn(err, e); } else { logger.warn(err); } throw new PersistenceException(e); } catch( InstantiationException e ) { String err = "Instantiation exception: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(e); } catch( IllegalAccessException e ) { String err = "IllegalAccessException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(e); } catch( RuntimeException e ) { logger.error("RuntimeException: " + e.getMessage(), e); throw new PersistenceException(e); } catch( Error e ) { String err = "Error: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(new RuntimeException(e)); } finally { if( !success ) { logger.warn("FAILED TRANSACTION (" + transactionId + "): " + holder.toString()); rollback(); } executionThread = null; } } finally { logger.debug("exit - execute(Class,Map)"); } } public Map<String,Object> execute(Execution event, Map<String,Object> args, String dsn) throws PersistenceException { logger.debug("enter - execute(Class,Map)"); try { StringBuilder holder = new StringBuilder(); boolean success = false; executionThread = Thread.currentThread(); state = "PREPARING"; try { Map<String,Object> res; if( connection == null ) { if( logger.isDebugEnabled() ) { logger.debug("New connection: " + transactionId); } open(event, dsn); } //stateargs = event.loadStatement(connection, args); state = "EXECUTING " + event.getClass().getName(); stackTrace = Thread.currentThread().getStackTrace(); res = event.executeEvent(this, args, holder); events.push(event); statements.push(holder.toString()); success = true; state = "AWAITING COMMIT: " + holder.toString(); logger.debug("return - execute(Execution, Map)"); return res; } catch( SQLException e ) { String err = "SQLException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.warn(err, e); } else { logger.warn(err); } throw new PersistenceException(e); } catch( RuntimeException e ) { logger.error("RuntimeException: " + e.getMessage(), e); throw new PersistenceException(e); } catch( Error e ) { String err = "Error: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(new RuntimeException(e)); } finally { if( !success ) { logger.warn("FAILED TRANSACTION (" + transactionId + "): " + holder.toString()); rollback(); } executionThread = null; } } finally { logger.debug("exit - execute(Class,Map)"); } } /** * Executes the specified event as part of this transaction. * @param event the event to execute in this transaction context * @param args the values to be used by the event * @return results from the transaction, can be null * @throws org.dasein.persist.PersistenceException an error occurred * interacting with the database * @deprecated use {@link #execute(Class, Map)} */ public HashMap<String,Object> execute(Execution event, Map<String,Object> args) throws PersistenceException { Map<String,Object> r = execute(event.getClass(), args); if( r == null ) { return null; } if( r instanceof HashMap ) { return (HashMap<String,Object>)r; } else { HashMap<String,Object> tmp = new HashMap<String,Object>(); tmp.putAll(r); return tmp; } } /** * Provides events with access to the connection supporting this * transaction. * @return the connection supporting this transaction */ public Connection getConnection() { return connection; } private Execution getEvent(Class<? extends Execution> cls) throws InstantiationException, IllegalAccessException { Stack<Execution> stack = eventCache.get(cls.getName()); Execution event; if( stack != null ) { // by not checking for empty, we can skip synchronization try { event = stack.pop(); } catch( EmptyStackException e ) { event = null; } if( event != null ) { return event; } } else { stack = new Stack<Execution>(); eventCache.put(cls.getName(), stack); } event = cls.newInstance(); return event; } /** * Each transaction has a number that helps identify it for debugging purposes. * @return the identifier for this transaction */ public int getTransactionId() { return transactionId; } /** * @return a unique hash code */ public int hashCode() { return transactionId; } /** * Opens a connection for the specified execution. * @param event the event causing the open * @throws SQLException * @throws PersistenceException */ private synchronized void open(Execution event, String dsn) throws SQLException, PersistenceException { logger.debug("enter - open(Execution)"); try { Connection conn; if( connection != null ) { return; } state = "OPENING"; openTime = System.currentTimeMillis(); if( logger.isDebugEnabled() ) { logger.debug("Opening " + transactionId); } try { InitialContext ctx = new InitialContext(); DataSource ds; if( dsn == null ) { dsn = event.getDataSource(); } state = "LOOKING UP"; ds = (DataSource)ctx.lookup(dsn); conn = ds.getConnection(); openTime = System.currentTimeMillis(); if( logger.isDebugEnabled() ) { logger.debug("Got connection for " + transactionId + ": " + conn); } state = "CONNECTED"; } catch( NamingException e ) { logger.error("Problem with datasource: " + e.getMessage()); throw new PersistenceException(e.getMessage()); } conn.setAutoCommit(false); conn.setReadOnly(readOnly); connection = conn; final int numConnections = connections.incrementAndGet(); final int numHighPoint = highPoint.get(); if( logger.isInfoEnabled() ) { logger.info("Incremented connection count to " + numConnections); } if( numConnections > numHighPoint) { if (highPoint.compareAndSet(numHighPoint, numConnections)) { if( logger.isInfoEnabled() ) { logger.info("A NEW CONNECTION HIGH POINT HAS BEEN REACHED: " + highPoint); } } } transactions.put(new Integer(transactionId), this); logger.debug("return - open(Execution)"); } finally { logger.debug("exit - open(Execution)"); } } private String elementToString(StackTraceElement element) { int no = element.getLineNumber(); String ln; if( no < 10 ) { ln = " " + no; } else if( no < 100 ) { ln = " " + no; } else if( no < 1000 ) { ln = " " + no; } else if( no < 10000 ) { ln = " " + no; } else { ln = " " + no; } return ln + " " + element.getFileName() + ": " + element.getClassName() + "." + element.getMethodName(); } private void logStackTrace() { if( stackTrace == null ) { logger.error("--> No stack trace, ID " + transactionId +" <--"); } else { StringBuilder sb = new StringBuilder("Stack trace for ").append(transactionId).append(":\n"); for( StackTraceElement element : stackTrace ) { sb.append(elementToString(element)).append('\n'); } logger.error(sb.toString()); } } /** * Rolls back the transaction and closes this transaction. The * transaction should no longer be referenced after this point. */ public void rollback() { rollback(false); } protected void rollback(boolean cancelStatements) { logger.debug("enter - rollback()"); try { if( connection == null ) { return; } if (cancelStatements) { int numCancelled = 0; for (Execution event : events) { final Statement stmt = event.statement; if (stmt != null) { try { if (!stmt.isClosed()) { stmt.cancel(); numCancelled += 1; } } catch (Throwable t) { logger.error("Problem cancelling statement: " + t.getMessage()); } } } if (numCancelled > 0) { if (numCancelled == 1) { logger.warn("Cancelled 1 query"); } else { logger.warn("Cancelled " + numCancelled + " queries"); } } } state = "ROLLING BACK"; logger.debug("Rolling back JDBC connection: " + transactionId); try { connection.rollback(); } catch( SQLException e ) { logger.error("Problem with rollback: " + e.getMessage(), e); } try { connection.close(); } catch( SQLException e ) { logger.error("Problem closing connection: " + e.getMessage(), e); } connection = null; final int numConnections = connections.decrementAndGet(); if( logger.isInfoEnabled() ) { logger.info("Reducing the number of connections from " + (numConnections+1) + " due to rollback."); } close(); dirty = true; logger.debug("return - rollback()"); } finally { logger.debug("exit - rollback()"); } } }
src/main/java/org/dasein/persist/Transaction.java
/** * Copyright (C) 1998-2011 enStratusNetworks LLC * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ /* $Id: Transaction.java,v 1.14 2009/07/02 01:36:20 greese Exp $ */ /* Copyright (c) 2002-2004 Valtira Corporation, All Rights Reserved */ package org.dasein.persist; // J2SE imports import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.EmptyStackException; import java.util.HashMap; import java.util.Map; import java.util.Stack; // J2EE imports import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; // Apache imports import org.apache.log4j.Logger; /** * Represents a database transaction to applications managing their * own transactions. To use this class, call <code>getInstance()</code> * to get a transaction and pass that transaction to all * <code>Execution</code> objects that need to execute in the same * transaction context. * <br/> * Last modified: $Date: 2009/07/02 01:36:20 $ * @version $Revision: 1.14 $ * @author George Reese */ public class Transaction { static private Logger logger = Logger.getLogger(Transaction.class); /** * A count of open connections. */ static private int connections = 0; /** * The most transactions ever open at a single time. */ static private int highPoint = 0; /** * The maid service cleans up dead transactions. */ static private Thread maid = null; /** * The next transaction ID to use. */ static private int nextTransaction = 1; /** * A list of open transactions. */ static private Map<Number,Transaction> transactions = new HashMap<Number,Transaction>(); static private Map<String,Stack<Execution>> eventCache = new HashMap<String,Stack<Execution>>(); /** * Cleans up transactions that somehow never got cleaned up. */ static private void clean() { while( true ) { ArrayList<Transaction> closing; int count; if( logger.isInfoEnabled() ) { logger.info("There are " + connections + " open connections right now (high point: " + highPoint + ")."); } try { Thread.sleep(1000L); } catch( InterruptedException ignore ) { /* ignore me */ } count = transactions.size(); if( count < 1 ) { continue; } if( logger.isInfoEnabled() ) { logger.info("Running the maid service on " + count + " transactions."); } closing = new ArrayList<Transaction>(); synchronized( transactions ) { long now = System.currentTimeMillis(); for( Transaction xaction : transactions.values() ) { long diff = (now - xaction.openTime)/1000L; if( diff > 10 ) { Thread t = xaction.executionThread; logger.warn("Open transaction " + xaction.transactionId + " has been open for " + diff + " seconds."); logger.warn("Transaction " + xaction.transactionId + " state: " + xaction.state); if( t== null ) { logger.warn("Thread: no execution thread active"); } else { logger.warn("Thread " + t.getName() + " (" + t.getState() + "):"); for( StackTraceElement elem : t.getStackTrace() ) { logger.warn("\t" + elem.toString()); } } } if( diff > 600 ) { closing.add(xaction); } } } for( Transaction xaction: closing ) { logger.warn("Encountered a stale transaction (" + xaction.transactionId + "), forcing a close: " + xaction.state); xaction.logStackTrace(); xaction.close(); } } } /** * Provides a new transaction instance to manage your transaction * context. * @return the transaction for your new transaction context */ static public Transaction getInstance() { return getInstance(false); } static public Transaction getInstance(boolean readOnly) { Transaction xaction; int xid; if( nextTransaction == Integer.MAX_VALUE ) { nextTransaction = 0; } xid = nextTransaction++; xaction = new Transaction(xid, readOnly); if( maid == null ) { synchronized( transactions ) { // this bizarreness avoids synchronizing for most cases if( maid == null ) { maid = new Thread() { public void run() { clean(); } }; maid.setDaemon(true); maid.setPriority(Thread.MIN_PRIORITY + 1); maid.setName("Transaction Maid"); maid.start(); } } } return xaction; } static public void report() { MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); StringBuilder sb = new StringBuilder(); sb.append("Dasein Connection Report (" + new Date() + "):"); sb.append("Open connections: " + connections); sb.append(", High connections: " + highPoint); sb.append(", Transaction cache size: " + transactions.size()); sb.append(", Event cache size: " + eventCache.size()); sb.append(", Heap memory usage: " + bean.getHeapMemoryUsage()); sb.append(", Non-heap memory usage: " + bean.getNonHeapMemoryUsage()); sb.append(", Free memory: " + (Runtime.getRuntime().freeMemory() / 1024000L) + "MB"); sb.append(", Total memory: " + (Runtime.getRuntime().totalMemory() / 1024000L) + "MB"); sb.append(", Max memory: " + (Runtime.getRuntime().maxMemory() / 1024000L) + "MB"); logger.info(sb.toString()); } /** * A connection object for this transaction. */ private Connection connection = null; /** * Marks the transaction as dirty and no longer able to be used. */ private boolean dirty = false; private Thread executionThread = null; /** * A stack of events that are part of this transaction. */ private Stack<Execution> events = new Stack<Execution>(); private Stack<String> statements = new Stack<String>(); /** * Marks the time the transaction was opened so it can be closed. */ private long openTime = 0L; /** * Defines this transaction as being a read-only transaction. */ private boolean readOnly = false; /** * A state tracker for debugging purposes. */ private String state = "NEW"; /** * A unique transaction identifier. */ private int transactionId; private StackTraceElement[] stackTrace; /** * Constructs a transaction object having the specified transaction ID. * @param xid the transaction ID that identifies the transaction * @param readOnly true if the transaction is just for reading. */ private Transaction(int xid, boolean readOnly) { super(); transactionId = xid; this.readOnly = readOnly; } /** * Closes the transaction. If the transaction has not been committed, * it is rolled back. */ public void close() { logger.debug("enter - close()"); try { state = "CLOSING"; if( connection != null ) { logger.warn("Connection not committed, rolling back."); rollback(); } logger.debug("Closing all open events."); if( !events.empty() ) { state = "CLOSING EVENTS"; do { Execution exec = (Execution)events.pop(); try { Stack<Execution> stack; exec.close(); stack = eventCache.get(exec.getClass().getName()); if( stack != null ) { stack.push(exec); } } catch( Throwable t ) { logger.error(t.getMessage(), t); } } while( !events.empty() ); } state = "CLOSED"; logger.debug("return - close()"); } finally { if( logger.isDebugEnabled() ) { logger.debug("Removing transaction: " + transactionId); } synchronized( transactions ) { transactions.remove(new Integer(transactionId)); } logger.debug("exit - close()"); events.clear(); statements.clear(); stackTrace = null; } } /** * Commits the transaction to the database and closes the transaction. * The transaction should not be used or referenced after calling * this method. * @throws org.dasein.persist.PersistenceException either you are trying * to commit to a used up transaction or a database error occurred * during the commit */ public void commit() throws PersistenceException { logger.debug("enter - commit()"); try { if( connection == null ) { if( dirty ) { throw new PersistenceException("Attempt to commit a committed or aborted transaction."); } logger.debug("return as no-op - commit()"); return; } state = "COMMITTING"; try { if( logger.isDebugEnabled() ) { logger.debug("Committing: " + transactionId); } connection.commit(); state = "CLOSING CONNECTIONS"; connection.close(); connection = null; if( logger.isInfoEnabled() ) { logger.info("Reducing the number of connections from " + connections + " due to commit."); } connections--; if( logger.isDebugEnabled() ) { logger.debug("Releasing: " + transactionId); } close(); logger.debug("return - commit()"); } catch( SQLException e ) { throw new PersistenceException(e.getMessage()); } finally { if( connection != null ) { logger.warn("Commit failed: " + transactionId); rollback(); } dirty = true; } } finally { logger.debug("exit - commit()"); } } public Map<String,Object> execute(Class<? extends Execution> cls, Map<String,Object> args) throws PersistenceException { return execute(cls, args, null); } public Map<String,Object> execute(Class<? extends Execution> cls, Map<String,Object> args, String dsn) throws PersistenceException { logger.debug("enter - execute(Class,Map)"); try { StringBuilder holder = new StringBuilder(); boolean success = false; executionThread = Thread.currentThread(); state = "PREPARING"; try { Execution event = getEvent(cls); Map<String,Object> res; if( connection == null ) { if( logger.isDebugEnabled() ) { logger.debug("New connection: " + transactionId); } open(event, dsn); } /* stateargs = event.loadStatement(connection, args); if( stateargs == null ) { state = "EXECUTING"; } else { state = "EXECUTING:\n" + stateargs; } */ state = "EXECUTING " + event.getClass().getName(); stackTrace = Thread.currentThread().getStackTrace(); res = event.executeEvent(this, args, holder); events.push(event); statements.push(holder.toString()); success = true; logger.debug("return - execute(Execution, Map)"); state = "AWAITING COMMIT: " + holder.toString(); return res; } catch( SQLException e ) { String err = "SQLException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.warn(err, e); } else { logger.warn(err); } throw new PersistenceException(e); } catch( InstantiationException e ) { String err = "Instantiation exception: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(e); } catch( IllegalAccessException e ) { String err = "IllegalAccessException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(e); } catch( RuntimeException e ) { logger.error("RuntimeException: " + e.getMessage(), e); throw new PersistenceException(e); } catch( Error e ) { String err = "Error: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(new RuntimeException(e)); } finally { if( !success ) { logger.warn("FAILED TRANSACTION (" + transactionId + "): " + holder.toString()); rollback(); } executionThread = null; } } finally { logger.debug("exit - execute(Class,Map)"); } } public Map<String,Object> execute(Execution event, Map<String,Object> args, String dsn) throws PersistenceException { logger.debug("enter - execute(Class,Map)"); try { StringBuilder holder = new StringBuilder(); boolean success = false; executionThread = Thread.currentThread(); state = "PREPARING"; try { Map<String,Object> res; if( connection == null ) { if( logger.isDebugEnabled() ) { logger.debug("New connection: " + transactionId); } open(event, dsn); } //stateargs = event.loadStatement(connection, args); state = "EXECUTING " + event.getClass().getName(); stackTrace = Thread.currentThread().getStackTrace(); res = event.executeEvent(this, args, holder); events.push(event); statements.push(holder.toString()); success = true; state = "AWAITING COMMIT: " + holder.toString(); logger.debug("return - execute(Execution, Map)"); return res; } catch( SQLException e ) { String err = "SQLException: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.warn(err, e); } else { logger.warn(err); } throw new PersistenceException(e); } catch( RuntimeException e ) { logger.error("RuntimeException: " + e.getMessage(), e); throw new PersistenceException(e); } catch( Error e ) { String err = "Error: " + e.getMessage(); if( logger.isDebugEnabled() ) { logger.error(err, e); } else { logger.error(err); } throw new PersistenceException(new RuntimeException(e)); } finally { if( !success ) { logger.warn("FAILED TRANSACTION (" + transactionId + "): " + holder.toString()); rollback(); } executionThread = null; } } finally { logger.debug("exit - execute(Class,Map)"); } } /** * Executes the specified event as part of this transaction. * @param event the event to execute in this transaction context * @param args the values to be used by the event * @return results from the transaction, can be null * @throws org.dasein.persist.PersistenceException an error occurred * interacting with the database * @deprecated use {@link #execute(Class, Map)} */ public HashMap<String,Object> execute(Execution event, Map<String,Object> args) throws PersistenceException { Map<String,Object> r = execute(event.getClass(), args); if( r == null ) { return null; } if( r instanceof HashMap ) { return (HashMap<String,Object>)r; } else { HashMap<String,Object> tmp = new HashMap<String,Object>(); tmp.putAll(r); return tmp; } } /** * Provides events with access to the connection supporting this * transaction. * @return the connection supporting this transaction */ public Connection getConnection() { return connection; } private Execution getEvent(Class<? extends Execution> cls) throws InstantiationException, IllegalAccessException { Stack<Execution> stack = eventCache.get(cls.getName()); Execution event; if( stack != null ) { // by not checking for empty, we can skip synchronization try { event = stack.pop(); } catch( EmptyStackException e ) { event = null; } if( event != null ) { return event; } } else { stack = new Stack<Execution>(); eventCache.put(cls.getName(), stack); } event = cls.newInstance(); return event; } /** * Each transaction has a number that helps identify it for debugging purposes. * @return the identifier for this transaction */ public int getTransactionId() { return transactionId; } /** * @return a unique hash code */ public int hashCode() { return transactionId; } /** * Opens a connection for the specified execution. * @param event the event causing the open * @throws SQLException * @throws PersistenceException */ private synchronized void open(Execution event, String dsn) throws SQLException, PersistenceException { logger.debug("enter - open(Execution)"); try { Connection conn; if( connection != null ) { return; } state = "OPENING"; openTime = System.currentTimeMillis(); if( logger.isDebugEnabled() ) { logger.debug("Opening " + transactionId); } try { InitialContext ctx = new InitialContext(); DataSource ds; if( dsn == null ) { dsn = event.getDataSource(); } state = "LOOKING UP"; ds = (DataSource)ctx.lookup(dsn); conn = ds.getConnection(); openTime = System.currentTimeMillis(); if( logger.isDebugEnabled() ) { logger.debug("Got connection for " + transactionId + ": " + conn); } state = "CONNECTED"; } catch( NamingException e ) { logger.error("Problem with datasource: " + e.getMessage()); throw new PersistenceException(e.getMessage()); } conn.setAutoCommit(false); conn.setReadOnly(readOnly); connection = conn; if( logger.isInfoEnabled() ) { logger.info("Incrementing connection count from " + connections); } connections++; if( connections > highPoint ) { highPoint = connections; if( logger.isInfoEnabled() ) { logger.info("A NEW CONNECTION HIGH POINT HAS BEEN REACHED: " + highPoint); } } synchronized( transactions ) { transactions.put(new Integer(transactionId), this); } logger.debug("return - open(Execution)"); } finally { logger.debug("exit - open(Execution)"); } } private String elementToString(StackTraceElement element) { int no = element.getLineNumber(); String ln; if( no < 10 ) { ln = " " + no; } else if( no < 100 ) { ln = " " + no; } else if( no < 1000 ) { ln = " " + no; } else if( no < 10000 ) { ln = " " + no; } else { ln = " " + no; } return ln + " " + element.getFileName() + ": " + element.getClassName() + "." + element.getMethodName(); } private void logStackTrace() { if( stackTrace == null ) { logger.error("--> No stack trace, ID " + transactionId +" <--"); } else { StringBuilder sb = new StringBuilder("Stack trace for ").append(transactionId).append(":\n"); for( StackTraceElement element : stackTrace ) { sb.append(elementToString(element)).append('\n'); } logger.error(sb.toString()); } } /** * Rolls back the transaction and closes this transaction. The * transaction should no longer be referenced after this point. */ public void rollback() { logger.debug("enter - rollback()"); try { if( connection == null ) { return; } state = "ROLLING BACK"; logger.debug("Rolling back JDBC connection: " + transactionId); try { connection.rollback(); } catch( SQLException e ) { logger.error("", e); } try { connection.close(); } catch( SQLException e ) { logger.error("", e); } connection = null; if( logger.isInfoEnabled() ) { logger.info("Reducing the number of connections from " + connections + " due to rollback."); } connections--; close(); dirty = true; logger.debug("return - rollback()"); } finally { logger.debug("exit - rollback()"); } } }
Reduce contention in transaction tracking
src/main/java/org/dasein/persist/Transaction.java
Reduce contention in transaction tracking
Java
artistic-2.0
b353d9bbdf347c4c9cf314db74d02a2b85a5ee0e
0
lawremi/PerFabricaAdAstra,lawremi/PerFabricaAdAstra
package org.pfaa.chemica.model; import java.awt.Color; import org.pfaa.chemica.model.ChemicalStateProperties.Gas; import org.pfaa.chemica.model.ChemicalStateProperties.Liquid; import org.pfaa.chemica.model.ChemicalStateProperties.Liquid.Yaws; import org.pfaa.chemica.model.ChemicalStateProperties.Solid; import org.pfaa.chemica.model.Formula.PartFactory; import org.pfaa.chemica.model.Hazard.SpecialCode; import org.pfaa.chemica.model.Vaporization.AntoineCoefficients; public interface Element extends Chemical, PartFactory, Metal { public double getAtomicWeight(); public int getDefaultOxidationState(); public Formula.Part _(int quantity); public Alloy alloy(Element solute, double weight); public Category getCategory(); public static enum Category { ALKALI_METAL, ALKALINE_EARTH_METAL, LANTHANIDE, ACTINIDE, TRANSITION_METAL, POST_TRANSITION_METAL, METALLOID, POLYATOMIC_NONMETAL, DIATOMIC_NONMETAL, NOBLE_GAS, UNKNOWN; public boolean isMetal() { return this.ordinal() < METALLOID.ordinal(); } } public static enum Elements implements Element { /* H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr R Sr Y Zr Nb Mo Tc Rb Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Ce La Pr Nd ... .. Th .. U ... */ /* * http://chemistrytable.webs.com/enthalpyentropyandgibbs.htm * http://www.periodictable.com/Properties/A/NFPALabel.html */ H("hydrogen", Category.DIATOMIC_NONMETAL, null, 1.00, +1), /* See Molecules.H2 for properties */ He("helium", Category.NOBLE_GAS, null, 4.00, 0, new Solid(0.187, new Thermo(9.85)), // artificial, He is weird new Fusion(0.95), new Liquid(0.13, new Thermo(-8.33, 18.4E3, -7.72E6, 1.18E9, 3.89E-6, 0.047, 11.8)), new Vaporization(4.22), new Gas(new Thermo(20.8, 0, 0, 0, 0, -6.2, 151))), Li("lithium", Category.ALKALI_METAL, Strength.WEAK, 6.94, +1, new Solid(new Color(240, 240, 240), 0.534, new Thermo(170, -883, 1977, -1487, -1.61, -31.2, 414), new Hazard(3, 2, 2, SpecialCode.WATER_REACTIVE)), new Fusion(454), new Liquid(0.512, new Thermo(32.5, -2.64, -6.33, 4.23, 0.00569, -7.12, 74.3) .addSegment(700, 26.0, 5.63, -4.01, 0.874, 0.344, -4.20, 66.4)), new Vaporization(1603), new Gas(new Thermo(23.3, -2.77, 0.767, -0.00360, -0.0352, 152, 166))), Be("beryllium", Category.ALKALINE_EARTH_METAL, Strength.STRONG, 9.01, +2, new Solid(new Color(40, 40, 40), 1.85, new Thermo(21.2, 5.69, 0.968, -0.00175, -0.588, -8.55, 30.1) .addSegment(1527, 30.0, -0.000396, 0.000169, -0.000026, -0.000105, -6.97, 40.8), new Hazard(3, 1, 0)), new Fusion(1560), new Liquid(1.69, new Thermo(25.4, 2.16, -0.00257, 0.000287, 0.00396, 5.44, 44.5)), new Vaporization(3243), new Gas(new Thermo(28.6, -5.38, 1.04, -0.0121, -426, 308, 164))), B("boron", Category.METALLOID, Strength.VERY_STRONG, 10.8, +3, new Solid(new Color(82, 53, 7), 2.37, new Thermo(10.2, 29.2, -18.0, 4.21, -0.551, -6.04, 7.09) .addSegment(1800, 25.1, 1.98, 0.338, -0.0400, -2.64, -14.4, 25.6), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(2349), new Liquid(2.08, new Thermo(48.9, 26.5, 31.8)), new Vaporization(4200), new Gas(new Thermo(20.7, 0.226, -0.112, 0.0169, 0.00871, 554, 178))), C("carbon", Category.POLYATOMIC_NONMETAL, Strength.WEAK /* graphite */, 12.0, +4, new Solid(Color.black, 2.27, new Thermo(0, 6.0, 9.25).addSegment(300, 10.7), new Hazard(0, 1, 0)), null, null, new Vaporization(3915), new Gas(new Thermo(21.2, -0.812, 0.449, -0.0433, -0.0131, 710, 184))), N("nitrogen", 14.0, -3), /* see Compounds.N2 for properties */ Na("sodium", 23.0, +1, new Solid(new Color(212, 216, 220), 0.968, new Thermo(72.6, -9.49, -731, 1415, -1.26, -21.8, 155), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(371), new Liquid(0.927, new Thermo(40.3, -28.2, 20.7, -3.64, -0.0799, -8.78, 114)), new Vaporization(2.46, 1874, -416), new Gas(new Thermo(20.8, 0.277, -0.392, 0.120, -0.00888, 101, 179))), Mg("magnesium", Category.ALKALINE_EARTH_METAL, Strength.MEDIUM, 24.3, +2, new Solid(new Color(157, 157, 157), 1.74, new Thermo(26.5, -1.53, 8.06, 0.572, -0.174, -8.50, 63.9), new Hazard(0, 1, 1)), new Fusion(923), new Liquid(1.58, new Thermo(4.79, 34.5, 34.3)), new Vaporization(1363), new Gas(new Thermo(20.8, 0.0356, -0.0319, 0.00911, 0.000461, 141) .addSegment(2200, 47.6, -15.4, 2.88, -0.121, -27.0, 97.4, 177))), Al("aluminum", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 31.0, +5, new Solid(new Color(177, 177, 177), 2.70, new Thermo(28.1, -5.41, 8.56, 3.43, -0.277, -9.15, 61.9), new Hazard(0, 1, 1)), new Fusion(933), new Liquid(2.38, new Thermo(10.6, 39.6, 31.8)), new Vaporization(5.74, 13204, -24.3), new Gas(new Thermo(20.4, 0.661, -0.314, 0.0451, 0.0782, 324, 189))), Si("silicon", Category.METALLOID, Strength.STRONG, 28.1, +4, new Solid(new Color(206, 227, 231), 2.33, new Thermo(22.8, 3.90, -0.0829, 0.0421, -0.354, -8.16, 43.3)), new Fusion(1687), new Liquid(2.57, new Thermo(48.5, 44.5, 27.2))), P("phosphorus", Category.POLYATOMIC_NONMETAL, null, 31.0, +5, new Solid(Color.white, 1.82, new Thermo(16.5, 43.3, -58.7, 25.6, -0.0867, -6.66, 50.0), new Hazard(4, 4, 2)), new Fusion(317.2), new Liquid(1.74, new Thermo(26.3, 1.04, -6.12, 1.09, 3.00, -7.23, 74.9)), new Vaporization(553), new Gas(new Thermo(20.4, 1.05, -1.10, 0.378, 0.011, 310, 188) .addSegment(2200, -2.11, 9.31, -0.558, -0.020, 29.3, 354, 190)) ), S("sulfur", Category.POLYATOMIC_NONMETAL, Strength.WEAK, 32.1, +4, new Solid(new Color(230, 230, 25), 2, new Thermo(21.2, 3.87, 22.3, -10.3, -0.0123, -7.09, 55.5), new Hazard()), new Fusion(388), new Liquid(1.82, new Thermo(4541, 26066, -55521, 42012, 54.6, 788, -10826) .addSegment(432, -37.9, 133, -95.3, 24.0, 7.65, 29.8, -13.2)), new Vaporization(718), new Gas(new Thermo(27.5, -13.3, 10.1, -2.66, -0.00558, 269, 204) .addSegment(1400, 16.6, 2.40, -0.256, 0.00582, 3.56, 278, 195)) ), Cl("chlorine", 34.5, -1), /* See Compounds.Cl2 for properties */ K("potassium", 39.1, +1, new Solid(new Color(219, 219, 219), 0.862, new Thermo(-63.5, -3226, 14644, -16229, 16.3, 120, 534), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(337), new Liquid(0.828, new Thermo(40.3, -30.5, 26.5, -5.73, -0.0635, -8.81, 128)), new Vaporization(new AntoineCoefficients(4.46, 4692, 24.2)), new Gas(new Thermo(20.7, 0.392, -0.417, 0.146, 0.00376, 82.8, 185) .addSegment(1800, 58.7, -27.4, 6.73, -0.421, -25.9, 32.4, 198))), Ca("calcium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 40.1, +2, new Solid(new Color(228, 237, 237), 1.55, new Thermo(19.8, 10.1, 14.5, -5.53, 0.178, -5.86, 62.9), new Hazard(3, 1, 2, SpecialCode.WATER_REACTIVE)), new Fusion(1115), new Liquid(1.38, new Thermo(7.79, 45.5, 35.0)), new Vaporization(new AntoineCoefficients(2.78, 3121, -595)), new Gas(new Thermo(122, -75, 19.2, -1.40, -64.5, 42.2, 217))), // Skipped Sc Ti("titanium", Category.TRANSITION_METAL, Strength.STRONG, 47.9, +4, new Solid(new Color(230, 230, 230), 4.51, new Thermo(23.1, 5.54, -2.06, 1.61, -0.0561, -0.433, 64.1), new Hazard(1, 1, 2)), new Fusion(1941), new Liquid(4.11, new Thermo(13.7, 39.2, -22.1)), new Vaporization(3560), new Gas(new Thermo(9.27, 6.09, 0.577, -0.110, 6.50, 483, 204))), V("vanadium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 50.9, +5, new Solid(new Color(145, 170, 190), 6.0, new Thermo(26.3, 1.40, 2.21, 0.404, -0.176, -8.52, 59.3), new Hazard(2, 1, 0)), new Fusion(2183), new Liquid(5.5, new Thermo(17.3, 36.1, 46.2)), new Vaporization(3680), new Gas(new Thermo(32.0, -9.12, 2.94, -0.190, 1.41, 505, 220))), Cr("chromium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 52.0, +3, new Solid(new Color(212, 216, 220), 7.19, new Thermo(7.49, 71.5, -91.7, 46.0, 0.138, -4.23, 15.8) .addSegment(600, 18.5, 5.48, 7.90, -1.15, 1.27, -2.68, 48.1), new Hazard(2, 1, 1)), new Fusion(2180), new Liquid(6.3, new Thermo(21.6, 36.2, 39.3)), new Vaporization(2944), new Gas(new Thermo(13.7, -3.42, 0.394, -16.7, 383, 183, 397))), Mn("manganese", Category.TRANSITION_METAL, Strength.STRONG, 54.9, +4, new Solid(new Color(212, 216, 220), 7.21, new Thermo(27.2, 5.24, 7.78, -2.12, -0.282, -9.37, 61.5) .addSegment(980, 52.3, -28.7, 21.5, -4.98, -2.43, -21.2, 90.7) .addSegment(1361, 19.1, 31.4, -15.0, 3.21, 1.87, -2.76, 48.8) .addSegment(1412, -534, 679, -296, 46.4, 161, 469, -394)), new Fusion(1519), new Liquid(5.95, new Thermo(16.3, 43.5, 46.0)), new Vaporization(2334), new Gas(new Thermo(188, -97.8, 20.2, -1.27, -177, 1.55, 220))), Fe("iron", Category.TRANSITION_METAL, Strength.STRONG, 55.8, +3, new Solid(Color.gray, 7.87, new Thermo(24.0, 8.37, 0.000277, -8.60E-5, -5.00E-6, 0.268, 62.1), new Hazard(1, 1, 0)), new Fusion(1811), new Liquid(6.98, new Thermo(12, 35, 46.0)), new Vaporization(3134), new Gas(new Thermo(11.3, 6.99, -1.11, 0.122, 5.69, 424, 206))), Co("cobalt", Category.TRANSITION_METAL, Strength.STRONG, 58.9, +2, new Solid(Color.gray, 8.90, new Thermo(11.0, 54.4, -55.5, 25.8, 0.165, -4.70, 30.3) .addSegment(700, -205, 516, -422, 130, 18.0, 94.6, -273) .addSegment(1394, -12418, 15326, -7087, 1167, 3320, 10139, -10473)), new Fusion(1768), new Liquid(7.75, new Thermo(45.6, -3.81, 1.03, -0.0967, -3.33, -8.14, 78.0)), new Vaporization(3200), new Gas(new Thermo(40.7, -8.46, 1.54, -0.0652, -11.1, 397, 213))), Ni("nickel", Category.TRANSITION_METAL, Strength.MEDIUM, 58.7, +2, new Solid(new Color(160, 160, 140), 8.91, new Thermo(13.7, 82.5, -175, 162, -0.0924, -6.83, 27.7) .addSegment(600, 1248, -1258, 0, 0, -165, -789, 1213) .addSegment(700, 16.5, 18.7, -6.64, 1.72, 1.87, -0.468, 51.7), new Hazard(2, 4, 1)), new Fusion(1728), new Liquid(7.81, new Thermo(17.5, 41.5, 38.9)), new Vaporization(3186), new Gas(new Thermo(27.1, -2.59, 0.295, 0.0152, 0.0418, 421, 214))), Cu("copper", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2, new Solid(new Color(208, 147, 29), 8.96, new Thermo(17.7, 28.1, -31.3, 14.0, 0.0686, -6.06, 47.9), new Hazard(1, 1, 0)), new Fusion(1358), new Liquid(8.02, new Thermo(17.5, 41.5, 32.8)), new Vaporization(2835), new Gas(new Thermo(-80.5, 49.4, -7.58, 0.0405, 133, 520, 194))), Zn("zinc", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2, new Solid(new Color(230, 230, 230), 7.14, new Thermo(25.6, -4.41, 20.4, -7.40, -0.0458, -7.56, 72.9), new Hazard(2, 0, 0)), new Fusion(673), new Liquid(6.57, new Thermo(6.52, 50.8, 31.4)), new Vaporization(1180), new Gas(new Thermo(18.2, 2.31, -0.737, 0.0800, 1.07, 127, 185))), Ga("gallium", Category.POST_TRANSITION_METAL, Strength.WEAK, 69.7, +3, new Solid(new Color(212, 216, 220), 5.91, new Thermo(102, -348, 603, -361, -1.49, -24.7, 236), new Hazard(1, 0, 0)), new Fusion(303), new Liquid(6.10, new Thermo(24.6, 2.70, -1.27, 0.197, 0.286, -0.909, 89.9)), new Vaporization(2673), new Gas(new Thermo(20.3, 0.570, -0.210, 0.0258, 3.05, 273, 201))), // TODO: Ge As("arsenic", 74.9, +3, new Solid(new Color(112, 112, 112), 5.73, new Thermo(0, 35.1, 21.6, 9.79), new Hazard(3, 2, 0)), null, null, new Vaporization(887), new Gas(new Thermo(74.3))), O("oxygen", 16.0, -2), /* See Compounds.O2 for properties */ F("fluorine", 19.0, -1), /* See Compounds.F2 for properties, solid density 1.7 */ Sr("strontium", 87.6, +2, new Solid(new Color(212, 216, 220), 2.64, new Thermo(23.9, 9.30, 0.920, 0.0352, 0.00493, -7.53, 81.8), new Hazard(4, 0, 2, SpecialCode.WATER_REACTIVE)), new Fusion(1050), new Liquid(2.38, new Thermo(0.91, 50.9, 39.5)), new Vaporization(1650), new Gas(new Thermo(19.4, 3.74, -3.19, 0.871, 0.0540, 158, 187) .addSegment(2700, -39.0, -1.70, 7.99, -0.852, 188, 355, 243))), Y("yttrium", Category.TRANSITION_METAL, null, 88.9, +3, new Solid(new Color(212, 216, 220), 4.47, new Thermo(0, 44.4, 24.4, 6.99)), new Fusion(1799), new Liquid(4.24, new Thermo(50.7)), new Vaporization(3203), new Gas(new Thermo(164))), Zr("zirconium", Category.TRANSITION_METAL, Strength.STRONG, 91.2, +4, new Solid(new Color(212, 216, 220), 6.52, new Thermo(29, -12.6, 20.7, -5.91, -0.157, -8.79, 76.0), new Hazard(1, 1, 0)), new Fusion(2128), new Liquid(5.8, new Thermo(17.4, 47.6, 41.8)), new Vaporization(4650), new Gas(new Thermo(39.5, -6.52, 2.26, -0.194, -12.5, 578, 212))), Nb("niobium", Category.TRANSITION_METAL, Strength.STRONG, 92.9, +5, new Solid(new Color(135, 150, 160), 8.57, new Thermo(22.0, 9.89, -5.65, 1.76, 0.0218, -6.88, 60.5), new Hazard(1, 1, 0)), new Fusion(2750), new Liquid(Double.NaN, new Thermo(29.7, 47.3, 33.5)), new Vaporization(5017), new Gas(new Thermo(-14637, 5142, -675, 31.5, 47657, 42523, 6194))), Mo("molybdenum", Category.TRANSITION_METAL, Strength.STRONG, 96, +4, new Solid(new Color(105, 105, 105), 10.3, new Thermo(24.7, 3.96, -1.27, 1.15, -0.17, -8.11, 56.4) .addSegment(1900, 1231, -963, 284, -28, -712, -1486, 574), new Hazard(1, 3, 0)), new Fusion(2896), new Liquid(9.33, new Thermo(41.6, 43.1, 37.7)), new Vaporization(4912), new Gas(new Thermo(67.9, -40.5, 11.7, -0.819, -22.1, 601, 232))), Rb("rubidium", 85.5, +1, new Solid(new Color(175, 175, 175), 1.53, new Thermo(9.45, 65.3, 45.5, -26.8, -0.108, -6.43, 66.3), new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)), new Fusion(312), new Liquid(1.46, new Thermo(35.5, -12.9, 8.55, -0.00283, -0.000119, -7.90, 130)), new Vaporization(961), new Gas(new Thermo(20.6, 0.462, -0.495, 0.174, 0.00439, 74.7, 195) .addSegment(1800, 74.1, -39.2, 9.91, -0.679, -35.1, 4.97, 214))), Ag("silver", 108, +1, new Solid(new Color(213, 213, 213), 10.5, new Thermo(0, 42.6, 23.4, 6.28), new Hazard(1, 1, 0)), new Fusion(1235), new Liquid(9.32, new Thermo(24.7, 52.3, 339, -45)), new Vaporization(1.95, 2505, -1195), new Gas(new Thermo(285, 173, Double.NaN))), Cd("cadmium", 112, +2, new Solid(new Color(190, 190, 210), 8.65, new Thermo(0, 51.8, 22.8, 10.3), new Hazard(2, 2, 0)), new Fusion(594), new Liquid(8.00, new Thermo(Double.NaN, 62.2, 29.7)), new Vaporization(1040), new Gas(new Thermo(112, 168, 20.8))), // TODO: In Sn("tin", 119, +4, new Solid(new Color(212, 216, 220), 7.28, new Thermo(0, 51.2, 23.1, 19.6), new Hazard(1, 3, 3)), new Fusion(505), new Liquid(6.97, new Thermo(65.1)), // FIXME: need liquid heat capacity new Vaporization(6.60, 16867, 15.5), new Gas(new Thermo(168))), Sb("antimony", 122, +3, new Solid(new Color(212, 216, 220), 6.70, new Thermo(0, 45.7, 23.1, 7.45), // NOTE: heating is extremely dangerous new Hazard(4, 4, 2)), new Fusion(904), new Liquid(6.53, new Thermo(67.6)), new Vaporization(2.26, 4475, -152), new Gas(new Thermo(168))), Cs("caesium", 133, +1, new Solid(new Color(170, 160, 115), 1.93, new Thermo(57.0, -50.0, 48.6, -16.7, -1.22, -19.3, 160), new Hazard(4, 3, 3, SpecialCode.WATER_REACTIVE)), new Fusion(302), new Liquid(1.84, new Thermo(30.0, 0.506, 0.348, -0.0995, 0.197, -6.23, 129)), new Vaporization(3.70, 3453, -26.8), new Gas(new Thermo(76.5, 175, 20.8) .addSegment(1000, 34.5, -13.8, 4.13, -0.138, -3.95, 58.2, 211) .addSegment(4000, -181, 80.0, -9.19, 0.330, 374, 518, 242))), Ba("barium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 137, +2, new Solid(new Color(70, 70, 70), 3.51, new Thermo(83.8, -406, 915, -520, -14.6, 248) .addSegment(583, 76.7, -188, 296, -114, -4.34, -25.6, 189) .addSegment(768, 26.2, 28.6, -23.7, 6.95, 1.04, -5.80, 90), new Hazard(2, 1, 2)), new Fusion(1000), new Liquid(3.34, new Thermo(55.0, -18.7, 2.76, 1.28, 3.02, -8.42, 135)), new Vaporization(4.08, 7599, -45.7), new Gas(new Thermo(-623, 430, -97.0, 7.47, 488, 1077, 19.0) .addSegment(4000, 770, -284, 41.4, -2.13, -1693, -1666, -26.3))), // Skipped Lu and Hf Ta("tantalum", Category.TRANSITION_METAL, Strength.STRONG, 181, +5, new Solid(new Color(185, 190, 200), 16.7, new Thermo(20.7, 17.3, -15.7, 5.61, 0.0616, -6.60, 62.4) .addSegment(1300, -43.9, 73.0, -27.4, 4.00, 26.3, 60.2, 25.7), new Hazard(1, 1, 0)), new Fusion(3290), new Liquid(15, new Thermo(30.8, 50.4, 41.8)), new Vaporization(5731), new Gas(new Thermo(29.5, 3.42, -0.566, 0.0697, -4.93, 763, 208))), W("tungsten", Category.TRANSITION_METAL, Strength.VERY_STRONG, 184, +6, new Solid(new Color(140, 140, 140), 19.3, new Thermo(24.0, 2.64, 1.26, -0.255, -0.0484, -7.43, 60.5) .addSegment(1900, -22.6, 90.3, -44.3, 7.18, -24.1, -9.98, -14.2), new Hazard(1, 2, 1)), new Fusion(3695), new Liquid(17.6, new Thermo(46.9, 45.7, 35.6)), new Vaporization(6203), new Gas(new Thermo(174))), Re("rhenium", 186, +7, new Solid(new Color(212, 216, 220), 21.0, new Thermo(0, 36.9, 26.4, 2.22)), new Fusion(3459), new Liquid(18.9, new Thermo(54.4))), Au("gold", 197, +3, new Solid(new Color(255, 215, 0), 19.3, new Thermo(0, 47.4, 23.2, 6.16, -0.618, -0.0355), new Hazard(2, 0, 0)), new Fusion(1337), new Liquid(17.3, new Thermo(57.8)), // FIXME: better thermodynamics for liquid gold! new Vaporization(5.47, 17292, -71), new Gas(new Thermo(366, 180, 20.8))), Hg("mercury", Category.TRANSITION_METAL, null, 201, +2, new Solid(new Color(155, 155, 155), 14.25, new Thermo(-2.18, 66.1, 21.5, 29.2)), new Fusion(234), new Liquid(new Color(188, 188, 188), 13.5, new Thermo(0, 75.9, 28), new Hazard(3, 0, 0), new Yaws(-0.275, 137, 4.18E-6, -1.20E-9)), new Vaporization(4.86, 3007, -10.0), new Gas(new Thermo(20.7, 0.179, -0.0801, 0.0105, 0.00701, 55.2, 200))), // Skipped Tl Pb("lead", Category.POST_TRANSITION_METAL, Strength.WEAK, 207, +2, new Solid(new Color(65, 65, 65), 11.3, new Thermo(25.0, 5.44, 4.06, -1.24, -0.0107, -7.77, 93.2), new Hazard(2, 0, 0)), new Fusion(601), new Liquid(10.7, new Thermo(38.0, -14.6, 7.26, -1.03, -0.331, -7.94, 119)), new Vaporization(2022), new Gas(new Thermo(-85.7, 69.3, -13.3, 0.840, 63.1, 333, 170))), Bi("bismuth", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 209, +3, new Solid(new Color(213, 213, 213), 9.78, new Thermo(0, 56.7, 21.1, 14.7)), new Fusion(545), new Liquid(10.1, new Thermo(0 /* dummy */, 77.4, 31.8)), new Vaporization(1837), new Gas(new Thermo(175))), // Skipped Po, At, and many others... Ce("cerium", Category.LANTHANIDE, null, 140, +3, new Solid(new Color(212, 216, 220), 6.77, new Thermo(0, 72.0, 24.6, 0.005), new Hazard(2, 3, 2)), new Fusion(1068), new Liquid(6.55, new Thermo(77.1)), new Vaporization(3716), new Gas(new Thermo(184))), La("lanthanum", Category.LANTHANIDE, null, 139, +3, new Solid(new Color(212, 216, 220), 6.16, new Thermo(0, 56.9, 24.7, 4), new Hazard(2, 3, 2)), new Fusion(1193), new Liquid(5.94, new Thermo(62.1)), new Vaporization(3737), new Gas(new Thermo(169))), Nd("neodynium", Category.LANTHANIDE, null, 144, +3, new Solid(new Color(212, 216, 220), 7.01, new Thermo(0, 71.6, 26.2, 4), new Hazard(2, 3, 2)), new Fusion(1297), new Liquid(6.89, new Thermo(77.1)), new Vaporization(3347), new Gas(new Thermo(163))), Pr("praseodynium", Category.LANTHANIDE, null, 141, +3, new Solid(new Color(212, 216, 220), 6.77, new Thermo(0, 73.2, 26.0, 4), new Hazard(2, 3, 2)), new Fusion(1208), new Liquid(6.50, new Thermo(78.9)), new Vaporization(3403), new Gas(new Thermo(176))), Th("thorium", Category.ACTINIDE, Strength.MEDIUM, 232, +4, new Solid(new Color(64, 69, 70), 11.7, new Thermo(0, 51.8, 24.3, 10.2)), new Fusion(2115), new Liquid(Double.NaN, new Thermo(58.3)), new Vaporization(5061), new Gas(new Thermo(160))), U("uranium", Category.ACTINIDE, Strength.STRONG, 238, +6, new Solid(new Color(95, 95, 95), 19.1, new Thermo(0, 50.2, 9.68, 41.0, -2.65, 53.7) .addSegment(672, 41, 2.93) .addSegment(772, 42, 4.79)), new Fusion(1405), new Liquid(17.3, new Thermo(56.7)), new Vaporization(4404), new Gas(new Thermo(200))) ; private Chemical delegate; private double atomicWeight; private int defaultOxidationState; private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid, Vaporization vaporization, Gas gas) { Formula formula = new Formula(this._(1)); this.delegate = new SimpleChemical(formula, oreDictKey, solid, fusion, liquid, vaporization, gas); this.atomicWeight = atomicWeight; this.defaultOxidationState = defaultOxidationState; } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid, Vaporization vaporization) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, liquid, vaporization, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, liquid, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState) { this(oreDictKey, atomicWeight, defaultOxidationState, null); } @Override public Fusion getFusion() { return delegate.getFusion(); } @Override public Vaporization getVaporization() { return delegate.getVaporization(); } @Override public String getOreDictKey() { return delegate.getOreDictKey(); } @Override public ChemicalConditionProperties getProperties(Condition condition) { return delegate.getProperties(condition); } @Override public Mixture mix(IndustrialMaterial material, double weight) { return this.delegate.mix(material, weight); } @Override public Formula getFormula() { return delegate.getFormula(); } public Formula.Part _(int quantity) { return new Formula.Part(this, quantity); } @Override public Formula.Part getPart() { return this._(1); } @Override public double getAtomicWeight() { return this.atomicWeight; } @Override public int getDefaultOxidationState() { return this.defaultOxidationState; } @Override public Alloy alloy(Element solute, double weight) { return new SimpleAlloy(this, solute, weight); } } }
src/main/java/org/pfaa/chemica/model/Element.java
package org.pfaa.chemica.model; import java.awt.Color; import org.pfaa.chemica.model.ChemicalStateProperties.Gas; import org.pfaa.chemica.model.ChemicalStateProperties.Liquid; import org.pfaa.chemica.model.ChemicalStateProperties.Liquid.Yaws; import org.pfaa.chemica.model.ChemicalStateProperties.Solid; import org.pfaa.chemica.model.Formula.PartFactory; import org.pfaa.chemica.model.Hazard.SpecialCode; import org.pfaa.chemica.model.Vaporization.AntoineCoefficients; public interface Element extends Chemical, PartFactory, Metal { public double getAtomicWeight(); public int getDefaultOxidationState(); public Formula.Part _(int quantity); public Alloy alloy(Element solute, double weight); public Category getCategory(); public static enum Category { ALKALI_METAL, ALKALINE_EARTH_METAL, LANTHANIDE, ACTINIDE, TRANSITION_METAL, POST_TRANSITION_METAL, METALLOID, POLYATOMIC_NONMETAL, DIATOMIC_NONMETAL, NOBLE_GAS, UNKNOWN; public boolean isMetal() { return this.ordinal() < METALLOID.ordinal(); } } public static enum Elements implements Element { /* H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr R Sr Y Zr Nb Mo Tc Rb Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Ce La Pr Nd ... .. Th .. U ... */ /* * http://chemistrytable.webs.com/enthalpyentropyandgibbs.htm * http://www.periodictable.com/Properties/A/NFPALabel.html */ H("hydrogen", 1.00, +1), /* See Molecules.H2 for properties */ Li("lithium", 6.94, +1, new Solid(new Color(240, 240, 240), 0.534, new Thermo(170, -883, 1977, -1487, -1.61, -31.2, 414), new Hazard(3, 2, 2, SpecialCode.WATER_REACTIVE)), new Fusion(454), new Liquid(0.512, new Thermo(32.5, -2.64, -6.33, 4.23, 0.00569, -7.12, 74.3) .addSegment(700, 26.0, 5.63, -4.01, 0.874, 0.344, -4.20, 66.4)), new Vaporization(1603), new Gas(new Thermo(23.3, -2.77, 0.767, -0.00360, -0.0352, 152, 166))), Be("beryllium", Category.ALKALINE_EARTH_METAL, Strength.STRONG, 9.01, +2, new Solid(new Color(40, 40, 40), 1.85, new Thermo(21.2, 5.69, 0.968, -0.00175, -0.588, -8.55, 30.1) .addSegment(1527, 30.0, -0.000396, 0.000169, -0.000026, -0.000105, -6.97, 40.8), new Hazard(3, 1, 0)), new Fusion(1560), new Liquid(1.69, new Thermo(25.4, 2.16, -0.00257, 0.000287, 0.00396, 5.44, 44.5)), new Vaporization(3243), new Gas(new Thermo(28.6, -5.38, 1.04, -0.0121, -426, 308, 164))), B("boron", Category.METALLOID, Strength.VERY_STRONG, 10.8, +3, new Solid(new Color(82, 53, 7), 2.37, new Thermo(10.2, 29.2, -18.0, 4.21, -0.551, -6.04, 7.09) .addSegment(1800, 25.1, 1.98, 0.338, -0.0400, -2.64, -14.4, 25.6), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(2349), new Liquid(2.08, new Thermo(48.9, 26.5, 31.8)), new Vaporization(4200), new Gas(new Thermo(20.7, 0.226, -0.112, 0.0169, 0.00871, 554, 178))), C("carbon", Category.POLYATOMIC_NONMETAL, Strength.WEAK /* graphite */, 12.0, +4, new Solid(Color.black, 2.27, new Thermo(0, 6.0, 9.25).addSegment(300, 10.7), new Hazard(0, 1, 0)), null, null, new Vaporization(3915), new Gas(new Thermo(21.2, -0.812, 0.449, -0.0433, -0.0131, 710, 184))), N("nitrogen", 14.0, -3), /* see Compounds.N2 for properties */ Na("sodium", 23.0, +1, new Solid(new Color(212, 216, 220), 0.968, new Thermo(72.6, -9.49, -731, 1415, -1.26, -21.8, 155), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(371), new Liquid(0.927, new Thermo(40.3, -28.2, 20.7, -3.64, -0.0799, -8.78, 114)), new Vaporization(2.46, 1874, -416), new Gas(new Thermo(20.8, 0.277, -0.392, 0.120, -0.00888, 101, 179))), Mg("magnesium", Category.ALKALINE_EARTH_METAL, Strength.MEDIUM, 24.3, +2, new Solid(new Color(157, 157, 157), 1.74, new Thermo(26.5, -1.53, 8.06, 0.572, -0.174, -8.50, 63.9), new Hazard(0, 1, 1)), new Fusion(923), new Liquid(1.58, new Thermo(4.79, 34.5, 34.3)), new Vaporization(1363), new Gas(new Thermo(20.8, 0.0356, -0.0319, 0.00911, 0.000461, 141) .addSegment(2200, 47.6, -15.4, 2.88, -0.121, -27.0, 97.4, 177))), Al("aluminum", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 31.0, +5, new Solid(new Color(177, 177, 177), 2.70, new Thermo(28.1, -5.41, 8.56, 3.43, -0.277, -9.15, 61.9), new Hazard(0, 1, 1)), new Fusion(933), new Liquid(2.38, new Thermo(10.6, 39.6, 31.8)), new Vaporization(5.74, 13204, -24.3), new Gas(new Thermo(20.4, 0.661, -0.314, 0.0451, 0.0782, 324, 189))), Si("silicon", Category.METALLOID, Strength.STRONG, 28.1, +4, new Solid(new Color(206, 227, 231), 2.33, new Thermo(22.8, 3.90, -0.0829, 0.0421, -0.354, -8.16, 43.3)), new Fusion(1687), new Liquid(2.57, new Thermo(48.5, 44.5, 27.2))), P("phosphorus", Category.POLYATOMIC_NONMETAL, null, 31.0, +5, new Solid(Color.white, 1.82, new Thermo(16.5, 43.3, -58.7, 25.6, -0.0867, -6.66, 50.0), new Hazard(4, 4, 2)), new Fusion(317.2), new Liquid(1.74, new Thermo(26.3, 1.04, -6.12, 1.09, 3.00, -7.23, 74.9)), new Vaporization(553), new Gas(new Thermo(20.4, 1.05, -1.10, 0.378, 0.011, 310, 188) .addSegment(2200, -2.11, 9.31, -0.558, -0.020, 29.3, 354, 190)) ), S("sulfur", Category.POLYATOMIC_NONMETAL, Strength.WEAK, 32.1, +4, new Solid(new Color(230, 230, 25), 2, new Thermo(21.2, 3.87, 22.3, -10.3, -0.0123, -7.09, 55.5), new Hazard()), new Fusion(388), new Liquid(1.82, new Thermo(4541, 26066, -55521, 42012, 54.6, 788, -10826) .addSegment(432, -37.9, 133, -95.3, 24.0, 7.65, 29.8, -13.2)), new Vaporization(718), new Gas(new Thermo(27.5, -13.3, 10.1, -2.66, -0.00558, 269, 204) .addSegment(1400, 16.6, 2.40, -0.256, 0.00582, 3.56, 278, 195)) ), Cl("chlorine", 34.5, -1), /* See Compounds.Cl2 for properties */ K("potassium", 39.1, +1, new Solid(new Color(219, 219, 219), 0.862, new Thermo(-63.5, -3226, 14644, -16229, 16.3, 120, 534), new Hazard(3, 3, 2, SpecialCode.WATER_REACTIVE)), new Fusion(337), new Liquid(0.828, new Thermo(40.3, -30.5, 26.5, -5.73, -0.0635, -8.81, 128)), new Vaporization(new AntoineCoefficients(4.46, 4692, 24.2)), new Gas(new Thermo(20.7, 0.392, -0.417, 0.146, 0.00376, 82.8, 185) .addSegment(1800, 58.7, -27.4, 6.73, -0.421, -25.9, 32.4, 198))), Ca("calcium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 40.1, +2, new Solid(new Color(228, 237, 237), 1.55, new Thermo(19.8, 10.1, 14.5, -5.53, 0.178, -5.86, 62.9), new Hazard(3, 1, 2, SpecialCode.WATER_REACTIVE)), new Fusion(1115), new Liquid(1.38, new Thermo(7.79, 45.5, 35.0)), new Vaporization(new AntoineCoefficients(2.78, 3121, -595)), new Gas(new Thermo(122, -75, 19.2, -1.40, -64.5, 42.2, 217))), // Skipped Sc Ti("titanium", Category.TRANSITION_METAL, Strength.STRONG, 47.9, +4, new Solid(new Color(230, 230, 230), 4.51, new Thermo(23.1, 5.54, -2.06, 1.61, -0.0561, -0.433, 64.1), new Hazard(1, 1, 2)), new Fusion(1941), new Liquid(4.11, new Thermo(13.7, 39.2, -22.1)), new Vaporization(3560), new Gas(new Thermo(9.27, 6.09, 0.577, -0.110, 6.50, 483, 204))), V("vanadium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 50.9, +5, new Solid(new Color(145, 170, 190), 6.0, new Thermo(26.3, 1.40, 2.21, 0.404, -0.176, -8.52, 59.3), new Hazard(2, 1, 0)), new Fusion(2183), new Liquid(5.5, new Thermo(17.3, 36.1, 46.2)), new Vaporization(3680), new Gas(new Thermo(32.0, -9.12, 2.94, -0.190, 1.41, 505, 220))), Cr("chromium", Category.TRANSITION_METAL, Strength.VERY_STRONG, 52.0, +3, new Solid(new Color(212, 216, 220), 7.19, new Thermo(7.49, 71.5, -91.7, 46.0, 0.138, -4.23, 15.8) .addSegment(600, 18.5, 5.48, 7.90, -1.15, 1.27, -2.68, 48.1), new Hazard(2, 1, 1)), new Fusion(2180), new Liquid(6.3, new Thermo(21.6, 36.2, 39.3)), new Vaporization(2944), new Gas(new Thermo(13.7, -3.42, 0.394, -16.7, 383, 183, 397))), Mn("manganese", Category.TRANSITION_METAL, Strength.STRONG, 54.9, +4, new Solid(new Color(212, 216, 220), 7.21, new Thermo(27.2, 5.24, 7.78, -2.12, -0.282, -9.37, 61.5) .addSegment(980, 52.3, -28.7, 21.5, -4.98, -2.43, -21.2, 90.7) .addSegment(1361, 19.1, 31.4, -15.0, 3.21, 1.87, -2.76, 48.8) .addSegment(1412, -534, 679, -296, 46.4, 161, 469, -394)), new Fusion(1519), new Liquid(5.95, new Thermo(16.3, 43.5, 46.0)), new Vaporization(2334), new Gas(new Thermo(188, -97.8, 20.2, -1.27, -177, 1.55, 220))), Fe("iron", Category.TRANSITION_METAL, Strength.STRONG, 55.8, +3, new Solid(Color.gray, 7.87, new Thermo(24.0, 8.37, 0.000277, -8.60E-5, -5.00E-6, 0.268, 62.1), new Hazard(1, 1, 0)), new Fusion(1811), new Liquid(6.98, new Thermo(12, 35, 46.0)), new Vaporization(3134), new Gas(new Thermo(11.3, 6.99, -1.11, 0.122, 5.69, 424, 206))), Co("cobalt", Category.TRANSITION_METAL, Strength.STRONG, 58.9, +2, new Solid(Color.gray, 8.90, new Thermo(11.0, 54.4, -55.5, 25.8, 0.165, -4.70, 30.3) .addSegment(700, -205, 516, -422, 130, 18.0, 94.6, -273) .addSegment(1394, -12418, 15326, -7087, 1167, 3320, 10139, -10473)), new Fusion(1768), new Liquid(7.75, new Thermo(45.6, -3.81, 1.03, -0.0967, -3.33, -8.14, 78.0)), new Vaporization(3200), new Gas(new Thermo(40.7, -8.46, 1.54, -0.0652, -11.1, 397, 213))), Ni("nickel", Category.TRANSITION_METAL, Strength.MEDIUM, 58.7, +2, new Solid(new Color(160, 160, 140), 8.91, new Thermo(13.7, 82.5, -175, 162, -0.0924, -6.83, 27.7) .addSegment(600, 1248, -1258, 0, 0, -165, -789, 1213) .addSegment(700, 16.5, 18.7, -6.64, 1.72, 1.87, -0.468, 51.7), new Hazard(2, 4, 1)), new Fusion(1728), new Liquid(7.81, new Thermo(17.5, 41.5, 38.9)), new Vaporization(3186), new Gas(new Thermo(27.1, -2.59, 0.295, 0.0152, 0.0418, 421, 214))), Cu("copper", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2, new Solid(new Color(208, 147, 29), 8.96, new Thermo(17.7, 28.1, -31.3, 14.0, 0.0686, -6.06, 47.9), new Hazard(1, 1, 0)), new Fusion(1358), new Liquid(8.02, new Thermo(17.5, 41.5, 32.8)), new Vaporization(2835), new Gas(new Thermo(-80.5, 49.4, -7.58, 0.0405, 133, 520, 194))), Zn("zinc", Category.TRANSITION_METAL, Strength.MEDIUM, 63.5, +2, new Solid(new Color(230, 230, 230), 7.14, new Thermo(25.6, -4.41, 20.4, -7.40, -0.0458, -7.56, 72.9), new Hazard(2, 0, 0)), new Fusion(673), new Liquid(6.57, new Thermo(6.52, 50.8, 31.4)), new Vaporization(1180), new Gas(new Thermo(18.2, 2.31, -0.737, 0.0800, 1.07, 127, 185))), Ga("gallium", Category.POST_TRANSITION_METAL, Strength.WEAK, 69.7, +3, new Solid(new Color(212, 216, 220), 5.91, new Thermo(102, -348, 603, -361, -1.49, -24.7, 236), new Hazard(1, 0, 0)), new Fusion(303), new Liquid(6.10, new Thermo(24.6, 2.70, -1.27, 0.197, 0.286, -0.909, 89.9)), new Vaporization(2673), new Gas(new Thermo(20.3, 0.570, -0.210, 0.0258, 3.05, 273, 201))), // TODO: Ge As("arsenic", 74.9, +3, new Solid(new Color(112, 112, 112), 5.73, new Thermo(0, 35.1, 21.6, 9.79), new Hazard(3, 2, 0)), null, null, new Vaporization(887), new Gas(new Thermo(74.3))), O("oxygen", 16.0, -2), /* See Compounds.O2 for properties */ F("fluorine", 19.0, -1), /* See Compounds.F2 for properties, solid density 1.7 */ Sr("strontium", 87.6, +2, new Solid(new Color(212, 216, 220), 2.64, new Thermo(23.9, 9.30, 0.920, 0.0352, 0.00493, -7.53, 81.8), new Hazard(4, 0, 2, SpecialCode.WATER_REACTIVE)), new Fusion(1050), new Liquid(2.38, new Thermo(0.91, 50.9, 39.5)), new Vaporization(1650), new Gas(new Thermo(19.4, 3.74, -3.19, 0.871, 0.0540, 158, 187) .addSegment(2700, -39.0, -1.70, 7.99, -0.852, 188, 355, 243))), Y("yttrium", Category.TRANSITION_METAL, null, 88.9, +3, new Solid(new Color(212, 216, 220), 4.47, new Thermo(0, 44.4, 24.4, 6.99)), new Fusion(1799), new Liquid(4.24, new Thermo(50.7)), new Vaporization(3203), new Gas(new Thermo(164))), Zr("zirconium", Category.TRANSITION_METAL, Strength.STRONG, 91.2, +4, new Solid(new Color(212, 216, 220), 6.52, new Thermo(29, -12.6, 20.7, -5.91, -0.157, -8.79, 76.0), new Hazard(1, 1, 0)), new Fusion(2128), new Liquid(5.8, new Thermo(17.4, 47.6, 41.8)), new Vaporization(4650), new Gas(new Thermo(39.5, -6.52, 2.26, -0.194, -12.5, 578, 212))), Nb("niobium", Category.TRANSITION_METAL, Strength.STRONG, 92.9, +5, new Solid(new Color(135, 150, 160), 8.57, new Thermo(22.0, 9.89, -5.65, 1.76, 0.0218, -6.88, 60.5), new Hazard(1, 1, 0)), new Fusion(2750), new Liquid(Double.NaN, new Thermo(29.7, 47.3, 33.5)), new Vaporization(5017), new Gas(new Thermo(-14637, 5142, -675, 31.5, 47657, 42523, 6194))), Mo("molybdenum", Category.TRANSITION_METAL, Strength.STRONG, 96, +4, new Solid(new Color(105, 105, 105), 10.3, new Thermo(24.7, 3.96, -1.27, 1.15, -0.17, -8.11, 56.4) .addSegment(1900, 1231, -963, 284, -28, -712, -1486, 574), new Hazard(1, 3, 0)), new Fusion(2896), new Liquid(9.33, new Thermo(41.6, 43.1, 37.7)), new Vaporization(4912), new Gas(new Thermo(67.9, -40.5, 11.7, -0.819, -22.1, 601, 232))), Rb("rubidium", 85.5, +1, new Solid(new Color(175, 175, 175), 1.53, new Thermo(9.45, 65.3, 45.5, -26.8, -0.108, -6.43, 66.3), new Hazard(2, 3, 0, SpecialCode.WATER_REACTIVE)), new Fusion(312), new Liquid(1.46, new Thermo(35.5, -12.9, 8.55, -0.00283, -0.000119, -7.90, 130)), new Vaporization(961), new Gas(new Thermo(20.6, 0.462, -0.495, 0.174, 0.00439, 74.7, 195) .addSegment(1800, 74.1, -39.2, 9.91, -0.679, -35.1, 4.97, 214))), Ag("silver", 108, +1, new Solid(new Color(213, 213, 213), 10.5, new Thermo(0, 42.6, 23.4, 6.28), new Hazard(1, 1, 0)), new Fusion(1235), new Liquid(9.32, new Thermo(24.7, 52.3, 339, -45)), new Vaporization(1.95, 2505, -1195), new Gas(new Thermo(285, 173, Double.NaN))), Cd("cadmium", 112, +2, new Solid(new Color(190, 190, 210), 8.65, new Thermo(0, 51.8, 22.8, 10.3), new Hazard(2, 2, 0)), new Fusion(594), new Liquid(8.00, new Thermo(Double.NaN, 62.2, 29.7)), new Vaporization(1040), new Gas(new Thermo(112, 168, 20.8))), // TODO: In Sn("tin", 119, +4, new Solid(new Color(212, 216, 220), 7.28, new Thermo(0, 51.2, 23.1, 19.6), new Hazard(1, 3, 3)), new Fusion(505), new Liquid(6.97, new Thermo(65.1)), // FIXME: need liquid heat capacity new Vaporization(6.60, 16867, 15.5), new Gas(new Thermo(168))), Sb("antimony", 122, +3, new Solid(new Color(212, 216, 220), 6.70, new Thermo(0, 45.7, 23.1, 7.45), // NOTE: heating is extremely dangerous new Hazard(4, 4, 2)), new Fusion(904), new Liquid(6.53, new Thermo(67.6)), new Vaporization(2.26, 4475, -152), new Gas(new Thermo(168))), Cs("caesium", 133, +1, new Solid(new Color(170, 160, 115), 1.93, new Thermo(57.0, -50.0, 48.6, -16.7, -1.22, -19.3, 160), new Hazard(4, 3, 3, SpecialCode.WATER_REACTIVE)), new Fusion(302), new Liquid(1.84, new Thermo(30.0, 0.506, 0.348, -0.0995, 0.197, -6.23, 129)), new Vaporization(3.70, 3453, -26.8), new Gas(new Thermo(76.5, 175, 20.8) .addSegment(1000, 34.5, -13.8, 4.13, -0.138, -3.95, 58.2, 211) .addSegment(4000, -181, 80.0, -9.19, 0.330, 374, 518, 242))), Ba("barium", Category.ALKALINE_EARTH_METAL, Strength.WEAK, 137, +2, new Solid(new Color(70, 70, 70), 3.51, new Thermo(83.8, -406, 915, -520, -14.6, 248) .addSegment(583, 76.7, -188, 296, -114, -4.34, -25.6, 189) .addSegment(768, 26.2, 28.6, -23.7, 6.95, 1.04, -5.80, 90), new Hazard(2, 1, 2)), new Fusion(1000), new Liquid(3.34, new Thermo(55.0, -18.7, 2.76, 1.28, 3.02, -8.42, 135)), new Vaporization(4.08, 7599, -45.7), new Gas(new Thermo(-623, 430, -97.0, 7.47, 488, 1077, 19.0) .addSegment(4000, 770, -284, 41.4, -2.13, -1693, -1666, -26.3))), // Skipped Lu and Hf Ta("tantalum", Category.TRANSITION_METAL, Strength.STRONG, 181, +5, new Solid(new Color(185, 190, 200), 16.7, new Thermo(20.7, 17.3, -15.7, 5.61, 0.0616, -6.60, 62.4) .addSegment(1300, -43.9, 73.0, -27.4, 4.00, 26.3, 60.2, 25.7), new Hazard(1, 1, 0)), new Fusion(3290), new Liquid(15, new Thermo(30.8, 50.4, 41.8)), new Vaporization(5731), new Gas(new Thermo(29.5, 3.42, -0.566, 0.0697, -4.93, 763, 208))), W("tungsten", Category.TRANSITION_METAL, Strength.VERY_STRONG, 184, +6, new Solid(new Color(140, 140, 140), 19.3, new Thermo(24.0, 2.64, 1.26, -0.255, -0.0484, -7.43, 60.5) .addSegment(1900, -22.6, 90.3, -44.3, 7.18, -24.1, -9.98, -14.2), new Hazard(1, 2, 1)), new Fusion(3695), new Liquid(17.6, new Thermo(46.9, 45.7, 35.6)), new Vaporization(6203), new Gas(new Thermo(174))), Re("rhenium", 186, +7, new Solid(new Color(212, 216, 220), 21.0, new Thermo(0, 36.9, 26.4, 2.22)), new Fusion(3459), new Liquid(18.9, new Thermo(54.4))), Au("gold", 197, +3, new Solid(new Color(255, 215, 0), 19.3, new Thermo(0, 47.4, 23.2, 6.16, -0.618, -0.0355), new Hazard(2, 0, 0)), new Fusion(1337), new Liquid(17.3, new Thermo(57.8)), // FIXME: better thermodynamics for liquid gold! new Vaporization(5.47, 17292, -71), new Gas(new Thermo(366, 180, 20.8))), Hg("mercury", Category.TRANSITION_METAL, null, 201, +2, new Solid(new Color(155, 155, 155), 14.25, new Thermo(-2.18, 66.1, 21.5, 29.2)), new Fusion(234), new Liquid(new Color(188, 188, 188), 13.5, new Thermo(0, 75.9, 28), new Hazard(3, 0, 0), new Yaws(-0.275, 137, 4.18E-6, -1.20E-9)), new Vaporization(4.86, 3007, -10.0), new Gas(new Thermo(20.7, 0.179, -0.0801, 0.0105, 0.00701, 55.2, 200))), // Skipped Tl Pb("lead", Category.POST_TRANSITION_METAL, Strength.WEAK, 207, +2, new Solid(new Color(65, 65, 65), 11.3, new Thermo(25.0, 5.44, 4.06, -1.24, -0.0107, -7.77, 93.2), new Hazard(2, 0, 0)), new Fusion(601), new Liquid(10.7, new Thermo(38.0, -14.6, 7.26, -1.03, -0.331, -7.94, 119)), new Vaporization(2022), new Gas(new Thermo(-85.7, 69.3, -13.3, 0.840, 63.1, 333, 170))), Bi("bismuth", Category.POST_TRANSITION_METAL, Strength.MEDIUM, 209, +3, new Solid(new Color(213, 213, 213), 9.78, new Thermo(0, 56.7, 21.1, 14.7)), new Fusion(545), new Liquid(10.1, new Thermo(0 /* dummy */, 77.4, 31.8)), new Vaporization(1837), new Gas(new Thermo(175))), // Skipped Po, At, and many others... Ce("cerium", Category.LANTHANIDE, null, 140, +3, new Solid(new Color(212, 216, 220), 6.77, new Thermo(0, 72.0, 24.6, 0.005), new Hazard(2, 3, 2)), new Fusion(1068), new Liquid(6.55, new Thermo(77.1)), new Vaporization(3716), new Gas(new Thermo(184))), La("lanthanum", Category.LANTHANIDE, null, 139, +3, new Solid(new Color(212, 216, 220), 6.16, new Thermo(0, 56.9, 24.7, 4), new Hazard(2, 3, 2)), new Fusion(1193), new Liquid(5.94, new Thermo(62.1)), new Vaporization(3737), new Gas(new Thermo(169))), Nd("neodynium", Category.LANTHANIDE, null, 144, +3, new Solid(new Color(212, 216, 220), 7.01, new Thermo(0, 71.6, 26.2, 4), new Hazard(2, 3, 2)), new Fusion(1297), new Liquid(6.89, new Thermo(77.1)), new Vaporization(3347), new Gas(new Thermo(163))), Pr("praseodynium", Category.LANTHANIDE, null, 141, +3, new Solid(new Color(212, 216, 220), 6.77, new Thermo(0, 73.2, 26.0, 4), new Hazard(2, 3, 2)), new Fusion(1208), new Liquid(6.50, new Thermo(78.9)), new Vaporization(3403), new Gas(new Thermo(176))), Th("thorium", Category.ACTINIDE, Strength.MEDIUM, 232, +4, new Solid(new Color(64, 69, 70), 11.7, new Thermo(0, 51.8, 24.3, 10.2)), new Fusion(2115), new Liquid(Double.NaN, new Thermo(58.3)), new Vaporization(5061), new Gas(new Thermo(160))), U("uranium", Category.ACTINIDE, Strength.STRONG, 238, +6, new Solid(new Color(95, 95, 95), 19.1, new Thermo(0, 50.2, 9.68, 41.0, -2.65, 53.7) .addSegment(672, 41, 2.93) .addSegment(772, 42, 4.79)), new Fusion(1405), new Liquid(17.3, new Thermo(56.7)), new Vaporization(4404), new Gas(new Thermo(200))) ; private Chemical delegate; private double atomicWeight; private int defaultOxidationState; private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid, Vaporization vaporization, Gas gas) { Formula formula = new Formula(this._(1)); this.delegate = new SimpleChemical(formula, oreDictKey, solid, fusion, liquid, vaporization, gas); this.atomicWeight = atomicWeight; this.defaultOxidationState = defaultOxidationState; } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid, Vaporization vaporization) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, liquid, vaporization, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion, Liquid liquid) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, liquid, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid, Fusion fusion) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, fusion, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState, Solid solid) { this(oreDictKey, atomicWeight, defaultOxidationState, solid, null); } private Elements(String oreDictKey, double atomicWeight, int defaultOxidationState) { this(oreDictKey, atomicWeight, defaultOxidationState, null); } @Override public Fusion getFusion() { return delegate.getFusion(); } @Override public Vaporization getVaporization() { return delegate.getVaporization(); } @Override public String getOreDictKey() { return delegate.getOreDictKey(); } @Override public ChemicalConditionProperties getProperties(Condition condition) { return delegate.getProperties(condition); } @Override public Mixture mix(IndustrialMaterial material, double weight) { return this.delegate.mix(material, weight); } @Override public Formula getFormula() { return delegate.getFormula(); } public Formula.Part _(int quantity) { return new Formula.Part(this, quantity); } @Override public Formula.Part getPart() { return this._(1); } @Override public double getAtomicWeight() { return this.atomicWeight; } @Override public int getDefaultOxidationState() { return this.defaultOxidationState; } @Override public Alloy alloy(Element solute, double weight) { return new SimpleAlloy(this, solute, weight); } } }
add helium
src/main/java/org/pfaa/chemica/model/Element.java
add helium
Java
bsd-2-clause
2d71120482463cf3b02d1ba988cfba4f2b359d1f
0
UltraNurd/robot-mason-gp,UltraNurd/robot-mason-gp
/** * @file Tournament.java * @author [email protected] * @date 2012.03.17 */ package edu.harvard.seas.cs266.naptime; import sim.engine.SimState; import sim.field.continuous.Continuous2D; import sim.util.Double2D; /** * Implements a simulation of the robot foraging field. * * @author [email protected] */ @SuppressWarnings("serial") public class Tournament extends SimState { /** * The length of the field from goal to goal. */ public static final int fieldLength = 220; /** * The width of the field (between the non-goal sides). */ public static final int fieldWidth = 150; /** * Representation of 2-D space where robots will forage for food. */ public Continuous2D field = new Continuous2D(1.0, fieldLength, fieldWidth); /** * Initial count of food particles in the field (may get parameterized). */ public int nTreats = 20; /** * Creates the simulation. * * @param seed Seed for the simulation's RNG. */ public Tournament(long seed) { super(seed); } /** * Implements simulation initialization */ public void start() { // Start the simulation super.start(); // Clear the field of food and robots field.clear(); // Add some randomly distributed food to the field for (int t = 0; t < nTreats; t++) { Treat treat = new Treat(); field.setObjectLocation(treat, new Double2D(field.getWidth()*(random.nextDouble()*0.8 + 0.1), field.getHeight()*(random.nextDouble()*0.8 + 0.1))); } } /** * Runs simulation by invoking SimState.doLoop. * * @param args MASON command-line args which we don't use. */ public static void main(String[] args) { // Run the simulation using parent class convenience method. doLoop(Tournament.class, args); System.exit(0); } }
simulator/Tournament/src/edu/harvard/seas/cs266/naptime/Tournament.java
/** * @file Tournament.java * @author [email protected] * @date 2012.03.17 */ package edu.harvard.seas.cs266.naptime; import sim.engine.SimState; import sim.field.continuous.Continuous2D; import sim.util.Double2D; /** * Implements a simulation of the robot foraging field. * * @author [email protected] */ @SuppressWarnings("serial") public class Tournament extends SimState { /** * The length of the field from goal to goal. */ public static final int fieldLength = 220; /** * The width of the field (between the non-goal sides). */ public static final int fieldWidth = 150; /** * Representation of 2-D space where robots will forage for food. */ public Continuous2D field = new Continuous2D(1.0, fieldLength, fieldWidth); /** * Initial count of food particles in the field (may get parameterized). */ public int nTreats = 20; /** * Creates the simulation. * * @param seed Seed for the simulation's RNG. */ public Tournament(long seed) { super(seed); } /** * Implements simulation initialization */ public void start() { // Start the simulation super.start(); // Clear the field of food and robots field.clear(); // Add some randomly distributed food to the field for (int t = 0; t < nTreats; t++) { Treat treat = new Treat(); field.setObjectLocation(treat, new Double2D(field.getWidth()*random.nextDouble(), field.getHeight()*random.nextDouble())); } } /** * Runs simulation by invoking SimState.doLoop. * * @param args MASON command-line args which we don't use. */ public static void main(String[] args) { // Run the simulation using parent class convenience method. doLoop(Tournament.class, args); System.exit(0); } }
start balls away from walls
simulator/Tournament/src/edu/harvard/seas/cs266/naptime/Tournament.java
start balls away from walls
Java
bsd-3-clause
c169ef42810e1cfcea27014cdda53eba0d5d52b7
0
James137137/FactionChat
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nz.co.lolnet.james137137.FactionChat; /** * * @author James */ public class FactionChatMessage { String format; String message; boolean allowCostomColour; String playerPrefix; String playerName; String playerSuffix; String playerFactionTitle; String playerFactionRank; String FacitonName; String otherFactionName; public FactionChatMessage(String format, String message, boolean allowCostomColour, String playerPrefix, String playerName, String playerSuffix, String playerFactionTitle, String playerFactionRank, String FacitonName, String otherFactionName) { this.format = format; this.message = message; this.allowCostomColour = allowCostomColour; this.playerPrefix = playerPrefix; this.playerName = playerName; this.playerSuffix = playerSuffix; this.playerFactionTitle = playerFactionTitle; this.playerFactionRank = playerFactionRank; this.FacitonName = FacitonName; this.otherFactionName = otherFactionName; } public FactionChatMessage(String format, String message, boolean allowCostomColour) { this.format = format; this.message = message; this.allowCostomColour = allowCostomColour; this.playerPrefix = null; this.playerName = null; this.playerSuffix = null; this.playerFactionTitle = null; this.playerFactionRank = null; this.FacitonName = null; this.otherFactionName = null; } @Override public String toString() { String output; if (allowCostomColour) { message = message.replaceAll("/&", "/and"); message = message.replaceAll("&", "" + (char) 167); message = message.replaceAll("/and", "&"); } output = message; if (format != null) { format = format.replaceAll("/&", "/and"); format = format.replaceAll("&", "" + (char) 167); format = format.replaceAll("/and", "&"); if (playerName != null) { format = format.replaceAll("%PLAYER%", playerName); } if (playerPrefix != null) { format = format.replaceAll("%PREFIX%", playerPrefix); } if (playerSuffix != null) { format = format.replaceAll("%SUFFIX%", playerSuffix); } if (playerFactionTitle != null) { format = format.replaceAll("%TITLE%", playerFactionTitle); } if (playerFactionRank != null) { format = format.replaceAll("%FACTIONRANK%", playerFactionRank); } if (FacitonName != null) { format = format.replaceAll("%FACTION%", FacitonName); } if (otherFactionName != null) { format = format.replaceAll("%OTHERFACTION%", otherFactionName); } format = format.replaceAll(" ", " "); //removing double spaces format = format.replaceAll("%MESSAGE%", message); output = format; } return output; } }
src/main/java/nz/co/lolnet/james137137/FactionChat/FactionChatMessage.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nz.co.lolnet.james137137.FactionChat; /** * * @author James */ public class FactionChatMessage { String format; String message; boolean allowCostomColour; String playerPrefix; String playerName; String playerSuffix; String playerFactionTitle; String playerFactionRank; String FacitonName; String otherFactionName; public FactionChatMessage(String format, String message, boolean allowCostomColour, String playerPrefix, String playerName, String playerSuffix, String playerFactionTitle, String playerFactionRank, String FacitonName, String otherFactionName) { this.format = format; this.message = message; this.allowCostomColour = allowCostomColour; this.playerPrefix = playerPrefix; this.playerName = playerName; this.playerSuffix = playerSuffix; this.playerFactionTitle = playerFactionTitle; this.playerFactionRank = playerFactionRank; this.FacitonName = FacitonName; this.otherFactionName = otherFactionName; } public FactionChatMessage(String format, String message, boolean allowCostomColour) { this.format = format; this.message = message; this.allowCostomColour = allowCostomColour; this.playerPrefix = null; this.playerName = null; this.playerSuffix = null; this.playerFactionTitle = null; this.playerFactionRank = null; this.FacitonName = null; this.otherFactionName = null; } @Override public String toString() { String output; if (allowCostomColour) { message = message.replaceAll("/&", "/and"); message = message.replaceAll("&", "" + (char) 167); message = message.replaceAll("/and", "&"); } output = message; if (format != null) { format = format.replaceAll("/&", "/and"); format = format.replaceAll("&", "" + (char) 167); format = format.replaceAll("/and", "&"); if (playerName != null) { format = format.replaceAll("%PLAYER%", playerName); } if (playerPrefix != null) { format = format.replaceAll("%PREFIX%", playerPrefix); } if (playerSuffix != null) { format = format.replaceAll("%SUFFIX%", playerSuffix); } if (playerFactionTitle != null) { format = format.replaceAll("%TITLE%", playerFactionTitle); } if (playerFactionRank != null) { format = format.replaceAll("%FACTIONRANK%", playerFactionRank); } if (FacitonName != null) { format = format.replaceAll("%FACTION%", FacitonName); } if (otherFactionName != null) { format = format.replaceAll("%OTHERFACTION%", otherFactionName); } format = format.replaceAll("%MESSAGE%", message); output = format; } return output; } }
Fixed issue with double spaces if player had no title https://github.com/James137137/FactionChat/issues/26
src/main/java/nz/co/lolnet/james137137/FactionChat/FactionChatMessage.java
Fixed issue with double spaces if player had no title
Java
bsd-3-clause
d17cbd2824f338385cba99f27e62754516a27191
0
galmeida/raven-java,reki2000/raven-java6,reki2000/raven-java6,buckett/raven-java,littleyang/raven-java,littleyang/raven-java,galmeida/raven-java,buckett/raven-java
package net.kencochrane.raven.connection; import net.kencochrane.raven.Raven; import net.kencochrane.raven.event.Event; import net.kencochrane.raven.marshaller.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; /** * Basic connection to a Sentry server, using HTTP and HTTPS. * <p> * It is possible to enable the "naive mode" to allow a connection over SSL using a certificate with a wildcard. * </p> */ public class HttpConnection extends AbstractConnection { private static final Logger logger = LoggerFactory.getLogger(HttpConnection.class); /** * HTTP Header for the user agent. */ private static final String USER_AGENT = "User-Agent"; /** * HTTP Header for the authentication to Sentry. */ private static final String SENTRY_AUTH = "X-Sentry-Auth"; /** * Default timeout of an HTTP connection to Sentry. */ private static final int DEFAULT_TIMEOUT = 10000; /** * HostnameVerifier allowing wildcard certificates to work without adding them to the truststore. */ private static final HostnameVerifier NAIVE_VERIFIER = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession sslSession) { return true; } }; /** * URL of the Sentry endpoint. */ private final URL sentryUrl; /** * Marshaller used to transform and send the {@link Event} over a stream. */ private Marshaller marshaller; /** * Timeout of an HTTP connection to Sentry. */ private int timeout = DEFAULT_TIMEOUT; /** * Setting allowing to bypass the security system which requires wildcard certificates * to be added to the truststore. */ private boolean bypassSecurity = false; public HttpConnection(URL sentryUrl, String publicKey, String secretKey) { super(publicKey, secretKey); this.sentryUrl = sentryUrl; } public static URL getSentryApiUrl(URI sentryUri, String projectId) { try { String url = sentryUri.toString() + "api/" + projectId + "/store/"; return new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Couldn't build a valid URL from the Sentry API.", e); } } private HttpURLConnection getConnection() { try { HttpURLConnection connection = (HttpURLConnection) sentryUrl.openConnection(); if (bypassSecurity && connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(NAIVE_VERIFIER); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(timeout); connection.setRequestProperty(USER_AGENT, Raven.NAME); connection.setRequestProperty(SENTRY_AUTH, getAuthHeader()); return connection; } catch (IOException e) { throw new IllegalStateException("Couldn't set up a connection to the sentry server.", e); } } @Override protected void doSend(Event event) { HttpURLConnection connection = getConnection(); try { connection.connect(); OutputStream outputStream = connection.getOutputStream(); marshaller.marshall(event, outputStream); outputStream.close(); connection.getInputStream().close(); } catch (IOException e) { if (connection.getErrorStream() != null) { throw new ConnectionException(getErrorMessageFromStream(connection.getErrorStream()), e); } else { throw new ConnectionException("An exception occurred while submitting the event to the sentry server." , e); } } finally { connection.disconnect(); } } private String getErrorMessageFromStream(InputStream errorStream) { BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); StringBuilder sb = new StringBuilder(); try { String line; while ((line = reader.readLine()) != null) sb.append(line).append("\n"); //Remove last \n sb.deleteCharAt(sb.length() - 1); } catch (Exception e2) { logger.error("Exception while reading the error message from the connection.", e2); } return sb.toString(); } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMarshaller(Marshaller marshaller) { this.marshaller = marshaller; } public void setBypassSecurity(boolean bypassSecurity) { this.bypassSecurity = bypassSecurity; } @Override public void close() throws IOException { } }
raven/src/main/java/net/kencochrane/raven/connection/HttpConnection.java
package net.kencochrane.raven.connection; import net.kencochrane.raven.Raven; import net.kencochrane.raven.event.Event; import net.kencochrane.raven.marshaller.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; /** * Basic connection to a Sentry server, using HTTP and HTTPS. * <p> * It is possible to enable the "naive mode" to allow a connection over SSL using a certificate with a wildcard. * </p> */ public class HttpConnection extends AbstractConnection { private static final Logger logger = LoggerFactory.getLogger(HttpConnection.class); /** * HTTP Header for the user agent. */ private static final String USER_AGENT = "User-Agent"; /** * HTTP Header for the authentication to Sentry. */ private static final String SENTRY_AUTH = "X-Sentry-Auth"; /** * Default timeout of an HTTP connection to Sentry. */ private static final int DEFAULT_TIMEOUT = 10000; /** * HostnameVerifier allowing wildcard certificates to work without adding them to the truststore. */ private static final HostnameVerifier NAIVE_VERIFIER = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession sslSession) { return true; } }; /** * URL of the Sentry endpoint. */ private final URL sentryUrl; /** * Marshaller used to transform and send the {@link Event} over a stream. */ private Marshaller marshaller; /** * Timeout of an HTTP connection to Sentry. */ private int timeout = DEFAULT_TIMEOUT; /** * Setting allowing to bypass the security system which requires wildcard certificates * to be added to the truststore. */ private boolean bypassSecurity = false; public HttpConnection(URL sentryUrl, String publicKey, String secretKey) { super(publicKey, secretKey); this.sentryUrl = sentryUrl; } public static URL getSentryApiUrl(URI sentryUri, String projectId) { try { String url = sentryUri.toString() + "api/" + projectId + "/store/"; return new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Couldn't get a valid URL from the DSN.", e); } } private HttpURLConnection getConnection() { try { HttpURLConnection connection = (HttpURLConnection) sentryUrl.openConnection(); if (bypassSecurity && connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setHostnameVerifier(NAIVE_VERIFIER); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(timeout); connection.setRequestProperty(USER_AGENT, Raven.NAME); connection.setRequestProperty(SENTRY_AUTH, getAuthHeader()); return connection; } catch (IOException e) { throw new IllegalStateException("Couldn't set up a connection to the sentry server.", e); } } @Override protected void doSend(Event event) { HttpURLConnection connection = getConnection(); try { connection.connect(); OutputStream outputStream = connection.getOutputStream(); marshaller.marshall(event, outputStream); outputStream.close(); connection.getInputStream().close(); } catch (IOException e) { if (connection.getErrorStream() != null) { throw new ConnectionException(getErrorMessageFromStream(connection.getErrorStream()), e); } else { throw new ConnectionException("An exception occurred while submitting the event to the sentry server." , e); } } finally { connection.disconnect(); } } private String getErrorMessageFromStream(InputStream errorStream) { BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); StringBuilder sb = new StringBuilder(); try { String line; while ((line = reader.readLine()) != null) sb.append(line).append("\n"); //Remove last \n sb.deleteCharAt(sb.length() - 1); } catch (Exception e2) { logger.error("Exception while reading the error message from the connection.", e2); } return sb.toString(); } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMarshaller(Marshaller marshaller) { this.marshaller = marshaller; } public void setBypassSecurity(boolean bypassSecurity) { this.bypassSecurity = bypassSecurity; } @Override public void close() throws IOException { } }
Improve exception message to not mention DSN if not necessary
raven/src/main/java/net/kencochrane/raven/connection/HttpConnection.java
Improve exception message to not mention DSN if not necessary
Java
bsd-3-clause
cb04e3298f7288e54f788467359e0706256deba1
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program; import org.hisp.dhis.android.core.common.CollectionCleaner; import org.hisp.dhis.android.core.common.CollectionCleanerImpl; import org.hisp.dhis.android.core.common.GenericHandler; import org.hisp.dhis.android.core.common.HandleAction; import org.hisp.dhis.android.core.common.IdentifiableHandlerImpl; import org.hisp.dhis.android.core.common.IdentifiableObjectStore; import org.hisp.dhis.android.core.common.ObjectStyle; import org.hisp.dhis.android.core.common.ObjectStyleHandler; import org.hisp.dhis.android.core.common.ObjectStyleModel; import org.hisp.dhis.android.core.common.ObjectStyleModelBuilder; import org.hisp.dhis.android.core.common.OrphanCleaner; import org.hisp.dhis.android.core.common.OrphanCleanerImpl; import org.hisp.dhis.android.core.data.database.DatabaseAdapter; import org.hisp.dhis.android.core.period.FeatureType; import org.hisp.dhis.android.core.systeminfo.DHISVersionManager; import java.util.Collection; public class ProgramStageHandler extends IdentifiableHandlerImpl<ProgramStage, ProgramStageModel> { private final ProgramStageSectionHandler programStageSectionHandler; private final ProgramStageDataElementHandler programStageDataElementHandler; private final GenericHandler<ObjectStyle, ObjectStyleModel> styleHandler; private final OrphanCleaner<ProgramStage, ProgramStageDataElement> programStageDataElementCleaner; private final OrphanCleaner<ProgramStage, ProgramStageSection> programStageSectionCleaner; private final CollectionCleaner<ProgramStage> collectionCleaner; private final DHISVersionManager versionManager; ProgramStageHandler(IdentifiableObjectStore<ProgramStageModel> programStageStore, ProgramStageSectionHandler programStageSectionHandler, ProgramStageDataElementHandler programStageDataElementHandler, GenericHandler<ObjectStyle, ObjectStyleModel> styleHandler, OrphanCleaner<ProgramStage, ProgramStageDataElement> programStageDataElementCleaner, OrphanCleaner<ProgramStage, ProgramStageSection> programStageSectionCleaner, CollectionCleaner<ProgramStage> collectionCleaner, DHISVersionManager versionManager) { super(programStageStore); this.programStageSectionHandler = programStageSectionHandler; this.programStageDataElementHandler = programStageDataElementHandler; this.styleHandler = styleHandler; this.programStageDataElementCleaner = programStageDataElementCleaner; this.programStageSectionCleaner = programStageSectionCleaner; this.collectionCleaner = collectionCleaner; this.versionManager = versionManager; } @Override protected ProgramStage beforeObjectHandled(ProgramStage programStage) { ProgramStage.Builder builder = programStage.toBuilder(); if (versionManager.is2_29()) { programStage = programStage.captureCoordinates() ? builder.featureType(FeatureType.POINT).build() : builder.featureType(FeatureType.NONE).build(); } else { programStage = builder.captureCoordinates(programStage.featureType() != FeatureType.NONE).build(); } return programStage; } @Override protected void afterObjectHandled(ProgramStage programStage, HandleAction action) { programStageDataElementHandler.handleProgramStageDataElements( programStage.programStageDataElements()); programStageSectionHandler.handleProgramStageSection(programStage.uid(), programStage.programStageSections()); styleHandler.handle(programStage.style(), new ObjectStyleModelBuilder(programStage.uid(), ProgramStageModel.TABLE)); if (action == HandleAction.Update) { programStageDataElementCleaner.deleteOrphan(programStage, programStage.programStageDataElements()); programStageSectionCleaner.deleteOrphan(programStage, programStage.programStageSections()); } } @Override protected void afterCollectionHandled(Collection<ProgramStage> programStages) { collectionCleaner.deleteNotPresent(programStages); } public static ProgramStageHandler create(DatabaseAdapter databaseAdapter, DHISVersionManager versionManager) { return new ProgramStageHandler( ProgramStageStore.create(databaseAdapter), ProgramStageSectionHandler.create(databaseAdapter), ProgramStageDataElementHandler.create(databaseAdapter), ObjectStyleHandler.create(databaseAdapter), new OrphanCleanerImpl<ProgramStage, ProgramStageDataElement>(ProgramStageDataElementModel.TABLE, ProgramStageDataElementModel.Columns.PROGRAM_STAGE, databaseAdapter), new OrphanCleanerImpl<ProgramStage, ProgramStageSection>(ProgramStageSectionModel.TABLE, ProgramStageSectionModel.Columns.PROGRAM_STAGE, databaseAdapter), new CollectionCleanerImpl<ProgramStage>(ProgramStageModel.TABLE, databaseAdapter), versionManager); } }
core/src/main/java/org/hisp/dhis/android/core/program/ProgramStageHandler.java
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program; import org.hisp.dhis.android.core.common.CollectionCleaner; import org.hisp.dhis.android.core.common.CollectionCleanerImpl; import org.hisp.dhis.android.core.common.GenericHandler; import org.hisp.dhis.android.core.common.HandleAction; import org.hisp.dhis.android.core.common.IdentifiableHandlerImpl; import org.hisp.dhis.android.core.common.IdentifiableObjectStore; import org.hisp.dhis.android.core.common.ObjectStyle; import org.hisp.dhis.android.core.common.ObjectStyleHandler; import org.hisp.dhis.android.core.common.ObjectStyleModel; import org.hisp.dhis.android.core.common.ObjectStyleModelBuilder; import org.hisp.dhis.android.core.common.OrphanCleaner; import org.hisp.dhis.android.core.common.OrphanCleanerImpl; import org.hisp.dhis.android.core.data.database.DatabaseAdapter; import java.util.Collection; public class ProgramStageHandler extends IdentifiableHandlerImpl<ProgramStage, ProgramStageModel> { private final ProgramStageSectionHandler programStageSectionHandler; private final ProgramStageDataElementHandler programStageDataElementHandler; private final GenericHandler<ObjectStyle, ObjectStyleModel> styleHandler; private final OrphanCleaner<ProgramStage, ProgramStageDataElement> programStageDataElementCleaner; private final OrphanCleaner<ProgramStage, ProgramStageSection> programStageSectionCleaner; private final CollectionCleaner<ProgramStage> collectionCleaner; ProgramStageHandler(IdentifiableObjectStore<ProgramStageModel> programStageStore, ProgramStageSectionHandler programStageSectionHandler, ProgramStageDataElementHandler programStageDataElementHandler, GenericHandler<ObjectStyle, ObjectStyleModel> styleHandler, OrphanCleaner<ProgramStage, ProgramStageDataElement> programStageDataElementCleaner, OrphanCleaner<ProgramStage, ProgramStageSection> programStageSectionCleaner, CollectionCleaner<ProgramStage> collectionCleaner) { super(programStageStore); this.programStageSectionHandler = programStageSectionHandler; this.programStageDataElementHandler = programStageDataElementHandler; this.styleHandler = styleHandler; this.programStageDataElementCleaner = programStageDataElementCleaner; this.programStageSectionCleaner = programStageSectionCleaner; this.collectionCleaner = collectionCleaner; } @Override protected void afterObjectHandled(ProgramStage programStage, HandleAction action) { programStageDataElementHandler.handleProgramStageDataElements( programStage.programStageDataElements()); programStageSectionHandler.handleProgramStageSection(programStage.uid(), programStage.programStageSections()); styleHandler.handle(programStage.style(), new ObjectStyleModelBuilder(programStage.uid(), ProgramStageModel.TABLE)); if (action == HandleAction.Update) { programStageDataElementCleaner.deleteOrphan(programStage, programStage.programStageDataElements()); programStageSectionCleaner.deleteOrphan(programStage, programStage.programStageSections()); } } @Override protected void afterCollectionHandled(Collection<ProgramStage> programStages) { collectionCleaner.deleteNotPresent(programStages); } public static ProgramStageHandler create(DatabaseAdapter databaseAdapter) { return new ProgramStageHandler( ProgramStageStore.create(databaseAdapter), ProgramStageSectionHandler.create(databaseAdapter), ProgramStageDataElementHandler.create(databaseAdapter), ObjectStyleHandler.create(databaseAdapter), new OrphanCleanerImpl<ProgramStage, ProgramStageDataElement>(ProgramStageDataElementModel.TABLE, ProgramStageDataElementModel.Columns.PROGRAM_STAGE, databaseAdapter), new OrphanCleanerImpl<ProgramStage, ProgramStageSection>(ProgramStageSectionModel.TABLE, ProgramStageSectionModel.Columns.PROGRAM_STAGE, databaseAdapter), new CollectionCleanerImpl<ProgramStage>(ProgramStageModel.TABLE, databaseAdapter)); } }
program-stage-feature-type: override beforeObjectHandled on ProgramStageHandler
core/src/main/java/org/hisp/dhis/android/core/program/ProgramStageHandler.java
program-stage-feature-type: override beforeObjectHandled on ProgramStageHandler
Java
isc
ac5168a6389c3512f091cb5c9203c2ae39f0849c
0
pradeep1991singh/react-native-secure-key-store,pradeep1991singh/react-native-secure-key-store,pradeep1991singh/react-native-secure-key-store
/** * React Native Secure Key Store * Store keys securely in Android Keystore * Ref: cordova-plugin-secure-key-store */ package com.reactlibrary.securekeystore; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import android.util.Log; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Calendar; import androidx.annotation.Nullable; import com.facebook.react.bridge.ReadableMap; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.x500.X500Principal; public class RNSecureKeyStoreModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public RNSecureKeyStoreModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNSecureKeyStore"; } @ReactMethod public void set(String alias, String input, @Nullable ReadableMap options, Promise promise) { try { setCipherText(alias, input); promise.resolve("stored ciphertext in app storage"); } catch (Exception e) { e.printStackTrace(); Log.e(Constants.TAG, "Exception: " + e.getMessage()); promise.reject("{\"code\":9,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + e.getMessage() + "}"); } } private PublicKey getOrCreatePublicKey(String alias) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(getKeyStore()); keyStore.load(null); if (!keyStore.containsAlias(alias) || keyStore.getCertificate(alias) == null) { Log.i(Constants.TAG, "no existing asymmetric keys for alias"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 50); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext()) .setAlias(alias) .setSubject(new X500Principal("CN=" + alias)) .setSerialNumber(BigInteger.ONE) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", getKeyStore()); generator.initialize(spec); generator.generateKeyPair(); Log.i(Constants.TAG, "created new asymmetric keys for alias"); } return keyStore.getCertificate(alias).getPublicKey(); } private byte[] encryptRsaPlainText(PublicKey publicKey, byte[] plainTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return encryptCipherText(cipher, plainTextBytes); } private byte[] encryptAesPlainText(SecretKey secretKey, String plainText) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return encryptCipherText(cipher, plainText); } private byte[] encryptCipherText(Cipher cipher, String plainText) throws GeneralSecurityException, IOException { return encryptCipherText(cipher, plainText.getBytes("UTF-8")); } private byte[] encryptCipherText(Cipher cipher, byte[] plainTextBytes) throws GeneralSecurityException, IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher); cipherOutputStream.write(plainTextBytes); cipherOutputStream.close(); return outputStream.toByteArray(); } private SecretKey getOrCreateSecretKey(String alias) throws GeneralSecurityException, IOException { try { return getSymmetricKey(alias); } catch (FileNotFoundException fnfe) { Log.i(Constants.TAG, "no existing symmetric key for alias"); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //32bytes / 256bits AES key keyGenerator.init(256); SecretKey secretKey = keyGenerator.generateKey(); PublicKey publicKey = getOrCreatePublicKey(alias); Storage.writeValues(getContext(), Constants.SKS_KEY_FILENAME + alias, encryptRsaPlainText(publicKey, secretKey.getEncoded())); Log.i(Constants.TAG, "created new symmetric keys for alias"); return secretKey; } } private void setCipherText(String alias, String input) throws GeneralSecurityException, IOException { Storage.writeValues(getContext(), Constants.SKS_DATA_FILENAME + alias, encryptAesPlainText(getOrCreateSecretKey(alias), input)); } @ReactMethod public void get(String alias, Promise promise) { try { promise.resolve(getPlainText(alias)); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); promise.reject("404", "{\"code\":404,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + fnfe.getMessage() + "}", fnfe); } catch (Exception e) { e.printStackTrace(); Log.e(Constants.TAG, "Exception: " + e.getMessage()); promise.reject("{\"code\":1,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + e.getMessage() + "}"); } } private PrivateKey getPrivateKey(String alias) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(getKeyStore()); keyStore.load(null); return (PrivateKey) keyStore.getKey(alias, null); } private byte[] decryptRsaCipherText(PrivateKey privateKey, byte[] cipherTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return decryptCipherText(cipher, cipherTextBytes); } private byte[] decryptAesCipherText(SecretKey secretKey, byte[] cipherTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); return decryptCipherText(cipher, cipherTextBytes); } private byte[] decryptCipherText(Cipher cipher, byte[] cipherTextBytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(cipherTextBytes); CipherInputStream cipherInputStream = new CipherInputStream(bais, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int bytesRead = cipherInputStream.read(buffer); while (bytesRead != -1) { baos.write(buffer, 0, bytesRead); bytesRead = cipherInputStream.read(buffer); } return baos.toByteArray(); } private SecretKey getSymmetricKey(String alias) throws GeneralSecurityException, IOException { byte[] cipherTextBytes = Storage.readValues(getContext(), Constants.SKS_KEY_FILENAME + alias); return new SecretKeySpec(decryptRsaCipherText(getPrivateKey(alias), cipherTextBytes), Constants.AES_ALGORITHM); } private String getPlainText(String alias) throws GeneralSecurityException, IOException { SecretKey secretKey = getSymmetricKey(alias); byte[] cipherTextBytes = Storage.readValues(getContext(), Constants.SKS_DATA_FILENAME + alias); return new String(decryptAesCipherText(secretKey, cipherTextBytes), "UTF-8"); } @ReactMethod public void remove(String alias, Promise promise) { Storage.resetValues(getContext(), new String[] { Constants.SKS_DATA_FILENAME + alias, Constants.SKS_KEY_FILENAME + alias, }); promise.resolve("cleared alias"); } private Context getContext() { return getReactApplicationContext(); } private String getKeyStore() { try { KeyStore.getInstance(Constants.KEYSTORE_PROVIDER_1); return Constants.KEYSTORE_PROVIDER_1; } catch (Exception err) { try { KeyStore.getInstance(Constants.KEYSTORE_PROVIDER_2); return Constants.KEYSTORE_PROVIDER_2; } catch (Exception e) { return Constants.KEYSTORE_PROVIDER_3; } } } }
android/src/main/java/com/reactlibrary/securekeystore/RNSecureKeyStoreModule.java
/** * React Native Secure Key Store * Store keys securely in Android Keystore * Ref: cordova-plugin-secure-key-store */ package com.reactlibrary.securekeystore; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import android.util.Log; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Calendar; import android.support.annotation.Nullable; import com.facebook.react.bridge.ReadableMap; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.x500.X500Principal; public class RNSecureKeyStoreModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public RNSecureKeyStoreModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNSecureKeyStore"; } @ReactMethod public void set(String alias, String input, @Nullable ReadableMap options, Promise promise) { try { setCipherText(alias, input); promise.resolve("stored ciphertext in app storage"); } catch (Exception e) { e.printStackTrace(); Log.e(Constants.TAG, "Exception: " + e.getMessage()); promise.reject("{\"code\":9,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + e.getMessage() + "}"); } } private PublicKey getOrCreatePublicKey(String alias) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(getKeyStore()); keyStore.load(null); if (!keyStore.containsAlias(alias) || keyStore.getCertificate(alias) == null) { Log.i(Constants.TAG, "no existing asymmetric keys for alias"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 50); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext()) .setAlias(alias) .setSubject(new X500Principal("CN=" + alias)) .setSerialNumber(BigInteger.ONE) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", getKeyStore()); generator.initialize(spec); generator.generateKeyPair(); Log.i(Constants.TAG, "created new asymmetric keys for alias"); } return keyStore.getCertificate(alias).getPublicKey(); } private byte[] encryptRsaPlainText(PublicKey publicKey, byte[] plainTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return encryptCipherText(cipher, plainTextBytes); } private byte[] encryptAesPlainText(SecretKey secretKey, String plainText) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return encryptCipherText(cipher, plainText); } private byte[] encryptCipherText(Cipher cipher, String plainText) throws GeneralSecurityException, IOException { return encryptCipherText(cipher, plainText.getBytes("UTF-8")); } private byte[] encryptCipherText(Cipher cipher, byte[] plainTextBytes) throws GeneralSecurityException, IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher); cipherOutputStream.write(plainTextBytes); cipherOutputStream.close(); return outputStream.toByteArray(); } private SecretKey getOrCreateSecretKey(String alias) throws GeneralSecurityException, IOException { try { return getSymmetricKey(alias); } catch (FileNotFoundException fnfe) { Log.i(Constants.TAG, "no existing symmetric key for alias"); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //32bytes / 256bits AES key keyGenerator.init(256); SecretKey secretKey = keyGenerator.generateKey(); PublicKey publicKey = getOrCreatePublicKey(alias); Storage.writeValues(getContext(), Constants.SKS_KEY_FILENAME + alias, encryptRsaPlainText(publicKey, secretKey.getEncoded())); Log.i(Constants.TAG, "created new symmetric keys for alias"); return secretKey; } } private void setCipherText(String alias, String input) throws GeneralSecurityException, IOException { Storage.writeValues(getContext(), Constants.SKS_DATA_FILENAME + alias, encryptAesPlainText(getOrCreateSecretKey(alias), input)); } @ReactMethod public void get(String alias, Promise promise) { try { promise.resolve(getPlainText(alias)); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); promise.reject("404", "{\"code\":404,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + fnfe.getMessage() + "}", fnfe); } catch (Exception e) { e.printStackTrace(); Log.e(Constants.TAG, "Exception: " + e.getMessage()); promise.reject("{\"code\":1,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + e.getMessage() + "}"); } } private PrivateKey getPrivateKey(String alias) throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(getKeyStore()); keyStore.load(null); return (PrivateKey) keyStore.getKey(alias, null); } private byte[] decryptRsaCipherText(PrivateKey privateKey, byte[] cipherTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return decryptCipherText(cipher, cipherTextBytes); } private byte[] decryptAesCipherText(SecretKey secretKey, byte[] cipherTextBytes) throws GeneralSecurityException, IOException { Cipher cipher = Cipher.getInstance(Constants.AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); return decryptCipherText(cipher, cipherTextBytes); } private byte[] decryptCipherText(Cipher cipher, byte[] cipherTextBytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(cipherTextBytes); CipherInputStream cipherInputStream = new CipherInputStream(bais, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int bytesRead = cipherInputStream.read(buffer); while (bytesRead != -1) { baos.write(buffer, 0, bytesRead); bytesRead = cipherInputStream.read(buffer); } return baos.toByteArray(); } private SecretKey getSymmetricKey(String alias) throws GeneralSecurityException, IOException { byte[] cipherTextBytes = Storage.readValues(getContext(), Constants.SKS_KEY_FILENAME + alias); return new SecretKeySpec(decryptRsaCipherText(getPrivateKey(alias), cipherTextBytes), Constants.AES_ALGORITHM); } private String getPlainText(String alias) throws GeneralSecurityException, IOException { SecretKey secretKey = getSymmetricKey(alias); byte[] cipherTextBytes = Storage.readValues(getContext(), Constants.SKS_DATA_FILENAME + alias); return new String(decryptAesCipherText(secretKey, cipherTextBytes), "UTF-8"); } @ReactMethod public void remove(String alias, Promise promise) { Storage.resetValues(getContext(), new String[] { Constants.SKS_DATA_FILENAME + alias, Constants.SKS_KEY_FILENAME + alias, }); promise.resolve("cleared alias"); } private Context getContext() { return getReactApplicationContext(); } private String getKeyStore() { try { KeyStore.getInstance(Constants.KEYSTORE_PROVIDER_1); return Constants.KEYSTORE_PROVIDER_1; } catch (Exception err) { try { KeyStore.getInstance(Constants.KEYSTORE_PROVIDER_2); return Constants.KEYSTORE_PROVIDER_2; } catch (Exception e) { return Constants.KEYSTORE_PROVIDER_3; } } } }
fix: RN 0.60+
android/src/main/java/com/reactlibrary/securekeystore/RNSecureKeyStoreModule.java
fix: RN 0.60+
Java
mit
a45c1c8a88b8e0b9b499e19802acff6315ed95e5
0
simple-elf/selenide,simple-elf/selenide,simple-elf/selenide,codeborne/selenide,simple-elf/selenide,codeborne/selenide,codeborne/selenide
package com.codeborne.selenide.webdriver; import com.codeborne.selenide.WebDriverRunner; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import java.util.logging.Logger; import static com.codeborne.selenide.Configuration.browserBinary; import static com.codeborne.selenide.Configuration.headless; class FirefoxDriverFactory extends AbstractDriverFactory { private static final Logger log = Logger.getLogger(FirefoxDriverFactory.class.getName()); @Override boolean supports() { return WebDriverRunner.isFirefox(); } @Override WebDriver create(final Proxy proxy) { return createFirefoxDriver(proxy); } private WebDriver createFirefoxDriver(final Proxy proxy) { FirefoxOptions options = createFirefoxOptions(proxy); return new FirefoxDriver(options); } FirefoxOptions createFirefoxOptions(Proxy proxy) { FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setHeadless(headless); if (!browserBinary.isEmpty()) { firefoxOptions.setBinary(browserBinary); } firefoxOptions.addPreference("network.automatic-ntlm-auth.trusted-uris", "http://,https://"); firefoxOptions.addPreference("network.automatic-ntlm-auth.allow-non-fqdn", true); firefoxOptions.addPreference("network.negotiate-auth.delegation-uris", "http://,https://"); firefoxOptions.addPreference("network.negotiate-auth.trusted-uris", "http://,https://"); firefoxOptions.addPreference("network.http.phishy-userpass-length", 255); firefoxOptions.addPreference("security.csp.enable", false); firefoxOptions.merge(createCommonCapabilities(proxy)); firefoxOptions = transferFirefoxProfileFromSystemProperties(firefoxOptions); return firefoxOptions; } private FirefoxOptions transferFirefoxProfileFromSystemProperties(FirefoxOptions currentFirefoxOptions) { String prefix = "firefoxprofile."; FirefoxProfile profile = new FirefoxProfile(); for (String key : System.getProperties().stringPropertyNames()) { if (key.startsWith(prefix)) { String capability = key.substring(prefix.length()); String value = System.getProperties().getProperty(key); log.config("Use " + key + "=" + value); if (value.equals("true") || value.equals("false")) { profile.setPreference(capability, Boolean.valueOf(value)); } else if (value.matches("^-?\\d+$")) { //if integer profile.setPreference(capability, Integer.parseInt(value)); } else { profile.setPreference(capability, value); } } } return currentFirefoxOptions.setProfile(profile); } }
src/main/java/com/codeborne/selenide/webdriver/FirefoxDriverFactory.java
package com.codeborne.selenide.webdriver; import com.codeborne.selenide.WebDriverRunner; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import java.io.File; import java.util.logging.Logger; import static com.codeborne.selenide.Configuration.browserBinary; import static com.codeborne.selenide.Configuration.headless; class FirefoxDriverFactory extends AbstractDriverFactory { private static final Logger log = Logger.getLogger(FirefoxDriverFactory.class.getName()); @Override boolean supports() { return WebDriverRunner.isFirefox(); } @Override WebDriver create(final Proxy proxy) { return createFirefoxDriver(proxy); } private WebDriver createFirefoxDriver(final Proxy proxy) { FirefoxOptions options = createFirefoxOptions(proxy); return new FirefoxDriver(options); } FirefoxOptions createFirefoxOptions(Proxy proxy) { FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setHeadless(headless); if (!browserBinary.isEmpty()) { firefoxOptions.setBinary(browserBinary); } firefoxOptions.addPreference("network.automatic-ntlm-auth.trusted-uris", "http://,https://"); firefoxOptions.addPreference("network.automatic-ntlm-auth.allow-non-fqdn", true); firefoxOptions.addPreference("network.negotiate-auth.delegation-uris", "http://,https://"); firefoxOptions.addPreference("network.negotiate-auth.trusted-uris", "http://,https://"); firefoxOptions.addPreference("network.http.phishy-userpass-length", 255); firefoxOptions.addPreference("security.csp.enable", false); firefoxOptions.merge(createCommonCapabilities(proxy)); firefoxOptions = transferFirefoxProfileFromSystemProperties(firefoxOptions); return firefoxOptions; } private FirefoxOptions transferFirefoxProfileFromSystemProperties(FirefoxOptions currentFirefoxOptions) { String prefix = "firefoxprofile."; FirefoxProfile profile = new FirefoxProfile(); for (String key : System.getProperties().stringPropertyNames()) { if (key.startsWith(prefix)) { String capability = key.substring(prefix.length()); String value = System.getProperties().getProperty(key); log.config("Use " + key + "=" + value); if (value.equals("true") || value.equals("false")) { profile.setPreference(capability, Boolean.valueOf(value)); } else if (value.matches("^-?\\d+$")) { //if integer profile.setPreference(capability, Integer.parseInt(value)); } else { profile.setPreference(capability, value); } } } return currentFirefoxOptions.setProfile(profile); } }
removed unused import
src/main/java/com/codeborne/selenide/webdriver/FirefoxDriverFactory.java
removed unused import
Java
mit
58fecdcdefa2ef2e9abb2e08d9d7c7a6b7d2027f
0
sathiya-mit/jenkins,pjanouse/jenkins,daniel-beck/jenkins,v1v/jenkins,oleg-nenashev/jenkins,viqueen/jenkins,bkmeneguello/jenkins,batmat/jenkins,viqueen/jenkins,Vlatombe/jenkins,ikedam/jenkins,damianszczepanik/jenkins,jenkinsci/jenkins,recena/jenkins,jenkinsci/jenkins,pjanouse/jenkins,daniel-beck/jenkins,andresrc/jenkins,viqueen/jenkins,Vlatombe/jenkins,rsandell/jenkins,damianszczepanik/jenkins,rsandell/jenkins,batmat/jenkins,sathiya-mit/jenkins,bkmeneguello/jenkins,MarkEWaite/jenkins,batmat/jenkins,godfath3r/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,andresrc/jenkins,Vlatombe/jenkins,damianszczepanik/jenkins,Vlatombe/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,rsandell/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,Jochen-A-Fuerbacher/jenkins,rsandell/jenkins,rsandell/jenkins,batmat/jenkins,viqueen/jenkins,v1v/jenkins,Jochen-A-Fuerbacher/jenkins,v1v/jenkins,andresrc/jenkins,recena/jenkins,bkmeneguello/jenkins,recena/jenkins,andresrc/jenkins,viqueen/jenkins,sathiya-mit/jenkins,godfath3r/jenkins,batmat/jenkins,v1v/jenkins,godfath3r/jenkins,daniel-beck/jenkins,andresrc/jenkins,DanielWeber/jenkins,andresrc/jenkins,sathiya-mit/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,patbos/jenkins,ikedam/jenkins,v1v/jenkins,rsandell/jenkins,rsandell/jenkins,Jochen-A-Fuerbacher/jenkins,damianszczepanik/jenkins,jenkinsci/jenkins,patbos/jenkins,Jochen-A-Fuerbacher/jenkins,bkmeneguello/jenkins,jenkinsci/jenkins,sathiya-mit/jenkins,andresrc/jenkins,daniel-beck/jenkins,patbos/jenkins,patbos/jenkins,batmat/jenkins,v1v/jenkins,oleg-nenashev/jenkins,jenkinsci/jenkins,stephenc/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,jenkinsci/jenkins,ikedam/jenkins,bkmeneguello/jenkins,sathiya-mit/jenkins,stephenc/jenkins,Jochen-A-Fuerbacher/jenkins,ikedam/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,viqueen/jenkins,recena/jenkins,MarkEWaite/jenkins,viqueen/jenkins,daniel-beck/jenkins,stephenc/jenkins,batmat/jenkins,Vlatombe/jenkins,stephenc/jenkins,stephenc/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,stephenc/jenkins,stephenc/jenkins,Vlatombe/jenkins,DanielWeber/jenkins,pjanouse/jenkins,bkmeneguello/jenkins,bkmeneguello/jenkins,patbos/jenkins,daniel-beck/jenkins,pjanouse/jenkins,godfath3r/jenkins,pjanouse/jenkins,recena/jenkins,patbos/jenkins,damianszczepanik/jenkins,ikedam/jenkins,v1v/jenkins,sathiya-mit/jenkins,damianszczepanik/jenkins,DanielWeber/jenkins,pjanouse/jenkins,ikedam/jenkins,Jochen-A-Fuerbacher/jenkins,recena/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,rsandell/jenkins,patbos/jenkins,recena/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,ikedam/jenkins,ikedam/jenkins,DanielWeber/jenkins,daniel-beck/jenkins
package jenkins.security; import hudson.Extension; import hudson.model.User; import org.acegisecurity.Authentication; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.springframework.dao.DataAccessException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Logger; import static java.util.logging.Level.*; /** * Checks if the password given in the BASIC header matches the user's API token. * * @author Kohsuke Kawaguchi * @since 1.576 */ @Extension public class BasicHeaderApiTokenAuthenticator extends BasicHeaderAuthenticator { /** * Note: if the token does not exist or does not match, we do not use {@link SecurityListener#fireFailedToAuthenticate(String)} * because it will be done in the {@link BasicHeaderRealPasswordAuthenticator} in the case the password is not valid either */ @Override public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { ApiTokenProperty t = u.getProperty(ApiTokenProperty.class); if (t != null && t.matchesPassword(password)) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } catch (UsernameNotFoundException x) { // The token was valid, but the impersonation failed. This token is clearly not his real password, // so there's no point in continuing the request processing. Report this error and abort. LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } } return null; } private static final Logger LOGGER = Logger.getLogger(BasicHeaderApiTokenAuthenticator.class.getName()); }
core/src/main/java/jenkins/security/BasicHeaderApiTokenAuthenticator.java
package jenkins.security; import hudson.Extension; import hudson.model.User; import org.acegisecurity.Authentication; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.springframework.dao.DataAccessException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Logger; import static java.util.logging.Level.*; /** * Checks if the password given in the BASIC header matches the user's API token. * * @author Kohsuke Kawaguchi * @since 1.576 */ @Extension public class BasicHeaderApiTokenAuthenticator extends BasicHeaderAuthenticator { /** * Note: if the token does not exist or does not match, we do not use {@link SecurityListener#fireFailedToAuthenticate(String)} * because it will be done in the {@link BasicHeaderRealPasswordAuthenticator} in the case the password is not valid either */ @Override public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { // attempt to authenticate as API token User u = User.getById(username, true); ApiTokenProperty t = u.getProperty(ApiTokenProperty.class); if (t!=null && t.matchesPassword(password)) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } catch (UsernameNotFoundException x) { // The token was valid, but the impersonation failed. This token is clearly not his real password, // so there's no point in continuing the request processing. Report this error and abort. LOGGER.log(WARNING, "API token matched for user "+username+" but the impersonation failed",x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; } private static final Logger LOGGER = Logger.getLogger(BasicHeaderApiTokenAuthenticator.class.getName()); }
[SECURITY-1162]
core/src/main/java/jenkins/security/BasicHeaderApiTokenAuthenticator.java
[SECURITY-1162]
Java
mit
e506bb23399e443cc59c2976cffba7777b90b26e
0
nulab/zxcvbn4j
package com.nulabinc.zxcvbn.matchers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dictionary { private static final String RESOURCES_PACKAGE_PATH = "/com/nulabinc/zxcvbn/matchers/dictionarys/"; private static final ResourceLoader RESOURCE_LOADER = new ResourceLoader(); private static final String EXT = ".txt"; private static final String UTF_8 = "UTF-8"; private static String buildResourcePath(String filename) { return RESOURCES_PACKAGE_PATH + filename + EXT; } private static final String[] DICTIONARY_PARAMS = { "us_tv_and_film", "english_wikipedia", "passwords", "surnames", "male_names", "female_names" }; public static final Map<String, String[]> FREQUENCY_LISTS; static { FREQUENCY_LISTS = read(); } private static Map<String, String[]> read() { Map<String, String[]> freqLists = new HashMap<>(); for (String filename: DICTIONARY_PARAMS) { List<String> words = new ArrayList<>(); try(InputStream is = RESOURCE_LOADER.getInputStream(buildResourcePath(filename)); // Reasons for not using StandardCharsets // refs: https://github.com/nulab/zxcvbn4j/issues/62 BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8))) { String line; while ((line = br.readLine()) != null) { words.add(line); } } catch (IOException e) { throw new RuntimeException("Error while reading " + filename); } freqLists.put(filename, words.toArray(new String[]{})); } return freqLists; } }
src/main/java/com/nulabinc/zxcvbn/matchers/Dictionary.java
package com.nulabinc.zxcvbn.matchers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dictionary { private static final ResourceLoader RESOURCE_LOADER = new ResourceLoader(); private static final String RESOURCES_PACKAGE_PATH = "/com/nulabinc/zxcvbn/matchers/dictionarys/"; private static final String EXT = ".txt"; private static final String UTF_8 = "UTF-8"; private static String buildResourcePath(String filename) { return RESOURCES_PACKAGE_PATH + filename + EXT; } private static final String[] DICTIONARY_PARAMS = { "us_tv_and_film", "english_wikipedia", "passwords", "surnames", "male_names", "female_names" }; public static final Map<String, String[]> FREQUENCY_LISTS; static { FREQUENCY_LISTS = read(); } private static Map<String, String[]> read() { Map<String, String[]> freqLists = new HashMap<>(); for (String filename: DICTIONARY_PARAMS) { List<String> words = new ArrayList<>(); try(InputStream is = RESOURCE_LOADER.getInputStream(buildResourcePath(filename)); // Reasons for not using StandardCharsets // refs: https://github.com/nulab/zxcvbn4j/issues/62 BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8))) { String line; while ((line = br.readLine()) != null) { words.add(line); } } catch (IOException e) { throw new RuntimeException("Error while reading " + filename); } freqLists.put(filename, words.toArray(new String[]{})); } return freqLists; } }
avoid unnecessary diffs
src/main/java/com/nulabinc/zxcvbn/matchers/Dictionary.java
avoid unnecessary diffs
Java
mit
54dd53eca8ea88375b05a43075f363c1acd3a4bd
0
blendee/blendee
package org.blendee.util; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.function.Consumer; import java.util.regex.Pattern; import org.blendee.internal.TransactionManager; import org.blendee.internal.TransactionShell; import org.blendee.jdbc.AutoCloseableFinalizer; import org.blendee.jdbc.BTransaction; import org.blendee.jdbc.BlendeeManager; import org.blendee.jdbc.ContextManager; import org.blendee.jdbc.Initializer; import org.blendee.jdbc.MetadataFactory; import org.blendee.jdbc.OptionKey; import org.blendee.jdbc.TransactionFactory; import org.blendee.selector.AnchorOptimizerFactory; import org.blendee.selector.ColumnRepositoryFactory; import org.blendee.sql.RelationshipFactory; import org.blendee.sql.ValueExtractorsConfigure; /** * Blendee 全体を対象とする、簡易操作クラスです。 * @author 千葉 哲嗣 */ public class Blendee { private Class<? extends MetadataFactory> defaultMetadataFactoryClass = AnnotationMetadataFactory.class; private Class<? extends TransactionFactory> defaultTransactionFactoryClass = DriverTransactionFactory.class; private Class<? extends ColumnRepositoryFactory> defaultColumnRepositoryFactoryClass = FileColumnRepositoryFactory.class; private List<Consumer<Initializer>> consumers; /** * @param consumers */ @SuppressWarnings("unchecked") public Blendee(Consumer<Initializer>... consumers) { this.consumers = Arrays.asList(consumers); } /** * Blendee を使用可能な状態にします。 * @param initValues Blendee を初期化するための値 */ public void start(Properties initValues) { Map<OptionKey<?>, Object> param = new HashMap<>(); initValues.forEach((k, v) -> { ParsableOptionKey<?> key = BlendeeConstants.convert((String) k); param.put(key, key.parse((String) v).get()); }); start(param); } /** * Blendee を使用可能な状態にします。 * @param initValues Blendee を初期化するための値 */ public void start(Map<OptionKey<?>, ?> initValues) { Initializer init = new Initializer(); init.setOptions(new HashMap<>(initValues)); BlendeeConstants.SCHEMA_NAMES.extract(initValues).ifPresent(names -> { for (String name : names) { init.addSchemaName(name); } }); BlendeeConstants.ENABLE_LOG.extract(initValues).ifPresent(flag -> init.enableLog(flag)); BlendeeConstants.USE_LAZY_TRANSACTION.extract(initValues).ifPresent(flag -> init.setUseLazyTransaction(flag)); BlendeeConstants.USE_METADATA_CACHE.extract(initValues).ifPresent(flag -> init.setUseMetadataCache(flag)); BlendeeConstants.AUTO_CLOSE_INTERVAL_MILLIS.extract(initValues).ifPresent(millis -> init.setAutoCloseIntervalMillis(millis)); BlendeeConstants.LOG_STACKTRACE_FILTER.extract(initValues).ifPresent(filter -> init.setLogStackTraceFilter(Pattern.compile(filter))); BlendeeConstants.ERROR_CONVERTER_CLASS.extract(initValues).ifPresent(clazz -> init.setErrorConverterClass(clazz)); Optional.ofNullable( BlendeeConstants.METADATA_FACTORY_CLASS.extract(initValues).orElseGet( () -> Optional.of(getDefaultMetadataFactoryClass()) .filter(c -> BlendeeConstants.ANNOTATED_ROW_PACKAGES.extract(initValues).isPresent()) .orElse(null))) .ifPresent(clazz -> init.setMetadataFactoryClass(clazz)); Optional.ofNullable( BlendeeConstants.TRANSACTION_FACTORY_CLASS.extract(initValues).orElseGet( () -> Optional.of(getDefaultTransactionFactoryClass()) .filter( c -> BlendeeConstants.JDBC_DRIVER_CLASS_NAME.extract(initValues) .filter(name -> name.length() > 0) .isPresent()) .orElse(null))) .ifPresent(clazz -> init.setTransactionFactoryClass(clazz)); ContextManager.get(BlendeeManager.class).initialize(init); consumers.forEach(c -> c.accept(init)); BlendeeConstants.VALUE_EXTRACTORS_CLASS.extract(initValues) .ifPresent(clazz -> ContextManager.get(ValueExtractorsConfigure.class).setValueExtractorsClass(clazz)); AnchorOptimizerFactory anchorOptimizerFactory = ContextManager.get(AnchorOptimizerFactory.class); BlendeeConstants.CAN_ADD_NEW_ENTRIES.extract(initValues) .ifPresent(flag -> anchorOptimizerFactory.setCanAddNewEntries(flag)); anchorOptimizerFactory.setColumnRepositoryFactoryClass( BlendeeConstants.COLUMN_REPOSITORY_FACTORY_CLASS.extract(initValues) .orElseGet(() -> getDefaultColumnRepositoryFactoryClass())); } /** * 現在接続中の JDBC インスタンスをすべてクローズし、このコンテキストの Blendee を終了します。 */ public static void stop() { AutoCloseableFinalizer finalizer = ContextManager.get(BlendeeManager.class).getAutoCloseableFinalizer(); finalizer.stop(); finalizer.closeAll(); } /** * トランザクション内で任意の処理を実行します。 * @param function {@link Function} の実装 * @throws Exception 処理内で起こった例外 */ public static void execute(Function function) throws Exception { if (ContextManager.get(BlendeeManager.class).hasConnection()) throw new IllegalStateException("既にトランザクションが開始されています"); TransactionManager.start(new TransactionShell() { @Override public void execute() throws Exception { function.execute(getTransaction()); } }); } /** * デフォルト {@link MetadataFactory} を返します。 * @return デフォルト {@link MetadataFactory} */ public synchronized Class<? extends MetadataFactory> getDefaultMetadataFactoryClass() { return defaultMetadataFactoryClass; } /** * デフォルト {@link MetadataFactory} をセットします。 * @param defaultMetadataFactoryClass デフォルト {@link MetadataFactory} */ public synchronized void setDefaultMetadataFactoryClass( Class<? extends MetadataFactory> defaultMetadataFactoryClass) { this.defaultMetadataFactoryClass = defaultMetadataFactoryClass; } /** * デフォルト {@link TransactionFactory} を返します。 * @return デフォルト {@link TransactionFactory} */ public synchronized Class<? extends TransactionFactory> getDefaultTransactionFactoryClass() { return defaultTransactionFactoryClass; } /** * デフォルト {@link TransactionFactory} をセットします。 * @param defaultTransactionFactoryClass デフォルト {@link TransactionFactory} */ public synchronized void setDefaultTransactionFactoryClass( Class<? extends TransactionFactory> defaultTransactionFactoryClass) { this.defaultTransactionFactoryClass = defaultTransactionFactoryClass; } /** * デフォルト {@link ColumnRepositoryFactory} を返します。 * @return デフォルト {@link ColumnRepositoryFactory} */ public synchronized Class<? extends ColumnRepositoryFactory> getDefaultColumnRepositoryFactoryClass() { return defaultColumnRepositoryFactoryClass; } /** * デフォルト {@link ColumnRepositoryFactory} をセットします。 * @param defaultColumnRepositoryFactoryClass デフォルト {@link ColumnRepositoryFactory} */ public synchronized void setDefaultColumnRepositoryFactoryClass( Class<? extends ColumnRepositoryFactory> defaultColumnRepositoryFactoryClass) { this.defaultColumnRepositoryFactoryClass = defaultColumnRepositoryFactoryClass; } /** * Blendee が持つ定義情報の各キャッシュをクリアします。 */ public static void clearCache() { ContextManager.get(BlendeeManager.class).clearMetadataCache(); ContextManager.get(RelationshipFactory.class).clearCache(); } /** * トランザクション内で行う任意の処理を表しています。 */ @FunctionalInterface public interface Function { /** * トランザクション内で呼び出されます。 <br> * 処理が終了した時点で commit が行われます。 <br> * 例外を投げた場合は rollback が行われます。 * @param transaction この処理のトランザクション * @throws Exception 処理内で起こった例外 */ void execute(BTransaction transaction) throws Exception; } }
blendee.core/src/org/blendee/util/Blendee.java
package org.blendee.util; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.function.Consumer; import java.util.regex.Pattern; import org.blendee.internal.TransactionManager; import org.blendee.internal.TransactionShell; import org.blendee.jdbc.AutoCloseableFinalizer; import org.blendee.jdbc.BTransaction; import org.blendee.jdbc.BlendeeManager; import org.blendee.jdbc.ContextManager; import org.blendee.jdbc.Initializer; import org.blendee.jdbc.MetadataFactory; import org.blendee.jdbc.OptionKey; import org.blendee.jdbc.TransactionFactory; import org.blendee.selector.AnchorOptimizerFactory; import org.blendee.selector.ColumnRepositoryFactory; import org.blendee.sql.RelationshipFactory; import org.blendee.sql.ValueExtractorsConfigure; /** * Blendee 全体を対象とする、簡易操作クラスです。 * @author 千葉 哲嗣 */ public class Blendee { private Class<? extends MetadataFactory> defaultMetadataFactoryClass = AnnotationMetadataFactory.class; private Class<? extends TransactionFactory> defaultTransactionFactoryClass = DriverTransactionFactory.class; private Class<? extends ColumnRepositoryFactory> defaultColumnRepositoryFactoryClass = FileColumnRepositoryFactory.class; /** * Blendee を使用可能な状態にします。 * @param initValues Blendee を初期化するための値 * @param consumer {@link Initializer} 調整 */ public void start( Properties initValues, @SuppressWarnings("unchecked") Consumer<Initializer>... consumer) { Map<OptionKey<?>, Object> param = new HashMap<>(); initValues.forEach((k, v) -> { ParsableOptionKey<?> key = BlendeeConstants.convert((String) k); param.put(key, key.parse((String) v).get()); }); start(param, consumer); } /** * Blendee を使用可能な状態にします。 * @param initValues Blendee を初期化するための値 * @param consumer {@link Initializer} 調整 */ public void start( Map<OptionKey<?>, ?> initValues, @SuppressWarnings("unchecked") Consumer<Initializer>... consumer) { Initializer init = new Initializer(); init.setOptions(new HashMap<>(initValues)); BlendeeConstants.SCHEMA_NAMES.extract(initValues).ifPresent(names -> { for (String name : names) { init.addSchemaName(name); } }); BlendeeConstants.ENABLE_LOG.extract(initValues).ifPresent(flag -> init.enableLog(flag)); BlendeeConstants.USE_LAZY_TRANSACTION.extract(initValues).ifPresent(flag -> init.setUseLazyTransaction(flag)); BlendeeConstants.USE_METADATA_CACHE.extract(initValues).ifPresent(flag -> init.setUseMetadataCache(flag)); BlendeeConstants.AUTO_CLOSE_INTERVAL_MILLIS.extract(initValues).ifPresent(millis -> init.setAutoCloseIntervalMillis(millis)); BlendeeConstants.LOG_STACKTRACE_FILTER.extract(initValues).ifPresent(filter -> init.setLogStackTraceFilter(Pattern.compile(filter))); BlendeeConstants.ERROR_CONVERTER_CLASS.extract(initValues).ifPresent(clazz -> init.setErrorConverterClass(clazz)); Optional.ofNullable( BlendeeConstants.METADATA_FACTORY_CLASS.extract(initValues).orElseGet( () -> Optional.of(getDefaultMetadataFactoryClass()) .filter(c -> BlendeeConstants.ANNOTATED_ROW_PACKAGES.extract(initValues).isPresent()) .orElse(null))) .ifPresent(clazz -> init.setMetadataFactoryClass(clazz)); Optional.ofNullable( BlendeeConstants.TRANSACTION_FACTORY_CLASS.extract(initValues).orElseGet( () -> Optional.of(getDefaultTransactionFactoryClass()) .filter( c -> BlendeeConstants.JDBC_DRIVER_CLASS_NAME.extract(initValues) .filter(name -> name.length() > 0) .isPresent()) .orElse(null))) .ifPresent(clazz -> init.setTransactionFactoryClass(clazz)); ContextManager.get(BlendeeManager.class).initialize(init); Arrays.asList(consumer).forEach(c -> c.accept(init)); BlendeeConstants.VALUE_EXTRACTORS_CLASS.extract(initValues) .ifPresent(clazz -> ContextManager.get(ValueExtractorsConfigure.class).setValueExtractorsClass(clazz)); AnchorOptimizerFactory anchorOptimizerFactory = ContextManager.get(AnchorOptimizerFactory.class); BlendeeConstants.CAN_ADD_NEW_ENTRIES.extract(initValues) .ifPresent(flag -> anchorOptimizerFactory.setCanAddNewEntries(flag)); anchorOptimizerFactory.setColumnRepositoryFactoryClass( BlendeeConstants.COLUMN_REPOSITORY_FACTORY_CLASS.extract(initValues) .orElseGet(() -> getDefaultColumnRepositoryFactoryClass())); } /** * 現在接続中の JDBC インスタンスをすべてクローズし、このコンテキストの Blendee を終了します。 */ public static void stop() { AutoCloseableFinalizer finalizer = ContextManager.get(BlendeeManager.class).getAutoCloseableFinalizer(); finalizer.stop(); finalizer.closeAll(); } /** * トランザクション内で任意の処理を実行します。 * @param function {@link Function} の実装 * @throws Exception 処理内で起こった例外 */ public static void execute(Function function) throws Exception { if (ContextManager.get(BlendeeManager.class).hasConnection()) throw new IllegalStateException("既にトランザクションが開始されています"); TransactionManager.start(new TransactionShell() { @Override public void execute() throws Exception { function.execute(getTransaction()); } }); } /** * デフォルト {@link MetadataFactory} を返します。 * @return デフォルト {@link MetadataFactory} */ public synchronized Class<? extends MetadataFactory> getDefaultMetadataFactoryClass() { return defaultMetadataFactoryClass; } /** * デフォルト {@link MetadataFactory} をセットします。 * @param defaultMetadataFactoryClass デフォルト {@link MetadataFactory} */ public synchronized void setDefaultMetadataFactoryClass( Class<? extends MetadataFactory> defaultMetadataFactoryClass) { this.defaultMetadataFactoryClass = defaultMetadataFactoryClass; } /** * デフォルト {@link TransactionFactory} を返します。 * @return デフォルト {@link TransactionFactory} */ public synchronized Class<? extends TransactionFactory> getDefaultTransactionFactoryClass() { return defaultTransactionFactoryClass; } /** * デフォルト {@link TransactionFactory} をセットします。 * @param defaultTransactionFactoryClass デフォルト {@link TransactionFactory} */ public synchronized void setDefaultTransactionFactoryClass( Class<? extends TransactionFactory> defaultTransactionFactoryClass) { this.defaultTransactionFactoryClass = defaultTransactionFactoryClass; } /** * デフォルト {@link ColumnRepositoryFactory} を返します。 * @return デフォルト {@link ColumnRepositoryFactory} */ public synchronized Class<? extends ColumnRepositoryFactory> getDefaultColumnRepositoryFactoryClass() { return defaultColumnRepositoryFactoryClass; } /** * デフォルト {@link ColumnRepositoryFactory} をセットします。 * @param defaultColumnRepositoryFactoryClass デフォルト {@link ColumnRepositoryFactory} */ public synchronized void setDefaultColumnRepositoryFactoryClass( Class<? extends ColumnRepositoryFactory> defaultColumnRepositoryFactoryClass) { this.defaultColumnRepositoryFactoryClass = defaultColumnRepositoryFactoryClass; } /** * Blendee が持つ定義情報の各キャッシュをクリアします。 */ public static void clearCache() { ContextManager.get(BlendeeManager.class).clearMetadataCache(); ContextManager.get(RelationshipFactory.class).clearCache(); } /** * トランザクション内で行う任意の処理を表しています。 */ @FunctionalInterface public interface Function { /** * トランザクション内で呼び出されます。 <br> * 処理が終了した時点で commit が行われます。 <br> * 例外を投げた場合は rollback が行われます。 * @param transaction この処理のトランザクション * @throws Exception 処理内で起こった例外 */ void execute(BTransaction transaction) throws Exception; } }
update
blendee.core/src/org/blendee/util/Blendee.java
update
Java
epl-1.0
082d3097a77641960ac22208d65925f14bde9175
0
Beagle-PSE/Beagle,Beagle-PSE/Beagle,Beagle-PSE/Beagle
package de.uka.ipd.sdq.beagle.core.timeout; /** * Always says that the timeout isn't reached. * * @author Christoph Michelbach */ public class NoTimeout extends Timeout { @Override public boolean isReached() { return false; } }
Core/src/main/java/de/uka/ipd/sdq/beagle/core/timeout/NoTimeout.java
package de.uka.ipd.sdq.beagle.core.timeout; /** * Always says that the timeout isn't reached. * * @author Christoph Michelbach */ public class NoTimeout implements Timeout { @Override public boolean isReached() { return false; } }
Adapted `NoTimeout` to new design.
Core/src/main/java/de/uka/ipd/sdq/beagle/core/timeout/NoTimeout.java
Adapted `NoTimeout` to new design.
Java
epl-1.0
1d71547a31f6d4905df96796517ae69b96213560
0
abreslav/alvor,abreslav/alvor,abreslav/alvor
package ee.stacc.productivity.edsl.main; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.eclipse.jdt.core.IJavaElement; import ee.stacc.productivity.edsl.checkers.IAbstractStringChecker; import ee.stacc.productivity.edsl.checkers.ISQLErrorHandler; import ee.stacc.productivity.edsl.checkers.IStringNodeDescriptor; import ee.stacc.productivity.edsl.crawler.AbstractStringEvaluator; import ee.stacc.productivity.edsl.crawler.NodeRequest; import ee.stacc.productivity.edsl.crawler.NodeSearchEngine; /** * This is main class * - finds hotspots * - creates abstract strings * - runs checkers * */ public class JavaElementChecker { private static final String HOTSPOTS = "hotspots"; /* * The map must contain an entry * hotspots=classname,methodname,index;classname,methodname,index;... * E.g.: * hotspots=java.util.Connection,prepareStatement,1;blah.blah.Blah,blah,5 * Trailing ';' is not required */ public List<IStringNodeDescriptor> findHotspots(IJavaElement scope, Map<String, Object> options) { List<NodeRequest> requests = parseNodeRequests(options); if (requests.isEmpty()) { throw new IllegalArgumentException("No hotspots found"); } NodeSearchEngine.clearCache(); return AbstractStringEvaluator.evaluateMethodArgumentAtCallSites(requests, scope, 0); } public void checkHotspots( List<IStringNodeDescriptor> hotspots, ISQLErrorHandler errorHandler, List<IAbstractStringChecker> checkers, Map<String, Object> options) { for (IAbstractStringChecker checker : checkers) { checker.checkAbstractStrings(hotspots, errorHandler, options); } } private List<NodeRequest> parseNodeRequests(Map<String, Object> options) { if (options == null) { return Collections.emptyList(); } Object option = options.get(HOTSPOTS); if (option == null) { return Collections.emptyList(); } String allHotspots = option.toString(); System.out.println("Hotspots:"); List<NodeRequest> requests = new ArrayList<NodeRequest>(); for (String hotspot : allHotspots.split(";")) { if (hotspot.length() == 0) { continue; } String[] split = hotspot.split(","); if (split.length != 3) { System.err.println("Malformed hotspot: " + hotspot); continue; } String className = split[0]; String methodName = split[1]; String argumentIndex = split[2]; try { int index = Integer.parseInt(argumentIndex); NodeRequest nodeRequest = new NodeRequest(className, methodName, index); requests.add(nodeRequest); } catch (NumberFormatException e) { System.err.println("Number format error: " + argumentIndex); } } return requests; } }
ee.stacc.productivity.edsl.crawler/src/ee/stacc/productivity/edsl/main/JavaElementChecker.java
package ee.stacc.productivity.edsl.main; import java.util.Arrays; import java.util.List; import java.util.Map; import org.eclipse.jdt.core.IJavaElement; import ee.stacc.productivity.edsl.checkers.IAbstractStringChecker; import ee.stacc.productivity.edsl.checkers.ISQLErrorHandler; import ee.stacc.productivity.edsl.checkers.IStringNodeDescriptor; import ee.stacc.productivity.edsl.crawler.AbstractStringEvaluator; import ee.stacc.productivity.edsl.crawler.NodeRequest; import ee.stacc.productivity.edsl.crawler.NodeSearchEngine; /** * This is main class * - finds hotspots * - creates abstract strings * - runs checkers * */ public class JavaElementChecker { public List<IStringNodeDescriptor> findHotspots(IJavaElement scope, Map<String, Object> options) { NodeSearchEngine.clearCache(); List<IStringNodeDescriptor> descriptors = AbstractStringEvaluator.evaluateMethodArgumentAtCallSites(Arrays.asList( new NodeRequest("org.springframework.jdbc.core.simple.SimpleJdbcTemplate", "queryForInt", 1), new NodeRequest("org.springframework.jdbc.core.simple.SimpleJdbcTemplate", "queryForObject", 1), new NodeRequest("org.springframework.jdbc.core.simple.SimpleJdbcTemplate", "queryForLong", 1), new NodeRequest("org.springframework.jdbc.core.simple.SimpleJdbcTemplate", "query", 1), new NodeRequest("org.araneaframework.backend.list.helper.ListSqlHelper", "setSqlQuery", 1), new NodeRequest("java.sql.Connection", "prepareStatement", 1) ), scope, 0); return descriptors; } public void checkHotspots(List<IStringNodeDescriptor> hotspots, ISQLErrorHandler errorHandler, List<IAbstractStringChecker> checkers, Map<String, Object> options) { for (IStringNodeDescriptor stringNodeDescriptor : hotspots) { System.out.println(stringNodeDescriptor.getAbstractValue()); } for (IAbstractStringChecker checker : checkers) { checker.checkAbstractStrings(hotspots, errorHandler, options); } } }
Hotspot patterns are read from a property file
ee.stacc.productivity.edsl.crawler/src/ee/stacc/productivity/edsl/main/JavaElementChecker.java
Hotspot patterns are read from a property file
Java
lgpl-2.1
371e855fe5c8ca0a19ded1f898b5b8c968f2e5a2
0
wolfgangmm/exist,patczar/exist,joewiz/exist,wshager/exist,eXist-db/exist,hungerburg/exist,dizzzz/exist,patczar/exist,RemiKoutcherawy/exist,wshager/exist,eXist-db/exist,jessealama/exist,shabanovd/exist,windauer/exist,MjAbuz/exist,jessealama/exist,dizzzz/exist,joewiz/exist,lcahlander/exist,zwobit/exist,adamretter/exist,shabanovd/exist,eXist-db/exist,ambs/exist,opax/exist,dizzzz/exist,adamretter/exist,jensopetersen/exist,RemiKoutcherawy/exist,jensopetersen/exist,RemiKoutcherawy/exist,ambs/exist,ljo/exist,hungerburg/exist,olvidalo/exist,dizzzz/exist,kohsah/exist,opax/exist,jensopetersen/exist,kohsah/exist,zwobit/exist,MjAbuz/exist,wshager/exist,lcahlander/exist,ljo/exist,opax/exist,wolfgangmm/exist,RemiKoutcherawy/exist,olvidalo/exist,MjAbuz/exist,wshager/exist,zwobit/exist,dizzzz/exist,jensopetersen/exist,olvidalo/exist,windauer/exist,ljo/exist,RemiKoutcherawy/exist,joewiz/exist,lcahlander/exist,ambs/exist,eXist-db/exist,kohsah/exist,wshager/exist,ambs/exist,adamretter/exist,wolfgangmm/exist,shabanovd/exist,hungerburg/exist,windauer/exist,adamretter/exist,jensopetersen/exist,jessealama/exist,lcahlander/exist,jensopetersen/exist,RemiKoutcherawy/exist,kohsah/exist,shabanovd/exist,wshager/exist,ljo/exist,MjAbuz/exist,jessealama/exist,lcahlander/exist,lcahlander/exist,wolfgangmm/exist,zwobit/exist,adamretter/exist,patczar/exist,jessealama/exist,windauer/exist,wolfgangmm/exist,eXist-db/exist,patczar/exist,joewiz/exist,zwobit/exist,wolfgangmm/exist,jessealama/exist,opax/exist,MjAbuz/exist,ambs/exist,hungerburg/exist,dizzzz/exist,shabanovd/exist,adamretter/exist,zwobit/exist,kohsah/exist,joewiz/exist,ljo/exist,opax/exist,patczar/exist,shabanovd/exist,joewiz/exist,olvidalo/exist,hungerburg/exist,MjAbuz/exist,windauer/exist,eXist-db/exist,kohsah/exist,olvidalo/exist,patczar/exist,ambs/exist,windauer/exist,ljo/exist
package org.exist.xquery.functions.util; import org.exist.dom.NodeSet; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.exist.storage.DBBroker; import org.exist.xmldb.DatabaseInstanceManager; import org.exist.xquery.XPathException; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.DatabaseManager; import org.xmldb.api.modules.XPathQueryService; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; /** * * @author [email protected] */ public class EvalTest { private XPathQueryService service; private Collection root = null; private Database database = null; public EvalTest() { } @Before public void setUp() throws Exception { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null); service = (XPathQueryService) root.getService("XQueryService", "1.0"); } @After public void tearDown() throws Exception { DatabaseManager.deregisterDatabase(database); DatabaseInstanceManager dim = (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0"); dim.shutdown(); // clear instance variables service = null; root = null; //System.out.println("tearDown PASSED"); } @Test public void testEval() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $query := 'let $a := 1 return $a'\n" + "return\n" + "util:eval($query)"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1", r); } catch (XMLDBException e) { System.out.println("testEval(): " + e); fail(e.getMessage()); } } @Test public void testEvalwithPI() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $query := 'let $a := <test><?pi test?></test> return count($a//processing-instruction())'\n" + "return\n" + "util:eval($query)"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1", r); } catch (XMLDBException e) { System.out.println("testEval(): " + e); fail(e.getMessage()); } } @Test public void testEvalInline() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $xml := document{<test><a><b/></a></test>}\n" + "let $query := 'count(.//*)'\n" + "return\n" + "util:eval-inline($xml,$query)"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("3", r); } catch (XMLDBException e) { System.out.println("testEvalInline(): " + e); fail(e.getMessage()); } } @Test public void testEvalWithContextVariable() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $xml := <test><a/><b/></test>\n" + "let $context := <static-context>\n" + "<variable name='xml'>{$xml}</variable>\n" + "</static-context>\n" + "let $query := 'count($xml//*) mod 2 = 0'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testEvalWithContextVariable(): " + e); fail(e.getMessage()); } } @Test public void testEvalSupplyingContext() throws XPathException { ResourceSet result = null; String r = "test"; try { String query = "let $xml := <test><a/></test>\n" + "let $context := <static-context>\n" + "<default-context>{$xml}</default-context>\n" + "</static-context>\n" + "let $query := 'count(.//*) mod 2 = 0'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testEvalSupplyingContext(): " + e); fail(e.getMessage()); } } @Test public void testEvalSupplyingContextAndVariable() throws XPathException { ResourceSet result = null; String r = "test"; try { String query = "let $xml := <test><a/></test>\n" + "let $context := <static-context>\n" + "<variable name='xml'>{$xml}</variable>\n" + "<default-context>{$xml}</default-context>\n" + "</static-context>\n" + "let $query := 'count($xml//*) + count(.//*)'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("3", r); } catch (XMLDBException e) { System.out.println("testEvalSupplyingContextAndVariable(): " + e); fail(e.getMessage()); } } }
test/src/org/exist/xquery/functions/util/EvalTest.java
package org.exist.xquery.functions.util; import org.exist.dom.NodeSet; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.exist.storage.DBBroker; import org.exist.xmldb.DatabaseInstanceManager; import org.exist.xquery.XPathException; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.DatabaseManager; import org.xmldb.api.modules.XPathQueryService; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; /** * * @author [email protected] */ public class EvalTest { private XPathQueryService service; private Collection root = null; private Database database = null; public EvalTest() { } @Before public void setUp() throws Exception { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null); service = (XPathQueryService) root.getService("XQueryService", "1.0"); } @After public void tearDown() throws Exception { DatabaseManager.deregisterDatabase(database); DatabaseInstanceManager dim = (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0"); dim.shutdown(); // clear instance variables service = null; root = null; //System.out.println("tearDown PASSED"); } @Test public void testEval() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $query := 'let $a := 1 return $a'\n" + "return\n" + "util:eval($query)"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("1", r); } catch (XMLDBException e) { System.out.println("testEval(): " + e); fail(e.getMessage()); } } @Test public void testEvalInline() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $xml := document{<test><a><b/></a></test>}\n" + "let $query := 'count(.//*)'\n" + "return\n" + "util:eval-inline($xml,$query)"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("3", r); } catch (XMLDBException e) { System.out.println("testEvalInline(): " + e); fail(e.getMessage()); } } @Test public void testEvalWithContextVariable() throws XPathException { ResourceSet result = null; String r = ""; try { String query = "let $xml := <test><a/><b/></test>\n" + "let $context := <static-context>\n" + "<variable name='xml'>{$xml}</variable>\n" + "</static-context>\n" + "let $query := 'count($xml//*) mod 2 = 0'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testEvalWithContextVariable(): " + e); fail(e.getMessage()); } } @Test public void testEvalSupplyingContext() throws XPathException { ResourceSet result = null; String r = "test"; try { String query = "let $xml := <test><a/></test>\n" + "let $context := <static-context>\n" + "<default-context>{$xml}</default-context>\n" + "</static-context>\n" + "let $query := 'count(.//*) mod 2 = 0'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("true", r); } catch (XMLDBException e) { System.out.println("testEvalSupplyingContext(): " + e); fail(e.getMessage()); } } @Test public void testEvalSupplyingContextAndVariable() throws XPathException { ResourceSet result = null; String r = "test"; try { String query = "let $xml := <test><a/></test>\n" + "let $context := <static-context>\n" + "<variable name='xml'>{$xml}</variable>\n" + "<default-context>{$xml}</default-context>\n" + "</static-context>\n" + "let $query := 'count($xml//*) + count(.//*)'\n" + "return\n" + "util:eval-with-context($query, $context, false())"; result = service.query(query); r = (String) result.getResource(0).getContent(); assertEquals("3", r); } catch (XMLDBException e) { System.out.println("testEvalSupplyingContextAndVariable(): " + e); fail(e.getMessage()); } } }
[documentation.README] removed incorrect version information svn path=/trunk/eXist/; revision=9317
test/src/org/exist/xquery/functions/util/EvalTest.java
[documentation.README] removed incorrect version information