此处将为大家介绍关于com.mysql.jdbc.Util的实例源码的详细内容,此外,我们还将为您介绍关于com.esotericsoftware.kryo.util.Util的实例源码、com.go
此处将为大家介绍关于com.mysql.jdbc.Util的实例源码的详细内容,此外,我们还将为您介绍关于com.esotericsoftware.kryo.util.Util的实例源码、com.google.android.exoplayer.util.Util的实例源码、com.google.android.exoplayer2.util.Util的实例源码、com.intellij.openapi.projectRoots.ui.Util的实例源码的有用信息。
本文目录一览:- com.mysql.jdbc.Util的实例源码
- com.esotericsoftware.kryo.util.Util的实例源码
- com.google.android.exoplayer.util.Util的实例源码
- com.google.android.exoplayer2.util.Util的实例源码
- com.intellij.openapi.projectRoots.ui.Util的实例源码
com.mysql.jdbc.Util的实例源码
/** * Tests Util.isJdbcInterface() * * @throws Exception */ public void testIsJdbcInterface() throws Exception { // Classes directly or indirectly implementing JDBC interfaces. assertTrue(Util.isJdbcInterface(PreparedStatement.class)); assertTrue(Util.isJdbcInterface(StatementImpl.class)); assertTrue(Util.isJdbcInterface(Statement.class)); assertTrue(Util.isJdbcInterface(ResultSetImpl.class)); Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class<?>[] { Statement.class },new InvocationHandler() { public Object invoke(Object proxy,Method method,Object[] args) throws Throwable { return null; } }); assertTrue(Util.isJdbcInterface(s.getClass())); // Classes not implementing JDBC interfaces. assertFalse(Util.isJdbcInterface(Util.class)); assertFalse(Util.isJdbcInterface(UtilsTest.class)); }
/** * Tests Util.isJdbcPackage() * * @throws Exception */ public void testIsJdbcPackage() throws Exception { // JDBC packages. assertTrue(Util.isJdbcPackage("java.sql")); assertTrue(Util.isJdbcPackage("javax.sql")); assertTrue(Util.isJdbcPackage("javax.sql.rowset")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc.jdbc2.optional")); // Non-JDBC packages. assertFalse(Util.isJdbcPackage("java")); assertFalse(Util.isJdbcPackage("java.lang")); assertFalse(Util.isJdbcPackage("com")); assertFalse(Util.isJdbcPackage("com.MysqL")); }
public void testReservedWords() throws Exception { if (Util.isJdbc4()) { // there is a specific JCDB4 test for this return; } final String MysqLKeywords = "ACCESSIBLE,ANALYZE,ASENSITIVE,BEFORE,BIGINT,BINARY,BLOB,CALL,CHANGE,CONDITION,DATABASE,DATABASES,DAY_HOUR," + "DAY_MICROSECOND,DAY_MINUTE,DAY_SECOND,DELAYED,DETERMINISTIC,disTINCTROW,DIV,DUAL,EACH,ELSEIF,ENCLOSED,ESCAPED,EXIT,EXPLAIN,FLOAT4,FLOAT8," + "FORCE,FULLTEXT,GENERATED,HIGH_PRIORITY,HOUR_MICROSECOND,HOUR_MINUTE,HOUR_SECOND,IF,IGnorE,INDEX,INFILE,INOUT,INT1,INT2,INT3,INT4,INT8," + "IO_AFTER_GTIDS,IO_BEFORE_GTIDS,IteraTE,KEYS,KILL,LEAVE,LIMIT,LINEAR,LInes,LOAD,LOCALTIME,LOCALTIMESTAMP,LOCK,LONG,LONGBLOB,LONGTEXT,LOOP," + "LOW_PRIORITY,MASTER_BIND,MASTER_SSL_VERIFY_SERVER_CERT,MAXVALUE,MEDIUMBLOB,MEDIUMINT,MEDIUMTEXT,MIDDLEINT,MINUTE_MICROSECOND,MINUTE_SECOND," + "MOD,MODIFIES,NO_WRITE_TO_binlog,OPTIMIZE,OPTIMIZER_COSTS,OPTIONALLY,OUT,OUTFILE,PARTITION,PURGE,RANGE,READS,READ_WRITE,REGEXP,RELEASE," + "RENAME,REPEAT,REPLACE,REQUIRE,RESIGNAL,RETURN,RLIKE,SCHEMAS,SECOND_MICROSECOND,SENSITIVE,SEParaTOR,SHOW,SIGNAL,SPATIAL,SPECIFIC," + "sqlEXCEPTION,sqlWARNING,sql_BIG_RESULT,sql_CALC_FOUND_ROWS,sql_SMALL_RESULT,SSL,STARTING,STORED,STRAIGHT_JOIN,TERMINATED,TINYBLOB,tinyint," + "TINYTEXT,TRIGGER,UNDO,UNLOCK,UNSIGNED,USE,UTC_DATE,UTC_TIME,UTC_TIMESTAMP,VARBINARY,VARCHaraCTER,VIRTUAL,WHILE,XOR,YEAR_MONTH,ZEROFILL"; assertEquals("MysqL keywords don't match expected.",MysqLKeywords,this.conn.getMetaData().getsqlKeywords()); }
/** * Recursively checks for interfaces on the given object to determine * if it implements a java.sql interface,and if so,proxies the * instance so that we can catch and fire sql errors. * * @param toProxy * @param clazz */ private Object proxyIfInterfaceIsJdbc(Object toProxy,Class<?> clazz) { Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> iclass : interfaces) { String packageName = Util.getPackageName(iclass); if ("java.sql".equals(packageName) || "javax.sql".equals(packageName)) { return Proxy.newProxyInstance(toProxy.getClass().getClassLoader(),interfaces,new ConnectionErrorFiringInvocationHandler(toProxy)); } return proxyIfInterfaceIsJdbc(toProxy,iclass); } return toProxy; }
private void populateMapWithSessionStatusValues(Connection connection,Map<String,String> toPopulate) throws sqlException { java.sql.Statement stmt = null; java.sql.ResultSet rs = null; try { toPopulate.clear(); stmt = connection.createStatement(); rs = stmt.executeQuery("SHOW SESSION STATUS"); Util.resultSetToMap(toPopulate,rs); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } }
/** * Tests Util.isJdbcInterface() * * @throws Exception */ public void testIsJdbcInterface() throws Exception { // Classes directly or indirectly implementing JDBC interfaces. assertTrue(Util.isJdbcInterface(PreparedStatement.class)); assertTrue(Util.isJdbcInterface(StatementImpl.class)); assertTrue(Util.isJdbcInterface(Statement.class)); assertTrue(Util.isJdbcInterface(ResultSetImpl.class)); Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(),Object[] args) throws Throwable { return null; } }); assertTrue(Util.isJdbcInterface(s.getClass())); // Classes not implementing JDBC interfaces. assertFalse(Util.isJdbcInterface(Util.class)); assertFalse(Util.isJdbcInterface(UtilsTest.class)); }
private void populateMapWithSessionStatusValues(Connection connection,rs); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } }
public void testReservedWords() throws Exception { if (Util.isJdbc4()) { // there is a specific JCDB4 test for this return; } final String MysqLKeywords = "ACCESSIBLE,this.conn.getMetaData().getsqlKeywords()); }
/** * Recursively checks for interfaces on the given object to determine * if it implements a java.sql interface,iclass); } return toProxy; }
private void populateMapWithSessionStatusValues(Connection connection,rs); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } }
private void populateMapWithSessionStatusValues(Connection connection,rs); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } }
/** * Tests Util.isJdbcInterface() * * @throws Exception */ public void testIsJdbcInterface() throws Exception { // Classes directly or indirectly implementing JDBC interfaces. assertTrue(Util.isJdbcInterface(PreparedStatement.class)); assertTrue(Util.isJdbcInterface(StatementImpl.class)); assertTrue(Util.isJdbcInterface(Statement.class)); assertTrue(Util.isJdbcInterface(ResultSetImpl.class)); Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(),Object[] args) throws Throwable { return null; } }); assertTrue(Util.isJdbcInterface(s.getClass())); // Classes not implementing JDBC interfaces. assertFalse(Util.isJdbcInterface(Util.class)); assertFalse(Util.isJdbcInterface(UtilsTest.class)); }
/** * Tests Util.isJdbcPackage() * * @throws Exception */ public void testIsJdbcPackage() throws Exception { // JDBC packages. assertTrue(Util.isJdbcPackage("java.sql")); assertTrue(Util.isJdbcPackage("javax.sql")); assertTrue(Util.isJdbcPackage("javax.sql.rowset")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc.jdbc2.optional")); // Non-JDBC packages. assertFalse(Util.isJdbcPackage("java")); assertFalse(Util.isJdbcPackage("java.lang")); assertFalse(Util.isJdbcPackage("com")); assertFalse(Util.isJdbcPackage("com.MysqL")); }
public void testReservedWords() throws Exception { if (Util.isJdbc4()) { // there is a specific JCDB4 test for this return; } final String MysqLKeywords = "ACCESSIBLE,this.conn.getMetaData().getsqlKeywords()); }
/** * Recursively checks for interfaces on the given object to determine * if it implements a java.sql interface,iclass); } return toProxy; }
/** * Tests Util.isJdbcInterface() * * @throws Exception */ public void testIsJdbcInterface() throws Exception { // Classes directly or indirectly implementing JDBC interfaces. assertTrue(Util.isJdbcInterface(PreparedStatement.class)); assertTrue(Util.isJdbcInterface(StatementImpl.class)); assertTrue(Util.isJdbcInterface(Statement.class)); assertTrue(Util.isJdbcInterface(ResultSetImpl.class)); Statement s = (Statement) Proxy.newProxyInstance(this.getClass().getClassLoader(),Object[] args) throws Throwable { return null; } }); assertTrue(Util.isJdbcInterface(s.getClass())); // Classes not implementing JDBC interfaces. assertFalse(Util.isJdbcInterface(Util.class)); assertFalse(Util.isJdbcInterface(UtilsTest.class)); }
/** * Tests Util.isJdbcPackage() * * @throws Exception */ public void testIsJdbcPackage() throws Exception { // JDBC packages. assertTrue(Util.isJdbcPackage("java.sql")); assertTrue(Util.isJdbcPackage("javax.sql")); assertTrue(Util.isJdbcPackage("javax.sql.rowset")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc")); assertTrue(Util.isJdbcPackage("com.MysqL.jdbc.jdbc2.optional")); // Non-JDBC packages. assertFalse(Util.isJdbcPackage("java")); assertFalse(Util.isJdbcPackage("java.lang")); assertFalse(Util.isJdbcPackage("com")); assertFalse(Util.isJdbcPackage("com.MysqL")); }
/** * Checks if setting useCursorFetch to "true" automatically enables * server-side prepared statements. */ public void testcouplingOfCursorFetch() throws Exception { if (!versionMeetsMinimum(5,0)) { return; } Connection fetchConn = null; try { Properties props = new Properties(); props.setProperty("useServerPrepStmts","false"); // force the issue props.setProperty("useCursorFetch","true"); fetchConn = getConnectionWithProps(props); String classname = "com.MysqL.jdbc.ServerPreparedStatement"; if (Util.isJdbc42()) { classname = "com.MysqL.jdbc.JDBC42ServerPreparedStatement"; } else if (Util.isJdbc4()) { classname = "com.MysqL.jdbc.JDBC4ServerPreparedStatement"; } assertEquals(classname,fetchConn.prepareStatement("SELECT 1").getClass().getName()); } finally { if (fetchConn != null) { fetchConn.close(); } } }
/** 34703 [NEW]: isValild() aborts Connection on timeout */ public void testBug34703() throws Exception { if (!com.MysqL.jdbc.Util.isJdbc4()) { return; } Method isValid = java.sql.Connection.class.getmethod("isValid",new Class[] { Integer.TYPE }); Connection newConn = getConnectionWithProps((Properties) null); isValid.invoke(newConn,new Object[] { new Integer(1) }); Thread.sleep(2000); assertTrue(((Boolean) isValid.invoke(newConn,new Object[] { new Integer(0) })).booleanValue()); }
/** * Tests fix for Bug#16634180 - LOCK WAIT TIMEOUT EXCEEDED CAUSES sqlEXCEPTION,SHOULD CAUSE sqlTRANSIENTEXCEPTION * * @throws Exception * if the test fails. */ public void testBug16634180() throws Exception { if (Util.isJdbc4()) { // relevant JDBC4+ test is testsuite.regression.jdbc4.ConnectionRegressionTest.testBug16634180() return; } createTable("testBug16634180","(pk integer primary key,val integer)","InnoDB"); this.stmt.executeUpdate("insert into testBug16634180 values(0,0)"); Connection c1 = null; Connection c2 = null; try { c1 = getConnectionWithProps(new Properties()); c1.setAutoCommit(false); Statement s1 = c1.createStatement(); s1.executeUpdate("update testBug16634180 set val=val+1 where pk=0"); c2 = getConnectionWithProps(new Properties()); c2.setAutoCommit(false); Statement s2 = c2.createStatement(); try { s2.executeUpdate("update testBug16634180 set val=val+1 where pk=0"); fail("ER_LOCK_WAIT_TIMEOUT should be thrown."); } catch (MysqLTransientException ex) { assertEquals(MysqLErrorNumbers.ER_LOCK_WAIT_TIMEOUT,ex.getErrorCode()); assertEquals(sqlError.sql_STATE_ROLLBACK_SERIALIZATION_FAILURE,ex.getsqlState()); assertEquals("Lock wait timeout exceeded; try restarting transaction",ex.getMessage()); } } finally { if (c1 != null) { c1.close(); } if (c2 != null) { c2.close(); } } }
/** * Tests fix for BUG#73163 - indexoutofboundsexception thrown preparing statement. * * This bug occurs only if running with Java6+. Duplicated in testsuite.regression.StatementRegressionTest.testBug73163(). * * @throws Exception * if the test fails. */ public void testBug73163() throws Exception { try { stmt = conn.prepareStatement("LOAD DATA INFILE ? INTO TABLE testBug73163"); } catch (sqlException e) { if (e.getCause() instanceof indexoutofboundsexception && Util.isJdbc4()) { fail("IOOBE thrown in Java6+ while preparing a LOAD DATA statement with placeholders."); } else { throw e; } } }
/** * Tests fix for BUG#73163 - indexoutofboundsexception thrown preparing statement. * * This bug occurs only if running with Java6+. Duplicated in testsuite.regression.StatementRegressionTest.jdbc4.testBug73163(). * * @throws Exception * if the test fails. */ public void testBug73163() throws Exception { try { this.stmt = this.conn.prepareStatement("LOAD DATA INFILE ? INTO TABLE testBug73163"); } catch (sqlException e) { if (e.getCause() instanceof indexoutofboundsexception && Util.isJdbc4()) { fail("IOOBE thrown in Java6+ while preparing a LOAD DATA statement with placeholders."); } else { throw e; } } }
/** * Tests fix for BUG#17248345 - GETFUNCTIONCOLUMNS() METHOD RETURNS COLUMNS OF PROCEDURE. (this happens when * functions and procedures have a common name) * * @throws Exception * if the test fails. */ public void testBug17248345() throws Exception { if (Util.isJdbc4()) { // there is a specific JCDB4 test for this return; } Connection testConn; // create one stored procedure and one function with same name createFunction("testBug17248345","(funccol INT) RETURNS INT DETERMINISTIC RETURN 1"); createProcedure("testBug17248345","(IN proccol INT) SELECT 1"); // test with standard connection (getProceduresReturnsFunctions=true & useinformationSchema=false) assertFalse("Property useinformationSchema should be false",((ConnectionProperties) this.conn).getUseinformationSchema()); assertTrue("Property getProceduresReturnsFunctions should be true",((ConnectionProperties) this.conn).getGetProceduresReturnsFunctions()); checkMetaDataInfoForBug17248345(this.conn); // test with property useinformationSchema=true (getProceduresReturnsFunctions=true) testConn = getConnectionWithProps("useinformationSchema=true"); assertTrue("Property useinformationSchema should be true",((ConnectionProperties) testConn).getUseinformationSchema()); assertTrue("Property getProceduresReturnsFunctions should be true",((ConnectionProperties) testConn).getGetProceduresReturnsFunctions()); checkMetaDataInfoForBug17248345(testConn); testConn.close(); // test with property getProceduresReturnsFunctions=false (useinformationSchema=false) testConn = getConnectionWithProps("getProceduresReturnsFunctions=false"); assertFalse("Property useinformationSchema should be false",((ConnectionProperties) testConn).getUseinformationSchema()); assertFalse("Property getProceduresReturnsFunctions should be false",((ConnectionProperties) testConn).getGetProceduresReturnsFunctions()); checkMetaDataInfoForBug17248345(testConn); testConn.close(); // test with property useinformationSchema=true & getProceduresReturnsFunctions=false testConn = getConnectionWithProps("useinformationSchema=true,getProceduresReturnsFunctions=false"); assertTrue("Property useinformationSchema should be true",((ConnectionProperties) testConn).getGetProceduresReturnsFunctions()); checkMetaDataInfoForBug17248345(testConn); testConn.close(); }
protected static MysqLPooledConnection getInstance(com.MysqL.jdbc.Connection connection) throws sqlException { if (!Util.isJdbc4()) { return new MysqLPooledConnection(connection); } return (MysqLPooledConnection) Util.handleNewInstance(JDBC_4_POOLED_CONNECTION_WRAPPER_CTOR,new Object[] { connection },connection.getExceptionInterceptor()); }
public static String findCallingClassAndMethod(Throwable t) { String stackTraceAsstring = Util.stackTracetoString(t); String callingClassAndMethod = CALLER_informatION_NOT_AVAILABLE; int endInternalMethods = stackTraceAsstring.lastIndexOf("com.MysqL.jdbc"); if (endInternalMethods != -1) { int endOfLine = -1; int compliancePackage = stackTraceAsstring.indexOf("com.MysqL.jdbc.compliance",endInternalMethods); if (compliancePackage != -1) { endOfLine = compliancePackage - LINE_SEParaTOR_LENGTH; } else { endOfLine = stackTraceAsstring.indexOf(LINE_SEParaTOR,endInternalMethods); } if (endOfLine != -1) { int nextEndOfLine = stackTraceAsstring.indexOf(LINE_SEParaTOR,endOfLine + LINE_SEParaTOR_LENGTH); if (nextEndOfLine != -1) { callingClassAndMethod = stackTraceAsstring.substring(endOfLine + LINE_SEParaTOR_LENGTH,nextEndOfLine); } else { callingClassAndMethod = stackTraceAsstring.substring(endOfLine + LINE_SEParaTOR_LENGTH); } } } if (!callingClassAndMethod.startsWith("\tat ") && !callingClassAndMethod.startsWith("at ")) { return "at " + callingClassAndMethod; } return callingClassAndMethod; }
protected static SuspendableXAConnection getInstance(Connection MysqLConnection) throws sqlException { if (!Util.isJdbc4()) { return new SuspendableXAConnection(MysqLConnection); } return (SuspendableXAConnection) Util.handleNewInstance(JDBC_4_XA_CONNECTION_WRAPPER_CTOR,new Object[] { MysqLConnection },MysqLConnection.getExceptionInterceptor()); }
protected static SuspendableXAConnection getInstance(Connection MysqLConnection) throws sqlException { if (!Util.isJdbc4()) { return new SuspendableXAConnection(MysqLConnection); } return (SuspendableXAConnection) Util.handleNewInstance(JDBC_4_XA_CONNECTION_WRAPPER_CTOR,MysqLConnection.getExceptionInterceptor()); }
protected static CallableStatementWrapper getInstance(ConnectionWrapper c,MysqLPooledConnection conn,CallableStatement toWrap) throws sqlException { if (!Util.isJdbc4()) { return new CallableStatementWrapper(c,conn,toWrap); } return (CallableStatementWrapper) Util.handleNewInstance(JDBC_4_CALLABLE_STATEMENT_WRAPPER_CTOR,new Object[] { c,toWrap },conn.getExceptionInterceptor()); }
protected static StatementWrapper getInstance(ConnectionWrapper c,Statement toWrap) throws sqlException { if (!Util.isJdbc4()) { return new StatementWrapper(c,toWrap); } return (StatementWrapper) Util.handleNewInstance(JDBC_4_STATEMENT_WRAPPER_CTOR,conn.getExceptionInterceptor()); }
protected static MysqLPooledConnection getInstance(com.MysqL.jdbc.Connection connection) throws sqlException { if (!Util.isJdbc4()) { return new MysqLPooledConnection(connection); } return (MysqLPooledConnection) Util.handleNewInstance(JDBC_4_POOLED_CONNECTION_WRAPPER_CTOR,connection.getExceptionInterceptor()); }
protected static ConnectionWrapper getInstance(MysqLPooledConnection MysqLPooledConnection,Connection MysqLConnection,boolean forXa) throws sqlException { if (!Util.isJdbc4()) { return new ConnectionWrapper(MysqLPooledConnection,MysqLConnection,forXa); } return (ConnectionWrapper) Util.handleNewInstance(JDBC_4_CONNECTION_WRAPPER_CTOR,new Object[] { MysqLPooledConnection,Boolean.valueOf(forXa) },MysqLPooledConnection.getExceptionInterceptor()); }
/** * Checks if setting useCursorFetch to "true" automatically enables * server-side prepared statements. */ public void testcouplingOfCursorFetch() throws Exception { if (!versionMeetsMinimum(5,fetchConn.prepareStatement("SELECT 1").getClass().getName()); } finally { if (fetchConn != null) { fetchConn.close(); } } }
protected static StatementWrapper getInstance(ConnectionWrapper c,conn.getExceptionInterceptor()); }
/** * Tests fix for Bug#16634180 - LOCK WAIT TIMEOUT EXCEEDED CAUSES sqlEXCEPTION,ex.getMessage()); } } finally { if (c1 != null) { c1.close(); } if (c2 != null) { c2.close(); } } }
/** * Tests fix for BUG#73163 - indexoutofboundsexception thrown preparing statement. * * This bug occurs only if running with Java6+. Duplicated in testsuite.regression.StatementRegressionTest.testBug73163(). * * @throws Exception * if the test fails. */ public void testBug73163() throws Exception { try { stmt = conn.prepareStatement("LOAD DATA INFILE ? INTO TABLE testBug73163"); } catch (sqlException e) { if (e.getCause() instanceof indexoutofboundsexception && Util.isJdbc4()) { fail("IOOBE thrown in Java6+ while preparing a LOAD DATA statement with placeholders."); } else { throw e; } } }
/** * Tests fix for BUG#73163 - indexoutofboundsexception thrown preparing statement. * * This bug occurs only if running with Java6+. Duplicated in testsuite.regression.StatementRegressionTest.jdbc4.testBug73163(). * * @throws Exception * if the test fails. */ public void testBug73163() throws Exception { try { this.stmt = this.conn.prepareStatement("LOAD DATA INFILE ? INTO TABLE testBug73163"); } catch (sqlException e) { if (e.getCause() instanceof indexoutofboundsexception && Util.isJdbc4()) { fail("IOOBE thrown in Java6+ while preparing a LOAD DATA statement with placeholders."); } else { throw e; } } }
protected static PreparedStatementWrapper getInstance(ConnectionWrapper c,PreparedStatement toWrap) throws sqlException { if (!Util.isJdbc4()) { return new PreparedStatementWrapper(c,toWrap); } return (PreparedStatementWrapper) Util.handleNewInstance(JDBC_4_PREPARED_STATEMENT_WRAPPER_CTOR,conn.getExceptionInterceptor()); }
/** * Tests fix for BUG#17248345 - GETFUNCTIONCOLUMNS() METHOD RETURNS COLUMNS OF PROCEDURE. (this happens when * functions and procedures have a common name) * * @throws Exception * if the test fails. */ public void testBug17248345() throws Exception { if (Util.isJdbc4()) { // there is a specific JCDB4 test for this return; } Connection testConn; // create one stored procedure and one function with same name createFunction("testBug17248345",((ConnectionProperties) testConn).getGetProceduresReturnsFunctions()); checkMetaDataInfoForBug17248345(testConn); testConn.close(); }
protected static ConnectionWrapper getInstance(MysqLPooledConnection MysqLPooledConnection,MysqLPooledConnection.getExceptionInterceptor()); }
public static String findCallingClassAndMethod(Throwable t) { String stackTraceAsstring = Util.stackTracetoString(t); String callingClassAndMethod = CALLER_informatION_NOT_AVAILABLE; int endInternalMethods = stackTraceAsstring.lastIndexOf("com.MysqL.jdbc"); if (endInternalMethods != -1) { int endOfLine = -1; int compliancePackage = stackTraceAsstring.indexOf("com.MysqL.jdbc.compliance",nextEndOfLine); } else { callingClassAndMethod = stackTraceAsstring.substring(endOfLine + LINE_SEParaTOR_LENGTH); } } } if (!callingClassAndMethod.startsWith("\tat ") && !callingClassAndMethod.startsWith("at ")) { return "at " + callingClassAndMethod; } return callingClassAndMethod; }
com.esotericsoftware.kryo.util.Util的实例源码
protected void checkIncorrectObject(T object) { if (object != null && !(object instanceof Serializable)) { String className = Util.className(object.getClass()); throw new IllegalArgumentException(String.format("Class is not registered: %s\nNote: To register this class use: kryo.register(\"%s\".class);",className,className)); } }
protected void checkIncorrectClass(Class type) { if (type != null && !Serializable.class.isAssignableFrom(type)) { throw new IllegalArgumentException(String.format("Class is not registered: %s\nNote: To register this class use: kryo.register(\"%s\".class);",Util.className(type),Util.className(type))); } }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
@Override public boolean useReferences(Class type) { return !Util.isWrapperClass(type); }
/** Called when the list of cached fields must be rebuilt. This is done any time settings are changed that affect which fields * will be used. It is called from the constructor for FieldSerializer,but not for subclasses. Subclasses must call this from * their constructor. */ protected void rebuildCachedFields () { if (TRACE && generics != null) trace("kryo","generic type parameters are: " + Arrays.toString(generics)); if (type.isInterface()) { fields = new CachedField[0]; // No fields to serialize. return; } hasObjectFields = false; // For generic classes,generate a mapping from type variable names to the concrete types // This mapping is the same for the whole class. Generics genScope = buildGenericsScope(type,generics); genericsScope = genScope; // Push proper scopes at serializer construction time if (genericsScope != null) kryo.pushGenericsScope(type,genericsScope); // Collect all fields. List<Field> allFields = new ArrayList(); Class nextClass = type; while (nextClass != Object.class) { Field[] declaredFields = nextClass.getDeclaredFields(); if (declaredFields != null) { for (Field f : declaredFields) { if (Modifier.isstatic(f.getModifiers())) continue; allFields.add(f); } } nextClass = nextClass.getSuperclass(); } ObjectMap context = kryo.getContext(); IntArray useAsm = new IntArray(); // Sort fields by their offsets if (useMemRegions && !useAsmEnabled && unsafe() != null) { Field[] allFieldsArray = softFieldsByOffset(allFields); allFields = Arrays.asList(allFieldsArray); } // Todo: useAsm is modified as a side effect,this should be pulled out of buildValidFields List<Field> validFields = buildValidFields(false,allFields,context,useAsm); List<Field> validTransientFields = buildValidFields(true,useAsm); // Use ReflectASM for any public fields. if (useAsmEnabled && !Util.isAndroid && Modifier.isPublic(type.getModifiers()) && useAsm.indexOf(1) != -1) { try { access = FieldAccess.get(type); } catch (RuntimeException ignored) { } } List<CachedField> cachedFields = new ArrayList(validFields.size()); List<CachedField> cachedTransientFields = new ArrayList(validTransientFields.size()); createCachedFields(useAsm,validFields,cachedFields,0); createCachedFields(useAsm,validTransientFields,cachedTransientFields,validFields.size()); Collections.sort(cachedFields,this); fields = cachedFields.toArray(new CachedField[cachedFields.size()]); Collections.sort(cachedTransientFields,this); transientFields = cachedTransientFields.toArray(new CachedField[cachedTransientFields.size()]); initializeCachedFields(); if (genericsScope != null) kryo.popGenericsScope(); }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
final private void writeLittleEndianInt (int val) { if (isLittleEndian) writeInt(val); else writeInt(Util.swapInt(val)); }
final private void writeLittleEndianLong (long val) { if (isLittleEndian) writeLong(val); else writeLong(Util.swapLong(val)); }
/** Returns true if the specified type is final. Final types can be serialized more efficiently because they are * non-polymorphic. * <p> * This can be overridden to force non-final classes to be treated as final. Eg,if an application uses ArrayList extensively * but never uses an ArrayList subclass,treating ArrayList as final Could allow FieldSerializer to save 1-2 bytes per * ArrayList field. */ public boolean isFinal (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (type.isArray()) return Modifier.isFinal(Util.getElementClass(type).getModifiers()); return Modifier.isFinal(type.getModifiers()); }
/** Returns true if the specified type is final. Final types can be serialized more efficiently because they are * non-polymorphic. * <p> * This can be overridden to force non-final classes to be treated as final. Eg,treating ArrayList as final Could allow FieldSerializer to save 1-2 bytes per * ArrayList field. */ public boolean isFinal (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (type.isArray()) return Modifier.isFinal(Util.getElementClass(type).getModifiers()); return Modifier.isFinal(type.getModifiers()); }
/** Returns true if the specified type is final. Final types can be serialized more efficiently because they are * non-polymorphic. * <p> * This can be overridden to force non-final classes to be treated as final. Eg,treating ArrayList as final Could allow FieldSerializer to save 1-2 bytes per * ArrayList field. */ public boolean isFinal (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (type.isArray()) return Modifier.isFinal(Util.getElementClass(type).getModifiers()); return Modifier.isFinal(type.getModifiers()); }
com.google.android.exoplayer.util.Util的实例源码
private VideoPlayer.RendererBuilder getRendererBuilder() { String userAgent = Util.getUserAgent(getActivity(),"ExoVideoPlayer"); Uri contentUri = Uri.parse(mSelectedVideo.videoUrl); int contentType = Util.inferContentType(contentUri.getLastPathSegment()); switch (contentType) { case Util.TYPE_OTHER: { return new ExtractorRendererBuilder(getActivity(),userAgent,contentUri); } case Util.TYPE_DASH: { // Implement your own DRM callback here. MediaDrmCallback drmCallback = new WidevineTestMediaDrmCallback(null,null); return new DashRendererBuilder(getActivity(),contentUri.toString(),drmCallback); } case Util.TYPE_HLS: { return new HlsRendererBuilder(getActivity(),contentUri.toString()); } default: { throw new IllegalStateException("Unsupported type: " + contentType); } } }
private RendererBuilder getRendererBuilder() { Uri contentUri = Uri.parse(mDataSource); String userAgent = Util.getUserAgent(mAppContext,"IjkExoMediaPlayer"); int contentType = inferContentType(contentUri); switch (contentType) { case Util.TYPE_SS: return new SmoothStreamingRendererBuilder(mAppContext,new SmoothStreamingTestMediaDrmCallback()); /* case Util.TYPE_DASH: return new DashRendererBuilder(mAppContext,new WidevineTestMediaDrmCallback(contentId,provider));*/ case Util.TYPE_HLS: return new HlsRendererBuilder(mAppContext,contentUri.toString()); case Util.TYPE_OTHER: default: return new ExtractorRendererBuilder(mAppContext,contentUri); } }
public StreamElement(String baseUri,String chunkTemplate,int type,String subType,long timescale,String name,int qualityLevels,int maxWidth,int maxHeight,int displayWidth,int displayHeight,String language,TrackElement[] tracks,List<Long> chunkStartTimes,long lastChunkDuration) { this.baseUri = baseUri; this.chunkTemplate = chunkTemplate; this.type = type; this.subType = subType; this.timescale = timescale; this.name = name; this.qualityLevels = qualityLevels; this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.displayWidth = displayWidth; this.displayHeight = displayHeight; this.language = language; this.tracks = tracks; this.chunkCount = chunkStartTimes.size(); this.chunkStartTimes = chunkStartTimes; lastChunkDurationUs = Util.scaleLargeTimestamp(lastChunkDuration,C.MICROS_PER_SECOND,timescale); chunkStartTimesUs = Util.scaleLargeTimestamps(chunkStartTimes,timescale); }
/** * @param sources The upstream sources from which the renderer obtains samples. * @param mediaCodecSelector A decoder selector. * @param drmSessionManager For use with encrypted media. May be null if support for encrypted * media is not required. * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions. * For example a media file may start with a short clear region so as to allow playback to * begin in parallel with key acquisition. This parameter specifies whether the renderer is * permitted to play clear regions of encrypted media files before {@code drmSessionManager} * has obtained the keys necessary to decrypt encrypted regions of the media. * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. */ public MediaCodecTrackRenderer(SampleSource[] sources,MediaCodecSelector mediaCodecSelector,DrmSessionManager drmSessionManager,boolean playClearSamplesWithoutKeys,Handler eventHandler,EventListener eventListener) { super(sources); Assertions.checkState(Util.SDK_INT >= 16); this.mediaCodecSelector = Assertions.checkNotNull(mediaCodecSelector); this.drmSessionManager = drmSessionManager; this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys; this.eventHandler = eventHandler; this.eventListener = eventListener; deviceNeedsAutoFrcWorkaround = deviceNeedsAutoFrcWorkaround(); codecCounters = new CodecCounters(); sampleHolder = new SampleHolder(SampleHolder.BUFFER_REPLACEMENT_MODE_disABLED); formatHolder = new MediaFormatHolder(); decodeOnlyPresentationTimestamps = new ArrayList<>(); outputBufferInfo = new MediaCodec.BufferInfo(); codecReconfigurationState = RECONfigURATION_STATE_NONE; codecReinitializationState = REINITIALIZATION_STATE_NONE; }
@SuppressWarnings("NonAtomicVolatileUpdate") @Override public void load() throws IOException,InterruptedException { DataSpec loadDataSpec = Util.getRemainderDataSpec(dataSpec,bytesLoaded); try { // Create and open the input. ExtractorInput input = new DefaultExtractorInput(dataSource,loadDataSpec.absoluteStreamPosition,dataSource.open(loadDataSpec)); if (bytesLoaded == 0) { // Set the target to ourselves. extractorWrapper.init(this); } // Load and parse the initialization data. try { int result = Extractor.RESULT_CONTINUE; while (result == Extractor.RESULT_CONTINUE && !loadCanceled) { result = extractorWrapper.read(input); } } finally { bytesLoaded = (int) (input.getPosition() - dataSpec.absoluteStreamPosition); } } finally { dataSource.close(); } }
private RendererBuilder getRendererBuilder() { String userAgent = Util.getUserAgent(getActivity(),"ExoPlayerDemo"); Uri uri = Uri.parse(mStreamUrl); int contentType = inferContentType(uri,null); switch (contentType) { // case TYPE_SS: // return new SmoothStreamingRendererBuilder(this,null,// new SmoothStreamingTestMediaDrmCallback()); // case TYPE_DASH: // return new DashRendererBuilder(this,// new WidevineTestMediaDrmCallback(contentId,provider)); case TYPE_HLS: return new HlsRendererBuilder(getContext(),mStreamUrl); case TYPE_OTHER: return new ExtractorRendererBuilder(getContext(),uri); default: throw new IllegalStateException("Unsupported type: " + contentType); } }
@SuppressWarnings("NonAtomicVolatileUpdate") @Override public void load() throws IOException,dataSource.open(loadDataSpec)); if (bytesLoaded == 0) { // Set the target to ourselves. extractorWrapper.init(this); } // Load and parse the initialization data. try { int result = Extractor.RESULT_CONTINUE; while (result == Extractor.RESULT_CONTINUE && !loadCanceled) { result = extractorWrapper.read(input); } } finally { bytesLoaded = (int) (input.getPosition() - dataSpec.absoluteStreamPosition); } } finally { dataSource.close(); } }
/** * Given viewport dimensions and video dimensions,computes the maximum size of the video as it * will be rendered to fit inside of the viewport. */ private static Point getMaxVideoSizeInViewport(boolean orientationMayChange,int viewportWidth,int viewportHeight,int videoWidth,int videoHeight) { if (orientationMayChange && (videoWidth > videoHeight) != (viewportWidth > viewportHeight)) { // Rotation is allowed,and the video will be larger in the rotated viewport. int tempViewportWidth = viewportWidth; viewportWidth = viewportHeight; viewportHeight = tempViewportWidth; } if (videoWidth * viewportHeight >= videoHeight * viewportWidth) { // Horizontal letter-Boxing along top and bottom. return new Point(viewportWidth,Util.ceilDivide(viewportWidth * videoHeight,videoWidth)); } else { // Vertical letter-Boxing along edges. return new Point(Util.ceilDivide(viewportHeight * videoWidth,videoHeight),viewportHeight); } }
/** * @param source The upstream source from which the renderer obtains samples. * @param drmSessionManager For use with encrypted media. May be null if support for encrypted * media is not required. * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions. * For example a media file may start with a short clear region so as to allow playback * to * begin in parallel with key acquisision. This parameter specifies whether the renderer * is * permitted to play clear regions of encrypted media files before * {@code drmSessionManager} * has obtained the keys necessary to decrypt encrypted regions of the media. * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. */ public MediaCodecTrackRenderer(SampleSource source,EventListener eventListener) { Assertions.checkState(Util.SDK_INT >= 16); this.source = source.register(); this.drmSessionManager = drmSessionManager; this.playClearSamplesWithoutKeys = playClearSamplesWithoutKeys; this.eventHandler = eventHandler; this.eventListener = eventListener; codecCounters = new CodecCounters(); sampleHolder = new SampleHolder(SampleHolder.BUFFER_REPLACEMENT_MODE_disABLED); formatHolder = new MediaFormatHolder(); decodeOnlyPresentationTimestamps = new ArrayList<>(); outputBufferInfo = new MediaCodec.BufferInfo(); codecReconfigurationState = RECONfigURATION_STATE_NONE; codecReinitializationState = REINITIALIZATION_STATE_NONE; }
private void flushCodec() throws ExoPlaybackException { codecHotswapTimeMs = -1; inputIndex = -1; outputIndex = -1; waitingForFirstSyncFrame = true; waitingForKeys = false; decodeOnlyPresentationTimestamps.clear(); // Workaround for framework bugs. // See [Internal: b/8347958],[Internal: b/8578467],[Internal: b/8543366]. if (Util.SDK_INT >= 18 && codecReinitializationState == REINITIALIZATION_STATE_NONE) { codec.flush(); codecHasQueuedBuffers = false; } else { releaseCodec(); maybeInitCodec(); } if (codecReconfigured && format != null) { // Any reconfiguration data that we send shortly before the flush may be discarded. We // avoid this issue by sending reconfiguration data following every flush. codecReconfigurationState = RECONfigURATION_STATE_WRITE_PENDING; } }
public AudioTrack() { releasingConditionVariable = new ConditionVariable(true); if (Util.SDK_INT >= 18) { try { getLatencyMethod = android.media.AudioTrack.class.getmethod("getLatency",(Class<?>[]) null); } catch (NoSuchMethodException e) { // There's no guarantee this method exists. Do nothing. } } if (Util.SDK_INT >= 19) { audioTrackUtil = new AudioTrackUtilV19(); } else { audioTrackUtil = new AudioTrackUtil(); } playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT]; volume = 1.0f; startMediaTimeState = START_NOT_SET; }
/** * {@link android.media.AudioTrack#getPlaybackHeadPosition()} returns a value intended to be * interpreted as an unsigned 32 bit integer,which also wraps around periodically. This method * returns the playback head position as a long that will only wrap around if the value exceeds * {@link Long#MAX_VALUE} (which in practice will never happen). * * @return {@link android.media.AudioTrack#getPlaybackHeadPosition()} of {@link #audioTrack} * expressed as a long. */ public long getPlaybackHeadPosition() { long rawPlaybackHeadPosition = 0xFFFFFFFFL & audioTrack.getPlaybackHeadPosition(); if (Util.SDK_INT <= 22 && isPassthrough) { // Work around issues with passthrough/direct AudioTracks on platform API versions 21/22: // - After resetting,the new AudioTrack's playback position continues to increase for a // short time from the old AudioTrack's position,while in the PLAYSTATE_STOPPED state. // - The playback head position jumps back to zero on paused passthrough/direct audio // tracks. See [Internal: b/19187573]. if (audioTrack.getPlayState() == android.media.AudioTrack.PLAYSTATE_STOPPED) { // Prevent detecting a wrapped position. lastRawPlaybackHeadPosition = rawPlaybackHeadPosition; } else if (audioTrack.getPlayState() == android.media.AudioTrack.PLAYSTATE_PAUSED && rawPlaybackHeadPosition == 0) { passthroughWorkaroundPauSEOffset = lastRawPlaybackHeadPosition; } rawPlaybackHeadPosition += passthroughWorkaroundPauSEOffset; } if (lastRawPlaybackHeadPosition > rawPlaybackHeadPosition) { // The value must have wrapped around. rawPlaybackHeadWrapCount++; } lastRawPlaybackHeadPosition = rawPlaybackHeadPosition; return rawPlaybackHeadPosition + (rawPlaybackHeadWrapCount << 32); }
/** * Returns whether the specified codec is usable for decoding on the current device. */ private static boolean isCodecUsableDecoder(MediaCodecInfo info,boolean secureDecodersExplicit) { if (info.isEncoder() || !name.startsWith("OMX.") || (!secureDecodersExplicit && name.endsWith(".secure"))) { return false; } // Work around an issue where creating a particular MP3 decoder on some devices on platform API // version 16 crashes mediaserver. if (Util.SDK_INT == 16 && ("dlxu".equals(Util.DEVICE) // HTC Butterfly || "protou".equals(Util.DEVICE) // HTC Desire X || "C6602".equals(Util.DEVICE) || "C6603".equals(Util.DEVICE)) // Sony Xperia Z && name.equals("OMX.qcom.audio.decoder.mp3")) { return false; } // Work around an issue where the VP8 decoder on Samsung galaxy S4 Mini does not render video. if (Util.SDK_INT <= 19 && Util.DEVICE != null && Util.DEVICE.startsWith("serrano") && "samsung".equals(Util.MANUFACTURER) && name.equals("OMX.SEC.vp8.dec")) { return false; } return true; }
@Override public void close() throws HttpDataSourceException { try { if (inputStream != null) { Util.maybeTerminateInputStream(connection,bytesRemaining()); try { inputStream.close(); } catch (IOException e) { throw new HttpDataSourceException(e,dataSpec); } } } finally { inputStream = null; closeConnection(); if (opened) { opened = false; if (listener != null) { listener.onTransferEnd(); } } } }
public StreamElement(String baseUri,timescale); }
private void closeCurrentOutputStream() throws IOException { if (outputStream == null) { return; } boolean success = false; try { outputStream.flush(); outputStream.getFD().sync(); success = true; } finally { Util.closeQuietly(outputStream); if (success) { cache.commitFile(file); } else { file.delete(); } outputStream = null; file = null; } }
@Override public byte[] executeKeyRequest(UUID uuid,KeyRequest request) throws Exception { String url = request.getDefaultUrl(); if (TextUtils.isEmpty(url)) { url = PLAYREADY_TEST_DEFAULT_URI; } return Util.executePost(url,request.getData(),KEY_REQUEST_PROPERTIES); }
public SmoothStreamingRendererBuilder(Context context,String userAgent,String url,MediaDrmCallback drmCallback) { this.context = context; this.userAgent = userAgent; this.url = Util.toLowerInvariant(url).endsWith("/manifest") ? url : url + "/Manifest"; this.drmCallback = drmCallback; }
@Override public byte[] executeKeyRequest(UUID uuid,KeyRequest request) throws IOException { String url = request.getDefaultUrl(); if (TextUtils.isEmpty(url)) { url = defaultUri; } return Util.executePost(url,null); }
public SmoothStreamingRendererBuilder(Context context,MediaDrmCallback drmCallback) { this.context = context; this.userAgent = userAgent; this.url = Util.toLowerInvariant(url).endsWith("/manifest") ? url : url + "/Manifest"; this.drmCallback = drmCallback; }
private VideoPlayer.RendererBuilder getRendererBuilder() { String userAgent = Util.getUserAgent(getActivity(),contentUri); } default: { throw new IllegalStateException("Unsupported type: " + contentType); } } }
@Override public byte[] executeKeyRequest(UUID uuid,KeyRequest request) throws Exception { String url = request.getDefaultUrl(); if (TextUtils.isEmpty(url)) { url = PLAYREADY_TEST_DEFAULT_URI; } return Util.executePost(url,KEY_REQUEST_PROPERTIES); }
public SmoothStreamingRendererBuilder(Context context,MediaDrmCallback drmCallback) { this.context = context; this.userAgent = userAgent; this.url = Util.toLowerInvariant(url).endsWith("/manifest") ? url : url + "/Manifest"; this.drmCallback = drmCallback; }
private RendererBuilder getHpLibRendererBuilder() { String userAgent = Util.getUserAgent(activity,"HpLib"); switch (video_type.get(currentTrackIndex)) { case "hls": return new HlsRendererBuilder(activity,video_url.get(currentTrackIndex)); case "others": return new ExtractorRendererBuilder(activity,Uri.parse(video_url.get(currentTrackIndex))); default: throw new IllegalStateException("Unsupported type: " + video_url.get(currentTrackIndex)); } }
public static boolean isCrappysamsung() { if (Util.SDK_INT <= 19 && "samsung".equals(Util.MANUFACTURER)) { return true; } return false; }
@Override public Long parse(String connectionUrl,InputStream inputStream) throws ParserException,IOException { String firstLine = new BufferedReader(new InputStreamReader(inputStream)).readLine(); try { return Util.parseXsDateTime(firstLine); } catch (ParseException e) { throw new ParserException(e); } }
public SmoothStreamingRendererBuilder(Context context,MediaDrmCallback drmCallback) { this.context = context; this.userAgent = userAgent; this.url = Util.toLowerInvariant(url).endsWith("/manifest") ? url : url + "/Manifest"; this.drmCallback = drmCallback; }
public void test24FpsH264Fixed() throws IOException { if (Util.SDK_INT < 23) { // Pass. return; } String streamName = "test_24fps_h264_fixed"; testDashPlayback(getActivity(),streamName,H264_24_MANIFEST,AAC_AUdio_REPRESENTATION_ID,false,H264_BASELINE_480P_24FPS_VIDEO_REPRESENTATION_ID); }
@Override public void onError(Exception e) { if (e instanceof UnsupportedDrmException) { // Special case DRM failures. UnsupportedDrmException unsupportedDrmException = (UnsupportedDrmException) e; int stringId = Util.SDK_INT < 18 ? R.string.drm_error_not_supported : unsupportedDrmException.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME ? R.string.drm_error_unsupported_scheme : R.string.drm_error_unkNown; Toast.makeText(getApplicationContext(),stringId,Toast.LENGTH_LONG).show(); } playerNeedsPrepare = true; updateButtonVisibilities(); showControls(); goatMediaController.showError(); }
public SmoothStreamingRendererBuilder(Context context,MediaDrmCallback drmCallback) { this.context = context; this.userAgent = userAgent; this.url = Util.toLowerInvariant(url).endsWith("/manifest") ? url : url + "/Manifest"; this.drmCallback = drmCallback; }
/** * Instantiates a new sample extractor reading from the specified {@code uri}. * * @param context Context for resolving {@code uri}. * @param uri The content URI from which to extract data. * @param headers Headers to send with requests for data. */ public FrameworkSampleSource(Context context,Uri uri,Map<String,String> headers) { Assertions.checkState(Util.SDK_INT >= 16); this.context = Assertions.checkNotNull(context); this.uri = Assertions.checkNotNull(uri); this.headers = headers; fileDescriptor = null; fileDescriptorOffset = 0; fileDescriptorLength = 0; }
@Override public void onError(Exception e) { String errorString = null; if (e instanceof UnsupportedDrmException) { // Special case DRM failures. UnsupportedDrmException unsupportedDrmException = (UnsupportedDrmException) e; errorString = getString(Util.SDK_INT < 18 ? R.string.video_error_drm_not_supported : unsupportedDrmException.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME ? R.string.video_error_drm_unsupported_scheme : R.string.video_error_drm_unkNown); } else if (e instanceof ExoPlaybackException && e.getCause() instanceof DecoderInitializationException) { // Special case for decoder initialization failures. DecoderInitializationException decoderInitializationException = (DecoderInitializationException) e.getCause(); if (decoderInitializationException.decoderName == null) { if (decoderInitializationException.getCause() instanceof DecoderQueryException) { errorString = getString(R.string.video_error_querying_decoders); } else if (decoderInitializationException.secureDecoderrequired) { errorString = getString(R.string.video_error_no_secure_decoder,decoderInitializationException.mimeType); } else { errorString = getString(R.string.video_error_no_decoder,decoderInitializationException.mimeType); } } else { errorString = getString(R.string.video_error_instantiating_decoder,decoderInitializationException.decoderName); } } if (errorString != null) { Toast.makeText(getApplicationContext(),errorString,Toast.LENGTH_LONG).show(); } playerNeedsPrepare = true; showControls(); }
/** * Returns the sample index of the closest synchronization sample at or before the given * timestamp,if one is available. * * @param timeUs Timestamp adjacent to which to find a synchronization sample. * @return Index of the synchronization sample,or {@link #NO_SAMPLE} if none. */ public int getIndexOfEarlierOrEqualSynchronizationSample(long timeUs) { // Video frame timestamps may not be sorted,so the behavior of this call can be undefined. // Frames are not reordered past synchronization samples so this works in practice. int startIndex = Util.binarySearchFloor(timestampsUs,timeUs,true,false); for (int i = startIndex; i >= 0; i--) { if ((flags[i] & C.SAMPLE_FLAG_SYNC) != 0) { return i; } } return NO_SAMPLE; }
private void configureSubtitleView() { CaptionStyleCompat style; float fontScale; if (Util.SDK_INT >= 19) { style = getUserCaptionStyleV19(); fontScale = getUserCaptionFontScaleV19(); } else { style = CaptionStyleCompat.DEFAULT; fontScale = 1.0f; } subtitleLayout.setStyle(style); subtitleLayout.setFractionalTextSize(SubtitleLayout.DEFAULT_TEXT_SIZE_FRACTION * fontScale); }
@Override protected void onOutputFormatChanged(android.media.MediaFormat outputFormat) { boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT) && outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BottOM) && outputFormat.containsKey(KEY_CROP_TOP); currentWidth = hasCrop ? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1 : outputFormat.getInteger(android.media.MediaFormat.KEY_WIDTH); currentHeight = hasCrop ? outputFormat.getInteger(KEY_CROP_BottOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1 : outputFormat.getInteger(android.media.MediaFormat.KEY_HEIGHT); currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio; if (Util.SDK_INT >= 21) { // On API level 21 and above the decoder applies the rotation when rendering to the surface. // Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations,we need // to flip the width,height and pixel aspect ratio to reflect the rotation that was applied. if (pendingRotationdegrees == 90 || pendingRotationdegrees == 270) { int rotatedHeight = currentWidth; currentWidth = currentHeight; currentHeight = rotatedHeight; currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio; } } else { // On API level 20 and below the decoder does not apply the rotation. currentUnappliedRotationdegrees = pendingRotationdegrees; } }
public void testH264Adaptive() throws IOException { if (Util.SDK_INT < 16 || shouldSkipAdaptiveTest(MimeTypes.VIDEO_H264)) { // Pass. return; } String streamName = "test_h264_adaptive"; testDashPlayback(getActivity(),H264_MANIFEST,ALLOW_ADDITIONAL_VIDEO_FORMATS,H264_CDD_ADAPTIVE); }
public DecoderInitializationException(MediaFormat mediaFormat,Throwable cause,boolean secureDecoderrequired,String decoderName) { super("Decoder init Failed: " + decoderName + "," + mediaFormat,cause); this.mimeType = mediaFormat.mimeType; this.secureDecoderrequired = secureDecoderrequired; this.decoderName = decoderName; this.diagnosticInfo = Util.SDK_INT >= 21 ? getDiagnosticInfoV21(cause) : null; }
/** * Instantiates a new sample extractor reading from the specified seekable {@code fileDescriptor}. * The caller is responsible for releasing the file descriptor. * * @param fileDescriptor File descriptor from which to read. * @param fileDescriptorOffset The offset in bytes where the data to be extracted starts. * @param fileDescriptorLength The length in bytes of the data to be extracted. */ public FrameworkSampleSource(FileDescriptor fileDescriptor,long fileDescriptorOffset,long fileDescriptorLength) { Assertions.checkState(Util.SDK_INT >= 16); this.fileDescriptor = Assertions.checkNotNull(fileDescriptor); this.fileDescriptorOffset = fileDescriptorOffset; this.fileDescriptorLength = fileDescriptorLength; context = null; uri = null; headers = null; }
@Override public int readData(int track,long positionUs,MediaFormatHolder formatHolder,SampleHolder sampleHolder,boolean onlyReaddiscontinuity) { Assertions.checkState(prepared); Assertions.checkState(trackStates[track] != TRACK_STATE_disABLED); if (pendingdiscontinuities[track]) { pendingdiscontinuities[track] = false; return disCONTINUITY_READ; } if (onlyReaddiscontinuity) { return nothing_READ; } if (trackStates[track] != TRACK_STATE_FORMAT_SENT) { formatHolder.format = MediaFormat.createFromFrameworkMediaFormatV16( extractor.getTrackFormat(track)); formatHolder.drmInitData = Util.SDK_INT >= 18 ? getDrmInitDataV18() : null; trackStates[track] = TRACK_STATE_FORMAT_SENT; return FORMAT_READ; } int extractorTrackIndex = extractor.getSampleTrackIndex(); if (extractorTrackIndex == track) { if (sampleHolder.data != null) { int offset = sampleHolder.data.position(); sampleHolder.size = extractor.readSampleData(sampleHolder.data,offset); sampleHolder.data.position(offset + sampleHolder.size); } else { sampleHolder.size = 0; } sampleHolder.timeUs = extractor.getSampleTime(); sampleHolder.flags = extractor.getSampleFlags() & ALLOWED_FLAGS_MASK; if (sampleHolder.isEncrypted()) { sampleHolder.cryptoInfo.setFromExtractorV16(extractor); } seekPositionUs = C.UNKNowN_TIME_US; extractor.advance(); return SAMPLE_READ; } else { return extractorTrackIndex < 0 ? END_OF_STREAM : nothing_READ; } }
com.google.android.exoplayer2.util.Util的实例源码
private MediaSource buildMediaSource(Uri uri,String overrideExtension) { int type = Util.inferContentType(!TextUtils.isEmpty(overrideExtension) ? "." + overrideExtension : uri.getLastPathSegment()); switch (type) { case C.TYPE_SS: return new SsMediaSource(uri,buildDataSourceFactory(false),new DefaultSsChunkSource.Factory(mediaDataSourceFactory),mainHandler,null); case C.TYPE_DASH: return new DashMediaSource(uri,new DefaultDashChunkSource.Factory(mediaDataSourceFactory),null); case C.TYPE_HLS: return new HlsMediaSource(uri,mediaDataSourceFactory,null); case C.TYPE_OTHER: return new ExtractorMediaSource(uri,new DefaultExtractorsFactory(),null); default: { throw new IllegalStateException("Unsupported type: " + type); } } }
@Override public long open(DataSpec dataSpec) throws IOException { Assertions.checkState(dataSource == null); String scheme = dataSpec.uri.getScheme(); if (Util.isLocalFileUri(dataSpec.uri)) { if (dataSpec.uri.getPath().startsWith("/android_asset/")) { dataSource = getAssetDataSource(); } else { dataSource = getFileDataSource(); } } else if (SCHEME_ASSET.equals(scheme)) { dataSource = getAssetDataSource(); } else if (SCHEME_CONTENT.equals(scheme)) { dataSource = getContentDataSource(); } else if (SCHEME_RTMP.equals(scheme)) { dataSource = getRtmpDataSource(); } else { dataSource = baseDataSource; } // Open the source and return. return dataSource.open(dataSpec); }
private MediaSource buildMediaSource(Uri uri,String overrideExtension) { DataSource.Factory mediaDataSourceFactory = buildDataSourceFactory(true); int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri) : Util.inferContentType("." + overrideExtension); switch (type) { case C.TYPE_SS: return new SsMediaSource(uri,null); default: { throw new IllegalStateException("Unsupported type: " + type); } } }
@TargetApi(21) @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(com.google.android.exoplayer2.ui.DefaultTimeBar.class.getCanonicalName()); info.setContentDescription(getProgresstext()); if (duration <= 0) { return; } if (Util.SDK_INT >= 21) { info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); } else if (Util.SDK_INT >= 16) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } }
private void drawPlayhead(Canvas canvas) { if (duration <= 0) { return; } int playheadX = Util.constrainValue(scrubberBar.right,scrubberBar.left,progressBar.right); int playheadY = scrubberBar.centerY(); if (scrubberDrawable == null) { int scrubberSize = (scrubbing || isFocused()) ? scrubberDraggedSize : (isEnabled() ? scrubberEnabledSize : scrubberdisabledSize); int playheadRadius = scrubberSize / 2; canvas.drawCircle(playheadX,playheadY,playheadRadius,scrubberPaint); } else { int scrubberDrawableWidth = scrubberDrawable.getIntrinsicWidth(); int scrubberDrawableHeight = scrubberDrawable.getIntrinsicHeight(); scrubberDrawable.setBounds( playheadX - scrubberDrawableWidth / 2,playheadY - scrubberDrawableHeight / 2,playheadX + scrubberDrawableWidth / 2,playheadY + scrubberDrawableHeight / 2); scrubberDrawable.draw(canvas); } }
/** * Incrementally scrubs the position by {@code positionChange}. * * @param positionChange The change in the scrubber position,in milliseconds. May be negative. * @return Returns whether the scrubber position changed. */ private boolean scrubIncrementally(long positionChange) { if (duration <= 0) { return false; } long scrubberPosition = getScrubberPosition(); scrubPosition = Util.constrainValue(scrubberPosition + positionChange,duration); if (scrubPosition == scrubberPosition) { return false; } if (!scrubbing) { startScrubbing(); } for (OnScrubListener listener : listeners) { listener.onScrubMove(this,scrubPosition); } update(); return true; }
@Override protected List<SampleGroup> doInBackground(String... uris) { List<SampleGroup> result = new ArrayList<>(); Context context = getApplicationContext(); String userAgent = Util.getUserAgent(context,"ExoPlayerDemo"); DataSource dataSource = new DefaultDataSource(context,null,userAgent,false); for (String uri : uris) { DataSpec dataSpec = new DataSpec(Uri.parse(uri)); InputStream inputStream = new DataSourceInputStream(dataSource,dataSpec); try { readSampleGroups(new JsonReader(new InputStreamReader(inputStream,"UTF-8")),result); } catch (Exception e) { Log.e(TAG,"Error loading sample list: " + uri,e); sawError = true; } finally { Util.closeQuietly(dataSource); } } return result; }
/** * Incrementally scrubs the position by {@code positionChange}. * * @param positionChange The change in the scrubber position,duration); if (scrubPosition == scrubberPosition) { return false; } if (!scrubbing) { startScrubbing(); } for (OnScrubListener listener : listeners) { listener.onScrubMove(this,scrubPosition); } update(); return true; }
private MediaSource buildMediaSource(Uri uri,eventLogger); case C.TYPE_DASH: return new DashMediaSource(uri,eventLogger); case C.TYPE_HLS: return new HlsMediaSource(uri,eventLogger); case C.TYPE_OTHER: return new ExtractorMediaSource(uri,eventLogger); default: { throw new IllegalStateException("Unsupported type: " + type); } } }
private SimpleExoPlayer setupPlayer(){ Log.d(TAG,"Setting up Player."); videoView.setKeepScreenOn(true); mUserAgent = Util.getUserAgent(getContext(),getResources().getString(R.string.app_name)); AdaptiveTrackSelection.Factory trackSelectorFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); DefaultTrackSelector trackSelector = new DefaultTrackSelector(trackSelectorFactory); LoadControl loadControl = new DefaultLoadControl(); DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(getContext(),DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF); exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory,trackSelector,loadControl); MyListener listener = new MyListener(exoPlayer,this); exoPlayer.addVideoListener(listener); exoPlayer.addListener(listener); exoPlayer.setPlayWhenReady(mPlaybackState); exoPlayer.prepare(buildMediaSource(Uri.parse(mRecording.getRecordingUrl()),"")); return exoPlayer; }
@Override public final void load() throws IOException,InterruptedException { try { dataSource.open(dataSpec); limit = 0; int bytesRead = 0; while (bytesRead != C.RESULT_END_OF_INPUT && !loadCanceled) { maybeExpandData(); bytesRead = dataSource.read(data,limit,READ_GRANULARITY); if (bytesRead != -1) { limit += bytesRead; } } if (!loadCanceled) { consume(data,limit); } } finally { Util.closeQuietly(dataSource); } }
/** * Given viewport dimensions and video dimensions,computes the maximum size of the video as it * will be rendered to fit inside of the viewport. */ private static Point getMaxVideoSizeInViewport(boolean orientationMayChange,int viewportWidth,int viewportHeight,int videoWidth,int videoHeight) { if (orientationMayChange && (videoWidth > videoHeight) != (viewportWidth > viewportHeight)) { // Rotation is allowed,and the video will be larger in the rotated viewport. int tempViewportWidth = viewportWidth; viewportWidth = viewportHeight; viewportHeight = tempViewportWidth; } if (videoWidth * viewportHeight >= videoHeight * viewportWidth) { // Horizontal letter-Boxing along top and bottom. return new Point(viewportWidth,Util.ceilDivide(viewportWidth * videoHeight,videoWidth)); } else { // Vertical letter-Boxing along edges. return new Point(Util.ceilDivide(viewportHeight * videoWidth,videoHeight),viewportHeight); } }
private void initializePlayer(Uri videoUri){ if (mExoPlayer == null){ TrackSelector trackSelector = new DefaultTrackSelector(); LoadControl loadControl = new DefaultLoadControl(); mExoPlayer = ExoPlayerFactory.newSimpleInstance(getContext(),loadControl); mExoPlayer.addListener(this); mExoPlayer.seekTo(currentPosition); mPlayerView.setPlayer(mExoPlayer); String userAgent = Util.getUserAgent(getContext(),"Tasty"); MediaSource mediaSource = new ExtractorMediaSource(videoUri,new DefaultDataSourceFactory( getContext(),userAgent),null); mExoPlayer.prepare(mediaSource); if (playWhenReady) mExoPlayer.setPlayWhenReady(true); else mExoPlayer.setPlayWhenReady(false); } }
@Override public long getTimeUs(long position) { if (!isSeekable() || position < firstFramePosition) { return 0L; } double offsetByte = 256.0 * (position - firstFramePosition) / sizeBytes; int prevIoUsTocPosition = Util.binarySearchFloor(tableOfContents,(long) offsetByte,true,false) + 1; long prevIoUsTime = getTimeUsForTocPosition(prevIoUsTocPosition); // Linearly interpolate the time taking into account the next entry. long prevIoUsByte = prevIoUsTocPosition == 0 ? 0 : tableOfContents[prevIoUsTocPosition - 1]; long nextByte = prevIoUsTocPosition == 99 ? 256 : tableOfContents[prevIoUsTocPosition]; long nextTime = getTimeUsForTocPosition(prevIoUsTocPosition + 1); long timeOffset = nextByte == prevIoUsByte ? 0 : (long) ((nextTime - prevIoUsTime) * (offsetByte - prevIoUsByte) / (nextByte - prevIoUsByte)); return prevIoUsTime + timeOffset; }
public void testWidevineOfflineLicense() throws Exception { if (Util.SDK_INT < 22) { // Pass. return; } String streamName = "test_widevine_h264_fixed_offline"; DashHostedTestEncParameters parameters = newDashHostedTestEncParameters( WIDEVINE_H264_MANIFEST_PREFIX,MimeTypes.VIDEO_H264); TestOfflineLicenseHelper helper = new TestOfflineLicenseHelper(parameters); try { byte[] keySetId = helper.downloadLicense(); testDashPlayback(getActivity(),streamName,parameters,WIDEVINE_AAC_AUdio_REPRESENTATION_ID,false,keySetId,WIDEVINE_H264_CDD_FIXED); helper.renewLicense(); } finally { helper.releaseResources(); } }
public void testWidevineOfflineLicenseExpiresOnPause() throws Exception { if (Util.SDK_INT < 22) { // Pass. return; } String streamName = "test_widevine_h264_fixed_offline"; DashHostedTestEncParameters parameters = newDashHostedTestEncParameters( WIDEVINE_H264_MANIFEST_PREFIX,MimeTypes.VIDEO_H264); TestOfflineLicenseHelper helper = new TestOfflineLicenseHelper(parameters); try { byte[] keySetId = helper.downloadLicense(); // During playback pause until the license expires then continue playback Pair<Long,Long> licenseDurationRemainingSec = helper.getLicenseDurationRemainingSec(); long licenseDuration = licenseDurationRemainingSec.first; assertTrue("License duration should be less than 30 sec. " + "Server settings might have changed.",licenseDuration < 30); ActionSchedule schedule = new ActionSchedule.Builder(TAG) .delay(3000).pause().delay(licenseDuration * 1000 + 2000).play().build(); // DefaultDrmSessionManager should renew the license and stream play fine testDashPlayback(getActivity(),schedule,WIDEVINE_H264_CDD_FIXED); } finally { helper.releaseResources(); } }
@TargetApi(21) @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(com.google.android.exoplayer2.ui.DefaultTimeBar.class.getCanonicalName()); info.setContentDescription(getProgresstext()); if (duration <= 0) { return; } if (Util.SDK_INT >= 21) { info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); } else if (Util.SDK_INT >= 16) { info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_playback); ButterKnife.bind(this); mSurfaceView.setKeepScreenOn(true); mPlaybackControllFragment = (OverlayFragment) getFragmentManager().findFragmentById(R.id.playback_controls_fragment); mUserAgent = Util.getUserAgent(this,getResources().getString(R.string.app_name)); synchronized (this) { if (player == null) { setupPlayer(); } } }
private MediaSource buildMediaSource(Uri uri,null); default: { throw new IllegalStateException("Unsupported type: " + type); } } }
/** * Infer content type int. * * @param fileName the file name * @return the int */ @C.ContentType public static int inferContentType(String fileName) { fileName = Util.toLowerInvariant(fileName); if (fileName.matches(".*m3u8.*")) { return C.TYPE_HLS; } else if (fileName.matches(".*mpd.*")) { return C.TYPE_DASH; } else if (fileName.matches(".*\\.ism(l)?(/manifest(\\(.+\\))?)?")) { return C.TYPE_SS; } else { return C.TYPE_OTHER; } }
private void initExoPlayer() { DefaultBandwidthMeter bwMeter = new DefaultBandwidthMeter(); AdaptiveTrackSelection.Factory trackFactory = new AdaptiveTrackSelection.Factory(bwMeter); DefaultTrackSelector trackSelector = new DefaultTrackSelector(trackFactory); player = ExoPlayerFactory.newSimpleInstance(this,trackSelector); videoView.setPlayer(player); DataSource.Factory dsFactory = new DefaultDataSourceFactory(getBaseContext(),Util.getUserAgent(this,"Traxy"),bwMeter); ExtractorsFactory exFactory = new DefaultExtractorsFactory(); Uri mediaUri = Uri.parse(entry.getUrl()); MediaSource videoSource = new ExtractorMediaSource(mediaUri,dsFactory,exFactory,null); player.prepare(videoSource); }
/** * Ensures {@code peekBuffer} is large enough to store at least {@code length} bytes from the * current peek position. */ private void ensureSpaceForPeek(int length) { int @R_301_3881@Length = peekBufferPosition + length; if (@R_301_3881@Length > peekBuffer.length) { int newPeekCapacity = Util.constrainValue(peekBuffer.length * 2,@R_301_3881@Length + PEEK_MIN_FREE_SPACE_AFTER_RESIZE,@R_301_3881@Length + PEEK_MAX_FREE_SPACE); peekBuffer = Arrays.copyOf(peekBuffer,newPeekCapacity); } }
@Override public boolean equals(Object obj) { if (!(obj instanceof SchemeData)) { return false; } if (obj == this) { return true; } SchemeData other = (SchemeData) obj; return mimeType.equals(other.mimeType) && Util.areEqual(uuid,other.uuid) && Arrays.equals(data,other.data); }
private void drawTimeBar(Canvas canvas) { int progressBarHeight = progressBar.height(); int barTop = progressBar.centerY() - progressBarHeight / 2; int barBottom = barTop + progressBarHeight; if (duration <= 0) { canvas.drawRect(progressBar.left,barTop,progressBar.right,barBottom,unplayedPaint); return; } int bufferedLeft = bufferedBar.left; int bufferedRight = bufferedBar.right; int progressLeft = Math.max(Math.max(progressBar.left,bufferedRight),scrubberBar.right); if (progressLeft < progressBar.right) { canvas.drawRect(progressLeft,unplayedPaint); } bufferedLeft = Math.max(bufferedLeft,scrubberBar.right); if (bufferedRight > bufferedLeft) { canvas.drawRect(bufferedLeft,bufferedRight,bufferedPaint); } if (scrubberBar.width() > 0) { canvas.drawRect(scrubberBar.left,scrubberBar.right,playedPaint); } int adMarkerOffset = adMarkerWidth / 2; for (int i = 0; i < adGroupCount; i++) { long adGroupTimeMs = Util.constrainValue(adGroupTimesMs[i],duration); int markerPositionOffset = (int) (progressBar.width() * adGroupTimeMs / duration) - adMarkerOffset; int markerLeft = progressBar.left + Math.min(progressBar.width() - adMarkerWidth,Math.max(0,markerPositionOffset)); Paint paint = playedAdGroups[i] ? playedAdMarkerPaint : adMarkerPaint; canvas.drawRect(markerLeft,markerLeft + adMarkerWidth,paint); } }
/** * @param audioCapabilities The audio capabilities for playback on this device. May be null if the * default capabilities (no encoded audio passthrough support) should be assumed. * @param audioProcessors An array of {@link AudioProcessor}s that will process PCM audio before * output. May be empty. * @param listener Listener for audio track events. */ public AudioTrack(AudioCapabilities audioCapabilities,AudioProcessor[] audioProcessors,Listener listener) { this.audioCapabilities = audioCapabilities; this.listener = listener; releasingConditionVariable = new ConditionVariable(true); if (Util.SDK_INT >= 18) { try { getLatencyMethod = android.media.AudioTrack.class.getmethod("getLatency",(Class<?>[]) null); } catch (NoSuchMethodException e) { // There's no guarantee this method exists. Do nothing. } } if (Util.SDK_INT >= 19) { audioTrackUtil = new AudioTrackUtilV19(); } else { audioTrackUtil = new AudioTrackUtil(); } channelMappingAudioProcessor = new ChannelMappingAudioProcessor(); sonicAudioProcessor = new SonicAudioProcessor(); availableAudioProcessors = new AudioProcessor[3 + audioProcessors.length]; availableAudioProcessors[0] = new resamplingAudioProcessor(); availableAudioProcessors[1] = channelMappingAudioProcessor; System.arraycopy(audioProcessors,availableAudioProcessors,2,audioProcessors.length); availableAudioProcessors[2 + audioProcessors.length] = sonicAudioProcessor; playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT]; volume = 1.0f; startMediaTimeState = START_NOT_SET; streamType = C.STREAM_TYPE_DEFAULT; audioSessionId = C.AUdio_SESSION_ID_UNSET; playbackParameters = PlaybackParameters.DEFAULT; drainingAudioProcessorIndex = C.INDEX_UNSET; this.audioProcessors = new AudioProcessor[0]; outputBuffers = new ByteBuffer[0]; playbackParametersCheckpoints = new LinkedList<>(); }
/** * Returns whether {@code brand} is an ftyp atom brand that is compatible with the MP4 extractors. */ private static boolean isCompatibleBrand(int brand) { // Accept all brands starting '3gp'. if (brand >>> 8 == Util.getIntegerCodeForString("3gp")) { return true; } for (int compatibleBrand : COMPATIBLE_BRANDS) { if (compatibleBrand == brand) { return true; } } return false; }
/** * Returns a {@link XingSeeker} for seeking in the stream,if @R_301_3881@ information is present. * Returns {@code null} if not. On returning,{@code frame}'s position is not specified so the * caller should reset it. * * @param mpegAudioHeader The MPEG audio header associated with the frame. * @param frame The data in this audio frame,with its position set to immediately after the * 'Xing' or 'Info' tag. * @param position The position (byte offset) of the start of this frame in the stream. * @param inputLength The length of the stream in bytes. * @return A {@link XingSeeker} for seeking in the stream,or {@code null} if the @R_301_3881@ * information is not present. */ public static XingSeeker create(MpegAudioHeader mpegAudioHeader,ParsableByteArray frame,long position,long inputLength) { int samplesPerFrame = mpegAudioHeader.samplesPerFrame; int sampleRate = mpegAudioHeader.sampleRate; long firstFramePosition = position + mpegAudioHeader.frameSize; int flags = frame.readInt(); int frameCount; if ((flags & 0x01) != 0x01 || (frameCount = frame.readUnsignedIntToInt()) == 0) { // If the frame count is missing/invalid,the header can't be used to determine the duration. return null; } long durationUs = Util.scaleLargeTimestamp(frameCount,samplesPerFrame * C.MICROS_PER_SECOND,sampleRate); if ((flags & 0x06) != 0x06) { // If the size in bytes or table of contents is missing,the stream is not seekable. return new XingSeeker(firstFramePosition,durationUs,inputLength); } long sizeBytes = frame.readUnsignedIntToInt(); frame.skipBytes(1); long[] tableOfContents = new long[99]; for (int i = 0; i < 99; i++) { tableOfContents[i] = frame.readUnsignedByte(); } // Todo: Handle encoder delay and padding in 3 bytes offset by xingBase + 213 bytes: // delay = (frame.readUnsignedByte() << 4) + (frame.readUnsignedByte() >> 4); // padding = ((frame.readUnsignedByte() & 0x0F) << 8) + frame.readUnsignedByte(); return new XingSeeker(firstFramePosition,inputLength,tableOfContents,sizeBytes,mpegAudioHeader.frameSize); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } PrivFrame other = (PrivFrame) obj; return Util.areEqual(owner,other.owner) && Arrays.equals(privateData,other.privateData); }
@Override public boolean evaluate(String contentType) { contentType = Util.toLowerInvariant(contentType); return !TextUtils.isEmpty(contentType) && (!contentType.contains("text") || contentType.contains("text/vtt")) && !contentType.contains("html") && !contentType.contains("xml"); }
private void initializePlayer(Uri mediaUri) { if (mExoPlayer == null) { // Create an instance of the ExoPlayer. TrackSelector trackSelector = new DefaultTrackSelector(); LoadControl loadControl = new DefaultLoadControl(); mExoPlayer = ExoPlayerFactory.newSimpleInstance(getContext(),loadControl); binding.exoStepFragmentPlayerView.setPlayer(mExoPlayer); mExoPlayer.addListener(this); String userAgent = Util.getUserAgent(getContext(),"RecipestepVideo"); MediaSource mediaSource = new ExtractorMediaSource(mediaUri,null); mExoPlayer.prepare(mediaSource); mExoPlayer.setPlayWhenReady(true); } }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } TextinformationFrame other = (TextinformationFrame) obj; return id.equals(other.id) && Util.areEqual(description,other.description) && Util.areEqual(value,other.value); }
@Override public void onResume() { super.onResume(); if ((Util.SDK_INT <= 23 || mTubiExoPlayer == null)) { setupExo(); } }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } EventMessage other = (EventMessage) obj; return durationMs == other.durationMs && id == other.id && Util.areEqual(schemeIdUri,other.schemeIdUri) && Util.areEqual(value,other.value) && Arrays.equals(messageData,other.messageData); }
@Override protected void configureCodec(MediaCodecInfo codecInfo,MediaCodec codec,Format format,MediaCrypto crypto) throws DecoderQueryException { codecMaxValues = getCodecMaxValues(codecInfo,format,streamFormats); MediaFormat mediaFormat = getMediaFormat(format,codecMaxValues,deviceNeedsAutoFrcWorkaround,tunnelingAudioSessionId); codec.configure(mediaFormat,surface,crypto,0); if (Util.SDK_INT >= 23 && tunneling) { tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec); } }
@Override public void onStop() { super.onStop(); if (Util.SDK_INT > 23) { releasePlayer(); } }
@Override public void onStart() { super.onStart(); if (Util.SDK_INT > 23) { initializePlayer(); } }
@Override public void onResume() { super.onResume(); if ((Util.SDK_INT <= 23 || player == null)) { initializePlayer(); } }
public void setPattern(int patternBlocksToEncrypt,int patternBlocksToSkip) { this.patternBlocksToEncrypt = patternBlocksToEncrypt; this.patternBlocksToSkip = patternBlocksToSkip; if (Util.SDK_INT >= 24) { patternHolder.set(patternBlocksToEncrypt,patternBlocksToSkip); } }
/** * Returns the underlying audio track {@code positionUs} with any applicable speedup applied. */ private long applySpeedup(long positionUs) { while (!playbackParametersCheckpoints.isEmpty() && positionUs >= playbackParametersCheckpoints.getFirst().positionUs) { // We are playing (or about to play) media with the new playback parameters,so update them. PlaybackParametersCheckpoint checkpoint = playbackParametersCheckpoints.remove(); playbackParameters = checkpoint.playbackParameters; playbackParametersPositionUs = checkpoint.positionUs; playbackParametersOffsetUs = checkpoint.mediaTimeUs - startMediaTimeUs; } if (playbackParameters.speed == 1f) { return positionUs + playbackParametersOffsetUs - playbackParametersPositionUs; } if (playbackParametersCheckpoints.isEmpty() && sonicAudioProcessor.getoutputByteCount() >= SONIC_MIN_BYTES_FOR_SPEEDUP) { return playbackParametersOffsetUs + Util.scaleLargeTimestamp(positionUs - playbackParametersPositionUs,sonicAudioProcessor.getInputByteCount(),sonicAudioProcessor.getoutputByteCount()); } // We are playing drained data at a prevIoUs playback speed,or don't have enough bytes to // calculate an accurate speedup,so fall back to multiplying by the speed. return playbackParametersOffsetUs + (long) ((double) playbackParameters.speed * (positionUs - playbackParametersPositionUs)); }
com.intellij.openapi.projectRoots.ui.Util的实例源码
@Override public VirtualFile[] selectFiles(@NotNull JComponent parent,@Nullable VirtualFile initialSelection,@Nullable Module contextModule,@NotNull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
private void onSpecifyUrlButtonClicked() { String defaultDocsUrl = mySdk == null ? "" : StringUtil.notNullize(((SdkType)mySdk.getSdkType()).getDefaultDocumentationUrl(mySdk),""); VirtualFile virtualFile = Util.showSpecifyJavadocUrlDialog(myPanel,defaultDocsUrl); if (virtualFile != null) { addElement(virtualFile); setModified(true); requestDefaultFocus(); setSelectedRoots(new Object[]{virtualFile}); } }
@Override public VirtualFile[] selectFiles(@NotNull JComponent parent,@NotNull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
@Override public VirtualFile[] selectFiles(@NotNull JComponent parent,@NotNull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
private void onSpecifyUrlButtonClicked() { final String defaultDocsUrl = mySdk == null ? "" : StringUtil.notNullize(((SdkType) mySdk.getSdkType()).getDefaultDocumentationUrl(mySdk),""); VirtualFile virtualFile = Util.showSpecifyJavadocUrlDialog(myPanel,defaultDocsUrl); if(virtualFile != null){ addElement(virtualFile); setModified(true); requestDefaultFocus(); setSelectedRoots(new Object[]{virtualFile}); } }
@Override public VirtualFile[] selectFiles(@NotNull JComponent parent,@NotNull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
@Override public VirtualFile[] selectFiles(@NotNull JComponent parent,@NotNull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
@Override public VirtualFile[] selectFiles(@Nonnull JComponent parent,@Nonnull LibraryEditor libraryEditor) { final VirtualFile vFile = Util.showSpecifyJavadocUrlDialog(parent); if (vFile != null) { return new VirtualFile[]{vFile}; } return VirtualFile.EMPTY_ARRAY; }
private void onSpecifyUrlButtonClicked() { final String defaultDocsUrl = mySdk == null ? "" : StringUtil.notNullize(((SdkType) mySdk.getSdkType()).getDefaultDocumentationUrl(mySdk),""); VirtualFile virtualFile = Util.showSpecifyJavadocUrlDialog(myComponent,defaultDocsUrl); if(virtualFile != null){ addElement(virtualFile); setModified(true); requestDefaultFocus(); setSelectedRoots(new Object[]{virtualFile}); } }
我们今天的关于com.mysql.jdbc.Util的实例源码的分享就到这里,谢谢您的阅读,如果想了解更多关于com.esotericsoftware.kryo.util.Util的实例源码、com.google.android.exoplayer.util.Util的实例源码、com.google.android.exoplayer2.util.Util的实例源码、com.intellij.openapi.projectRoots.ui.Util的实例源码的相关信息,可以在本站进行搜索。
本文标签: