proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
weibocom_motan
|
motan/motan-manager/src/main/java/com/weibo/utils/ZkClientWrapper.java
|
ZkClientWrapper
|
init
|
class ZkClientWrapper {
@Value("${registry.url}")
private String registryUrl;
private ZkClient zkClient;
@PostConstruct
void init() {<FILL_FUNCTION_BODY>}
@PreDestroy
void destory() {
zkClient = null;
}
public ZkClient getZkClient() {
return zkClient;
}
}
|
try {
zkClient = new ZkClient(registryUrl, 10000, 10000, new StringSerializer());
} catch (Exception e) {
throw new MotanFrameworkException("Fail to connect zookeeper, cause: " + e.getMessage());
}
| 113
| 77
| 190
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-consul/src/main/java/com/weibo/api/motan/registry/consul/ConsulHeartbeatManager.java
|
ConsulHeartbeatManager
|
start
|
class ConsulHeartbeatManager {
private MotanConsulClient client;
// 所有需要进行心跳的serviceid.
private ConcurrentHashSet<String> serviceIds = new ConcurrentHashSet<String>();
private ThreadPoolExecutor jobExecutor;
private ScheduledExecutorService heartbeatExecutor;
// 上一次心跳开关的状态
private boolean lastHeartBeatSwitcherStatus = false;
private volatile boolean currentHeartBeatSwitcherStatus = false;
// 开关检查次数。
private int switcherCheckTimes = 0;
public ConsulHeartbeatManager(MotanConsulClient client) {
this.client = client;
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(
10000);
jobExecutor = new ThreadPoolExecutor(5, 30, 30 * 1000,
TimeUnit.MILLISECONDS, workQueue);
}
public void start() {<FILL_FUNCTION_BODY>}
/**
* 判断心跳开关状态是否改变,如果心跳开关改变则更新lastHeartBeatSwitcherStatus为最新状态
*
* @param switcherStatus
* @return
*/
private boolean isSwitcherChange(boolean switcherStatus) {
boolean ret = false;
if (switcherStatus != lastHeartBeatSwitcherStatus) {
ret = true;
lastHeartBeatSwitcherStatus = switcherStatus;
LoggerUtil.info("heartbeat switcher change to " + switcherStatus);
}
return ret;
}
protected void processHeartbeat(boolean isPass) {
for (String serviceid : serviceIds) {
try {
jobExecutor.execute(new HeartbeatJob(serviceid, isPass));
} catch (RejectedExecutionException ree) {
LoggerUtil.error("execute heartbeat job fail! serviceid:"
+ serviceid + " is rejected");
}
}
}
public void close() {
heartbeatExecutor.shutdown();
jobExecutor.shutdown();
LoggerUtil.info("Consul heartbeatManager closed.");
}
/**
* 添加consul serviceid,添加后的serviceid会通过定时设置passing状态保持心跳。
*
* @param serviceid
*/
public void addHeartbeatServcieId(String serviceid) {
serviceIds.add(serviceid);
}
/**
* 移除serviceid,对应的serviceid不会在进行心跳。
*
* @param serviceid
*/
public void removeHeartbeatServiceId(String serviceid) {
serviceIds.remove(serviceid);
}
// 检查心跳开关是否打开
private boolean isHeartbeatOpen() {
return currentHeartBeatSwitcherStatus;
}
public void setHeartbeatOpen(boolean open) {
currentHeartBeatSwitcherStatus = open;
}
class HeartbeatJob implements Runnable {
private String serviceid;
private boolean isPass;
public HeartbeatJob(String serviceid, boolean isPass) {
super();
this.serviceid = serviceid;
this.isPass = isPass;
}
@Override
public void run() {
try {
if (isPass) {
client.checkPass(serviceid);
} else {
client.checkFail(serviceid);
}
} catch (Exception e) {
LoggerUtil.error(
"consul heartbeat-set check pass error!serviceid:"
+ serviceid, e);
}
}
}
public void setClient(MotanConsulClient client) {
this.client = client;
}
}
|
heartbeatExecutor.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// 由于consul的check set pass会导致consul
// server的写磁盘操作,过于频繁的心跳会导致consul
// 性能问题,只能将心跳方式改为较长的周期进行一次探测。又因为想在关闭心跳开关后尽快感知
// 就将心跳改为以较小周期检测心跳开关是否变动,连续检测多次后给consul server发送一次心跳。
// TODO 改为开关listener方式。
try {
boolean switcherStatus = isHeartbeatOpen();
if (isSwitcherChange(switcherStatus)) { // 心跳开关状态变更
processHeartbeat(switcherStatus);
} else {// 心跳开关状态未变更
if (switcherStatus) {// 开关为开启状态,则连续检测超过MAX_SWITCHER_CHECK_TIMES次发送一次心跳
switcherCheckTimes++;
if (switcherCheckTimes >= ConsulConstants.MAX_SWITCHER_CHECK_TIMES) {
processHeartbeat(true);
switcherCheckTimes = 0;
}
}
}
} catch (Exception e) {
LoggerUtil.error("consul heartbeat executor err:",
e);
}
}
}, ConsulConstants.SWITCHER_CHECK_CIRCLE,
ConsulConstants.SWITCHER_CHECK_CIRCLE, TimeUnit.MILLISECONDS);
| 970
| 417
| 1,387
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-consul/src/main/java/com/weibo/api/motan/registry/consul/ConsulRegistryFactory.java
|
ConsulRegistryFactory
|
createRegistry
|
class ConsulRegistryFactory extends AbstractRegistryFactory {
@Override
protected Registry createRegistry(URL url) {<FILL_FUNCTION_BODY>}
}
|
String host = ConsulConstants.DEFAULT_HOST;
int port = ConsulConstants.DEFAULT_PORT;
if (StringUtils.isNotBlank(url.getHost())) {
host = url.getHost();
}
if (url.getPort() > 0) {
port = url.getPort();
}
//可以使用不同的client实现
MotanConsulClient client = new ConsulEcwidClient(host, port);
return new ConsulRegistry(url, client);
| 43
| 126
| 169
|
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.registry.Registry getRegistry(com.weibo.api.motan.rpc.URL) <variables>private static final java.util.concurrent.locks.ReentrantLock lock,private static final ConcurrentHashMap<java.lang.String,com.weibo.api.motan.registry.Registry> registries
|
weibocom_motan
|
motan/motan-registry-consul/src/main/java/com/weibo/api/motan/registry/consul/ConsulUtils.java
|
ConsulUtils
|
buildService
|
class ConsulUtils {
/**
* 判断两个list中的url是否一致。 如果任意一个list为空,则返回false; 此方法并未做严格互相判等
*
* @param urls1
* @param urls2
* @return
*/
public static boolean isSame(List<URL> urls1, List<URL> urls2) {
if (urls1 == null || urls2 == null) {
return false;
}
if (urls1.size() != urls2.size()) {
return false;
}
return urls1.containsAll(urls2);
}
/**
* 根据服务的url生成consul对应的service
*
* @param url
* @return
*/
public static ConsulService buildService(URL url) {<FILL_FUNCTION_BODY>}
/**
* 根据service生成motan使用的
*
* @param service
* @return
*/
public static URL buildUrl(ConsulService service) {
URL url = null;
for (String tag : service.getTags()) {
if (tag.startsWith(ConsulConstants.CONSUL_TAG_MOTAN_URL)) {
String encodeUrl = tag.substring(tag.indexOf("_") + 1);
url = URL.valueOf(StringTools.urlDecode(encodeUrl));
}
}
if (url == null) {
Map<String, String> params = new HashMap<String, String>();
String group = service.getName().substring(ConsulConstants.CONSUL_SERVICE_MOTAN_PRE.length());
params.put(URLParamType.group.getName(), group);
params.put(URLParamType.nodeType.getName(), MotanConstants.NODE_TYPE_SERVICE);
String protocol = ConsulUtils.getProtocolFromTag(service.getTags().get(0));
url = new URL(protocol, service.getAddress(), service.getPort(),
ConsulUtils.getPathFromServiceId(service.getId()), params);
}
return url;
}
/**
* 根据url获取cluster信息,cluster 信息包括协议和path(rpc服务中的接口类)。
*
* @param url
* @return
*/
public static String getUrlClusterInfo(URL url) {
return url.getProtocol() + "-" + url.getPath();
}
/**
* 有motan的group生成consul的serivce name
*
* @param group
* @return
*/
public static String convertGroupToServiceName(String group) {
return ConsulConstants.CONSUL_SERVICE_MOTAN_PRE + group;
}
/**
* 从consul的service name中获取motan的group
*
* @param group
* @return
*/
public static String getGroupFromServiceName(String group) {
return group.substring(ConsulConstants.CONSUL_SERVICE_MOTAN_PRE.length());
}
/**
* 根据motan的url生成consul的serivce id。 serviceid 包括ip+port+rpc服务的接口类名
*
* @param url
* @return
*/
public static String convertConsulSerivceId(URL url) {
if (url == null) {
return null;
}
return convertServiceId(url.getHost(), url.getPort(), url.getPath());
}
/**
* 从consul 的serviceid中获取rpc服务的接口类名(url的path)
*
* @param serviceId
* @return
*/
public static String getPathFromServiceId(String serviceId) {
return serviceId.substring(serviceId.indexOf("-") + 1);
}
/**
* 从consul的tag获取motan的protocol
*
* @param tag
* @return
*/
public static String getProtocolFromTag(String tag) {
return tag.substring(ConsulConstants.CONSUL_TAG_MOTAN_PROTOCOL.length());
}
public static String convertServiceId(String host, int port, String path) {
return host + ":" + port + "-" + path;
}
}
|
ConsulService service = new ConsulService();
service.setAddress(url.getHost());
service.setId(ConsulUtils.convertConsulSerivceId(url));
service.setName(ConsulUtils.convertGroupToServiceName(url.getGroup()));
service.setPort(url.getPort());
service.setTtl(ConsulConstants.TTL);
List<String> tags = new ArrayList<String>();
tags.add(ConsulConstants.CONSUL_TAG_MOTAN_PROTOCOL + url.getProtocol());
tags.add(ConsulConstants.CONSUL_TAG_MOTAN_URL + StringTools.urlEncode(url.toFullStr()));
service.setTags(tags);
return service;
| 1,113
| 191
| 1,304
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-consul/src/main/java/com/weibo/api/motan/registry/consul/client/ConsulEcwidClient.java
|
ConsulEcwidClient
|
lookupHealthService
|
class ConsulEcwidClient extends MotanConsulClient {
protected ConsulClient client;
public ConsulEcwidClient(String host, int port) {
super(host, port);
client = new ConsulClient(host, port);
LoggerUtil.info("ConsulEcwidClient init finish. client host:" + host
+ ", port:" + port);
}
@Override
public void checkPass(String serviceid) {
client.agentCheckPass("service:" + serviceid);
}
@Override
public void registerService(ConsulService service) {
NewService newService = convertService(service);
client.agentServiceRegister(newService);
}
@Override
public void unregisterService(String serviceid) {
client.agentServiceDeregister(serviceid);
}
@Override
public ConsulResponse<List<ConsulService>> lookupHealthService(
String serviceName, long lastConsulIndex) {<FILL_FUNCTION_BODY>}
@Override
public String lookupCommand(String group) {
Response<GetValue> response = client.getKVValue(ConsulConstants.CONSUL_MOTAN_COMMAND + ConsulUtils.convertGroupToServiceName(group));
GetValue value = response.getValue();
String command = "";
if (value == null) {
LoggerUtil.info("no command in group: " + group);
} else if (value.getValue() != null) {
command = value.getDecodedValue();
}
return command;
}
private NewService convertService(ConsulService service) {
NewService newService = new NewService();
newService.setAddress(service.getAddress());
newService.setId(service.getId());
newService.setName(service.getName());
newService.setPort(service.getPort());
newService.setTags(service.getTags());
NewService.Check check = new NewService.Check();
check.setTtl(service.getTtl() + "s");
newService.setCheck(check);
return newService;
}
private ConsulService convertToConsulService(HealthService healthService) {
ConsulService service = new ConsulService();
Service org = healthService.getService();
service.setAddress(org.getAddress());
service.setId(org.getId());
service.setName(org.getService());
service.setPort(org.getPort());
service.setTags(org.getTags());
return service;
}
@Override
public void checkFail(String serviceid) {
client.agentCheckFail("service:" + serviceid);
}
}
|
QueryParams queryParams = new QueryParams(
ConsulConstants.CONSUL_BLOCK_TIME_SECONDS, lastConsulIndex);
Response<List<HealthService>> orgResponse = client.getHealthServices(
serviceName, true, queryParams);
ConsulResponse<List<ConsulService>> newResponse = null;
if (orgResponse != null && orgResponse.getValue() != null
&& !orgResponse.getValue().isEmpty()) {
List<HealthService> HealthServices = orgResponse.getValue();
List<ConsulService> ConsulServices = new ArrayList<ConsulService>(
HealthServices.size());
for (HealthService orgService : HealthServices) {
try {
ConsulService newService = convertToConsulService(orgService);
ConsulServices.add(newService);
} catch (Exception e) {
String servcieid = "null";
if (orgService.getService() != null) {
servcieid = orgService.getService().getId();
}
LoggerUtil.error(
"convert consul service fail. org consulservice:"
+ servcieid, e);
}
}
if (!ConsulServices.isEmpty()) {
newResponse = new ConsulResponse<List<ConsulService>>();
newResponse.setValue(ConsulServices);
newResponse.setConsulIndex(orgResponse.getConsulIndex());
newResponse.setConsulLastContact(orgResponse
.getConsulLastContact());
newResponse.setConsulKnownLeader(orgResponse
.isConsulKnownLeader());
}
}
return newResponse;
| 680
| 411
| 1,091
|
<methods>public void <init>(java.lang.String, int) ,public abstract void checkFail(java.lang.String) ,public abstract void checkPass(java.lang.String) ,public abstract java.lang.String lookupCommand(java.lang.String) ,public abstract ConsulResponse<List<com.weibo.api.motan.registry.consul.ConsulService>> lookupHealthService(java.lang.String, long) ,public abstract void registerService(com.weibo.api.motan.registry.consul.ConsulService) ,public abstract void unregisterService(java.lang.String) <variables>protected java.lang.String host,protected int port
|
weibocom_motan
|
motan/motan-registry-weibomesh/src/main/java/com/weibo/api/motan/registry/weibomesh/DefaultHttpMeshTransport.java
|
DefaultHttpMeshTransport
|
postManageRequest
|
class DefaultHttpMeshTransport implements MeshTransport {
private HttpClient httpClient;
private static final int DEFAULT_TIMEOUT = 5000;
public DefaultHttpMeshTransport() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(1000);
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(DEFAULT_TIMEOUT).
setConnectionRequestTimeout(DEFAULT_TIMEOUT).
setSocketTimeout(DEFAULT_TIMEOUT).
build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().
setConnectionManager(connectionManager).
setDefaultRequestConfig(requestConfig).
useSystemProperties();
this.httpClient = httpClientBuilder.build();
}
@Override
public ManageResponse getManageRequest(String url) throws MotanFrameworkException {
HttpGet httpGet = new HttpGet(url);
return executeRequest(httpGet, "");
}
@Override
public ManageResponse postManageRequest(String url, Map<String, String> params) throws MotanFrameworkException {
HttpPost httpPost = new HttpPost(url);
String content = "";
if (params != null && !params.isEmpty()) {
List<NameValuePair> paramList = new ArrayList();
StringBuilder sb = new StringBuilder(128);
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
sb.append(entry.getKey()).append(":").append(entry.getValue()).append(",");
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
content = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new MotanServiceException("DefaultHttpMeshTransport convert post parmas fail. request url:" + url, e);
}
}
return executeRequest(httpPost, content);
}
public ManageResponse postManageRequest(String url, String content) throws MotanFrameworkException {<FILL_FUNCTION_BODY>}
private ManageResponse executeRequest(HttpUriRequest httpRequest, String logContent) {
try {
return httpClient.execute(httpRequest, response -> {
int statusCode = response.getStatusLine().getStatusCode();
String statusMessage = response.getStatusLine().getReasonPhrase();
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
LoggerUtil.info("http request uri:" + httpRequest.getURI() + ", return code: " + statusCode
+ ", return message: " + content + ", req params:" + logContent);
return new ManageResponse(statusCode, content);
});
} catch (IOException e) {
throw new MotanServiceException("execute mesh manage requst fail. reqeust uri:" + httpRequest.getURI(), e);
}
}
}
|
HttpPost httpPost = new HttpPost(url);
if (content != null) {
try {
httpPost.setEntity(new StringEntity(content, "UTF-8"));
} catch (UnsupportedCharsetException e) {
throw new MotanServiceException("DefaultHttpMeshTransport convert post parmas fail. request url:" + url, e);
}
}
return executeRequest(httpPost, content);
| 759
| 107
| 866
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-weibomesh/src/main/java/com/weibo/api/motan/registry/weibomesh/MeshRegistryFactory.java
|
MeshRegistryFactory
|
getRegistryUri
|
class MeshRegistryFactory extends AbstractRegistryFactory {
@Override
protected Registry createRegistry(URL url) {
return new MeshRegistry(url, new DefaultHttpMeshTransport());
}
@Override
protected String getRegistryUri(URL url) {<FILL_FUNCTION_BODY>}
}
|
// registry uri with proxy registry
String proxyRegistry = url.getParameter(URLParamType.proxyRegistryUrlString.name());
if (StringUtils.isBlank(proxyRegistry)) {
proxyRegistry = url.getParameter(url.getParameter(URLParamType.meshRegistryName.name()));
}
String registryUri = url.getUri() + "?proxyRegistry=" + proxyRegistry;
return registryUri;
| 78
| 105
| 183
|
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.registry.Registry getRegistry(com.weibo.api.motan.rpc.URL) <variables>private static final java.util.concurrent.locks.ReentrantLock lock,private static final ConcurrentHashMap<java.lang.String,com.weibo.api.motan.registry.Registry> registries
|
weibocom_motan
|
motan/motan-registry-weibomesh/src/main/java/com/weibo/api/motan/registry/weibomesh/MeshRegistryListener.java
|
MeshRegistryListener
|
doNotify
|
class MeshRegistryListener implements NotifyListener {
private static int DEFAULT_COPY = 2;
private MeshRegistry meshRegistry;
private ConcurrentHashSet<NotifyListener> listeners = new ConcurrentHashSet<>();
private ImmutableList<URL> meshNodes;
private URL subscribeUrl;
private List<URL> backupNodes = null;
public MeshRegistryListener(MeshRegistry meshRegistry, URL subscribeUrl) {
this.meshRegistry = meshRegistry;
URL meshNode = subscribeUrl.createCopy();
URL meshUrl = meshRegistry.getUrl();
meshNode.setHost(meshUrl.getHost());
meshNode.setPort(meshUrl.getPort());
if (StringUtils.isNotBlank(meshUrl.getParameter(URLParamType.fusingThreshold.getName()))) {
meshNode.addParameter(URLParamType.fusingThreshold.getName(), meshUrl.getParameter(URLParamType.fusingThreshold.getName()));
}
int copy = meshUrl.getIntParameter(MeshRegistry.MESH_PARAM_COPY, DEFAULT_COPY);
ImmutableList.Builder builder = ImmutableList.builder();
for (int i = 0; i < copy; i++) {
builder.add(meshNode);
}
this.meshNodes = builder.build();
this.subscribeUrl = subscribeUrl;
}
@Override
public void notify(URL registryUrl, List<URL> urls) {
if (!CollectionUtil.isEmpty(urls)) {
this.backupNodes = urls;
if (!meshRegistry.isUseMesh()) { // 当前未使用mesh时,直接通知
doNotify(false);
}
}
}
// 确定通知时调用。
// 根据useMesh参数决定通知的节点,因此在调用此方法前需要自行判定是否正在使用mesh。
public void doNotify(boolean useMesh) {<FILL_FUNCTION_BODY>}
public List<URL> getUrls() {
if (!meshRegistry.isUseMesh() && !CollectionUtil.isEmpty(backupNodes)) {
return backupNodes;
}
return meshNodes;
}
public List<URL> getBackupNodes() {
return backupNodes;
}
public List<URL> getMeshNodes() {
return meshNodes;
}
public void addListener(NotifyListener listener) {
listeners.add(listener);
}
public boolean removeListener(NotifyListener listener) {
return listeners.remove(listener);
}
}
|
for (NotifyListener listener : listeners) {
try {
if (useMesh) {
listener.notify(meshRegistry.getUrl(), meshNodes);
} else {
if (CollectionUtil.isEmpty(backupNodes)) {
LoggerUtil.info("mesh registry backupNodes is empty, not notify. url:" + subscribeUrl.toSimpleString());
return; // 没有后备节点时,不做通知。
}
listener.notify(meshRegistry.getUrl(), backupNodes);
}
} catch (Exception e) {
LoggerUtil.warn("MeshRegistryListner notify fail. listner url:" + subscribeUrl.toSimpleString());
}
}
| 652
| 173
| 825
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-zookeeper/src/main/java/com/weibo/api/motan/registry/zookeeper/StringSerializer.java
|
StringSerializer
|
deserialize
|
class StringSerializer extends SerializableSerializer {
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {<FILL_FUNCTION_BODY>}
@Override
public byte[] serialize(Object obj) throws ZkMarshallingError {
try {
return obj.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
}
}
|
if (bytes == null){
return null;
}
try {
if (bytes.length > 1 && ByteUtil.bytes2short(bytes, 0) == ObjectStreamConstants.STREAM_MAGIC) {
return super.deserialize(bytes);
}
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ZkMarshallingError(e);
}
| 120
| 114
| 234
|
<no_super_class>
|
weibocom_motan
|
motan/motan-registry-zookeeper/src/main/java/com/weibo/api/motan/registry/zookeeper/ZookeeperRegistryFactory.java
|
ZookeeperRegistryFactory
|
createRegistry
|
class ZookeeperRegistryFactory extends AbstractRegistryFactory {
@Override
protected Registry createRegistry(URL registryUrl) {<FILL_FUNCTION_BODY>}
protected ZkClient createInnerZkClient(String zkServers, int sessionTimeout, int connectionTimeout) {
return new ZkClient(zkServers, sessionTimeout, connectionTimeout);
}
}
|
try {
int timeout = registryUrl.getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
int sessionTimeout = registryUrl.getIntParameter(URLParamType.registrySessionTimeout.getName(), URLParamType.registrySessionTimeout.getIntValue());
ZkClient zkClient = createInnerZkClient(registryUrl.getParameter("address"), sessionTimeout, timeout);
return new ZookeeperRegistry(registryUrl, zkClient);
} catch (ZkException e) {
LoggerUtil.error("[ZookeeperRegistry] fail to connect zookeeper, cause: " + e.getMessage());
throw e;
}
| 94
| 173
| 267
|
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.registry.Registry getRegistry(com.weibo.api.motan.rpc.URL) <variables>private static final java.util.concurrent.locks.ReentrantLock lock,private static final ConcurrentHashMap<java.lang.String,com.weibo.api.motan.registry.Registry> registries
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/BasicRefererConfigBean.java
|
BasicRefererConfigBean
|
extractRegistries
|
class BasicRefererConfigBean extends BasicRefererInterfaceConfig implements BeanNameAware, InitializingBean, BeanFactoryAware {
private String protocolNames;
private String registryNames;
private BeanFactory beanFactory;
@Override
public void setBeanName(String name) {
setId(name);
MotanNamespaceHandler.basicRefererConfigDefineNames.add(name);
}
public void setProtocol(String protocolNames) {
this.protocolNames = protocolNames;
}
public void setRegistry(String registryNames) {
this.registryNames = registryNames;
}
@Override
public void afterPropertiesSet() throws Exception {
setRegistries(extractRegistries(registryNames, beanFactory));
setProtocols(extractProtocols(protocolNames, beanFactory));
}
public List<ProtocolConfig> extractProtocols(String protocols, BeanFactory beanFactory) {
if (protocols != null && protocols.length() > 0) {
List<ProtocolConfig> protocolConfigList = SpringBeanUtil.getMultiBeans(beanFactory, protocols,
SpringBeanUtil.COMMA_SPLIT_PATTERN, ProtocolConfig.class);
return protocolConfigList;
} else {
return null;
}
}
public List<RegistryConfig> extractRegistries(String registries, BeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void setCheck(boolean value) {
setCheck(String.valueOf(value));
}
public void setAccessLog(boolean value) {
setAccessLog(String.valueOf(value));
}
}
|
if (registries != null && registries.length() > 0) {
List<RegistryConfig> registryConfigList = SpringBeanUtil.getMultiBeans(beanFactory, registries,
SpringBeanUtil.COMMA_SPLIT_PATTERN, RegistryConfig.class);
return registryConfigList;
} else {
return null;
}
| 457
| 92
| 549
|
<methods>public non-sealed void <init>() ,public java.lang.Boolean isDefault() ,public void setDefault(boolean) <variables>private java.lang.Boolean isDefault,private static final long serialVersionUID
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/BasicServiceConfigBean.java
|
BasicServiceConfigBean
|
extractProtocols
|
class BasicServiceConfigBean extends BasicServiceInterfaceConfig implements BeanNameAware,
InitializingBean, BeanFactoryAware {
private String registryNames;
BeanFactory beanFactory;
@Override
public void setBeanName(String name) {
setId(name);
MotanNamespaceHandler.basicServiceConfigDefineNames.add(name);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void afterPropertiesSet() throws Exception {
String protocol = ConfigUtil.extractProtocols(getExport());
setRegistries(extractRegistries(registryNames, beanFactory));
setProtocols(extractProtocols(protocol, beanFactory));
}
public List<ProtocolConfig> extractProtocols(String protocols, BeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
public List<RegistryConfig> extractRegistries(String registries, BeanFactory beanFactory) {
if (registries != null && registries.length() > 0) {
if (!registries.contains(",")) {
RegistryConfig registryConfig = beanFactory.getBean(registries, RegistryConfig.class);
return Collections.singletonList(registryConfig);
} else {
List<RegistryConfig> registryConfigList = SpringBeanUtil.getMultiBeans(beanFactory, registries,
SpringBeanUtil.COMMA_SPLIT_PATTERN, RegistryConfig.class);
return registryConfigList;
}
} else {
return null;
}
}
public void setRegistry(String registryNames) {
this.registryNames = registryNames;
}
public void setCheck(boolean value) {
setCheck(String.valueOf(value));
}
public void setAccessLog(boolean value) {
setAccessLog(String.valueOf(value));
}
}
|
if (protocols != null && protocols.length() > 0) {
List<ProtocolConfig> protocolConfigList = SpringBeanUtil.getMultiBeans(beanFactory, protocols,
SpringBeanUtil.COMMA_SPLIT_PATTERN, ProtocolConfig.class);
return protocolConfigList;
} else {
return null;
}
| 503
| 91
| 594
|
<methods>public non-sealed void <init>() ,public java.lang.Boolean isDefault() ,public void setDefault(boolean) <variables>private java.lang.Boolean isDefault,private static final long serialVersionUID
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/MotanNamespaceHandler.java
|
MotanNamespaceHandler
|
init
|
class MotanNamespaceHandler extends NamespaceHandlerSupport {
public final static Set<String> protocolDefineNames = new ConcurrentHashSet<>();
public final static Set<String> registryDefineNames = new ConcurrentHashSet<>();
public final static Set<String> basicServiceConfigDefineNames = new ConcurrentHashSet<>();
public final static Set<String> basicRefererConfigDefineNames = new ConcurrentHashSet<>();
@Override
public void init() {<FILL_FUNCTION_BODY>}
}
|
registerBeanDefinitionParser("referer", new MotanBeanDefinitionParser(RefererConfigBean.class, false));
registerBeanDefinitionParser("service", new MotanBeanDefinitionParser(ServiceConfigBean.class, true));
registerBeanDefinitionParser("protocol", new MotanBeanDefinitionParser(ProtocolConfig.class, true));
registerBeanDefinitionParser("registry", new MotanBeanDefinitionParser(RegistryConfig.class, true));
registerBeanDefinitionParser("basicService", new MotanBeanDefinitionParser(BasicServiceInterfaceConfig.class, true));
registerBeanDefinitionParser("basicReferer", new MotanBeanDefinitionParser(BasicRefererInterfaceConfig.class, true));
registerBeanDefinitionParser("spi", new MotanBeanDefinitionParser(SpiConfigBean.class, true));
registerBeanDefinitionParser("annotation", new MotanBeanDefinitionParser(AnnotationBean.class, true));
registerBeanDefinitionParser("meshClient", new MotanBeanDefinitionParser(MeshClientConfigBean.class, false));
Initializable initialization = InitializationFactory.getInitialization();
initialization.init();
| 127
| 251
| 378
|
<no_super_class>
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/RefererConfigBean.java
|
RefererConfigBean
|
checkAndConfigBasicConfig
|
class RefererConfigBean<T> extends RefererConfig<T> implements FactoryBean<T>, BeanFactoryAware, InitializingBean, DisposableBean {
private static final long serialVersionUID = 8381310907161365567L;
private transient BeanFactory beanFactory;
@Override
public T getObject() throws Exception {
return getRef();
}
@Override
public Class<?> getObjectType() {
return getInterface();
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void afterPropertiesSet() throws Exception {
// basicConfig需要首先配置,因为其他可能会依赖于basicConfig的配置
checkAndConfigBasicConfig();
if (checkAndConfigMeshClient()) { // 使用MeshClient时不需要检查其他项
return;
}
checkAndConfigProtocols();
checkAndConfigRegistry();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
/**
* 检查并配置basicConfig
*/
private void checkAndConfigBasicConfig() {<FILL_FUNCTION_BODY>}
/**
* 检查是否有MeshClient相关配置,是否需要配置默认MeshClient
* 如果使用默认MeshClient,如果初始化失败直接抛出异常,不支持通过check忽略此异常,尽早暴露问题
*
* @return true:使用MeshClient, false:不使用MeshClient
*/
private boolean checkAndConfigMeshClient() {
if ("default".equals(meshClientString)) {
meshClient = DefaultMeshClient.getDefault();
}
if (meshClient == null && meshClientString == null && getBasicReferer() != null) {
if ("default".equals(getBasicReferer().getMeshClientString())) {
meshClient = DefaultMeshClient.getDefault();
} else {
meshClient = getBasicReferer().getMeshClient();
}
}
return meshClient != null;
}
/**
* 检查是否已经装配protocols,否则按basicConfig--->default路径查找
*/
private void checkAndConfigProtocols() {
if (CollectionUtil.isEmpty(getProtocols()) && getBasicReferer() != null
&& !CollectionUtil.isEmpty(getBasicReferer().getProtocols())) {
setProtocols(getBasicReferer().getProtocols());
}
if (CollectionUtil.isEmpty(getProtocols())) {
for (String name : MotanNamespaceHandler.protocolDefineNames) {
ProtocolConfig pc = beanFactory.getBean(name, ProtocolConfig.class);
if (pc == null) {
continue;
}
if (MotanNamespaceHandler.protocolDefineNames.size() == 1) {
setProtocol(pc);
} else if (pc.isDefault() != null && pc.isDefault().booleanValue()) {
setProtocol(pc);
}
}
}
if (CollectionUtil.isEmpty(getProtocols())) {
setProtocol(MotanFrameworkUtil.getDefaultProtocolConfig());
}
}
/**
* 检查并配置registry
*/
public void checkAndConfigRegistry() {
if (CollectionUtil.isEmpty(getRegistries()) && getBasicReferer() != null
&& !CollectionUtil.isEmpty(getBasicReferer().getRegistries())) {
setRegistries(getBasicReferer().getRegistries());
}
if (CollectionUtil.isEmpty(getRegistries())) {
for (String name : MotanNamespaceHandler.registryDefineNames) {
RegistryConfig rc = beanFactory.getBean(name, RegistryConfig.class);
if (rc == null) {
continue;
}
if (MotanNamespaceHandler.registryDefineNames.size() == 1) {
setRegistry(rc);
} else if (rc.isDefault() != null && rc.isDefault().booleanValue()) {
setRegistry(rc);
}
}
}
if (CollectionUtil.isEmpty(getRegistries())) {
setRegistry(MotanFrameworkUtil.getDefaultRegistryConfig());
}
for (RegistryConfig registryConfig : getRegistries()) {
SpringBeanUtil.addRegistryParamBean(registryConfig, beanFactory);
}
}
}
|
if (getBasicReferer() == null) {
if (MotanNamespaceHandler.basicRefererConfigDefineNames.size() == 0) {
if (beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
String[] basicRefererConfigNames = listableBeanFactory.getBeanNamesForType
(BasicRefererInterfaceConfig
.class);
MotanNamespaceHandler.basicRefererConfigDefineNames.addAll(Arrays.asList(basicRefererConfigNames));
}
}
for (String name : MotanNamespaceHandler.basicRefererConfigDefineNames) {
BasicRefererInterfaceConfig biConfig = beanFactory.getBean(name, BasicRefererInterfaceConfig.class);
if (biConfig == null) {
continue;
}
if (MotanNamespaceHandler.basicRefererConfigDefineNames.size() == 1) {
setBasicReferer(biConfig);
} else if (biConfig.isDefault() != null && biConfig.isDefault().booleanValue()) {
setBasicReferer(biConfig);
}
}
}
| 1,151
| 283
| 1,434
|
<methods>public non-sealed void <init>() ,public synchronized void destroy() ,public com.weibo.api.motan.config.BasicRefererInterfaceConfig getBasicReferer() ,public List<ClusterSupport<T>> getClusterSupports() ,public java.lang.String getDirectUrl() ,public java.util.concurrent.atomic.AtomicBoolean getInitialized() ,public Class<?> getInterface() ,public List<com.weibo.api.motan.config.MethodConfig> getMethods() ,public T getRef() ,public java.lang.String getServiceInterface() ,public boolean hasMethods() ,public synchronized void initRef() ,public void setBasicReferer(com.weibo.api.motan.config.BasicRefererInterfaceConfig) ,public void setDirectUrl(java.lang.String) ,public void setInterface(Class<T>) ,public void setMethods(List<com.weibo.api.motan.config.MethodConfig>) ,public void setMethods(com.weibo.api.motan.config.MethodConfig) ,public void setServiceInterface(java.lang.String) <variables>private com.weibo.api.motan.config.BasicRefererInterfaceConfig basicReferer,private List<ClusterSupport<T>> clusterSupports,private java.lang.String directUrl,private final java.util.concurrent.atomic.AtomicBoolean initialized,private Class<T> interfaceClass,protected List<com.weibo.api.motan.config.MethodConfig> methods,private T ref,private static final long serialVersionUID,private java.lang.String serviceInterface
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/ServiceConfigBean.java
|
ServiceConfigBean
|
checkAndConfigExport
|
class ServiceConfigBean<T> extends ServiceConfig<T>
implements
BeanFactoryAware,
InitializingBean,
DisposableBean,
ApplicationListener<ContextRefreshedEvent> {
private static final long serialVersionUID = -7247592395983804440L;
private transient BeanFactory beanFactory;
@Override
public void destroy() throws Exception {
unexport();
}
@Override
public void afterPropertiesSet() throws Exception {
// 注意:basicConfig需要首先配置,因为其他可能会依赖于basicConfig的配置
checkAndConfigBasicConfig();
checkAndConfigExport();
checkAndConfigRegistry();
// 等spring初始化完毕后,再export服务
// export();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (!getExported().get()) {
export();
}
}
/**
* 检查并配置basicConfig
*/
private void checkAndConfigBasicConfig() {
if (getBasicService() == null) {
if (MotanNamespaceHandler.basicServiceConfigDefineNames.size() == 0) {
if (beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
String[] basicServiceConfigNames = listableBeanFactory.getBeanNamesForType
(BasicServiceInterfaceConfig
.class);
MotanNamespaceHandler.basicServiceConfigDefineNames.addAll(Arrays.asList(basicServiceConfigNames));
}
}
for (String name : MotanNamespaceHandler.basicServiceConfigDefineNames) {
BasicServiceInterfaceConfig biConfig = beanFactory.getBean(name, BasicServiceInterfaceConfig.class);
if (biConfig == null) {
continue;
}
if (MotanNamespaceHandler.basicServiceConfigDefineNames.size() == 1) {
setBasicService(biConfig);
} else if (biConfig.isDefault() != null && biConfig.isDefault().booleanValue()) {
setBasicService(biConfig);
}
}
}
}
/**
* 检查是否已经装配export,如果没有则到basicConfig查找
*/
private void checkAndConfigExport() {<FILL_FUNCTION_BODY>}
/**
* 检查并配置registry
*/
private void checkAndConfigRegistry() {
if (CollectionUtil.isEmpty(getRegistries()) && getBasicService() != null
&& !CollectionUtil.isEmpty(getBasicService().getRegistries())) {
setRegistries(getBasicService().getRegistries());
}
if (CollectionUtil.isEmpty(getRegistries())) {
for (String name : MotanNamespaceHandler.registryDefineNames) {
RegistryConfig rc = beanFactory.getBean(name, RegistryConfig.class);
if (rc == null) {
continue;
}
if (MotanNamespaceHandler.registryDefineNames.size() == 1) {
setRegistry(rc);
} else if (rc.isDefault() != null && rc.isDefault().booleanValue()) {
setRegistry(rc);
}
}
}
if (CollectionUtil.isEmpty(getRegistries())) {
setRegistry(MotanFrameworkUtil.getDefaultRegistryConfig());
}
for (RegistryConfig registryConfig : getRegistries()) {
SpringBeanUtil.addRegistryParamBean(registryConfig, beanFactory);
}
}
}
|
if (StringUtils.isBlank(getExport()) && getBasicService() != null
&& !StringUtils.isBlank(getBasicService().getExport())) {
setExport(getBasicService().getExport());
if (getBasicService().getProtocols() != null) {
setProtocols(new ArrayList<ProtocolConfig>(getBasicService().getProtocols()));
}
}
if (CollectionUtil.isEmpty(getProtocols()) && StringUtils.isNotEmpty(getExport())) {
Map<String, Integer> exportMap = ConfigUtil.parseExport(export);
if (!exportMap.isEmpty()) {
List<ProtocolConfig> protos = new ArrayList<ProtocolConfig>();
for (String p : exportMap.keySet()) {
ProtocolConfig proto = null;
try {
proto = beanFactory.getBean(p, ProtocolConfig.class);
} catch (NoSuchBeanDefinitionException e) {
}
if (proto == null) {
if (MotanConstants.PROTOCOL_MOTAN.equals(p)) {
proto = MotanFrameworkUtil.getDefaultProtocolConfig();
} else {
throw new MotanFrameworkException(String.format("cann't find %s ProtocolConfig bean! export:%s", p, export),
MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
}
protos.add(proto);
}
setProtocols(protos);
}
}
if (StringUtils.isEmpty(getExport()) || CollectionUtil.isEmpty(getProtocols())) {
throw new MotanFrameworkException(String.format("%s ServiceConfig must config right export value!", getInterface().getName()),
MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
| 927
| 446
| 1,373
|
<methods>public non-sealed void <init>() ,public synchronized void export() ,public com.weibo.api.motan.config.BasicServiceInterfaceConfig getBasicService() ,public static ConcurrentHashSet<java.lang.String> getExistingServices() ,public java.util.concurrent.atomic.AtomicBoolean getExported() ,public List<Exporter<T>> getExporters() ,public java.lang.String getHost() ,public Class<?> getInterface() ,public List<com.weibo.api.motan.config.MethodConfig> getMethods() ,public Map<java.lang.String,java.lang.Integer> getProtocolAndPort() ,public T getRef() ,public boolean hasMethods() ,public void setBasicService(com.weibo.api.motan.config.BasicServiceInterfaceConfig) ,public void setInterface(Class<T>) ,public void setMethods(com.weibo.api.motan.config.MethodConfig) ,public void setMethods(List<com.weibo.api.motan.config.MethodConfig>) ,public void setRef(T) ,public synchronized void unexport() <variables>private com.weibo.api.motan.config.BasicServiceInterfaceConfig basicService,private static final ConcurrentHashSet<java.lang.String> existingServices,private final java.util.concurrent.atomic.AtomicBoolean exported,private final List<Exporter<T>> exporters,private Class<T> interfaceClass,protected List<com.weibo.api.motan.config.MethodConfig> methods,private T ref,private static final long serialVersionUID
|
weibocom_motan
|
motan/motan-springsupport/src/main/java/com/weibo/api/motan/config/springsupport/util/SpringBeanUtil.java
|
SpringBeanUtil
|
getMultiBeans
|
class SpringBeanUtil {
public static final String COMMA_SPLIT_PATTERN = "\\s*[,]+\\s*";
public static <T> List<T> getMultiBeans(BeanFactory beanFactory, String names, String pattern, Class<T> clazz) {<FILL_FUNCTION_BODY>}
public static void addRegistryParamBean(RegistryConfig registryConfig, BeanFactory beanFactory) {
if (registryConfig.getProxyRegistry() == null) {
Map<String, String> addressParams = registryConfig.getAddressParams();
String proxyRegistryId = addressParams.get(URLParamType.proxyRegistryId);
if (StringUtils.isNotBlank(proxyRegistryId)) {
String identity = registryConfig.getId() + "-" + registryConfig.getName();
RegistryConfig proxyRegistry = beanFactory.getBean(proxyRegistryId, RegistryConfig.class);
if (proxyRegistry != null) {
registryConfig.setProxyRegistry(proxyRegistry);
LoggerUtil.info("add proxy registry bean by address params. proxyRegistryId:" + proxyRegistryId + ", RegistryConfig:" + identity);
} else {
LoggerUtil.warn("proxy registry bean not found. proxyRegistryId:" + proxyRegistryId + ", RegistryConfig:" + identity);
}
}
}
}
}
|
String[] nameArr = names.split(pattern);
List<T> beans = new ArrayList<T>();
for (String name : nameArr) {
if (name != null && name.length() > 0) {
beans.add(beanFactory.getBean(name, clazz));
}
}
return beans;
| 326
| 88
| 414
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyChannel.java
|
NettyChannel
|
request
|
class NettyChannel implements com.weibo.api.motan.transport.Channel {
private volatile ChannelState state = ChannelState.UNINIT;
private NettyClient nettyClient;
private org.jboss.netty.channel.Channel channel = null;
private InetSocketAddress remoteAddress;
private InetSocketAddress localAddress = null;
public NettyChannel(NettyClient nettyClient) {
this.nettyClient = nettyClient;
this.remoteAddress = new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort());
}
@Override
public Response request(Request request) throws TransportException {<FILL_FUNCTION_BODY>}
@Override
public boolean open() {
if (isAvailable()) {
LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: "
+ nettyClient.getUrl().getUri());
return true;
}
ChannelFuture channelFuture = null;
try {
synchronized (this) {
channelFuture = nettyClient.getBootstrap().connect(
new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));
long start = System.currentTimeMillis();
int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
if (timeout <= 0) {
throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.",
MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
// 不去依赖于connectTimeout
boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
boolean success = channelFuture.isSuccess();
if (result && success) {
channel = channelFuture.getChannel();
if (channel.getLocalAddress() != null && channel.getLocalAddress() instanceof InetSocketAddress) {
localAddress = (InetSocketAddress) channel.getLocalAddress();
}
state = ChannelState.ALIVE;
return true;
}
boolean connected = false;
if (channelFuture.getChannel() != null) {
connected = channelFuture.getChannel().isConnected();
}
if (channelFuture.getCause() != null) {
channelFuture.cancel();
throw new MotanServiceException("NettyChannel failed to connect to server, url: "
+ nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.getCause());
} else {
channelFuture.cancel();
throw new MotanServiceException("NettyChannel connect to server timeout url: "
+ nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected, false);
}
}
} catch (MotanServiceException e) {
throw e;
} catch (Exception e) {
if (channelFuture != null) {
channelFuture.getChannel().close();
}
throw new MotanServiceException("NettyChannel failed to connect to server, url: "
+ nettyClient.getUrl().getUri(), e);
} finally {
if (!state.isAliveState()) {
nettyClient.incrErrorCount(2, false); // 为避免死锁,client错误计数方法需在同步块外调用。
}
}
}
@Override
public synchronized void close() {
close(0);
}
@Override
public synchronized void close(int timeout) {
try {
state = ChannelState.CLOSE;
if (channel != null) {
channel.close();
}
} catch (Exception e) {
LoggerUtil.error("NettyChannel close Error: " + nettyClient.getUrl().getUri() + " local=" + localAddress, e);
}
}
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public boolean isClosed() {
return state.isCloseState();
}
@Override
public boolean isAvailable() {
return state.isAliveState() && channel != null && channel.isConnected();
}
@Override
public URL getUrl() {
return nettyClient.getUrl();
}
}
|
int timeout = 0;
if (request.getAttachments().get(MotanConstants.M2_TIMEOUT) != null) { // timeout from request
timeout = MathUtil.parseInt(request.getAttachments().get(MotanConstants.M2_TIMEOUT), 0);
}
if (timeout == 0) { // timeout from url
timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
}
if (timeout <= 0) {
throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.",
MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
ResponseFuture response = new DefaultResponseFuture(request, timeout, this.nettyClient.getUrl());
this.nettyClient.registerCallback(request.getRequestId(), response);
ChannelFuture writeFuture = this.channel.write(request);
boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
if (result && writeFuture.isSuccess()) {
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_CSEND, System.currentTimeMillis());
response.addListener(future -> {
if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
// 成功的调用
nettyClient.resetErrorCount();
} else {
// 失败的调用
nettyClient.incrErrorCount(future.getException());
}
});
return response;
}
writeFuture.cancel();
response = this.nettyClient.removeCallback(request.getRequestId());
if (response != null) {
response.cancel();
}
// 失败的调用
nettyClient.incrErrorCount(null);
if (writeFuture.getCause() != null) {
throw new MotanServiceException("NettyChannel send request to server Error: url="
+ nettyClient.getUrl().getUri() + " local=" + localAddress + " "
+ MotanFrameworkUtil.toString(request), writeFuture.getCause());
} else {
throw new MotanServiceException("NettyChannel send request to server Timeout: url="
+ nettyClient.getUrl().getUri() + " local=" + localAddress + " "
+ MotanFrameworkUtil.toString(request), false);
}
| 1,199
| 648
| 1,847
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyChannelFactory.java
|
NettyChannelFactory
|
activateObject
|
class NettyChannelFactory extends BasePoolableObjectFactory {
private String factoryName;
private NettyClient nettyClient;
public NettyChannelFactory(NettyClient nettyClient) {
super();
this.nettyClient = nettyClient;
this.factoryName = "NettyChannelFactory_" + nettyClient.getUrl().getHost() + "_"
+ nettyClient.getUrl().getPort();
}
public String getFactoryName() {
return factoryName;
}
@Override
public String toString() {
return factoryName;
}
@Override
public Object makeObject() {
NettyChannel nettyChannel = new NettyChannel(nettyClient);
nettyChannel.open();
return nettyChannel;
}
@Override
public void destroyObject(final Object obj) {
if (obj instanceof NettyChannel) {
NettyChannel client = (NettyChannel) obj;
URL url = nettyClient.getUrl();
try {
client.close();
LoggerUtil.info(factoryName + " client disconnect Success: " + url.getUri());
} catch (Exception e) {
LoggerUtil.error(factoryName + " client disconnect Error: " + url.getUri(), e);
}
}
}
@Override
public boolean validateObject(final Object obj) {
if (obj instanceof NettyChannel) {
final NettyChannel client = (NettyChannel) obj;
try {
return client.isAvailable();
} catch (final Exception e) {
return false;
}
} else {
return false;
}
}
@Override
public void activateObject(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj instanceof NettyChannel) {
final NettyChannel client = (NettyChannel) obj;
if (!client.isAvailable()) {
client.open();
}
}
| 450
| 51
| 501
|
<methods>public void <init>() ,public void activateObject(java.lang.Object) throws java.lang.Exception,public void destroyObject(java.lang.Object) throws java.lang.Exception,public abstract java.lang.Object makeObject() throws java.lang.Exception,public void passivateObject(java.lang.Object) throws java.lang.Exception,public boolean validateObject(java.lang.Object) <variables>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyChannelHandler.java
|
NettyChannelHandler
|
exceptionCaught
|
class NettyChannelHandler extends SimpleChannelHandler implements StatisticCallback {
private ThreadPoolExecutor threadPoolExecutor;
private MessageHandler messageHandler;
private Channel serverChannel;
private AtomicInteger rejectCounter = new AtomicInteger(0);
public NettyChannelHandler(Channel serverChannel) {
this.serverChannel = serverChannel;
}
public NettyChannelHandler(Channel serverChannel, MessageHandler messageHandler) {
this.serverChannel = serverChannel;
this.messageHandler = messageHandler;
}
public NettyChannelHandler(Channel serverChannel, MessageHandler messageHandler,
ThreadPoolExecutor threadPoolExecutor) {
this.serverChannel = serverChannel;
this.messageHandler = messageHandler;
this.threadPoolExecutor = threadPoolExecutor;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
LoggerUtil.info("NettyChannelHandler channelConnected: remote=" + ctx.getChannel().getRemoteAddress()
+ " local=" + ctx.getChannel().getLocalAddress() + " event=" + e.getClass().getSimpleName());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
LoggerUtil.info("NettyChannelHandler channelDisconnected: remote=" + ctx.getChannel().getRemoteAddress()
+ " local=" + ctx.getChannel().getLocalAddress() + " event=" + e.getClass().getSimpleName());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Object message = e.getMessage();
if (message instanceof Request) {
processRequest(ctx, e);
} else if (message instanceof Response) {
processResponse(ctx, e);
} else {
LoggerUtil.error("NettyChannelHandler messageReceived type not support: class=" + message.getClass());
throw new MotanFrameworkException("NettyChannelHandler messageReceived type not support: class=" + message.getClass());
}
}
/**
* <pre>
* request process: 主要来自于client的请求,需要使用threadPoolExecutor进行处理,避免service message处理比较慢导致ioThread被阻塞
* </pre>
*/
private void processRequest(final ChannelHandlerContext ctx, MessageEvent e) {
final Request request = (Request) e.getMessage();
request.setAttachment(URLParamType.host.getName(), NetUtils.getHostName(ctx.getChannel().getRemoteAddress()));
final long processStartTime = System.currentTimeMillis();
// 使用线程池方式处理
try {
threadPoolExecutor.execute(() -> {
try {
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_SEXECUTOR_START);
RpcContext.init(request);
processRequest(ctx, request, processStartTime);
} finally {
RpcContext.destroy();
}
});
} catch (RejectedExecutionException rejectException) {
DefaultResponse response = MotanFrameworkUtil.buildErrorResponse(request, new MotanServiceException("process thread pool is full, reject",
MotanErrorMsgConstant.SERVICE_REJECT, false));
response.setProcessTime(System.currentTimeMillis() - processStartTime);
e.getChannel().write(response);
LoggerUtil.warn("process thread pool is full, reject, active={} poolSize={} corePoolSize={} maxPoolSize={} taskCount={} requestId={}",
threadPoolExecutor.getActiveCount(), threadPoolExecutor.getPoolSize(),
threadPoolExecutor.getCorePoolSize(), threadPoolExecutor.getMaximumPoolSize(),
threadPoolExecutor.getTaskCount(), request.getRequestId());
rejectCounter.incrementAndGet();
}
}
private void processRequest(final ChannelHandlerContext ctx, final Request request, long processStartTime) {
Object result;
try {
result = messageHandler.handle(serverChannel, request);
} catch (Exception e) {
LoggerUtil.error("NettyChannelHandler processRequest fail!request:" + MotanFrameworkUtil.toString(request), e);
result = MotanFrameworkUtil.buildErrorResponse(request, new MotanServiceException("process request fail. errMsg:" + e.getMessage()));
}
if (result instanceof ResponseFuture) {
processAsyncResult(ctx, (ResponseFuture) result, request, processStartTime);
} else {
DefaultResponse response;
if (result instanceof DefaultResponse) {
response = (DefaultResponse) result;
} else {
response = new DefaultResponse(result);
}
processResult(ctx, response, request, processStartTime);
}
}
private void processResult(final ChannelHandlerContext ctx, final DefaultResponse response, final Request request, final long processStartTime) {
MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_PROCESS);
response.setSerializeNumber(request.getSerializeNumber());
response.setRpcProtocolVersion(request.getRpcProtocolVersion());
response.setRequestId(request.getRequestId());
response.setProcessTime(System.currentTimeMillis() - processStartTime);
ChannelFuture channelFuture = null;
if (ctx.getChannel().isConnected()) {
channelFuture = ctx.getChannel().write(response);
}
if (channelFuture != null) {
channelFuture.addListener(future -> {
MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_SSEND, System.currentTimeMillis());
response.onFinish();
});
} else { // execute the onFinish method of response if write fail
response.onFinish();
}
}
private void processAsyncResult(final ChannelHandlerContext ctx, final ResponseFuture responseFuture, final Request request, final long processStartTime) {
responseFuture.addListener((future) -> processResult(ctx, DefaultResponse.fromServerEndResponseFuture(responseFuture), request, processStartTime));
}
private void processResponse(ChannelHandlerContext ctx, MessageEvent e) {
messageHandler.handle(serverChannel, e.getMessage());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public String statisticCallback() {
int count = rejectCounter.getAndSet(0);
if (count > 0) {
return String.format("type: motan name: reject_request_pool total_count: %s reject_count: %s", threadPoolExecutor.getPoolSize(), count);
} else {
return null;
}
}
}
|
LoggerUtil.error("NettyChannelHandler exceptionCaught: remote=" + ctx.getChannel().getRemoteAddress()
+ " local=" + ctx.getChannel().getLocalAddress() + " event=" + e.getCause(), e.getCause());
ctx.getChannel().close();
| 1,661
| 77
| 1,738
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyDecoder.java
|
NettyDecoder
|
decode
|
class NettyDecoder extends FrameDecoder {
private Codec codec;
private com.weibo.api.motan.transport.Channel client;
private int maxContentLength = 0;
public NettyDecoder(Codec codec, com.weibo.api.motan.transport.Channel client, int maxContentLength) {
this.codec = codec;
this.client = client;
this.maxContentLength = maxContentLength;
}
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {<FILL_FUNCTION_BODY>}
private Object decodeV2(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
buffer.resetReaderIndex();
if (buffer.readableBytes() < 21) {
return null;
}
buffer.skipBytes(2);
boolean isRequest = isV2Request(buffer.readByte());
buffer.skipBytes(2);
long requestId = buffer.readLong();
int size = 13;
int metasize = buffer.readInt();
size += 4;
if (metasize > 0) {
size += metasize;
if (buffer.readableBytes() < metasize) {
buffer.resetReaderIndex();
return null;
}
buffer.skipBytes(metasize);
}
if (buffer.readableBytes() < 4) {
buffer.resetReaderIndex();
return null;
}
int bodysize = buffer.readInt();
checkMaxContext(bodysize, ctx, channel, isRequest, requestId, RpcProtocolVersion.VERSION_2);
size += 4;
if (bodysize > 0) {
size += bodysize;
if (buffer.readableBytes() < bodysize) {
buffer.resetReaderIndex();
return null;
}
}
byte[] data = new byte[size];
buffer.resetReaderIndex();
buffer.readBytes(data);
return decode(data, channel, isRequest, requestId, RpcProtocolVersion.VERSION_2);
}
private boolean isV2Request(byte b) {
return (b & 0x01) == 0x00;
}
private Object decodeV1(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
buffer.resetReaderIndex();
buffer.skipBytes(2);// skip magic num
byte messageType = (byte) buffer.readShort();
long requestId = buffer.readLong();
int dataLength = buffer.readInt();
// FIXME 如果dataLength过大,可能导致问题
if (buffer.readableBytes() < dataLength) {
buffer.resetReaderIndex();
return null;
}
checkMaxContext(dataLength, ctx, channel, messageType == MotanConstants.FLAG_REQUEST, requestId, RpcProtocolVersion.VERSION_1);
byte[] data = new byte[dataLength];
buffer.readBytes(data);
return decode(data, channel, messageType == MotanConstants.FLAG_REQUEST, requestId, RpcProtocolVersion.VERSION_1);
}
private void checkMaxContext(int dataLength, ChannelHandlerContext ctx, Channel channel, boolean isRequest, long requestId, RpcProtocolVersion version) throws Exception {
if (maxContentLength > 0 && dataLength > maxContentLength) {
LoggerUtil.warn("NettyDecoder transport data content length over of limit, size: {} > {}. remote={} local={}",
dataLength, maxContentLength, ctx.getChannel().getRemoteAddress(), ctx.getChannel().getLocalAddress());
Exception e = new MotanServiceException("NettyDecoder transport data content length over of limit, size: " + dataLength + " > " + maxContentLength);
if (isRequest) {
Response response = MotanFrameworkUtil.buildErrorResponse(requestId, version.getVersion(), e);
channel.write(response);
throw e;
} else {
throw e;
}
}
}
private Object decode(byte[] data, Channel channel, boolean isRequest, long requestId, RpcProtocolVersion version) {
String remoteIp = getRemoteIp(channel);
try {
return codec.decode(client, remoteIp, data);
} catch (Exception e) {
LoggerUtil.error("NettyDecoder decode fail! requestid=" + requestId + ", size:" + data.length + ", ip:" + remoteIp + ", e:" + e.getMessage());
if (isRequest) {
Response response = MotanFrameworkUtil.buildErrorResponse(requestId, version.getVersion(), e);
channel.write(response);
return null;
} else {
return MotanFrameworkUtil.buildErrorResponse(requestId, version.getVersion(), e);
}
}
}
private String getRemoteIp(Channel channel) {
String ip = "";
SocketAddress remote = channel.getRemoteAddress();
if (remote != null) {
try {
ip = ((InetSocketAddress) remote).getAddress().getHostAddress();
} catch (Exception e) {
LoggerUtil.warn("get remoteIp error!dedault will use. msg:" + e.getMessage() + ", remote:" + remote.toString());
}
}
return ip;
}
}
|
//根据版本号决定走哪个分支
if (buffer.readableBytes() <= MotanConstants.NETTY_HEADER) {
return null;
}
buffer.markReaderIndex();
int startIndex = buffer.readerIndex();
short type = buffer.readShort();
if (type != MotanConstants.NETTY_MAGIC_TYPE) {
buffer.resetReaderIndex();
throw new MotanFrameworkException("NettyDecoder transport header not support, type: " + type);
}
long requestStart = System.currentTimeMillis();
buffer.skipBytes(1);
int rpcVersion = (buffer.readByte() & 0xff) >>> 3;
Object result;
switch (rpcVersion) {
case 0:
result = decodeV1(ctx, channel, buffer);
break;
case 1:
result = decodeV2(ctx, channel, buffer);
break;
default:
result = decodeV2(ctx, channel, buffer);
}
if (result instanceof Request) {
Request request = (Request) result;
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_SRECEIVE, requestStart);
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_SDECODE);
request.setAttachment(MotanConstants.CONTENT_LENGTH, String.valueOf(buffer.readerIndex() - startIndex));
} else if (result instanceof Response) {
Response response = (Response) result;
MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_CRECEIVE, requestStart);
MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_CDECODE);
response.setAttachment(MotanConstants.CONTENT_LENGTH, String.valueOf(buffer.readerIndex() - startIndex));
}
return result;
| 1,345
| 475
| 1,820
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyEncoder.java
|
NettyEncoder
|
getType
|
class NettyEncoder extends OneToOneEncoder {
private Codec codec;
private com.weibo.api.motan.transport.Channel client;
public NettyEncoder(Codec codec, com.weibo.api.motan.transport.Channel client) {
this.codec = codec;
this.client = client;
}
@Override
protected Object encode(ChannelHandlerContext ctx, Channel nettyChannel, Object message) throws Exception {
byte[] data = encodeMessage(message);
ChannelBuffer channelBuffer;
short type = ByteUtil.bytes2short(data, 0);
if (type == DefaultRpcCodec.MAGIC) {
channelBuffer = encodeV1(message, data);
} else if (type == MotanV2Header.MAGIC) {
channelBuffer = encodeV2(data);
} else {
throw new MotanFrameworkException("can not encode message, unknown magic:" + type);
}
if (message instanceof Request) {
Request request = (Request) message;
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_CENCODE);
request.setAttachment(MotanConstants.CONTENT_LENGTH, String.valueOf(channelBuffer.readableBytes()));
} else if (message instanceof Response) {
Response response = (Response) message;
MotanFrameworkUtil.logEvent(response, MotanConstants.TRACE_SENCODE);
response.setAttachment(MotanConstants.CONTENT_LENGTH, String.valueOf(channelBuffer.readableBytes()));
}
return channelBuffer;
}
private ChannelBuffer encodeV2(byte[] data) throws Exception {
return ChannelBuffers.wrappedBuffer(data);
}
private ChannelBuffer encodeV1(Object message, byte[] data) throws Exception {
long requestId = getRequestId(message);
byte[] transportHeader = new byte[MotanConstants.NETTY_HEADER];
ByteUtil.short2bytes(MotanConstants.NETTY_MAGIC_TYPE, transportHeader, 0);
transportHeader[3] = getType(message);
ByteUtil.long2bytes(requestId, transportHeader, 4);
ByteUtil.int2bytes(data.length, transportHeader, 12);
return ChannelBuffers.wrappedBuffer(transportHeader, data);
}
private byte[] encodeMessage(Object message) throws IOException {
byte[] data = null;
if (message instanceof Response) {
try {
data = codec.encode(client, message);
} catch (Exception e) {
LoggerUtil.error("NettyEncoder encode error, identity=" + client.getUrl().getIdentity(), e);
long requestId = getRequestId(message);
Response response = MotanFrameworkUtil.buildErrorResponse(requestId, ((Response) message).getRpcProtocolVersion(), e);
data = codec.encode(client, response);
}
} else {
data = codec.encode(client, message);
}
return data;
}
private long getRequestId(Object message) {
if (message instanceof Request) {
return ((Request) message).getRequestId();
} else if (message instanceof Response) {
return ((Response) message).getRequestId();
} else {
return 0;
}
}
private byte getType(Object message) {<FILL_FUNCTION_BODY>}
}
|
if (message instanceof Request) {
return MotanConstants.FLAG_REQUEST;
} else if (message instanceof Response) {
return MotanConstants.FLAG_RESPONSE;
} else {
return MotanConstants.FLAG_OTHER;
}
| 857
| 68
| 925
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyServer.java
|
NettyServer
|
close
|
class NettyServer extends AbstractServer implements StatisticCallback {
// default io thread is Runtime.getRuntime().availableProcessors() * 2
private final static ChannelFactory channelFactory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(new DefaultThreadFactory("nettyServerBoss", true)),
Executors.newCachedThreadPool(new DefaultThreadFactory("nettyServerWorker", true)));
protected NettyServerChannelManage channelManage = null;
// 单端口需要对应单executor 1) 为了更好的隔离性 2) 为了防止被动releaseExternalResources:
private StandardThreadExecutor standardThreadExecutor = null;
private org.jboss.netty.channel.Channel serverChannel;
private ServerBootstrap bootstrap;
private MessageHandler messageHandler;
private NettyChannelHandler nettyChannelHandler;
public NettyServer(URL url, MessageHandler messageHandler) {
super(url);
this.messageHandler = messageHandler;
}
@Override
public Response request(Request request) throws TransportException {
throw new MotanFrameworkException("NettyServer request(Request request) method unSupport: url: " + url);
}
@Override
public synchronized boolean open() {
if (isAvailable()) {
LoggerUtil.warn("NettyServer ServerChannel already Open: url=" + url);
return true;
}
LoggerUtil.info("NettyServer ServerChannel start Open: url=" + url);
initServerBootstrap();
serverChannel = bootstrap.bind(new InetSocketAddress(url.getPort()));
setLocalAddress((InetSocketAddress) serverChannel.getLocalAddress());
if (url.getPort() == 0) {
url.setPort(getLocalAddress().getPort());
}
state = ChannelState.ALIVE;
StatsUtil.registryStatisticCallback(this);
LoggerUtil.info("NettyServer ServerChannel finish Open: url=" + url);
return state.isAliveState();
}
private synchronized void initServerBootstrap() {
boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(),
URLParamType.shareChannel.getBooleanValue());
final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(),
URLParamType.maxContentLength.getIntValue());
int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(),
URLParamType.maxServerConnection.getIntValue());
int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(),
URLParamType.workerQueueSize.getIntValue());
int minWorkerThread, maxWorkerThread;
if (shareChannel) {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(),
MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(),
MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
} else {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(),
MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(),
MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
}
standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor
: new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize,
new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true));
standardThreadExecutor.prestartAllCoreThreads();
// 连接数的管理,进行最大连接数的限制
channelManage = new NettyServerChannelManage(maxServerConnection);
bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
nettyChannelHandler = new NettyChannelHandler(NettyServer.this, messageHandler, standardThreadExecutor);
StatsUtil.registryStatisticCallback(nettyChannelHandler);
// FrameDecoder非线程安全,每个连接一个 Pipeline
bootstrap.setPipelineFactory(() -> {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("channel_manage", channelManage);
pipeline.addLast("decoder", new NettyDecoder(codec, NettyServer.this, maxContentLength));
pipeline.addLast("encoder", new NettyEncoder(codec, NettyServer.this));
pipeline.addLast("nettyChannelHandler", nettyChannelHandler);
return pipeline;
});
}
@Override
public synchronized void close() {
close(0);
}
@Override
public synchronized void close(int timeout) {<FILL_FUNCTION_BODY>}
public void cleanup() {
// close listen socket
if (serverChannel != null) {
serverChannel.close();
}
// close all client's channel
if (channelManage != null) {
channelManage.close();
}
// shutdown the threadPool
if (standardThreadExecutor != null) {
standardThreadExecutor.shutdownNow();
}
// 取消统计回调的注册
StatsUtil.unRegistryStatisticCallback(nettyChannelHandler);
StatsUtil.unRegistryStatisticCallback(this);
}
@Override
public boolean isClosed() {
return state.isCloseState();
}
@Override
public boolean isAvailable() {
return state.isAliveState();
}
@Override
public URL getUrl() {
return url;
}
/**
* 统计回调接口
*/
@Override
public String statisticCallback() {
return String.format(
"identity: %s connectionCount: %s taskCount: %s queueCount: %s maxThreadCount: %s maxTaskCount: %s",
url.getIdentity(), channelManage.getChannels().size(), standardThreadExecutor.getSubmittedTasksCount(),
standardThreadExecutor.getQueue().size(), standardThreadExecutor.getMaximumPoolSize(),
standardThreadExecutor.getMaxSubmittedTaskCount());
}
/**
* 是否已经绑定端口
*/
@Override
public boolean isBound() {
return serverChannel != null && serverChannel.isBound();
}
public MessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(MessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
@Override
public Map<String, Object> getRuntimeInfo() {
Map<String, Object> infos = super.getRuntimeInfo();
infos.put(RuntimeInfoKeys.CONNECTION_COUNT_KEY, channelManage.getChannels().size());
infos.put(RuntimeInfoKeys.TASK_COUNT_KEY, standardThreadExecutor.getSubmittedTasksCount());
infos.putAll(messageHandler.getRuntimeInfo());
return infos;
}
}
|
if (state.isCloseState()) {
return;
}
try {
cleanup();
if (state.isUnInitState()) {
LoggerUtil.info("NettyServer close fail: state={}, url={}", state.value, url.getUri());
return;
}
// 设置close状态
state = ChannelState.CLOSE;
LoggerUtil.info("NettyServer close Success: url={}", url.getUri());
} catch (Exception e) {
LoggerUtil.error("NettyServer close Error: url=" + url.getUri(), e);
}
| 1,849
| 160
| 2,009
|
<methods>public void <init>() ,public void <init>(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.transport.Channel getChannel(java.net.InetSocketAddress) ,public Collection<com.weibo.api.motan.transport.Channel> getChannels() ,public java.net.InetSocketAddress getLocalAddress() ,public java.net.InetSocketAddress getRemoteAddress() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public void setCodec(com.weibo.api.motan.codec.Codec) ,public void setLocalAddress(java.net.InetSocketAddress) ,public void setRemoteAddress(java.net.InetSocketAddress) ,public void setUrl(com.weibo.api.motan.rpc.URL) <variables>protected com.weibo.api.motan.codec.Codec codec,protected java.net.InetSocketAddress localAddress,protected java.net.InetSocketAddress remoteAddress,protected volatile com.weibo.api.motan.common.ChannelState state,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/NettyServerChannelManage.java
|
NettyServerChannelManage
|
getChannelKey
|
class NettyServerChannelManage extends SimpleChannelHandler {
private ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();
private int maxChannel = 0;
public NettyServerChannelManage(int maxChannel) {
super();
this.maxChannel = maxChannel;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Channel channel = ctx.getChannel();
String channelKey = getChannelKey((InetSocketAddress) channel.getLocalAddress(),
(InetSocketAddress) channel.getRemoteAddress());
if (channels.size() > maxChannel) {
// 超过最大连接数限制,直接close连接
LoggerUtil.warn("NettyServerChannelManage channelConnected channel size out of limit: limit={} current={}",
maxChannel, channels.size());
channel.close();
} else {
channels.put(channelKey, channel);
ctx.sendUpstream(e);
}
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Channel channel = ctx.getChannel();
String channelKey = getChannelKey((InetSocketAddress) channel.getLocalAddress(),
(InetSocketAddress) channel.getRemoteAddress());
channels.remove(channelKey);
ctx.sendUpstream(e);
}
public Map<String, Channel> getChannels() {
return channels;
}
/**
* close所有的连接
*/
public void close() {
for (Map.Entry<String, Channel> entry : channels.entrySet()) {
try {
Channel channel = entry.getValue();
if (channel != null) {
channel.close();
}
} catch (Exception e) {
LoggerUtil.error("NettyServerChannelManage close channel Error: " + entry.getKey(), e);
}
}
}
/**
* remote address + local address 作为连接的唯一标示
*
* @param local
* @param remote
* @return
*/
private String getChannelKey(InetSocketAddress local, InetSocketAddress remote) {<FILL_FUNCTION_BODY>}
}
|
String key = "";
if (local == null || local.getAddress() == null) {
key += "null-";
} else {
key += local.getAddress().getHostAddress() + ":" + local.getPort() + "-";
}
if (remote == null || remote.getAddress() == null) {
key += "null";
} else {
key += remote.getAddress().getHostAddress() + ":" + remote.getPort();
}
return key;
| 569
| 132
| 701
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/ProtectedExecutionHandler.java
|
ProtectedExecutionHandler
|
handleUpstream
|
class ProtectedExecutionHandler extends ExecutionHandler {
private ThreadPoolExecutor threadPoolExecutor;
ProtectedExecutionHandler(final ThreadPoolExecutor threadPoolExecutor) {
super(threadPoolExecutor);
this.threadPoolExecutor = threadPoolExecutor;
}
/**
* if RejectedExecutionException happen, send 503 exception to client
*/
@Override
public void handleUpstream(ChannelHandlerContext context, ChannelEvent e) throws Exception {<FILL_FUNCTION_BODY>}
}
|
try {
super.handleUpstream(context, e);
} catch (RejectedExecutionException rejectException) {
if (e instanceof MessageEvent) {
if (((MessageEvent) e).getMessage() instanceof Request) {
Request request = (Request) ((MessageEvent) e).getMessage();
DefaultResponse response = new DefaultResponse();
response.setRequestId(request.getRequestId());
response.setRpcProtocolVersion(request.getRpcProtocolVersion());
response.setException(new MotanServiceException("process thread pool is full, reject",
MotanErrorMsgConstant.SERVICE_REJECT, false));
e.getChannel().write(response);
LoggerUtil
.debug("process thread pool is full, reject, active={} poolSize={} corePoolSize={} maxPoolSize={} taskCount={} requestId={}",
threadPoolExecutor.getActiveCount(), threadPoolExecutor.getPoolSize(),
threadPoolExecutor.getCorePoolSize(), threadPoolExecutor.getMaximumPoolSize(),
threadPoolExecutor.getTaskCount(), request.getRequestId());
}
}
}
| 123
| 285
| 408
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/StandardThreadExecutor.java
|
StandardThreadExecutor
|
execute
|
class StandardThreadExecutor extends ThreadPoolExecutor {
public static final int DEFAULT_MIN_THREADS = 20;
public static final int DEFAULT_MAX_THREADS = 200;
public static final int DEFAULT_MAX_IDLE_TIME = 60 * 1000; // 1 minutes
protected AtomicInteger submittedTasksCount; // 正在处理的任务数
private int maxSubmittedTaskCount; // 最大允许同时处理的任务数
public StandardThreadExecutor() {
this(DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS);
}
public StandardThreadExecutor(int coreThread, int maxThreads) {
this(coreThread, maxThreads, maxThreads);
}
public StandardThreadExecutor(int coreThread, int maxThreads, long keepAliveTime, TimeUnit unit) {
this(coreThread, maxThreads, keepAliveTime, unit, maxThreads);
}
public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity) {
this(coreThreads, maxThreads, queueCapacity, Executors.defaultThreadFactory());
}
public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity, ThreadFactory threadFactory) {
this(coreThreads, maxThreads, DEFAULT_MAX_IDLE_TIME, TimeUnit.MILLISECONDS, queueCapacity, threadFactory);
}
public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit, int queueCapacity) {
this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, Executors.defaultThreadFactory());
}
public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit,
int queueCapacity, ThreadFactory threadFactory) {
this(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, threadFactory, new AbortPolicy());
}
public StandardThreadExecutor(int coreThreads, int maxThreads, long keepAliveTime, TimeUnit unit,
int queueCapacity, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(coreThreads, maxThreads, keepAliveTime, unit, new ExecutorQueue(), threadFactory, handler);
((ExecutorQueue) getQueue()).setStandardThreadExecutor(this);
submittedTasksCount = new AtomicInteger(0);
// 最大并发任务限制: 队列buffer数 + 最大线程数
maxSubmittedTaskCount = queueCapacity + maxThreads;
}
public void execute(Runnable command) {<FILL_FUNCTION_BODY>}
public int getSubmittedTasksCount() {
return this.submittedTasksCount.get();
}
public int getMaxSubmittedTaskCount() {
return maxSubmittedTaskCount;
}
protected void afterExecute(Runnable r, Throwable t) {
submittedTasksCount.decrementAndGet();
}
}
|
int count = submittedTasksCount.incrementAndGet();
// 超过最大的并发任务限制,进行 reject
// 依赖的LinkedTransferQueue没有长度限制,因此这里进行控制
if (count > maxSubmittedTaskCount) {
submittedTasksCount.decrementAndGet();
getRejectedExecutionHandler().rejectedExecution(command, this);
}
try {
super.execute(command);
} catch (RejectedExecutionException rx) {
// there could have been contention around the queue
if (!((ExecutorQueue) getQueue()).force(command)) {
submittedTasksCount.decrementAndGet();
getRejectedExecutionHandler().rejectedExecution(command, this);
}
}
| 741
| 194
| 935
|
<methods>public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.RejectedExecutionHandler) ,public void <init>(int, int, long, java.util.concurrent.TimeUnit, BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler) ,public void allowCoreThreadTimeOut(boolean) ,public boolean allowsCoreThreadTimeOut() ,public boolean awaitTermination(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public void execute(java.lang.Runnable) ,public int getActiveCount() ,public long getCompletedTaskCount() ,public int getCorePoolSize() ,public long getKeepAliveTime(java.util.concurrent.TimeUnit) ,public int getLargestPoolSize() ,public int getMaximumPoolSize() ,public int getPoolSize() ,public BlockingQueue<java.lang.Runnable> getQueue() ,public java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler() ,public long getTaskCount() ,public java.util.concurrent.ThreadFactory getThreadFactory() ,public boolean isShutdown() ,public boolean isTerminated() ,public boolean isTerminating() ,public int prestartAllCoreThreads() ,public boolean prestartCoreThread() ,public void purge() ,public boolean remove(java.lang.Runnable) ,public void setCorePoolSize(int) ,public void setKeepAliveTime(long, java.util.concurrent.TimeUnit) ,public void setMaximumPoolSize(int) ,public void setRejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) ,public void setThreadFactory(java.util.concurrent.ThreadFactory) ,public void shutdown() ,public List<java.lang.Runnable> shutdownNow() ,public java.lang.String toString() <variables>private static final int COUNT_BITS,private static final int COUNT_MASK,private static final boolean ONLY_ONE,private static final int RUNNING,private static final int SHUTDOWN,private static final int STOP,private static final int TERMINATED,private static final int TIDYING,private volatile boolean allowCoreThreadTimeOut,private long completedTaskCount,private volatile int corePoolSize,private final java.util.concurrent.atomic.AtomicInteger ctl,private static final java.util.concurrent.RejectedExecutionHandler defaultHandler,private volatile java.util.concurrent.RejectedExecutionHandler handler,private volatile long keepAliveTime,private int largestPoolSize,private final java.util.concurrent.locks.ReentrantLock mainLock,private volatile int maximumPoolSize,private static final java.lang.RuntimePermission shutdownPerm,private final java.util.concurrent.locks.Condition termination,private volatile java.util.concurrent.ThreadFactory threadFactory,private final BlockingQueue<java.lang.Runnable> workQueue,private final HashSet<java.util.concurrent.ThreadPoolExecutor.Worker> workers
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/admin/AdminHttpServer.java
|
AdminHttpServer
|
open
|
class AdminHttpServer extends AbstractAdminServer {
private final static ChannelFactory channelFactory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(new DefaultThreadFactory("AdminHttpServerBoss", true)),
Executors.newCachedThreadPool(new DefaultThreadFactory("AdminHttpServerWorker", true)));
private StandardThreadExecutor standardThreadExecutor = null;
private Channel serverChannel;
private volatile ChannelState state = ChannelState.UNINIT;
public AdminHttpServer(URL url, AdminHandler adminHandler) {
this.url = url;
this.adminHandler = adminHandler;
}
@Override
public boolean open() {<FILL_FUNCTION_BODY>}
private void processHttpRequest(MessageEvent event) {
HttpResponse httpResponse;
try {
HttpRequest httpRequest = (HttpRequest) event.getMessage();
// set remote ip
httpRequest.setHeader(URLParamType.host.getName(), ((InetSocketAddress) event.getChannel().getRemoteAddress()).getAddress().getHostAddress());
httpResponse = convertHttpResponse(adminHandler.handle(convertRequest(httpRequest)));
} catch (Exception e) {
LoggerUtil.error("AdminHttpServer convert request fail.", e);
httpResponse = buildErrorResponse(AdminUtil.toJsonErrorMessage(e.getMessage()));
}
sendResponse(event.getChannel(), httpResponse);
}
Request convertRequest(HttpRequest httpRequest) {
DefaultRequest request = new DefaultRequest();
Map<String, String> params = new ConcurrentHashMap<>();
// decode path and query params
QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.getUri());
for (Map.Entry<String, List<String>> entry : decoder.getParameters().entrySet()) {
params.put(entry.getKey(), entry.getValue().get(0));
}
request.setMethodName(decoder.getPath());
// decode post form params
decoder = new QueryStringDecoder("?" + httpRequest.getContent().toString(StandardCharsets.UTF_8));
for (Map.Entry<String, List<String>> entry : decoder.getParameters().entrySet()) {
params.put(entry.getKey(), entry.getValue().get(0));
}
request.setArguments(new Object[]{params});
// add headers to attachments
for (Map.Entry<String, String> entry : httpRequest.getHeaders()) {
request.setAttachment(entry.getKey(), entry.getValue());
}
return request;
}
HttpResponse convertHttpResponse(Response response) {
if (response.getException() != null) {
String errMsg;
if (response.getException() instanceof MotanAbstractException) {
errMsg = ((MotanAbstractException) response.getException()).getOriginMessage();
} else {
errMsg = response.getException().getMessage();
}
return buildErrorResponse(errMsg);
}
return buildOkResponse(response.getValue().toString());
}
private HttpResponse buildErrorResponse(String errorMessage) {
return buildHttpResponse(errorMessage.getBytes(StandardCharsets.UTF_8), SERVICE_UNAVAILABLE);
}
private HttpResponse buildOkResponse(String content) {
return buildHttpResponse(content.getBytes(StandardCharsets.UTF_8), OK);
}
private HttpResponse buildHttpResponse(byte[] content, HttpResponseStatus status) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
ChannelBuffer responseBuffer = new DynamicChannelBuffer(content.length);
responseBuffer.writeBytes(content);
response.setContent(responseBuffer);
response.setHeader("Content-Type", "text/html; charset=UTF-8");
response.setHeader("Content-Length", responseBuffer.writerIndex());
return response;
}
private void sendResponse(Channel ch, HttpResponse response) {
try {
ChannelFuture f = ch.write(response);
f.addListener(future -> future.getChannel().close());
} catch (Exception e) {
LoggerUtil.error("AdminHttpServer send response fail.", e);
ch.close();
}
}
@Override
public void close() {
if (state.isCloseState()) {
return;
}
if (serverChannel != null) {
serverChannel.close();
serverChannel = null;
}
if (standardThreadExecutor != null) {
standardThreadExecutor.shutdownNow();
standardThreadExecutor = null;
}
state = ChannelState.CLOSE;
LoggerUtil.info("AdminHttpServer close Success: url={}", url.getUri());
}
}
|
if (state.isAliveState()) {
return true;
}
final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(),
URLParamType.maxContentLength.getIntValue());
standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor
: new StandardThreadExecutor(5, 50, 500,
new DefaultThreadFactory("AdminHttpServer-" + url.getServerPortStr(), true));
standardThreadExecutor.prestartAllCoreThreads();
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setPipelineFactory(() -> {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, maxContentLength));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("nettyChannelHandler", new SimpleChannelUpstreamHandler() {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) {
try {
standardThreadExecutor.execute(() -> processHttpRequest(event));
} catch (Exception e) {
LoggerUtil.error("AdminHttpServer request is rejected by threadPool!", e);
sendResponse(event.getChannel(), buildErrorResponse(AdminUtil.toJsonErrorMessage("request is rejected by thread pool")));
}
}
});
return pipeline;
});
try {
serverChannel = bootstrap.bind(new InetSocketAddress(url.getPort()));
if (url.getPort() == 0) {
url.setPort(((InetSocketAddress) serverChannel.getLocalAddress()).getPort());
}
state = ChannelState.ALIVE;
LoggerUtil.info("AdminHttpServer Open: url=" + url);
return true;
} catch (Exception e) {
LoggerUtil.error("AdminHttpServer Open fail: url=" + url, e);
return false;
}
| 1,179
| 507
| 1,686
|
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.admin.AdminHandler getAdminHandler() ,public com.weibo.api.motan.rpc.URL getUrl() <variables>protected com.weibo.api.motan.admin.AdminHandler adminHandler,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-transport-netty/src/main/java/com/weibo/api/motan/transport/netty/admin/NettyAdminServerFactory.java
|
NettyAdminServerFactory
|
createServer
|
class NettyAdminServerFactory implements AdminServerFactory {
@Override
public AdminServer createServer(URL url, AdminHandler adminHandler) {<FILL_FUNCTION_BODY>}
}
|
if (adminHandler == null) {
throw new MotanFrameworkException("AdminHandler can not be null");
}
String protocol = url.getProtocol();
if ("http".equals(protocol)) {
return new AdminHttpServer(url, adminHandler);
} else if ("motan2".equals(protocol)) {
return new AdminRpcServer(url, adminHandler);
}
throw new MotanFrameworkException("unsupported admin server protocol: " + protocol);
| 51
| 119
| 170
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/CodecUtil.java
|
CodecUtil
|
encodeMessage
|
class CodecUtil {
public static byte[] encodeObjectToBytes(Channel channel, Codec codec, Object msg) {
try {
byte[] data = encodeMessage(channel, codec, msg);
short type = ByteUtil.bytes2short(data, 0);
if (type == DefaultRpcCodec.MAGIC) {
return encodeV1(msg, data);
} else if (type == MotanV2Header.MAGIC) {
return data;
} else {
throw new MotanFrameworkException("can not encode message, unknown magic:" + type);
}
} catch (IOException e) {
throw new MotanFrameworkException("encode error: isResponse=" + (msg instanceof Response), e, MotanErrorMsgConstant.FRAMEWORK_ENCODE_ERROR);
}
}
private static byte[] encodeV1(Object msg, byte[] data) throws IOException {
long requestId = getRequestId(msg);
byte[] result = new byte[MotanConstants.NETTY_HEADER + data.length];
ByteUtil.short2bytes(MotanConstants.NETTY_MAGIC_TYPE, result, 0);
result[3] = getType(msg);
ByteUtil.long2bytes(requestId, result, 4);
ByteUtil.int2bytes(data.length, result, 12);
System.arraycopy(data, 0, result, MotanConstants.NETTY_HEADER, data.length);
return result;
}
private static byte[] encodeMessage(Channel channel, Codec codec, Object msg) throws IOException {<FILL_FUNCTION_BODY>}
private static long getRequestId(Object message) {
if (message instanceof Request) {
return ((Request) message).getRequestId();
} else if (message instanceof Response) {
return ((Response) message).getRequestId();
} else {
return 0;
}
}
private static byte getType(Object message) {
if (message instanceof Request) {
return MotanConstants.FLAG_REQUEST;
} else if (message instanceof Response) {
return MotanConstants.FLAG_RESPONSE;
} else {
return MotanConstants.FLAG_OTHER;
}
}
}
|
byte[] data;
if (msg instanceof Response) {
try {
data = codec.encode(channel, msg);
} catch (Exception e) {
LoggerUtil.error("NettyEncoder encode error, identity=" + channel.getUrl().getIdentity(), e);
Response oriResponse = (Response) msg;
Response response = MotanFrameworkUtil.buildErrorResponse(oriResponse.getRequestId(), oriResponse.getRpcProtocolVersion(), e);
data = codec.encode(channel, response);
}
} else {
data = codec.encode(channel, msg);
}
if (msg instanceof Request) {
MotanFrameworkUtil.logEvent((Request) msg, MotanConstants.TRACE_CENCODE);
} else if (msg instanceof Response) {
MotanFrameworkUtil.logEvent((Response) msg, MotanConstants.TRACE_SENCODE);
}
return data;
| 562
| 233
| 795
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/NettyChannel.java
|
NettyChannel
|
close
|
class NettyChannel implements Channel {
private volatile ChannelState state = ChannelState.UNINIT;
private NettyClient nettyClient;
private io.netty.channel.Channel channel = null;
private InetSocketAddress remoteAddress;
private InetSocketAddress localAddress = null;
private ReentrantLock lock = new ReentrantLock();
private Codec codec;
public NettyChannel(NettyClient nettyClient) {
this.nettyClient = nettyClient;
this.remoteAddress = new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort());
codec = ExtensionLoader.getExtensionLoader(Codec.class).getExtension(nettyClient.getUrl().getParameter(URLParamType.codec.getName(), URLParamType.codec.getValue()));
}
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public Response request(Request request) throws TransportException {
int timeout = 0;
if (request.getAttachments().get(MotanConstants.M2_TIMEOUT) != null) { // timeout from request
timeout = MathUtil.parseInt(request.getAttachments().get(MotanConstants.M2_TIMEOUT), 0);
}
if (timeout == 0) { // timeout from url
timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
}
if (timeout <= 0) {
throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
ResponseFuture response = new DefaultResponseFuture(request, timeout, this.nettyClient.getUrl());
this.nettyClient.registerCallback(request.getRequestId(), response);
byte[] msg = CodecUtil.encodeObjectToBytes(this, codec, request);
ChannelFuture writeFuture = this.channel.writeAndFlush(msg);
request.setAttachment(MotanConstants.CONTENT_LENGTH, String.valueOf(msg.length));
boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
if (result && writeFuture.isSuccess()) {
MotanFrameworkUtil.logEvent(request, MotanConstants.TRACE_CSEND, System.currentTimeMillis());
response.addListener(future -> {
if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
// 成功的调用
nettyClient.resetErrorCount();
} else {
// 失败的调用
nettyClient.incrErrorCount(future.getException());
}
});
return response;
}
writeFuture.cancel(true);
response = this.nettyClient.removeCallback(request.getRequestId());
if (response != null) {
response.cancel();
}
// 失败的调用
nettyClient.incrErrorCount(null);
if (writeFuture.cause() != null) {
throw new MotanServiceException("NettyChannel send request to server Error: url="
+ nettyClient.getUrl().getUri() + " local=" + localAddress + " "
+ MotanFrameworkUtil.toString(request), writeFuture.cause());
} else {
throw new MotanServiceException("NettyChannel send request to server Timeout: url="
+ nettyClient.getUrl().getUri() + " local=" + localAddress + " "
+ MotanFrameworkUtil.toString(request), false);
}
}
@Override
public boolean open() {
if (isAvailable()) {
LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri());
return true;
}
ChannelFuture channelFuture = null;
try {
synchronized (this) {
long start = System.currentTimeMillis();
channelFuture = nettyClient.getBootstrap().connect(remoteAddress);
int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
if (timeout <= 0) {
throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
}
// 不去依赖于connectTimeout
boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
boolean success = channelFuture.isSuccess();
if (result && success) {
channel = channelFuture.channel();
if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) {
localAddress = (InetSocketAddress) channel.localAddress();
}
state = ChannelState.ALIVE;
return true;
}
boolean connected = false;
if (channelFuture.channel() != null) {
connected = channelFuture.channel().isActive();
}
if (channelFuture.cause() != null) {
channelFuture.cancel(true);
throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.cause());
} else {
channelFuture.cancel(true);
throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected, false);
}
}
} catch (MotanServiceException e) {
throw e;
} catch (Exception e) {
if (channelFuture != null) {
channelFuture.channel().close();
}
throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e);
} finally {
if (!state.isAliveState()) {
nettyClient.incrErrorCount(2, false); // 为避免死锁,client错误计数方法需在同步块外调用。
}
}
}
@Override
public synchronized void close() {
close(0);
}
@Override
public synchronized void close(int timeout) {<FILL_FUNCTION_BODY>}
@Override
public boolean isClosed() {
return state.isCloseState();
}
@Override
public boolean isAvailable() {
return state.isAliveState() && channel != null && channel.isActive();
}
public void reconnect() {
state = ChannelState.INIT;
}
public boolean isReconnect() {
return state.isInitState();
}
@Override
public URL getUrl() {
return nettyClient.getUrl();
}
public ReentrantLock getLock() {
return lock;
}
}
|
try {
state = ChannelState.CLOSE;
if (channel != null) {
channel.close();
}
} catch (Exception e) {
LoggerUtil.error("NettyChannel close Error: " + nettyClient.getUrl().getUri() + " local=" + localAddress, e);
}
| 1,871
| 87
| 1,958
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/NettyChannelFactory.java
|
NettyChannelFactory
|
rebuildObject
|
class NettyChannelFactory implements SharedObjectFactory<NettyChannel> {
private static final ExecutorService rebuildExecutorService = new StandardThreadExecutor(5, 30, 10L, TimeUnit.SECONDS, 100,
new DefaultThreadFactory("RebuildExecutorService", true),
new ThreadPoolExecutor.CallerRunsPolicy());
private NettyClient nettyClient;
private String factoryName;
public NettyChannelFactory(NettyClient nettyClient) {
this.nettyClient = nettyClient;
this.factoryName = "NettyChannelFactory_" + nettyClient.getUrl().getHost() + "_" + nettyClient.getUrl().getPort();
}
@Override
public NettyChannel makeObject() {
return new NettyChannel(nettyClient);
}
@Override
public boolean rebuildObject(NettyChannel nettyChannel, boolean async) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return factoryName;
}
class RebuildTask implements Runnable {
private NettyChannel channel;
public RebuildTask(NettyChannel channel) {
this.channel = channel;
}
@Override
public void run() {
try {
channel.getLock().lock();
channel.close();
channel.open();
LoggerUtil.info("rebuild channel success: " + channel.getUrl());
} catch (Exception e) {
LoggerUtil.error("rebuild error: " + this.toString() + ", " + channel.getUrl(), e);
} finally {
channel.getLock().unlock();
}
}
}
}
|
ReentrantLock lock = nettyChannel.getLock();
if (lock.tryLock()) {
try {
if (!nettyChannel.isAvailable() && !nettyChannel.isReconnect()) {
nettyChannel.reconnect();
if (async) {
rebuildExecutorService.submit(new RebuildTask(nettyChannel));
} else {
nettyChannel.close();
nettyChannel.open();
LoggerUtil.info("rebuild channel success: " + nettyChannel.getUrl());
}
}
} catch (Exception e) {
LoggerUtil.error("rebuild error: " + this.toString() + ", " + nettyChannel.getUrl(), e);
} finally {
lock.unlock();
}
return true;
}
return false;
| 423
| 203
| 626
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/NettyDecoder.java
|
NettyDecoder
|
decodeV2
|
class NettyDecoder extends ByteToMessageDecoder {
private Codec codec;
private Channel channel;
private int maxContentLength = 0;
public NettyDecoder(Codec codec, Channel channel, int maxContentLength) {
this.codec = codec;
this.channel = channel;
this.maxContentLength = maxContentLength;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() <= MotanConstants.NETTY_HEADER) {
return;
}
in.markReaderIndex();
short type = in.readShort();
if (type != MotanConstants.NETTY_MAGIC_TYPE) {
in.skipBytes(in.readableBytes());
throw new MotanFrameworkException("NettyDecoder transport header not support, type: " + type);
}
in.skipBytes(1);
int rpcVersion = (in.readByte() & 0xff) >>> 3;
switch (rpcVersion) {
case 0:
decodeV1(ctx, in, out);
break;
case 1:
decodeV2(ctx, in, out);
break;
default:
decodeV2(ctx, in, out);
}
}
private void decodeV2(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
private boolean isV2Request(byte b) {
return (b & 0x01) == 0x00;
}
private void decodeV1(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
long startTime = System.currentTimeMillis();
in.resetReaderIndex();
in.skipBytes(2);// skip magic num
byte messageType = (byte) in.readShort();
long requestId = in.readLong();
int dataLength = in.readInt();
checkMaxContext(dataLength, ctx, in, messageType == MotanConstants.FLAG_REQUEST, requestId, RpcProtocolVersion.VERSION_1);
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] data = new byte[dataLength];
in.readBytes(data);
decode(data, out, messageType == MotanConstants.FLAG_REQUEST, requestId, RpcProtocolVersion.VERSION_1).setStartTime(startTime);
}
private void checkMaxContext(int dataLength, ChannelHandlerContext ctx, ByteBuf byteBuf, boolean isRequest, long requestId, RpcProtocolVersion version) throws Exception {
if (maxContentLength > 0 && dataLength > maxContentLength) {
LoggerUtil.warn("NettyDecoder transport data content length over of limit, size: {} > {}. remote={} local={}",
dataLength, maxContentLength, ctx.channel().remoteAddress(), ctx.channel().localAddress());
// skip all readable Bytes in order to release this no-readable bytebuf in super.channelRead()
// that avoid this.decode() being invoked again after channel.close()
byteBuf.skipBytes(byteBuf.readableBytes());
Exception e = new MotanServiceException("NettyDecoder transport data content length over of limit, size: " + dataLength + " > " + maxContentLength);
if (isRequest) {
Response response = MotanFrameworkUtil.buildErrorResponse(requestId, version.getVersion(), e);
byte[] msg = CodecUtil.encodeObjectToBytes(channel, codec, response);
ctx.channel().writeAndFlush(msg);
throw e;
} else {
throw e;
}
}
}
private NettyMessage decode(byte[] data, List<Object> out, boolean isRequest, long requestId, RpcProtocolVersion version) {
NettyMessage message = new NettyMessage(isRequest, requestId, data, version);
out.add(message);
return message;
}
}
|
long startTime = System.currentTimeMillis();
in.resetReaderIndex();
if (in.readableBytes() < 21) {
return;
}
in.skipBytes(2);
boolean isRequest = isV2Request(in.readByte());
in.skipBytes(2);
long requestId = in.readLong();
int size = 13;
int metaSize = in.readInt();
size += 4;
if (metaSize > 0) {
checkMaxContext(metaSize, ctx, in, isRequest, requestId, RpcProtocolVersion.VERSION_2);
size += metaSize;
if (in.readableBytes() < metaSize) {
in.resetReaderIndex();
return;
}
in.skipBytes(metaSize);
}
if (in.readableBytes() < 4) {
in.resetReaderIndex();
return;
}
int bodySize = in.readInt();
size += 4;
if (bodySize > 0) {
checkMaxContext(bodySize, ctx, in, isRequest, requestId, RpcProtocolVersion.VERSION_2);
size += bodySize;
if (in.readableBytes() < bodySize) {
in.resetReaderIndex();
return;
}
}
byte[] data = new byte[size];
in.resetReaderIndex();
in.readBytes(data);
decode(data, out, isRequest, requestId, RpcProtocolVersion.VERSION_2).setStartTime(startTime);
| 1,024
| 387
| 1,411
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/NettyServer.java
|
NettyServer
|
open
|
class NettyServer extends AbstractServer implements StatisticCallback {
protected NettyServerChannelManage channelManage = null;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private Channel serverChannel;
private MessageHandler messageHandler;
private StandardThreadExecutor standardThreadExecutor = null;
private AtomicInteger rejectCounter = new AtomicInteger(0);
public AtomicInteger getRejectCounter() {
return rejectCounter;
}
public NettyServer(URL url, MessageHandler messageHandler) {
super(url);
this.messageHandler = messageHandler;
}
@Override
public boolean isBound() {
return serverChannel != null && serverChannel.isActive();
}
@Override
public Response request(Request request) throws TransportException {
throw new MotanFrameworkException("NettyServer request(Request request) method not support: url: " + url);
}
@Override
public boolean open() {<FILL_FUNCTION_BODY>}
@Override
public synchronized void close() {
close(0);
}
@Override
public synchronized void close(int timeout) {
if (state.isCloseState()) {
return;
}
try {
cleanup();
if (state.isUnInitState()) {
LoggerUtil.info("NettyServer close fail: state={}, url={}", state.value, url.getUri());
return;
}
// 设置close状态
state = ChannelState.CLOSE;
LoggerUtil.info("NettyServer close Success: url={}", url.getUri());
} catch (Exception e) {
LoggerUtil.error("NettyServer close Error: url=" + url.getUri(), e);
}
}
public void cleanup() {
// close listen socket
if (serverChannel != null) {
serverChannel.close();
}
if (bossGroup != null) {
bossGroup.shutdownGracefully();
bossGroup = null;
}
if (workerGroup != null) {
workerGroup.shutdownGracefully();
workerGroup = null;
}
// close all client's channel
if (channelManage != null) {
channelManage.close();
}
// shutdown the threadPool
if (standardThreadExecutor != null) {
standardThreadExecutor.shutdownNow();
}
// 取消统计回调的注册
StatsUtil.unRegistryStatisticCallback(this);
}
@Override
public boolean isClosed() {
return state.isCloseState();
}
@Override
public boolean isAvailable() {
return state.isAliveState();
}
@Override
public URL getUrl() {
return url;
}
@Override
public String statisticCallback() {
return String.format("identity: %s connectionCount: %s taskCount: %s queueCount: %s maxThreadCount: %s maxTaskCount: %s executorRejectCount: %s",
url.getIdentity(), channelManage.getChannels().size(), standardThreadExecutor.getSubmittedTasksCount(),
standardThreadExecutor.getQueue().size(), standardThreadExecutor.getMaximumPoolSize(),
standardThreadExecutor.getMaxSubmittedTaskCount(), rejectCounter.getAndSet(0));
}
@Override
public Map<String, Object> getRuntimeInfo() {
Map<String, Object> infos = super.getRuntimeInfo();
infos.put(RuntimeInfoKeys.CONNECTION_COUNT_KEY, channelManage.getChannels().size());
infos.put(RuntimeInfoKeys.TASK_COUNT_KEY, standardThreadExecutor.getSubmittedTasksCount());
infos.putAll(messageHandler.getRuntimeInfo());
return infos;
}
}
|
if (isAvailable()) {
LoggerUtil.warn("NettyServer ServerChannel already Open: url=" + url);
return state.isAliveState();
}
if (bossGroup == null) {
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
}
LoggerUtil.info("NettyServer ServerChannel start Open: url=" + url);
boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue());
int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), URLParamType.workerQueueSize.getIntValue());
int minWorkerThread, maxWorkerThread;
if (shareChannel) {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
} else {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
}
standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor
: new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true));
standardThreadExecutor.prestartAllCoreThreads();
channelManage = new NettyServerChannelManage(maxServerConnection);
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("channel_manage", channelManage);
pipeline.addLast("decoder", new NettyDecoder(codec, NettyServer.this, maxContentLength));
pipeline.addLast("encoder", new NettyEncoder());
NettyChannelHandler handler = new NettyChannelHandler(NettyServer.this, messageHandler, standardThreadExecutor);
pipeline.addLast("handler", handler);
}
});
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(url.getPort()));
channelFuture.syncUninterruptibly();
serverChannel = channelFuture.channel();
setLocalAddress((InetSocketAddress) serverChannel.localAddress());
if (url.getPort() == 0) {
url.setPort(getLocalAddress().getPort());
}
state = ChannelState.ALIVE;
StatsUtil.registryStatisticCallback(this);
LoggerUtil.info("NettyServer ServerChannel finish Open: url=" + url);
return state.isAliveState();
| 968
| 942
| 1,910
|
<methods>public void <init>() ,public void <init>(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.transport.Channel getChannel(java.net.InetSocketAddress) ,public Collection<com.weibo.api.motan.transport.Channel> getChannels() ,public java.net.InetSocketAddress getLocalAddress() ,public java.net.InetSocketAddress getRemoteAddress() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public void setCodec(com.weibo.api.motan.codec.Codec) ,public void setLocalAddress(java.net.InetSocketAddress) ,public void setRemoteAddress(java.net.InetSocketAddress) ,public void setUrl(com.weibo.api.motan.rpc.URL) <variables>protected com.weibo.api.motan.codec.Codec codec,protected java.net.InetSocketAddress localAddress,protected java.net.InetSocketAddress remoteAddress,protected volatile com.weibo.api.motan.common.ChannelState state,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/NettyServerChannelManage.java
|
NettyServerChannelManage
|
close
|
class NettyServerChannelManage extends ChannelInboundHandlerAdapter {
private ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<>();
private int maxChannel;
public NettyServerChannelManage(int maxChannel) {
super();
this.maxChannel = maxChannel;
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
if (channels.size() >= maxChannel) {
// 超过最大连接数限制,直接close连接
LoggerUtil.warn("NettyServerChannelManage channelConnected channel size out of limit: limit={} current={}", maxChannel, channels.size());
channel.close();
} else {
String channelKey = getChannelKey((InetSocketAddress) channel.localAddress(), (InetSocketAddress) channel.remoteAddress());
channels.put(channelKey, channel);
ctx.fireChannelRegistered();
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
String channelKey = getChannelKey((InetSocketAddress) channel.localAddress(), (InetSocketAddress) channel.remoteAddress());
channels.remove(channelKey);
ctx.fireChannelUnregistered();
}
public Map<String, Channel> getChannels() {
return channels;
}
/**
* close所有的连接
*/
public void close() {<FILL_FUNCTION_BODY>}
/**
* remote address + local address 作为连接的唯一标示
*
* @param local
* @param remote
* @return
*/
private String getChannelKey(InetSocketAddress local, InetSocketAddress remote) {
String key = "";
if (local == null || local.getAddress() == null) {
key += "null-";
} else {
key += local.getAddress().getHostAddress() + ":" + local.getPort() + "-";
}
if (remote == null || remote.getAddress() == null) {
key += "null";
} else {
key += remote.getAddress().getHostAddress() + ":" + remote.getPort();
}
return key;
}
}
|
for (Map.Entry<String, Channel> entry : channels.entrySet()) {
try {
Channel channel = entry.getValue();
if (channel != null) {
channel.close();
}
} catch (Exception e) {
LoggerUtil.error("NettyServerChannelManage close channel Error: " + entry.getKey(), e);
}
}
| 570
| 97
| 667
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/admin/AdminHttpServer.java
|
AdminHttpServer
|
convertRequest
|
class AdminHttpServer extends AbstractAdminServer {
private final Netty4HttpServer httpServer;
public AdminHttpServer(URL url, AdminHandler adminHandler) {
this.url = url;
this.adminHandler = adminHandler;
httpServer = new Netty4HttpServer(url, (channel, httpRequest) -> {
FullHttpResponse httpResponse;
try {
httpResponse = convertHttpResponse(adminHandler.handle(convertRequest(httpRequest)));
} catch (Exception e) {
httpResponse = NettyHttpUtil.buildErrorResponse(AdminUtil.toJsonErrorMessage(e.getMessage()));
}
return httpResponse;
});
}
private Request convertRequest(FullHttpRequest httpRequest) throws IOException {<FILL_FUNCTION_BODY>}
private FullHttpResponse convertHttpResponse(Response response) {
if (response.getException() != null) {
String errMsg;
if (response.getException() instanceof MotanAbstractException) {
errMsg = ((MotanAbstractException) response.getException()).getOriginMessage();
} else {
errMsg = response.getException().getMessage();
}
return NettyHttpUtil.buildErrorResponse(errMsg);
}
return NettyHttpUtil.buildResponse(response.getValue().toString());
}
@Override
public boolean open() {
return httpServer.open();
}
@Override
public void close() {
httpServer.close();
}
}
|
DefaultRequest request = new DefaultRequest();
Map<String, String> params = new ConcurrentHashMap<>();
// add headers to attachments
for (Map.Entry<String, String> entry : httpRequest.headers()) {
request.setAttachment(entry.getKey(), entry.getValue());
}
// add method and query params
request.setMethodName(NettyHttpUtil.addQueryParams(httpRequest.uri(), params));
// add post params
NettyHttpUtil.addPostParams(httpRequest, params);
request.setArguments(new Object[]{params});
return request;
| 370
| 152
| 522
|
<methods>public non-sealed void <init>() ,public com.weibo.api.motan.admin.AdminHandler getAdminHandler() ,public com.weibo.api.motan.rpc.URL getUrl() <variables>protected com.weibo.api.motan.admin.AdminHandler adminHandler,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/admin/NettyAdminServerFactory.java
|
NettyAdminServerFactory
|
createServer
|
class NettyAdminServerFactory implements AdminServerFactory {
@Override
public AdminServer createServer(URL url, AdminHandler adminHandler) {<FILL_FUNCTION_BODY>}
}
|
if (adminHandler == null) {
throw new MotanFrameworkException("AdminHandler can not be null");
}
String protocol = url.getProtocol();
if ("http".equals(protocol)) {
return new AdminHttpServer(url, adminHandler);
} else if ("motan2".equals(protocol)) {
return new AdminRpcServer(url, adminHandler);
}
throw new MotanFrameworkException("unsupported admin server protocol: " + protocol);
| 51
| 119
| 170
|
<no_super_class>
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/http/Netty4HttpServer.java
|
Netty4HttpServer
|
request
|
class Netty4HttpServer extends AbstractServer implements StatisticCallback {
private HttpMessageHandler httpMessageHandler;
private URL url;
private Channel channel;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private StandardThreadExecutor standardThreadExecutor;
public Netty4HttpServer(URL url, HttpMessageHandler httpMessageHandler) {
this.url = url;
this.httpMessageHandler = httpMessageHandler;
}
@Override
public synchronized boolean open() {
if (isAvailable()) {
return true;
}
if (channel != null) {
channel.close();
}
if (bossGroup == null) {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
}
boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), 500);
int minWorkerThread, maxWorkerThread;
if (shareChannel) {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
} else {
minWorkerThread =
url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread =
url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
}
final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor
: new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true));
standardThreadExecutor.prestartAllCoreThreads();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(maxContentLength));
ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
ch.pipeline().addLast("serverHandler", new SimpleChannelInboundHandler<FullHttpRequest>() {
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest httpRequest) {
httpRequest.content().retain();
try {
standardThreadExecutor.execute(() -> processHttpRequest(ctx, httpRequest));
} catch (Exception e) {
LoggerUtil.error("request is rejected by threadPool!", e);
httpRequest.content().release();
sendResponse(ctx, NettyHttpUtil.buildErrorResponse("request is rejected by thread pool!"));
}
}
});
}
}).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, false);
ChannelFuture f;
try {
f = b.bind(url.getPort()).sync();
channel = f.channel();
} catch (InterruptedException e) {
LoggerUtil.error("init http server fail.", e);
return false;
}
setLocalAddress((InetSocketAddress) channel.localAddress());
if (url.getPort() == 0) {
url.setPort(getLocalAddress().getPort());
}
state = ChannelState.ALIVE;
StatsUtil.registryStatisticCallback(this);
LoggerUtil.info("Netty4HttpServer ServerChannel finish Open: url=" + url);
return true;
}
private void processHttpRequest(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {
FullHttpResponse httpResponse;
try {
httpRequest.headers().set(URLParamType.host.getName(), ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress());
httpResponse = httpMessageHandler.handle(this, httpRequest);
} catch (Exception e) {
LoggerUtil.error("NettyHttpHandler process http request fail.", e);
httpResponse = NettyHttpUtil.buildErrorResponse(e.getMessage());
} finally {
httpRequest.content().release();
}
sendResponse(ctx, httpResponse);
}
private void sendResponse(ChannelHandlerContext ctx, FullHttpResponse httpResponse) {
boolean close = false;
try {
ctx.write(httpResponse);
ctx.flush();
} catch (Exception e) {
LoggerUtil.error("NettyHttpHandler write response fail.", e);
close = true;
} finally {
// close connection
if (close || httpResponse == null || !httpResponse.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true)) {
ctx.close();
}
}
}
@Override
public void close() {
close(0);
}
@Override
public boolean isAvailable() {
return state.isAliveState();
}
@Override
public boolean isBound() {
return channel != null && channel.isActive();
}
@Override
public Response request(Request request) throws TransportException {<FILL_FUNCTION_BODY>}
@Override
public synchronized void close(int timeout) {
if (state.isCloseState()) {
LoggerUtil.info("Netty4HttpServer close fail: already close, url={}", url.getUri());
return;
}
if (state.isUnInitState()) {
LoggerUtil.info("Netty4HttpServer close Fail: don't need to close because node is unInit state: url={}",
url.getUri());
return;
}
if (channel != null) {
channel.close();
}
if (bossGroup != null) {
bossGroup.shutdownGracefully();
}
if (workerGroup != null) {
workerGroup.shutdownGracefully();
}
if (standardThreadExecutor != null) {
standardThreadExecutor.shutdownNow();
}
workerGroup = null;
bossGroup = null;
standardThreadExecutor = null;
channel = null;
state = ChannelState.CLOSE;
StatsUtil.unRegistryStatisticCallback(this);
}
@Override
public boolean isClosed() {
return state.isCloseState();
}
@Override
public String statisticCallback() {
return null;
}
@Override
public URL getUrl() {
return url;
}
}
|
throw new MotanFrameworkException("Netty4HttpServer request(Request request) method unSupport: url: " + url);
| 1,861
| 32
| 1,893
|
<methods>public void <init>() ,public void <init>(com.weibo.api.motan.rpc.URL) ,public com.weibo.api.motan.transport.Channel getChannel(java.net.InetSocketAddress) ,public Collection<com.weibo.api.motan.transport.Channel> getChannels() ,public java.net.InetSocketAddress getLocalAddress() ,public java.net.InetSocketAddress getRemoteAddress() ,public Map<java.lang.String,java.lang.Object> getRuntimeInfo() ,public void setCodec(com.weibo.api.motan.codec.Codec) ,public void setLocalAddress(java.net.InetSocketAddress) ,public void setRemoteAddress(java.net.InetSocketAddress) ,public void setUrl(com.weibo.api.motan.rpc.URL) <variables>protected com.weibo.api.motan.codec.Codec codec,protected java.net.InetSocketAddress localAddress,protected java.net.InetSocketAddress remoteAddress,protected volatile com.weibo.api.motan.common.ChannelState state,protected com.weibo.api.motan.rpc.URL url
|
weibocom_motan
|
motan/motan-transport-netty4/src/main/java/com/weibo/api/motan/transport/netty4/http/NettyHttpUtil.java
|
NettyHttpUtil
|
addPostParams
|
class NettyHttpUtil {
/**
* @param uri request uri
* @param params used to save the parsed parameters
* @return request path from uri
*/
public static String addQueryParams(String uri, Map<String, String> params) {
QueryStringDecoder decoder = new QueryStringDecoder(uri);
// add query params
for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
params.put(entry.getKey(), entry.getValue().get(0));
}
return decoder.path();
}
public static void addPostParams(HttpRequest request, Map<String, String> params) throws IOException {<FILL_FUNCTION_BODY>}
public static FullHttpResponse buildResponse(String msg) {
return buildDefaultResponse(msg, HttpResponseStatus.OK);
}
public static FullHttpResponse buildErrorResponse(String errMsg) {
return buildDefaultResponse(errMsg, HttpResponseStatus.SERVICE_UNAVAILABLE);
}
public static FullHttpResponse buildDefaultResponse(String msg, HttpResponseStatus status) {
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.wrappedBuffer(msg
.getBytes()));
}
}
|
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
List<InterfaceHttpData> postList = decoder.getBodyHttpDatas();
for (InterfaceHttpData data : postList) {
if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
params.put(data.getName(), ((Attribute) data).getString());
}
}
| 320
| 101
| 421
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/AbstractBoxParser.java
|
AbstractBoxParser
|
parseBox
|
class AbstractBoxParser implements BoxParser {
private List<String> skippedTypes;
private static Logger LOG = LoggerFactory.getLogger(AbstractBoxParser.class.getName());
ThreadLocal<ByteBuffer> header = new ThreadLocal<ByteBuffer>() {
@Override
protected ByteBuffer initialValue() {
return ByteBuffer.allocate(32);
}
};
public abstract ParsableBox createBox(String type, byte[] userType, String parent);
/**
* Parses the next size and type, creates a box instance and parses the box's content.
*
* @param byteChannel the DataSource pointing to the ISO file
* @param parentType the current box's parent's type (null if no parent)
* @return the box just parsed
* @throws java.io.IOException if reading from <code>in</code> fails
*/
public ParsableBox parseBox(ReadableByteChannel byteChannel, String parentType) throws IOException {<FILL_FUNCTION_BODY>}
public AbstractBoxParser skippingBoxes(String... types) {
skippedTypes = Arrays.asList(types);
return this;
}
}
|
((Buffer)header.get()).rewind().limit(8);
int bytesRead = 0;
int b;
while ((b = byteChannel.read(header.get())) + bytesRead < 8) {
if (b < 0) {
throw new EOFException();
} else {
bytesRead += b;
}
}
((Buffer)header.get()).rewind();
long size = IsoTypeReader.readUInt32(header.get());
// do plausibility check
if (size < 8 && size > 1) {
LOG.error("Plausibility check failed: size < 8 (size = {}). Stop parsing!", size);
return null;
}
String type = IsoTypeReader.read4cc(header.get());
//System.err.println(type);
byte[] usertype = null;
long contentSize;
if (size == 1) {
header.get().limit(16);
byteChannel.read(header.get());
header.get().position(8);
size = IsoTypeReader.readUInt64(header.get());
contentSize = size - 16;
} else if (size == 0) {
throw new RuntimeException("box size of zero means 'till end of file. That is not yet supported");
} else {
contentSize = size - 8;
}
if (UserBox.TYPE.equals(type)) {
header.get().limit(header.get().limit() + 16);
byteChannel.read(header.get());
usertype = new byte[16];
for (int i = header.get().position() - 16; i < header.get().position(); i++) {
usertype[i - (header.get().position() - 16)] = header.get().get(i);
}
contentSize -= 16;
}
ParsableBox parsableBox = null;
if( skippedTypes != null && skippedTypes.contains(type) ) {
LOG.trace("Skipping box {} {} {}", type, usertype, parentType);
parsableBox = new SkipBox(type, usertype, parentType);
}
else {
LOG.trace("Creating box {} {} {}", type, usertype, parentType);
parsableBox = createBox(type, usertype, parentType);
}
//LOG.finest("Parsing " + box.getType());
// System.out.println("parsing " + Mp4Arrays.toString(box.getType()) + " " + box.getClass().getName() + " size=" + size);
((Buffer)header.get()).rewind();
parsableBox.parse(byteChannel, header.get(), contentSize, this);
return parsableBox;
| 300
| 714
| 1,014
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/BasicContainer.java
|
BasicContainer
|
getBoxes
|
class BasicContainer implements Container {
private List<Box> boxes = new ArrayList<Box>();
public BasicContainer() {
}
public BasicContainer(List<Box> boxes) {
this.boxes = boxes;
}
public List<Box> getBoxes() {
return boxes;
}
public void setBoxes(List<? extends Box> boxes) {
this.boxes = new ArrayList<Box>(boxes);
}
protected long getContainerSize() {
long contentSize = 0;
for (int i = 0; i < getBoxes().size(); i++) {
// it's quicker to iterate an array list like that since no iterator
// needs to be instantiated
contentSize += boxes.get(i).getSize();
}
return contentSize;
}
@SuppressWarnings("unchecked")
public <T extends Box> List<T> getBoxes(Class<T> clazz) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public <T extends Box> List<T> getBoxes(Class<T> clazz, boolean recursive) {
List<T> boxesToBeReturned = new ArrayList<T>(2);
List<Box> boxes = getBoxes();
for (int i = 0; i < boxes.size(); i++) {
Box boxe = boxes.get(i);
//clazz.isInstance(boxe) / clazz == boxe.getClass()?
// I hereby finally decide to use isInstance
if (clazz.isInstance(boxe)) {
boxesToBeReturned.add((T) boxe);
}
if (recursive && boxe instanceof Container) {
boxesToBeReturned.addAll(((Container) boxe).getBoxes(clazz, recursive));
}
}
return boxesToBeReturned;
}
/**
* Add <code>box</code> to the container and sets the parent correctly. If <code>box</code> is <code>null</code>
* nochange will be performed and no error thrown.
*
* @param box will be added to the container
*/
public void addBox(Box box) {
if (box != null) {
boxes = new ArrayList<Box>(getBoxes());
boxes.add(box);
}
}
public void initContainer(ReadableByteChannel readableByteChannel, long containerSize, BoxParser boxParser) throws IOException {
long contentProcessed = 0;
while (containerSize < 0 || contentProcessed < containerSize) {
try {
ParsableBox b = boxParser.parseBox(readableByteChannel, (this instanceof ParsableBox) ? ((ParsableBox) this).getType() : null);
boxes.add(b);
contentProcessed += b.getSize();
} catch (EOFException e) {
if (containerSize < 0) {
return;
} else {
throw e;
}
}
}
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(this.getClass().getSimpleName()).append("[");
for (int i = 0; i < boxes.size(); i++) {
if (i > 0) {
buffer.append(";");
}
buffer.append(boxes.get(i));
}
buffer.append("]");
return buffer.toString();
}
public final void writeContainer(WritableByteChannel bb) throws IOException {
for (Box box : getBoxes()) {
box.getBox(bb);
}
}
}
|
List<T> boxesToBeReturned = null;
T oneBox = null;
List<Box> boxes = getBoxes();
for (Box boxe : boxes) {
//clazz.isInstance(boxe) / clazz == boxe.getClass()?
// I hereby finally decide to use isInstance
if (clazz.isInstance(boxe)) {
if (oneBox == null) {
oneBox = (T) boxe;
} else {
if (boxesToBeReturned == null) {
boxesToBeReturned = new ArrayList<T>(2);
boxesToBeReturned.add(oneBox);
}
boxesToBeReturned.add((T) boxe);
}
}
}
if (boxesToBeReturned != null) {
return boxesToBeReturned;
} else if (oneBox != null) {
return Collections.singletonList(oneBox);
} else {
return Collections.emptyList();
}
| 949
| 261
| 1,210
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/IsoFile.java
|
IsoFile
|
close
|
class IsoFile extends BasicContainer implements Closeable {
private final ReadableByteChannel readableByteChannel;
private FileInputStream fis;
public IsoFile(String file) throws IOException {
this(new File(file));
}
public IsoFile(File file) throws IOException {
this.fis = new FileInputStream(file);
this.readableByteChannel = fis.getChannel();
initContainer(readableByteChannel, -1, new PropertyBoxParserImpl());
}
/**
* @param readableByteChannel the data source
* @throws IOException in case I/O error
*/
public IsoFile(ReadableByteChannel readableByteChannel) throws IOException {
this(readableByteChannel, new PropertyBoxParserImpl());
}
public IsoFile(ReadableByteChannel readableByteChannel, BoxParser boxParser) throws IOException {
this.readableByteChannel = readableByteChannel;
initContainer(readableByteChannel, -1, boxParser);
}
public static byte[] fourCCtoBytes(String fourCC) {
byte[] result = new byte[4];
if (fourCC != null) {
for (int i = 0; i < Math.min(4, fourCC.length()); i++) {
result[i] = (byte) fourCC.charAt(i);
}
}
return result;
}
public static String bytesToFourCC(byte[] type) {
byte[] result = new byte[]{0, 0, 0, 0};
if (type != null) {
System.arraycopy(type, 0, result, 0, Math.min(type.length, 4));
}
return new String(result, StandardCharsets.ISO_8859_1);
}
public long getSize() {
return getContainerSize();
}
/**
* Shortcut to get the MovieBox since it is often needed and present in
* nearly all ISO 14496 files (at least if they are derived from MP4 ).
*
* @return the MovieBox or <code>null</code>
*/
public MovieBox getMovieBox() {
for (Box box : getBoxes()) {
if (box instanceof MovieBox) {
return (MovieBox) box;
}
}
return null;
}
public void getBox(WritableByteChannel os) throws IOException {
writeContainer(os);
}
@Override
public void close() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "model(" + readableByteChannel + ")";
}
}
|
this.readableByteChannel.close();
if (this.fis != null) {
this.fis.close();
}
for (Box box : getBoxes()) {
if (box instanceof Closeable) {
((Closeable) box).close();
}
}
| 680
| 77
| 757
|
<methods>public void <init>() ,public void <init>(List<org.mp4parser.Box>) ,public void addBox(org.mp4parser.Box) ,public List<org.mp4parser.Box> getBoxes() ,public List<T> getBoxes(Class<T>) ,public List<T> getBoxes(Class<T>, boolean) ,public void initContainer(java.nio.channels.ReadableByteChannel, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setBoxes(List<? extends org.mp4parser.Box>) ,public java.lang.String toString() ,public final void writeContainer(java.nio.channels.WritableByteChannel) throws java.io.IOException<variables>private List<org.mp4parser.Box> boxes
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/PropertyBoxParserImpl.java
|
PropertyBoxParserImpl
|
invoke
|
class PropertyBoxParserImpl extends AbstractBoxParser {
public static Properties BOX_MAP_CACHE = null;
public Properties mapping;
static String[] EMPTY_STRING_ARRAY = new String[0];
Pattern constuctorPattern = Pattern.compile("(.*)\\((.*?)\\)");
StringBuilder buildLookupStrings = new StringBuilder();
ThreadLocal<String> clazzName = new ThreadLocal<>();
ThreadLocal<String[]> param = new ThreadLocal<>();
public PropertyBoxParserImpl(String... customProperties) {
if (BOX_MAP_CACHE != null) {
mapping = new Properties(BOX_MAP_CACHE);
} else {
InputStream is = ClassLoader.getSystemResourceAsStream("isoparser2-default.properties");
try {
mapping = new Properties();
try {
mapping.load(is);
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
Enumeration<URL> enumeration = cl.getResources("isoparser-custom.properties");
while (enumeration.hasMoreElements()) {
URL url = enumeration.nextElement();
try (InputStream customIS = url.openStream()) {
mapping.load(customIS);
}
}
for (String customProperty : customProperties) {
mapping.load(getClass().getResourceAsStream(customProperty));
}
BOX_MAP_CACHE = mapping;
} catch (IOException e) {
throw new RuntimeException(e);
}
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
// ignore - I can't help
}
}
}
}
public PropertyBoxParserImpl(Properties mapping) {
this.mapping = mapping;
}
@Override
public ParsableBox createBox(String type, byte[] userType, String parent) {
invoke(type, userType, parent);
String[] param = this.param.get();
try {
Class<ParsableBox> clazz = (Class<ParsableBox>) Class.forName(clazzName.get());
if (param.length > 0) {
Class[] constructorArgsClazz = new Class[param.length];
Object[] constructorArgs = new Object[param.length];
for (int i = 0; i < param.length; i++) {
if ("userType".equals(param[i])) {
constructorArgs[i] = userType;
constructorArgsClazz[i] = byte[].class;
} else if ("type".equals(param[i])) {
constructorArgs[i] = type;
constructorArgsClazz[i] = String.class;
} else if ("parent".equals(param[i])) {
constructorArgs[i] = parent;
constructorArgsClazz[i] = String.class;
} else {
throw new InternalError("No such param: " + param[i]);
}
}
Constructor<ParsableBox> constructorObject = clazz.getConstructor(constructorArgsClazz);
return constructorObject.newInstance(constructorArgs);
} else {
return clazz.getDeclaredConstructor().newInstance();
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public void invoke(String type, byte[] userType, String parent) {<FILL_FUNCTION_BODY>}
}
|
String constructor;
if (userType != null) {
if (!"uuid".equals((type))) {
throw new RuntimeException("we have a userType but no uuid box type. Something's wrong");
}
constructor = mapping.getProperty("uuid[" + Hex.encodeHex(userType).toUpperCase() + "]");
if (constructor == null) {
constructor = mapping.getProperty((parent) + "-uuid[" + Hex.encodeHex(userType).toUpperCase() + "]");
}
if (constructor == null) {
constructor = mapping.getProperty("uuid");
}
} else {
constructor = mapping.getProperty((type));
if (constructor == null) {
String lookup = buildLookupStrings.append(parent).append('-').append(type).toString();
buildLookupStrings.setLength(0);
constructor = mapping.getProperty(lookup);
}
}
if (constructor == null) {
constructor = mapping.getProperty("default");
}
if (constructor == null) {
throw new RuntimeException("No box object found for " + type);
}
if (!constructor.endsWith(")")) {
param.set(EMPTY_STRING_ARRAY);
clazzName.set(constructor);
} else {
Matcher m = constuctorPattern.matcher(constructor);
boolean matches = m.matches();
if (!matches) {
throw new RuntimeException("Cannot work with that constructor: " + constructor);
}
clazzName.set(m.group(1));
if (m.group(2).length() == 0) {
param.set(EMPTY_STRING_ARRAY);
} else {
param.set(m.group(2).length() > 0 ? m.group(2).split(",") : new String[]{});
}
}
| 928
| 477
| 1,405
|
<methods>public non-sealed void <init>() ,public abstract org.mp4parser.ParsableBox createBox(java.lang.String, byte[], java.lang.String) ,public org.mp4parser.ParsableBox parseBox(java.nio.channels.ReadableByteChannel, java.lang.String) throws java.io.IOException,public transient org.mp4parser.AbstractBoxParser skippingBoxes(java.lang.String[]) <variables>private static org.slf4j.Logger LOG,ThreadLocal<java.nio.ByteBuffer> header,private List<java.lang.String> skippedTypes
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/RewindableReadableByteChannel.java
|
RewindableReadableByteChannel
|
read
|
class RewindableReadableByteChannel implements ReadableByteChannel {
private final ReadableByteChannel readableByteChannel;
private final ByteBuffer buffer;
// If 'true', there are more bytes read from |readableByteChannel| than the allocated buffer size.
// The rewind is not possible in that case.
private boolean passedRewindPoint;
private int nextBufferWritePosition;
private int nextBufferReadPosition;
public RewindableReadableByteChannel(ReadableByteChannel readableByteChannel, int bufferCapacity) {
this.buffer = ByteBuffer.allocate(bufferCapacity);
this.readableByteChannel = readableByteChannel;
}
/**
* @see ReadableByteChannel#read(ByteBuffer)
*/
public int read(ByteBuffer dst) throws IOException {<FILL_FUNCTION_BODY>}
public void rewind() {
if (passedRewindPoint) {
throw new IllegalStateException("Passed the rewind point. Increase the buffer capacity.");
}
nextBufferReadPosition = 0;
}
/**
* @see ReadableByteChannel#isOpen()
*/
public boolean isOpen() {
return readableByteChannel.isOpen();
}
/**
* @see ReadableByteChannel#close()
*/
public void close() throws IOException {
readableByteChannel.close();
}
}
|
int initialDstPosition = dst.position();
// Read data from |readableByteChannel| into |buffer|.
((Buffer)buffer).limit(buffer.capacity());
((Buffer)buffer).position(nextBufferWritePosition);
if (buffer.capacity() > 0) {
readableByteChannel.read(buffer);
nextBufferWritePosition = buffer.position();
}
// Read data from |buffer| into |dst|.
((Buffer)buffer).position(nextBufferReadPosition);
((Buffer)buffer).limit(nextBufferWritePosition);
if (buffer.remaining() > dst.remaining()) {
((Buffer)buffer).limit(buffer.position() + dst.remaining());
}
dst.put(buffer);
nextBufferReadPosition = buffer.position();
// If |dst| still has capacity then read data from |readableByteChannel|.
int bytesRead = readableByteChannel.read(dst);
if (bytesRead > 0) {
// We passed the buffering capacity. It will not be possible to rewind
// |readableByteChannel| anymore.
passedRewindPoint = true;
} else if ((bytesRead == -1) && (dst.position() - initialDstPosition == 0)) {
return -1;
}
return dst.position() - initialDstPosition;
| 353
| 342
| 695
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/SkipBox.java
|
SkipBox
|
parse
|
class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
this.size = contentSize+8;
if( dataSource instanceof FileChannel ) {
FileChannel seekable = (FileChannel) dataSource;
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
| 275
| 106
| 381
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/UserBox.java
|
UserBox
|
toString
|
class UserBox extends AbstractBox {
public static final String TYPE = "uuid";
byte[] data;
public UserBox(byte[] userType) {
super(TYPE, userType);
}
protected long getContentSize() {
return data.length;
}
public String toString() {<FILL_FUNCTION_BODY>}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public void _parseDetails(ByteBuffer content) {
data = new byte[content.remaining()];
content.get(data);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.put(data);
}
}
|
return "UserBox[type=" + (getType()) +
";userType=" + new String(getUserType()) +
";contentLength=" + data.length + "]";
| 209
| 50
| 259
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/adobe/ActionMessageFormat0SampleEntryBox.java
|
ActionMessageFormat0SampleEntryBox
|
getSize
|
class ActionMessageFormat0SampleEntryBox extends AbstractSampleEntry {
public static final String TYPE = "amf0";
public ActionMessageFormat0SampleEntryBox() {
super(TYPE);
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(8);
dataSource.read(bb);
((Buffer)bb).position(6);// ignore 6 reserved bytes;
dataReferenceIndex = IsoTypeReader.readUInt16(bb);
initContainer(dataSource, contentSize - 8, boxParser);
}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
ByteBuffer bb = ByteBuffer.allocate(8);
((Buffer)bb).position(6);
IsoTypeWriter.writeUInt16(bb, dataReferenceIndex);
writableByteChannel.write((ByteBuffer) ((Buffer)bb).rewind());
writeContainer(writableByteChannel);
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
}
|
long s = getContainerSize();
long t = 8; // bytes to container start
return s + t + ((largeBox || (s + t) >= (1L << 32)) ? 16 : 8);
| 308
| 56
| 364
|
<methods>public abstract void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public int getDataReferenceIndex() ,public abstract void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setDataReferenceIndex(int) <variables>protected int dataReferenceIndex
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/AppleDataReferenceBox.java
|
AppleDataReferenceBox
|
_parseDetails
|
class AppleDataReferenceBox extends AbstractFullBox {
public static final String TYPE = "rdrf";
private int dataReferenceSize;
private String dataReferenceType;
private String dataReference;
public AppleDataReferenceBox() {
super(TYPE);
}
protected long getContentSize() {
return 12 + dataReferenceSize;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
byteBuffer.put(IsoFile.fourCCtoBytes(dataReferenceType));
IsoTypeWriter.writeUInt32(byteBuffer, dataReferenceSize);
byteBuffer.put(Utf8.convert(dataReference));
}
public long getDataReferenceSize() {
return dataReferenceSize;
}
public String getDataReferenceType() {
return dataReferenceType;
}
public String getDataReference() {
return dataReference;
}
}
|
parseVersionAndFlags(content);
dataReferenceType = IsoTypeReader.read4cc(content);
dataReferenceSize = CastUtils.l2i(IsoTypeReader.readUInt32(content));
dataReference = IsoTypeReader.readString(content, dataReferenceSize);
| 270
| 74
| 344
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/AppleGPSCoordinatesBox.java
|
AppleGPSCoordinatesBox
|
_parseDetails
|
class AppleGPSCoordinatesBox extends AbstractBox {
public static final String TYPE = "©xyz";
private static final int DEFAULT_LANG = 5575; //Empirical
String coords;
int lang = DEFAULT_LANG; //? Docs says lang, but it doesn't match anything in the traditional language map
public AppleGPSCoordinatesBox() {
super(TYPE);
}
public String getValue() {
return coords;
}
public void setValue(String iso6709String) {
lang = DEFAULT_LANG;
coords = iso6709String;
}
@Override
protected long getContentSize() {
return 4 + Utf8.utf8StringLengthInBytes(coords);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.putShort((short) coords.length());
byteBuffer.putShort((short) lang);
byteBuffer.put(Utf8.convert(coords));
}
@Override
protected void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public String toString() {
return "AppleGPSCoordinatesBox[" + coords + "]";
}
}
|
int length = content.getShort();
lang = content.getShort(); //Not sure if this is accurate. It always seems to be 15 c7
byte bytes[] = new byte[length];
content.get(bytes);
coords = Utf8.convert(bytes);
| 326
| 72
| 398
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/AppleLosslessSpecificBox.java
|
AppleLosslessSpecificBox
|
getContent
|
class AppleLosslessSpecificBox extends AbstractFullBox {
public static final String TYPE = "alac";
/*
Extradata: 32bit size 32bit tag (=alac) 32bit zero?
32bit max sample per frame 8bit ?? (zero?) 8bit sample
size 8bit history mult 8bit initial history 8bit kmodifier
8bit channels? 16bit ?? 32bit max coded frame size 32bit
bitrate? 32bit samplerate
*/
private long maxSamplePerFrame; // 32bi
private int unknown1; // 8bit
private int sampleSize; // 8bit
private int historyMult; // 8bit
private int initialHistory; // 8bit
private int kModifier; // 8bit
private int channels; // 8bit
private int unknown2; // 16bit
private long maxCodedFrameSize; // 32bit
private long bitRate; // 32bit
private long sampleRate; // 32bit
public AppleLosslessSpecificBox() {
super("alac");
}
public long getMaxSamplePerFrame() {
return maxSamplePerFrame;
}
public void setMaxSamplePerFrame(int maxSamplePerFrame) {
this.maxSamplePerFrame = maxSamplePerFrame;
}
public int getUnknown1() {
return unknown1;
}
public void setUnknown1(int unknown1) {
this.unknown1 = unknown1;
}
public int getSampleSize() {
return sampleSize;
}
public void setSampleSize(int sampleSize) {
this.sampleSize = sampleSize;
}
public int getHistoryMult() {
return historyMult;
}
public void setHistoryMult(int historyMult) {
this.historyMult = historyMult;
}
public int getInitialHistory() {
return initialHistory;
}
public void setInitialHistory(int initialHistory) {
this.initialHistory = initialHistory;
}
public int getKModifier() {
return kModifier;
}
public void setKModifier(int kModifier) {
this.kModifier = kModifier;
}
public int getChannels() {
return channels;
}
public void setChannels(int channels) {
this.channels = channels;
}
public int getUnknown2() {
return unknown2;
}
public void setUnknown2(int unknown2) {
this.unknown2 = unknown2;
}
public long getMaxCodedFrameSize() {
return maxCodedFrameSize;
}
public void setMaxCodedFrameSize(int maxCodedFrameSize) {
this.maxCodedFrameSize = maxCodedFrameSize;
}
public long getBitRate() {
return bitRate;
}
public void setBitRate(int bitRate) {
this.bitRate = bitRate;
}
public long getSampleRate() {
return sampleRate;
}
public void setSampleRate(int sampleRate) {
this.sampleRate = sampleRate;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
maxSamplePerFrame = IsoTypeReader.readUInt32(content);
unknown1 = IsoTypeReader.readUInt8(content);
sampleSize = IsoTypeReader.readUInt8(content);
historyMult = IsoTypeReader.readUInt8(content);
initialHistory = IsoTypeReader.readUInt8(content);
kModifier = IsoTypeReader.readUInt8(content);
channels = IsoTypeReader.readUInt8(content);
unknown2 = IsoTypeReader.readUInt16(content);
maxCodedFrameSize = IsoTypeReader.readUInt32(content);
bitRate = IsoTypeReader.readUInt32(content);
sampleRate = IsoTypeReader.readUInt32(content);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
protected long getContentSize() {
return 28;
}
}
|
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeUInt32(byteBuffer, maxSamplePerFrame);
IsoTypeWriter.writeUInt8(byteBuffer, unknown1);
IsoTypeWriter.writeUInt8(byteBuffer, sampleSize);
IsoTypeWriter.writeUInt8(byteBuffer, historyMult);
IsoTypeWriter.writeUInt8(byteBuffer, initialHistory);
IsoTypeWriter.writeUInt8(byteBuffer, kModifier);
IsoTypeWriter.writeUInt8(byteBuffer, channels);
IsoTypeWriter.writeUInt16(byteBuffer, unknown2);
IsoTypeWriter.writeUInt32(byteBuffer, maxCodedFrameSize);
IsoTypeWriter.writeUInt32(byteBuffer, bitRate);
IsoTypeWriter.writeUInt32(byteBuffer, sampleRate);
| 1,110
| 221
| 1,331
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/AppleRecordingYearBox.java
|
AppleRecordingYearBox
|
parseData
|
class AppleRecordingYearBox extends AppleDataBox {
DateFormat df;
Date date = new Date();
public AppleRecordingYearBox() {
super("©day", 1);
df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ssZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
}
protected static String iso8601toRfc822Date(String iso8601) {
iso8601 = iso8601.replaceAll("Z$", "+0000");
iso8601 = iso8601.replaceAll("([0-9][0-9]):([0-9][0-9])$", "$1$2");
return iso8601;
}
protected static String rfc822toIso8601Date(String rfc622) {
rfc622 = rfc622.replaceAll("\\+0000$", "Z");
return rfc622;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
protected byte[] writeData() {
return Utf8.convert(rfc822toIso8601Date(df.format(date)));
}
@Override
protected void parseData(ByteBuffer data) {<FILL_FUNCTION_BODY>}
@Override
protected int getDataLength() {
return Utf8.convert(rfc822toIso8601Date(df.format(date))).length;
}
}
|
String dateString = IsoTypeReader.readString(data, data.remaining());
try {
date = df.parse(iso8601toRfc822Date(dateString));
} catch (ParseException e) {
throw new RuntimeException(e);
}
| 446
| 74
| 520
|
<methods>public int getDataCountry() ,public int getDataLanguage() ,public int getDataType() ,public java.lang.String getLanguageString() ,public void setDataCountry(int) ,public void setDataLanguage(int) <variables>int dataCountry,int dataLanguage,int dataType,private static HashMap<java.lang.String,java.lang.String> language
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/AppleVariableSignedIntegerBox.java
|
AppleVariableSignedIntegerBox
|
setValue
|
class AppleVariableSignedIntegerBox extends AppleDataBox {
long value;
int intLength = 1;
protected AppleVariableSignedIntegerBox(String type) {
super(type, 15);
}
public int getIntLength() {
return intLength;
}
public void setIntLength(int intLength) {
this.intLength = intLength;
}
public long getValue() {
//patched by Tobias Bley / UltraMixer (04/25/2014)
if (!isParsed()) {
parseDetails();
}
return value;
}
public void setValue(long value) {<FILL_FUNCTION_BODY>}
@Override
protected byte[] writeData() {
int dLength = getDataLength();
ByteBuffer b = ByteBuffer.wrap(new byte[dLength]);
IsoTypeWriterVariable.write(value, b, dLength);
return b.array();
}
@Override
protected void parseData(ByteBuffer data) {
int intLength = data.remaining();
value = IsoTypeReaderVariable.read(data, intLength);
this.intLength = intLength;
}
@Override
protected int getDataLength() {
return intLength;
}
}
|
if (value <= 127 && value > -128) {
intLength = 1;
} else if (value <= 32767 && value > -32768 && intLength < 2) {
intLength = 2;
} else if (value <= 8388607 && value > -8388608 && intLength < 3) {
intLength = 3;
} else {
intLength = 4;
}
this.value = value;
| 337
| 129
| 466
|
<methods>public int getDataCountry() ,public int getDataLanguage() ,public int getDataType() ,public java.lang.String getLanguageString() ,public void setDataCountry(int) ,public void setDataLanguage(int) <variables>int dataCountry,int dataLanguage,int dataType,private static HashMap<java.lang.String,java.lang.String> language
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/BaseMediaInfoAtom.java
|
BaseMediaInfoAtom
|
getContent
|
class BaseMediaInfoAtom extends AbstractFullBox {
public static final String TYPE = "gmin";
short graphicsMode = 64;
int opColorR = 32768;
int opColorG = 32768;
int opColorB = 32768;
short balance;
short reserved;
public BaseMediaInfoAtom() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 16;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
@Override
protected void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
graphicsMode = content.getShort();
opColorR = IsoTypeReader.readUInt16(content);
opColorG = IsoTypeReader.readUInt16(content);
opColorB = IsoTypeReader.readUInt16(content);
balance = content.getShort();
reserved = content.getShort();
}
public short getGraphicsMode() {
return graphicsMode;
}
public void setGraphicsMode(short graphicsMode) {
this.graphicsMode = graphicsMode;
}
public int getOpColorR() {
return opColorR;
}
public void setOpColorR(int opColorR) {
this.opColorR = opColorR;
}
public int getOpColorG() {
return opColorG;
}
public void setOpColorG(int opColorG) {
this.opColorG = opColorG;
}
public int getOpColorB() {
return opColorB;
}
public void setOpColorB(int opColorB) {
this.opColorB = opColorB;
}
public short getBalance() {
return balance;
}
public void setBalance(short balance) {
this.balance = balance;
}
public short getReserved() {
return reserved;
}
public void setReserved(short reserved) {
this.reserved = reserved;
}
@Override
public String toString() {
return "BaseMediaInfoAtom{" +
"graphicsMode=" + graphicsMode +
", opColorR=" + opColorR +
", opColorG=" + opColorG +
", opColorB=" + opColorB +
", balance=" + balance +
", reserved=" + reserved +
'}';
}
}
|
writeVersionAndFlags(byteBuffer);
byteBuffer.putShort(graphicsMode);
IsoTypeWriter.writeUInt16(byteBuffer, opColorR);
IsoTypeWriter.writeUInt16(byteBuffer, opColorG);
IsoTypeWriter.writeUInt16(byteBuffer, opColorB);
byteBuffer.putShort(balance);
byteBuffer.putShort(reserved);
| 662
| 105
| 767
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/GenericMediaHeaderTextAtom.java
|
GenericMediaHeaderTextAtom
|
_parseDetails
|
class GenericMediaHeaderTextAtom extends AbstractBox {
public static final String TYPE = "text";
int unknown_1 = 65536;
int unknown_2;
int unknown_3;
int unknown_4;
int unknown_5 = 65536;
int unknown_6;
int unknown_7;
int unknown_8;
int unknown_9 = 1073741824;
public GenericMediaHeaderTextAtom() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 36;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.putInt(unknown_1);
byteBuffer.putInt(unknown_2);
byteBuffer.putInt(unknown_3);
byteBuffer.putInt(unknown_4);
byteBuffer.putInt(unknown_5);
byteBuffer.putInt(unknown_6);
byteBuffer.putInt(unknown_7);
byteBuffer.putInt(unknown_8);
byteBuffer.putInt(unknown_9);
}
@Override
protected void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public int getUnknown_1() {
return unknown_1;
}
public void setUnknown_1(int unknown_1) {
this.unknown_1 = unknown_1;
}
public int getUnknown_2() {
return unknown_2;
}
public void setUnknown_2(int unknown_2) {
this.unknown_2 = unknown_2;
}
public int getUnknown_3() {
return unknown_3;
}
public void setUnknown_3(int unknown_3) {
this.unknown_3 = unknown_3;
}
public int getUnknown_4() {
return unknown_4;
}
public void setUnknown_4(int unknown_4) {
this.unknown_4 = unknown_4;
}
public int getUnknown_5() {
return unknown_5;
}
public void setUnknown_5(int unknown_5) {
this.unknown_5 = unknown_5;
}
public int getUnknown_6() {
return unknown_6;
}
public void setUnknown_6(int unknown_6) {
this.unknown_6 = unknown_6;
}
public int getUnknown_7() {
return unknown_7;
}
public void setUnknown_7(int unknown_7) {
this.unknown_7 = unknown_7;
}
public int getUnknown_8() {
return unknown_8;
}
public void setUnknown_8(int unknown_8) {
this.unknown_8 = unknown_8;
}
public int getUnknown_9() {
return unknown_9;
}
public void setUnknown_9(int unknown_9) {
this.unknown_9 = unknown_9;
}
}
|
unknown_1 = content.getInt();
unknown_2 = content.getInt();
unknown_3 = content.getInt();
unknown_4 = content.getInt();
unknown_5 = content.getInt();
unknown_6 = content.getInt();
unknown_7 = content.getInt();
unknown_8 = content.getInt();
unknown_9 = content.getInt();
| 787
| 102
| 889
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/QuicktimeTextSampleEntry.java
|
QuicktimeTextSampleEntry
|
getSize
|
class QuicktimeTextSampleEntry extends AbstractSampleEntry {
public static final String TYPE = "text";
int displayFlags;
int textJustification;
int backgroundR;
int backgroundG;
int backgroundB;
long defaultTextBox;
long reserved1;
short fontNumber;
short fontFace;
byte reserved2;
short reserved3;
int foregroundR = 65535;
int foregroundG = 65535;
int foregroundB = 65535;
String fontName = "";
int dataReferenceIndex;
public QuicktimeTextSampleEntry() {
super(TYPE);
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
ByteBuffer content = ByteBuffer.allocate(CastUtils.l2i(contentSize));
dataSource.read(content);
((Buffer)content).position(6);
dataReferenceIndex = IsoTypeReader.readUInt16(content);
displayFlags = content.getInt();
textJustification = content.getInt();
backgroundR = IsoTypeReader.readUInt16(content);
backgroundG = IsoTypeReader.readUInt16(content);
backgroundB = IsoTypeReader.readUInt16(content);
defaultTextBox = IsoTypeReader.readUInt64(content);
reserved1 = IsoTypeReader.readUInt64(content);
fontNumber = content.getShort();
fontFace = content.getShort();
reserved2 = content.get();
reserved3 = content.getShort();
foregroundR = IsoTypeReader.readUInt16(content);
foregroundG = IsoTypeReader.readUInt16(content);
foregroundB = IsoTypeReader.readUInt16(content);
if (content.remaining() > 0) {
int length = IsoTypeReader.readUInt8(content);
byte[] myFontName = new byte[length];
content.get(myFontName);
fontName = new String(myFontName);
} else {
fontName = null;
}
// initContainer(); there are no child boxes!?
}
@Override
public void setBoxes(List<? extends Box> boxes) {
throw new RuntimeException("QuicktimeTextSampleEntries may not have child boxes");
}
@Override
public void addBox(Box box) {
throw new RuntimeException("QuicktimeTextSampleEntries may not have child boxes");
}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
ByteBuffer byteBuffer = ByteBuffer.allocate(52 + (fontName != null ? fontName.length() : 0));
((Buffer)byteBuffer).position(6);
IsoTypeWriter.writeUInt16(byteBuffer, dataReferenceIndex);
byteBuffer.putInt(displayFlags);
byteBuffer.putInt(textJustification);
IsoTypeWriter.writeUInt16(byteBuffer, backgroundR);
IsoTypeWriter.writeUInt16(byteBuffer, backgroundG);
IsoTypeWriter.writeUInt16(byteBuffer, backgroundB);
IsoTypeWriter.writeUInt64(byteBuffer, defaultTextBox);
IsoTypeWriter.writeUInt64(byteBuffer, reserved1);
byteBuffer.putShort(fontNumber);
byteBuffer.putShort(fontFace);
byteBuffer.put(reserved2);
byteBuffer.putShort(reserved3);
IsoTypeWriter.writeUInt16(byteBuffer, foregroundR);
IsoTypeWriter.writeUInt16(byteBuffer, foregroundG);
IsoTypeWriter.writeUInt16(byteBuffer, foregroundB);
if (fontName != null) {
IsoTypeWriter.writeUInt8(byteBuffer, fontName.length());
byteBuffer.put(fontName.getBytes());
}
writableByteChannel.write((ByteBuffer) ((Buffer)byteBuffer).rewind());
// writeContainer(writableByteChannel); there are no child boxes!?
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
public int getDisplayFlags() {
return displayFlags;
}
public void setDisplayFlags(int displayFlags) {
this.displayFlags = displayFlags;
}
public int getTextJustification() {
return textJustification;
}
public void setTextJustification(int textJustification) {
this.textJustification = textJustification;
}
public int getBackgroundR() {
return backgroundR;
}
public void setBackgroundR(int backgroundR) {
this.backgroundR = backgroundR;
}
public int getBackgroundG() {
return backgroundG;
}
public void setBackgroundG(int backgroundG) {
this.backgroundG = backgroundG;
}
public int getBackgroundB() {
return backgroundB;
}
public void setBackgroundB(int backgroundB) {
this.backgroundB = backgroundB;
}
public long getDefaultTextBox() {
return defaultTextBox;
}
public void setDefaultTextBox(long defaultTextBox) {
this.defaultTextBox = defaultTextBox;
}
public long getReserved1() {
return reserved1;
}
public void setReserved1(long reserved1) {
this.reserved1 = reserved1;
}
public short getFontNumber() {
return fontNumber;
}
public void setFontNumber(short fontNumber) {
this.fontNumber = fontNumber;
}
public short getFontFace() {
return fontFace;
}
public void setFontFace(short fontFace) {
this.fontFace = fontFace;
}
public byte getReserved2() {
return reserved2;
}
public void setReserved2(byte reserved2) {
this.reserved2 = reserved2;
}
public short getReserved3() {
return reserved3;
}
public void setReserved3(short reserved3) {
this.reserved3 = reserved3;
}
public int getForegroundR() {
return foregroundR;
}
public void setForegroundR(int foregroundR) {
this.foregroundR = foregroundR;
}
public int getForegroundG() {
return foregroundG;
}
public void setForegroundG(int foregroundG) {
this.foregroundG = foregroundG;
}
public int getForegroundB() {
return foregroundB;
}
public void setForegroundB(int foregroundB) {
this.foregroundB = foregroundB;
}
public String getFontName() {
return fontName;
}
public void setFontName(String fontName) {
this.fontName = fontName;
}
}
|
long s = getContainerSize() + 52 + (fontName != null ? fontName.length() : 0);
s += ((largeBox || (s + 8) >= (1L << 32)) ? 16 : 8);
return s;
| 1,826
| 66
| 1,892
|
<methods>public abstract void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public int getDataReferenceIndex() ,public abstract void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setDataReferenceIndex(int) <variables>protected int dataReferenceIndex
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/TrackLoadSettingsAtom.java
|
TrackLoadSettingsAtom
|
_parseDetails
|
class TrackLoadSettingsAtom extends AbstractBox {
public static final String TYPE = "load";
int preloadStartTime;
int preloadDuration;
int preloadFlags;
int defaultHints;
public TrackLoadSettingsAtom() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 16;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.putInt(preloadStartTime);
byteBuffer.putInt(preloadDuration);
byteBuffer.putInt(preloadFlags);
byteBuffer.putInt(defaultHints);
}
@Override
protected void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public int getPreloadStartTime() {
return preloadStartTime;
}
public void setPreloadStartTime(int preloadStartTime) {
this.preloadStartTime = preloadStartTime;
}
public int getPreloadDuration() {
return preloadDuration;
}
public void setPreloadDuration(int preloadDuration) {
this.preloadDuration = preloadDuration;
}
public int getPreloadFlags() {
return preloadFlags;
}
public void setPreloadFlags(int preloadFlags) {
this.preloadFlags = preloadFlags;
}
public int getDefaultHints() {
return defaultHints;
}
public void setDefaultHints(int defaultHints) {
this.defaultHints = defaultHints;
}
}
|
preloadStartTime = content.getInt();
preloadDuration = content.getInt();
preloadFlags = content.getInt();
defaultHints = content.getInt();
| 414
| 48
| 462
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/apple/Utf8AppleDataBox.java
|
Utf8AppleDataBox
|
getValue
|
class Utf8AppleDataBox extends AppleDataBox {
String value;
protected Utf8AppleDataBox(String type) {
super(type, 1);
}
public String getValue() {<FILL_FUNCTION_BODY>}
public void setValue(String value) {
this.value = value;
}
@DoNotParseDetail
public byte[] writeData() {
return Utf8.convert(value);
}
@Override
protected int getDataLength() {
return value.getBytes(Charset.forName("UTF-8")).length;
}
@Override
protected void parseData(ByteBuffer data) {
value = IsoTypeReader.readString(data, data.remaining());
}
}
|
//patched by Toias Bley / UltraMixer
if (!isParsed()) {
parseDetails();
}
return value;
| 199
| 41
| 240
|
<methods>public int getDataCountry() ,public int getDataLanguage() ,public int getDataType() ,public java.lang.String getLanguageString() ,public void setDataCountry(int) ,public void setDataLanguage(int) <variables>int dataCountry,int dataLanguage,int dataType,private static HashMap<java.lang.String,java.lang.String> language
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dece/AssetInformationBox.java
|
Entry
|
equals
|
class Entry {
public String namespace;
public String profileLevelIdc;
public String assetId;
public Entry(String namespace, String profileLevelIdc, String assetId) {
this.namespace = namespace;
this.profileLevelIdc = profileLevelIdc;
this.assetId = assetId;
}
@Override
public String toString() {
return "{" +
"namespace='" + namespace + '\'' +
", profileLevelIdc='" + profileLevelIdc + '\'' +
", assetId='" + assetId + '\'' +
'}';
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = namespace.hashCode();
result = 31 * result + profileLevelIdc.hashCode();
result = 31 * result + assetId.hashCode();
return result;
}
public int getSize() {
return 3 + Utf8.utf8StringLengthInBytes(namespace) +
Utf8.utf8StringLengthInBytes(profileLevelIdc) + Utf8.utf8StringLengthInBytes(assetId);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
if (!assetId.equals(entry.assetId)) return false;
if (!namespace.equals(entry.namespace)) return false;
if (!profileLevelIdc.equals(entry.profileLevelIdc)) return false;
return true;
| 312
| 108
| 420
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dece/AvcNalUnitStorageBox.java
|
AvcNalUnitStorageBox
|
toString
|
class AvcNalUnitStorageBox extends AbstractBox {
public static final String TYPE = "avcn";
AvcDecoderConfigurationRecord avcDecoderConfigurationRecord;
public AvcNalUnitStorageBox() {
super(TYPE);
}
public AvcNalUnitStorageBox(AvcConfigurationBox avcConfigurationBox) {
super(TYPE);
this.avcDecoderConfigurationRecord = avcConfigurationBox.getavcDecoderConfigurationRecord();
}
public AvcDecoderConfigurationRecord getAvcDecoderConfigurationRecord() {
return avcDecoderConfigurationRecord;
}
// just to display sps in isoviewer no practical use
public int getLengthSizeMinusOne() {
return avcDecoderConfigurationRecord.lengthSizeMinusOne;
}
public List<String> getSequenceParameterSetsAsStrings() {
return avcDecoderConfigurationRecord.getSequenceParameterSetsAsStrings();
}
public List<String> getSequenceParameterSetExtsAsStrings() {
return avcDecoderConfigurationRecord.getSequenceParameterSetExtsAsStrings();
}
public List<String> getPictureParameterSetsAsStrings() {
return avcDecoderConfigurationRecord.getPictureParameterSetsAsStrings();
}
@Override
protected long getContentSize() {
return avcDecoderConfigurationRecord.getContentSize();
}
@Override
public void _parseDetails(ByteBuffer content) {
this.avcDecoderConfigurationRecord = new AvcDecoderConfigurationRecord(content);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
this.avcDecoderConfigurationRecord.getContent(byteBuffer);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "AvcNalUnitStorageBox{" +
"SPS=" + avcDecoderConfigurationRecord.getSequenceParameterSetsAsStrings() +
",PPS=" + avcDecoderConfigurationRecord.getPictureParameterSetsAsStrings() +
",lengthSize=" + (avcDecoderConfigurationRecord.lengthSizeMinusOne + 1) +
'}';
| 459
| 97
| 556
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dece/BaseLocationBox.java
|
BaseLocationBox
|
getContent
|
class BaseLocationBox extends AbstractFullBox {
public static final String TYPE = "bloc";
String baseLocation = "";
String purchaseLocation = "";
public BaseLocationBox() {
super(TYPE);
}
public BaseLocationBox(String baseLocation, String purchaseLocation) {
super(TYPE);
this.baseLocation = baseLocation;
this.purchaseLocation = purchaseLocation;
}
public String getBaseLocation() {
return baseLocation;
}
public void setBaseLocation(String baseLocation) {
this.baseLocation = baseLocation;
}
public String getPurchaseLocation() {
return purchaseLocation;
}
public void setPurchaseLocation(String purchaseLocation) {
this.purchaseLocation = purchaseLocation;
}
@Override
protected long getContentSize() {
return 1028;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
baseLocation = IsoTypeReader.readString(content);
content.get(new byte[256 - Utf8.utf8StringLengthInBytes(baseLocation) - 1]);
purchaseLocation = IsoTypeReader.readString(content);
content.get(new byte[256 - Utf8.utf8StringLengthInBytes(purchaseLocation) - 1]);
content.get(new byte[512]);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseLocationBox that = (BaseLocationBox) o;
if (baseLocation != null ? !baseLocation.equals(that.baseLocation) : that.baseLocation != null) return false;
if (purchaseLocation != null ? !purchaseLocation.equals(that.purchaseLocation) : that.purchaseLocation != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = baseLocation != null ? baseLocation.hashCode() : 0;
result = 31 * result + (purchaseLocation != null ? purchaseLocation.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "BaseLocationBox{" +
"baseLocation='" + baseLocation + '\'' +
", purchaseLocation='" + purchaseLocation + '\'' +
'}';
}
}
|
writeVersionAndFlags(byteBuffer);
byteBuffer.put(Utf8.convert(baseLocation));
byteBuffer.put(new byte[256 - Utf8.utf8StringLengthInBytes(baseLocation)]); // string plus term zero
byteBuffer.put(Utf8.convert(purchaseLocation));
byteBuffer.put(new byte[256 - Utf8.utf8StringLengthInBytes(purchaseLocation)]); // string plus term zero
byteBuffer.put(new byte[512]);
| 662
| 129
| 791
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dece/ContentInformationBox.java
|
ContentInformationBox
|
getContent
|
class ContentInformationBox extends AbstractFullBox {
public static final String TYPE = "cinf";
String mimeSubtypeName;
String profileLevelIdc;
String codecs;
String protection;
String languages;
Map<String, String> brandEntries = new LinkedHashMap<String, String>();
Map<String, String> idEntries = new LinkedHashMap<String, String>();
public ContentInformationBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
long size = 4;
size += Utf8.utf8StringLengthInBytes(mimeSubtypeName) + 1;
size += Utf8.utf8StringLengthInBytes(profileLevelIdc) + 1;
size += Utf8.utf8StringLengthInBytes(codecs) + 1;
size += Utf8.utf8StringLengthInBytes(protection) + 1;
size += Utf8.utf8StringLengthInBytes(languages) + 1;
size += 1;
for (Map.Entry<String, String> brandEntry : brandEntries.entrySet()) {
size += Utf8.utf8StringLengthInBytes(brandEntry.getKey()) + 1;
size += Utf8.utf8StringLengthInBytes(brandEntry.getValue()) + 1;
}
size += 1;
for (Map.Entry<String, String> idEntry : idEntries.entrySet()) {
size += Utf8.utf8StringLengthInBytes(idEntry.getKey()) + 1;
size += Utf8.utf8StringLengthInBytes(idEntry.getValue()) + 1;
}
return size;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
@Override
protected void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
mimeSubtypeName = IsoTypeReader.readString(content);
profileLevelIdc = IsoTypeReader.readString(content);
codecs = IsoTypeReader.readString(content);
protection = IsoTypeReader.readString(content);
languages = IsoTypeReader.readString(content);
int brandEntryCount = IsoTypeReader.readUInt8(content);
while (brandEntryCount-- > 0) {
brandEntries.put(IsoTypeReader.readString(content), IsoTypeReader.readString(content));
}
int idEntryCount = IsoTypeReader.readUInt8(content);
while (idEntryCount-- > 0) {
idEntries.put(IsoTypeReader.readString(content), IsoTypeReader.readString(content));
}
}
public String getMimeSubtypeName() {
return mimeSubtypeName;
}
public void setMimeSubtypeName(String mimeSubtypeName) {
this.mimeSubtypeName = mimeSubtypeName;
}
public String getProfileLevelIdc() {
return profileLevelIdc;
}
public void setProfileLevelIdc(String profileLevelIdc) {
this.profileLevelIdc = profileLevelIdc;
}
public String getCodecs() {
return codecs;
}
public void setCodecs(String codecs) {
this.codecs = codecs;
}
public String getProtection() {
return protection;
}
public void setProtection(String protection) {
this.protection = protection;
}
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}
public Map<String, String> getBrandEntries() {
return brandEntries;
}
public void setBrandEntries(Map<String, String> brandEntries) {
this.brandEntries = brandEntries;
}
public Map<String, String> getIdEntries() {
return idEntries;
}
public void setIdEntries(Map<String, String> idEntries) {
this.idEntries = idEntries;
}
public static class BrandEntry {
String iso_brand;
String version;
public BrandEntry(String iso_brand, String version) {
this.iso_brand = iso_brand;
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrandEntry that = (BrandEntry) o;
if (iso_brand != null ? !iso_brand.equals(that.iso_brand) : that.iso_brand != null) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = iso_brand != null ? iso_brand.hashCode() : 0;
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}
|
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, mimeSubtypeName);
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, profileLevelIdc);
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, codecs);
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, protection);
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, languages);
IsoTypeWriter.writeUInt8(byteBuffer, brandEntries.size());
for (Map.Entry<String, String> brandEntry : brandEntries.entrySet()) {
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, brandEntry.getKey());
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, brandEntry.getValue());
}
IsoTypeWriter.writeUInt8(byteBuffer, idEntries.size());
for (Map.Entry<String, String> idEntry : idEntries.entrySet()) {
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, idEntry.getKey());
IsoTypeWriter.writeZeroTermUtf8String(byteBuffer, idEntry.getValue());
}
| 1,338
| 310
| 1,648
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dece/TrickPlayBox.java
|
Entry
|
toString
|
class Entry {
private int value;
public Entry() {
}
public Entry(int value) {
this.value = value;
}
public int getPicType() {
return (value >> 6) & 0x03;
}
public void setPicType(int picType) {
value = value & (0xff >> 3);
value = (picType & 0x03) << 6 | value;
}
public int getDependencyLevel() {
return value & 0x3f;
}
public void setDependencyLevel(int dependencyLevel) {
value = (dependencyLevel & 0x3f) | value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder();
sb.append("Entry");
sb.append("{picType=").append(getPicType());
sb.append(",dependencyLevel=").append(getDependencyLevel());
sb.append('}');
return sb.toString();
| 211
| 72
| 283
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dolby/AC3SpecificBox.java
|
AC3SpecificBox
|
toString
|
class AC3SpecificBox extends AbstractBox {
public static final String TYPE = "dac3";
int fscod;
int bsid;
int bsmod;
int acmod;
int lfeon;
int bitRateCode;
int reserved;
public AC3SpecificBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 3;
}
@Override
public void _parseDetails(ByteBuffer content) {
BitReaderBuffer brb = new BitReaderBuffer(content);
fscod = brb.readBits(2);
bsid = brb.readBits(5);
bsmod = brb.readBits(3);
acmod = brb.readBits(3);
lfeon = brb.readBits(1);
bitRateCode = brb.readBits(5);
reserved = brb.readBits(5);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
BitWriterBuffer bwb = new BitWriterBuffer(byteBuffer);
bwb.writeBits(fscod, 2);
bwb.writeBits(bsid, 5);
bwb.writeBits(bsmod, 3);
bwb.writeBits(acmod, 3);
bwb.writeBits(lfeon, 1);
bwb.writeBits(bitRateCode, 5);
bwb.writeBits(reserved, 5);
}
public int getFscod() {
return fscod;
}
public void setFscod(int fscod) {
this.fscod = fscod;
}
public int getBsid() {
return bsid;
}
public void setBsid(int bsid) {
this.bsid = bsid;
}
public int getBsmod() {
return bsmod;
}
public void setBsmod(int bsmod) {
this.bsmod = bsmod;
}
public int getAcmod() {
return acmod;
}
public void setAcmod(int acmod) {
this.acmod = acmod;
}
public int getLfeon() {
return lfeon;
}
public void setLfeon(int lfeon) {
this.lfeon = lfeon;
}
public int getBitRateCode() {
return bitRateCode;
}
public void setBitRateCode(int bitRateCode) {
this.bitRateCode = bitRateCode;
}
public int getReserved() {
return reserved;
}
public void setReserved(int reserved) {
this.reserved = reserved;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "AC3SpecificBox{" +
"fscod=" + fscod +
", bsid=" + bsid +
", bsmod=" + bsmod +
", acmod=" + acmod +
", lfeon=" + lfeon +
", bitRateCode=" + bitRateCode +
", reserved=" + reserved +
'}';
| 774
| 104
| 878
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dolby/DoViConfigurationBox.java
|
DoViConfigurationBox
|
_parseDetails
|
class DoViConfigurationBox extends AbstractBox {
public static final String TYPE = "dvcC";
private int dvVersionMajor;
private int dvVersionMinor;
private int dvProfile;
private int dvLevel;
private boolean rpuPresentFlag;
private boolean elPresentFlag;
private boolean blPresentFlag;
private long reserved1;
private long reserved2;
private long reserved3;
private long reserved4;
private long reserved5;
public DoViConfigurationBox() {
super(TYPE);
}
protected long getContentSize() {
return 24;
}
protected void getContent(ByteBuffer byteBuffer) {
IsoTypeWriter.writeUInt8(byteBuffer, dvVersionMajor);
IsoTypeWriter.writeUInt8(byteBuffer, dvVersionMinor);
int x = 0;
x += (dvProfile & 127) << 9;
x += (dvProfile & 63) << 3;
x += rpuPresentFlag?0x4:0;
x += elPresentFlag?0x2:0;
x += blPresentFlag?0x1:0;
IsoTypeWriter.writeUInt16(byteBuffer, x);
IsoTypeWriter.writeUInt32(byteBuffer, reserved1);
IsoTypeWriter.writeUInt32(byteBuffer, reserved2);
IsoTypeWriter.writeUInt32(byteBuffer, reserved3);
IsoTypeWriter.writeUInt32(byteBuffer, reserved4);
IsoTypeWriter.writeUInt32(byteBuffer, reserved5);
}
protected void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public int getDvVersionMajor() {
return dvVersionMajor;
}
public void setDvVersionMajor(int dvVersionMajor) {
this.dvVersionMajor = dvVersionMajor;
}
public int getDvVersionMinor() {
return dvVersionMinor;
}
public void setDvVersionMinor(int dvVersionMinor) {
this.dvVersionMinor = dvVersionMinor;
}
public int getDvProfile() {
return dvProfile;
}
public void setDvProfile(int dvProfile) {
this.dvProfile = dvProfile;
}
public int getDvLevel() {
return dvLevel;
}
public void setDvLevel(int dvLevel) {
this.dvLevel = dvLevel;
}
public boolean isRpuPresentFlag() {
return rpuPresentFlag;
}
public void setRpuPresentFlag(boolean rpuPresentFlag) {
this.rpuPresentFlag = rpuPresentFlag;
}
public boolean isElPresentFlag() {
return elPresentFlag;
}
public void setElPresentFlag(boolean elPresentFlag) {
this.elPresentFlag = elPresentFlag;
}
public boolean isBlPresentFlag() {
return blPresentFlag;
}
public void setBlPresentFlag(boolean blPresentFlag) {
this.blPresentFlag = blPresentFlag;
}
public long getReserved1() {
return reserved1;
}
public void setReserved1(long reserved1) {
this.reserved1 = reserved1;
}
public long getReserved2() {
return reserved2;
}
public void setReserved2(long reserved2) {
this.reserved2 = reserved2;
}
public long getReserved3() {
return reserved3;
}
public void setReserved3(long reserved3) {
this.reserved3 = reserved3;
}
public long getReserved4() {
return reserved4;
}
public void setReserved4(long reserved4) {
this.reserved4 = reserved4;
}
public long getReserved5() {
return reserved5;
}
public void setReserved5(long reserved5) {
this.reserved5 = reserved5;
}
}
|
dvVersionMajor = IsoTypeReader.readUInt8(content);
dvVersionMinor = IsoTypeReader.readUInt8(content);
int x = IsoTypeReader.readUInt16(content);
dvProfile = (x >> 9) & 127;
dvLevel = (x >> 3) & 63;
rpuPresentFlag = (x & 0x4) > 0;
elPresentFlag = (x & 0x2) > 0;
blPresentFlag = (x & 0x1) > 0;
reserved1 = IsoTypeReader.readUInt32(content);
reserved2 = IsoTypeReader.readUInt32(content);
reserved3 = IsoTypeReader.readUInt32(content);
reserved4 = IsoTypeReader.readUInt32(content);
reserved5 = IsoTypeReader.readUInt32(content);
| 1,089
| 238
| 1,327
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dolby/EC3SpecificBox.java
|
Entry
|
toString
|
class Entry {
public int fscod;
public int bsid;
public int bsmod;
public int acmod;
public int lfeon;
public int reserved;
public int num_dep_sub;
public int chan_loc;
public int reserved2;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Entry{" +
"fscod=" + fscod +
", bsid=" + bsid +
", bsmod=" + bsmod +
", acmod=" + acmod +
", lfeon=" + lfeon +
", reserved=" + reserved +
", num_dep_sub=" + num_dep_sub +
", chan_loc=" + chan_loc +
", reserved2=" + reserved2 +
'}';
| 104
| 130
| 234
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/dolby/MLPSpecificBox.java
|
MLPSpecificBox
|
_parseDetails
|
class MLPSpecificBox extends AbstractBox {
public static final String TYPE = "dmlp";
int format_info;
int peak_data_rate;
int reserved;
int reserved2;
public MLPSpecificBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 10;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
BitWriterBuffer bwb = new BitWriterBuffer(byteBuffer);
bwb.writeBits(format_info, 32);
bwb.writeBits(peak_data_rate, 15);
bwb.writeBits(reserved, 1);
bwb.writeBits(reserved2, 32);
//To change body of implemented methods use File | Settings | File Templates.
}
public int getFormat_info() {
return format_info;
}
public void setFormat_info(int format_info) {
this.format_info = format_info;
}
public int getPeak_data_rate() {
return peak_data_rate;
}
public void setPeak_data_rate(int peak_data_rate) {
this.peak_data_rate = peak_data_rate;
}
public int getReserved() {
return reserved;
}
public void setReserved(int reserved) {
this.reserved = reserved;
}
public int getReserved2() {
return reserved2;
}
public void setReserved2(int reserved2) {
this.reserved2 = reserved2;
}
}
|
BitReaderBuffer brb = new BitReaderBuffer(content);
format_info = brb.readBits(32);
peak_data_rate = brb.readBits(15);
reserved = brb.readBits(1);
reserved2 = brb.readBits(32);
| 466
| 80
| 546
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/BaseDescriptor.java
|
BaseDescriptor
|
getSizeSize
|
class BaseDescriptor {
int tag;
int sizeOfInstance;
int sizeBytes;
public BaseDescriptor() {
}
public int getTag() {
return tag;
}
public void writeSize(ByteBuffer bb, int size) {
int pos = bb.position();
int i = 0;
while (size > 0 || i < sizeBytes) {
i++;
if (size > 0) {
bb.put(pos + getSizeSize() - i, (byte) (size & 0x7f));
} else {
bb.put(pos + getSizeSize() - i, (byte) (0x80));
}
size >>>= 7;
}
((Buffer)bb).position(pos + getSizeSize());
}
public int getSizeSize() {<FILL_FUNCTION_BODY>}
public int getSize() {
return getContentSize() + getSizeSize() + 1;
}
public final void parse(int tag, ByteBuffer bb) throws IOException {
this.tag = tag;
int i = 0;
int tmp = IsoTypeReader.readUInt8(bb);
i++;
sizeOfInstance = tmp & 0x7f;
while (tmp >>> 7 == 1) { //nextbyte indicator bit
tmp = IsoTypeReader.readUInt8(bb);
i++;
//sizeOfInstance = sizeOfInstance<<7 | sizeByte;
sizeOfInstance = sizeOfInstance << 7 | tmp & 0x7f;
}
sizeBytes = i;
ByteBuffer detailSource = bb.slice();
((Buffer)detailSource).limit(sizeOfInstance);
parseDetail(detailSource);
assert detailSource.remaining() == 0 : this.getClass().getSimpleName() + " has not been fully parsed";
((Buffer)bb).position(bb.position() + sizeOfInstance);
}
public abstract void parseDetail(ByteBuffer bb) throws IOException;
public abstract ByteBuffer serialize();
abstract int getContentSize();
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BaseDescriptor");
sb.append("{tag=").append(tag);
sb.append(", sizeOfInstance=").append(sizeOfInstance);
sb.append('}');
return sb.toString();
}
}
|
int size = getContentSize();
int i = 0;
while (size > 0 || i < sizeBytes) {
size >>>= 7;
i++;
}
return i;
| 618
| 54
| 672
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/BitReaderBuffer.java
|
BitReaderBuffer
|
readBits
|
class BitReaderBuffer {
int initialPos;
int position;
private ByteBuffer buffer;
public BitReaderBuffer(ByteBuffer buffer) {
this.buffer = buffer;
initialPos = buffer.position();
}
public boolean readBool() {
return readBits(1) == 1;
}
public int readBits(int i) {<FILL_FUNCTION_BODY>}
public int getPosition() {
return position;
}
public int byteSync() {
int left = 8 - position % 8;
if (left == 8) {
left = 0;
}
readBits(left);
return left;
}
public int remainingBits() {
return buffer.limit() * 8 - position;
}
}
|
byte b = buffer.get(initialPos + position / 8);
int v = b < 0 ? b + 256 : b;
int left = 8 - position % 8;
int rc;
if (i <= left) {
rc = (v << (position % 8) & 0xFF) >> ((position % 8) + (left - i));
position += i;
} else {
int now = left;
int then = i - left;
rc = readBits(now);
rc = rc << then;
rc += readBits(then);
}
((Buffer)buffer).position(initialPos + (int) Math.ceil((double) position / 8));
return rc;
| 207
| 191
| 398
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/BitWriterBuffer.java
|
BitWriterBuffer
|
writeBits
|
class BitWriterBuffer {
int initialPos;
int position = 0;
private ByteBuffer buffer;
public BitWriterBuffer(ByteBuffer buffer) {
this.buffer = buffer;
this.initialPos = buffer.position();
}
public void writeBool(boolean b) {
writeBits(b ? 1 : 0, 1);
}
public void writeBits(int i, int numBits) {<FILL_FUNCTION_BODY>}
}
|
assert i <= ((1 << numBits) - 1) : String.format("Trying to write a value bigger (%s) than the number bits (%s) allows. " +
"Please mask the value before writing it and make your code is really working as intended.", i, (1 << numBits) - 1);
int left = 8 - position % 8;
if (numBits <= left) {
int current = (buffer.get(initialPos + position / 8));
current = current < 0 ? current + 256 : current;
current += i << (left - numBits);
buffer.put(initialPos + position / 8, (byte) (current > 127 ? current - 256 : current));
position += numBits;
} else {
int bitsSecondWrite = numBits - left;
writeBits(i >> bitsSecondWrite, left);
writeBits(i & (1 << bitsSecondWrite) - 1, bitsSecondWrite);
}
((Buffer)buffer).position(initialPos + position / 8 + ((position % 8 > 0) ? 1 : 0));
| 128
| 282
| 410
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/DecoderSpecificInfo.java
|
DecoderSpecificInfo
|
serialize
|
class DecoderSpecificInfo extends BaseDescriptor {
byte[] bytes;
public DecoderSpecificInfo() {
tag = 0x5;
}
@Override
public void parseDetail(ByteBuffer bb) throws IOException {
bytes = new byte[bb.remaining()];
bb.get(bytes);
}
public void setData(byte[] bytes) {
this.bytes = bytes;
}
int getContentSize() {
return bytes.length;
}
public ByteBuffer serialize() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("DecoderSpecificInfo");
sb.append("{bytes=").append(bytes == null ? "null" : Hex.encodeHex(bytes));
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DecoderSpecificInfo that = (DecoderSpecificInfo) o;
if (!Arrays.equals(bytes, that.bytes)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return bytes != null ? Arrays.hashCode(bytes) : 0;
}
}
|
ByteBuffer out = ByteBuffer.allocate(getSize());
IsoTypeWriter.writeUInt8(out, tag);
writeSize(out, getContentSize());
out.put(bytes);
return (ByteBuffer) ((Buffer)out).rewind();
| 382
| 68
| 450
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/ExtensionDescriptor.java
|
ExtensionDescriptor
|
allTags
|
class ExtensionDescriptor extends BaseDescriptor {
private static Logger LOG = LoggerFactory.getLogger(ExtensionDescriptor.class.getName());
ByteBuffer data;
//todo: add this better to the tags list?
//14496-1:2010 p.20:
//0x6A-0xBF Reserved for ISO use
//0xC0-0xFE User private
//
//ExtDescrTagStartRange = 0x6A
//ExtDescrTagEndRange = 0xFE
static int[] allTags() {<FILL_FUNCTION_BODY>}
@Override
public void parseDetail(ByteBuffer bb) throws IOException {
data = bb.slice();
((Buffer)bb).position(bb.position() + data.remaining());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ExtensionDescriptor");
sb.append("tag=").append(tag);
sb.append(",bytes=").append(Hex.encodeHex(data.array()));
sb.append('}');
return sb.toString();
}
@Override
public ByteBuffer serialize() {
ByteBuffer out = ByteBuffer.allocate(getSize());
IsoTypeWriter.writeUInt8(out, tag);
writeSize(out, getContentSize());
out.put(data.duplicate());
return out;
}
@Override
int getContentSize() {
return data.remaining();
}
}
|
int[] ints = new int[0xFE - 0x6A];
for (int i = 0x6A; i < 0xFE; i++) {
final int pos = i - 0x6A;
LOG.trace("pos: {}", pos);
ints[pos] = i;
}
return ints;
| 394
| 91
| 485
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/ExtensionProfileLevelDescriptor.java
|
ExtensionProfileLevelDescriptor
|
parseDetail
|
class ExtensionProfileLevelDescriptor extends BaseDescriptor {
byte[] bytes;
public ExtensionProfileLevelDescriptor() {
tag = 0x13;
}
@Override
public void parseDetail(ByteBuffer bb) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public ByteBuffer serialize() {
throw new RuntimeException("Not Implemented");
}
@Override
int getContentSize() {
throw new RuntimeException("Not Implemented");
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ExtensionDescriptor");
sb.append("{bytes=").append(bytes == null ? "null" : Hex.encodeHex(bytes));
sb.append('}');
return sb.toString();
}
}
|
if (getSize() > 0) {
bytes = new byte[getSize()];
bb.get(bytes);
}
| 209
| 37
| 246
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/InitialObjectDescriptor.java
|
InitialObjectDescriptor
|
parseDetail
|
class InitialObjectDescriptor extends ObjectDescriptorBase {
int urlFlag;
int includeInlineProfileLevelFlag;
int urlLength;
String urlString;
int oDProfileLevelIndication;
int sceneProfileLevelIndication;
int audioProfileLevelIndication;
int visualProfileLevelIndication;
int graphicsProfileLevelIndication;
List<ESDescriptor> esDescriptors = new ArrayList<ESDescriptor>();
List<ExtensionDescriptor> extensionDescriptors = new ArrayList<ExtensionDescriptor>();
List<BaseDescriptor> unknownDescriptors = new ArrayList<BaseDescriptor>();
private int objectDescriptorId;
@Override
public void parseDetail(ByteBuffer bb) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("InitialObjectDescriptor");
sb.append("{objectDescriptorId=").append(objectDescriptorId);
sb.append(", urlFlag=").append(urlFlag);
sb.append(", includeInlineProfileLevelFlag=").append(includeInlineProfileLevelFlag);
sb.append(", urlLength=").append(urlLength);
sb.append(", urlString='").append(urlString).append('\'');
sb.append(", oDProfileLevelIndication=").append(oDProfileLevelIndication);
sb.append(", sceneProfileLevelIndication=").append(sceneProfileLevelIndication);
sb.append(", audioProfileLevelIndication=").append(audioProfileLevelIndication);
sb.append(", visualProfileLevelIndication=").append(visualProfileLevelIndication);
sb.append(", graphicsProfileLevelIndication=").append(graphicsProfileLevelIndication);
sb.append(", esDescriptors=").append(esDescriptors);
sb.append(", extensionDescriptors=").append(extensionDescriptors);
sb.append(", unknownDescriptors=").append(unknownDescriptors);
sb.append('}');
return sb.toString();
}
}
|
int data = IsoTypeReader.readUInt16(bb);
objectDescriptorId = (data & 0xFFC0) >> 6;
urlFlag = (data & 0x3F) >> 5;
includeInlineProfileLevelFlag = (data & 0x1F) >> 4;
int sizeLeft = getSize() - 2;
if (urlFlag == 1) {
urlLength = IsoTypeReader.readUInt8(bb);
urlString = IsoTypeReader.readString(bb, urlLength);
sizeLeft = sizeLeft - (1 + urlLength);
} else {
oDProfileLevelIndication = IsoTypeReader.readUInt8(bb);
sceneProfileLevelIndication = IsoTypeReader.readUInt8(bb);
audioProfileLevelIndication = IsoTypeReader.readUInt8(bb);
visualProfileLevelIndication = IsoTypeReader.readUInt8(bb);
graphicsProfileLevelIndication = IsoTypeReader.readUInt8(bb);
sizeLeft = sizeLeft - 5;
if (sizeLeft > 2) {
final BaseDescriptor descriptor = ObjectDescriptorFactory.createFrom(-1, bb);
sizeLeft = sizeLeft - descriptor.getSize();
if (descriptor instanceof ESDescriptor) {
esDescriptors.add((ESDescriptor) descriptor);
} else {
unknownDescriptors.add(descriptor);
}
}
}
if (sizeLeft > 2) {
final BaseDescriptor descriptor = ObjectDescriptorFactory.createFrom(-1, bb);
if (descriptor instanceof ExtensionDescriptor) {
extensionDescriptors.add((ExtensionDescriptor) descriptor);
} else {
unknownDescriptors.add(descriptor);
}
}
| 519
| 452
| 971
|
<methods>public non-sealed void <init>() <variables>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/ObjectDescriptorFactory.java
|
ObjectDescriptorFactory
|
createFrom
|
class ObjectDescriptorFactory {
protected static Logger LOG = LoggerFactory.getLogger(ObjectDescriptorFactory.class);
protected static Map<Integer, Map<Integer, Class<? extends BaseDescriptor>>> descriptorRegistry = new HashMap<Integer, Map<Integer, Class<? extends BaseDescriptor>>>();
static {
Set<Class<? extends BaseDescriptor>> annotated = new HashSet<Class<? extends BaseDescriptor>>();
annotated.add(DecoderSpecificInfo.class);
annotated.add(SLConfigDescriptor.class);
annotated.add(BaseDescriptor.class);
annotated.add(ExtensionDescriptor.class);
annotated.add(ObjectDescriptorBase.class);
annotated.add(ProfileLevelIndicationDescriptor.class);
annotated.add(AudioSpecificConfig.class);
annotated.add(ExtensionProfileLevelDescriptor.class);
annotated.add(ESDescriptor.class);
annotated.add(DecoderConfigDescriptor.class);
//annotated.add(ObjectDescriptor.class);
for (Class<? extends BaseDescriptor> clazz : annotated) {
final Descriptor descriptor = clazz.getAnnotation(Descriptor.class);
final int[] tags = descriptor.tags();
final int objectTypeInd = descriptor.objectTypeIndication();
Map<Integer, Class<? extends BaseDescriptor>> tagMap = descriptorRegistry.get(objectTypeInd);
if (tagMap == null) {
tagMap = new HashMap<Integer, Class<? extends BaseDescriptor>>();
}
for (int tag : tags) {
tagMap.put(tag, clazz);
}
descriptorRegistry.put(objectTypeInd, tagMap);
}
}
public static BaseDescriptor createFrom(int objectTypeIndication, ByteBuffer bb) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int tag = IsoTypeReader.readUInt8(bb);
Map<Integer, Class<? extends BaseDescriptor>> tagMap = descriptorRegistry.get(objectTypeIndication);
if (tagMap == null) {
tagMap = descriptorRegistry.get(-1);
}
Class<? extends BaseDescriptor> aClass = tagMap.get(tag);
// if (tag == 0x00) {
// log.warning("Found illegal tag 0x00! objectTypeIndication " + Integer.toHexString(objectTypeIndication) +
// " and tag " + Integer.toHexString(tag) + " using: " + aClass);
// aClass = BaseDescriptor.class;
// }
BaseDescriptor baseDescriptor;
if (aClass == null || aClass.isInterface() || Modifier.isAbstract(aClass.getModifiers())) {
if (LOG.isWarnEnabled()) {
LOG.warn("No ObjectDescriptor found for objectTypeIndication {} and tag {} found: {}",
Integer.toHexString(objectTypeIndication), Integer.toHexString(tag), aClass);
}
baseDescriptor = new UnknownDescriptor();
} else {
try {
baseDescriptor = aClass.newInstance();
} catch (Exception e) {
LOG.error("Couldn't instantiate BaseDescriptor class " + aClass + " for objectTypeIndication " + objectTypeIndication + " and tag " + tag, e);
throw new RuntimeException(e);
}
}
//ByteBuffer orig = bb.slice();
baseDescriptor.parse(tag, bb);
//byte[] b1 = new byte[baseDescriptor.sizeOfInstance + baseDescriptor.sizeBytes];
//orig.get(b1);
//byte[] b2 = baseDescriptor.serialize().array();
//System.err.println(baseDescriptor.getClass().getName() + " orig: " + Hex.encodeHex(b1) + " serialized: " + Hex.encodeHex(b2));
return baseDescriptor;
| 454
| 517
| 971
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/ProfileLevelIndicationDescriptor.java
|
ProfileLevelIndicationDescriptor
|
equals
|
class ProfileLevelIndicationDescriptor extends BaseDescriptor {
int profileLevelIndicationIndex;
public ProfileLevelIndicationDescriptor() {
tag = 0x14;
}
@Override
public void parseDetail(ByteBuffer bb) throws IOException {
profileLevelIndicationIndex = IsoTypeReader.readUInt8(bb);
}
@Override
public ByteBuffer serialize() {
ByteBuffer out = ByteBuffer.allocate(getSize());
IsoTypeWriter.writeUInt8(out, 0x14);
writeSize(out, getContentSize());
IsoTypeWriter.writeUInt8(out, profileLevelIndicationIndex);
return out;
}
@Override
public int getContentSize() {
return 1;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ProfileLevelIndicationDescriptor");
sb.append("{profileLevelIndicationIndex=").append(Integer.toHexString(profileLevelIndicationIndex));
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return profileLevelIndicationIndex;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileLevelIndicationDescriptor that = (ProfileLevelIndicationDescriptor) o;
if (profileLevelIndicationIndex != that.profileLevelIndicationIndex) {
return false;
}
return true;
| 343
| 105
| 448
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/SLConfigDescriptor.java
|
SLConfigDescriptor
|
equals
|
class SLConfigDescriptor extends BaseDescriptor {
int predefined;
public SLConfigDescriptor() {
tag = 0x06;
}
public int getPredefined() {
return predefined;
}
public void setPredefined(int predefined) {
this.predefined = predefined;
}
@Override
public void parseDetail(ByteBuffer bb) throws IOException {
predefined = IsoTypeReader.readUInt8(bb);
}
int getContentSize() {
return 1;
}
public ByteBuffer serialize() {
ByteBuffer out = ByteBuffer.allocate(getSize());
IsoTypeWriter.writeUInt8(out, 6);
writeSize(out, getContentSize());
IsoTypeWriter.writeUInt8(out, predefined);
return out;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("SLConfigDescriptor");
sb.append("{predefined=").append(predefined);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return predefined;
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SLConfigDescriptor that = (SLConfigDescriptor) o;
if (predefined != that.predefined) {
return false;
}
return true;
| 349
| 93
| 442
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part1/objectdescriptors/UnknownDescriptor.java
|
UnknownDescriptor
|
toString
|
class UnknownDescriptor extends BaseDescriptor {
private static Logger LOG = LoggerFactory.getLogger(UnknownDescriptor.class);
private ByteBuffer data;
@Override
public void parseDetail(ByteBuffer bb) throws IOException {
data = bb.slice();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public ByteBuffer serialize() {
throw new RuntimeException("sdjlhfl");
}
@Override
int getContentSize() {
throw new RuntimeException("sdjlhfl");
}
}
|
final StringBuilder sb = new StringBuilder();
sb.append("UnknownDescriptor");
sb.append("{tag=").append(tag);
sb.append(", sizeOfInstance=").append(sizeOfInstance);
sb.append(", data=").append(data);
sb.append('}');
return sb.toString();
| 153
| 84
| 237
|
<methods>public void <init>() ,public int getSize() ,public int getSizeSize() ,public int getTag() ,public final void parse(int, java.nio.ByteBuffer) throws java.io.IOException,public abstract void parseDetail(java.nio.ByteBuffer) throws java.io.IOException,public abstract java.nio.ByteBuffer serialize() ,public java.lang.String toString() ,public void writeSize(java.nio.ByteBuffer, int) <variables>int sizeBytes,int sizeOfInstance,int tag
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/BitRateBox.java
|
BitRateBox
|
_parseDetails
|
class BitRateBox extends AbstractBox {
public static final String TYPE = "btrt";
private long bufferSizeDb;
private long maxBitrate;
private long avgBitrate;
public BitRateBox() {
super(TYPE);
}
protected long getContentSize() {
return 12;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
IsoTypeWriter.writeUInt32(byteBuffer, bufferSizeDb);
IsoTypeWriter.writeUInt32(byteBuffer, maxBitrate);
IsoTypeWriter.writeUInt32(byteBuffer, avgBitrate);
}
/**
* Get the size of the decoding buffer for the elementary stream in bytes.
*
* @return decoding buffer size
*/
public long getBufferSizeDb() {
return bufferSizeDb;
}
/**
* Sets the size of the decoding buffer for the elementary stream in bytes
*
* @param bufferSizeDb decoding buffer size
*/
public void setBufferSizeDb(long bufferSizeDb) {
this.bufferSizeDb = bufferSizeDb;
}
/**
* gets the maximum rate in bits/second over any window of one second.
*
* @return max bit rate
*/
public long getMaxBitrate() {
return maxBitrate;
}
/**
* Sets the maximum rate in bits/second over any window of one second.
*
* @param maxBitrate max bit rate
*/
public void setMaxBitrate(long maxBitrate) {
this.maxBitrate = maxBitrate;
}
/**
* Gets the average rate in bits/second over the entire presentation.
*
* @return average bit rate
*/
public long getAvgBitrate() {
return avgBitrate;
}
/**
* Sets the average rate in bits/second over the entire presentation.
*
* @param avgBitrate the track's average bit rate
*/
public void setAvgBitrate(long avgBitrate) {
this.avgBitrate = avgBitrate;
}
}
|
bufferSizeDb = IsoTypeReader.readUInt32(content);
maxBitrate = IsoTypeReader.readUInt32(content);
avgBitrate = IsoTypeReader.readUInt32(content);
| 583
| 61
| 644
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/ChunkOffset64BitBox.java
|
ChunkOffset64BitBox
|
_parseDetails
|
class ChunkOffset64BitBox extends ChunkOffsetBox {
public static final String TYPE = "co64";
private long[] chunkOffsets;
public ChunkOffset64BitBox() {
super(TYPE);
}
@Override
public long[] getChunkOffsets() {
return chunkOffsets;
}
@Override
public void setChunkOffsets(long[] chunkOffsets) {
this.chunkOffsets = chunkOffsets;
}
@Override
protected long getContentSize() {
return 8 + 8 * chunkOffsets.length;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeUInt32(byteBuffer, chunkOffsets.length);
for (long chunkOffset : chunkOffsets) {
IsoTypeWriter.writeUInt64(byteBuffer, chunkOffset);
}
}
}
|
parseVersionAndFlags(content);
int entryCount = CastUtils.l2i(IsoTypeReader.readUInt32(content));
chunkOffsets = new long[entryCount];
for (int i = 0; i < entryCount; i++) {
chunkOffsets[i] = IsoTypeReader.readUInt64(content);
}
| 277
| 93
| 370
|
<methods>public void <init>(java.lang.String) ,public abstract long[] getChunkOffsets() ,public abstract void setChunkOffsets(long[]) ,public java.lang.String toString() <variables>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/CompositionTimeToSample.java
|
CompositionTimeToSample
|
blowupCompositionTimes
|
class CompositionTimeToSample extends AbstractFullBox {
public static final String TYPE = "ctts";
List<Entry> entries = Collections.emptyList();
public CompositionTimeToSample() {
super(TYPE);
}
/**
* Decompresses the list of entries and returns the list of composition times.
*
* @param entries composition time to sample entries in compressed form
* @return decoding time per sample
*/
public static int[] blowupCompositionTimes(List<CompositionTimeToSample.Entry> entries) {<FILL_FUNCTION_BODY>}
protected long getContentSize() {
return 8 + 8 * entries.size();
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
int numberOfEntries = CastUtils.l2i(IsoTypeReader.readUInt32(content));
entries = new ArrayList<Entry>(numberOfEntries);
for (int i = 0; i < numberOfEntries; i++) {
Entry e = new Entry(CastUtils.l2i(IsoTypeReader.readUInt32(content)), content.getInt());
entries.add(e);
}
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeUInt32(byteBuffer, entries.size());
for (Entry entry : entries) {
IsoTypeWriter.writeUInt32(byteBuffer, entry.getCount());
byteBuffer.putInt(entry.getOffset());
}
}
public static class Entry {
int count;
int offset;
public Entry(int count, int offset) {
this.count = count;
this.offset = offset;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
@Override
public String toString() {
return "Entry{" +
"count=" + count +
", offset=" + offset +
'}';
}
}
}
|
long numOfSamples = 0;
for (CompositionTimeToSample.Entry entry : entries) {
numOfSamples += entry.getCount();
}
assert numOfSamples <= Integer.MAX_VALUE;
int[] decodingTime = new int[(int) numOfSamples];
int current = 0;
for (CompositionTimeToSample.Entry entry : entries) {
for (int i = 0; i < entry.getCount(); i++) {
decodingTime[current++] = entry.getOffset();
}
}
return decodingTime;
| 642
| 151
| 793
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/CompositionToDecodeBox.java
|
CompositionToDecodeBox
|
_parseDetails
|
class CompositionToDecodeBox extends AbstractFullBox {
public static final String TYPE = "cslg";
// A 32-bit unsigned integer that specifies the calculated value.
int compositionOffsetToDisplayOffsetShift;
// A 32-bit signed integer that specifies the calculated value.
int leastDisplayOffset;
// A 32-bit signed integer that specifies the calculated value.
int greatestDisplayOffset;
//A 32-bit signed integer that specifies the calculated value.
int displayStartTime;
//A 32-bit signed integer that specifies the calculated value.
int displayEndTime;
public CompositionToDecodeBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 24;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
byteBuffer.putInt(compositionOffsetToDisplayOffsetShift);
byteBuffer.putInt(leastDisplayOffset);
byteBuffer.putInt(greatestDisplayOffset);
byteBuffer.putInt(displayStartTime);
byteBuffer.putInt(displayEndTime);
}
public int getCompositionOffsetToDisplayOffsetShift() {
return compositionOffsetToDisplayOffsetShift;
}
public void setCompositionOffsetToDisplayOffsetShift(int compositionOffsetToDisplayOffsetShift) {
this.compositionOffsetToDisplayOffsetShift = compositionOffsetToDisplayOffsetShift;
}
public int getLeastDisplayOffset() {
return leastDisplayOffset;
}
public void setLeastDisplayOffset(int leastDisplayOffset) {
this.leastDisplayOffset = leastDisplayOffset;
}
public int getGreatestDisplayOffset() {
return greatestDisplayOffset;
}
public void setGreatestDisplayOffset(int greatestDisplayOffset) {
this.greatestDisplayOffset = greatestDisplayOffset;
}
public int getDisplayStartTime() {
return displayStartTime;
}
public void setDisplayStartTime(int displayStartTime) {
this.displayStartTime = displayStartTime;
}
public int getDisplayEndTime() {
return displayEndTime;
}
public void setDisplayEndTime(int displayEndTime) {
this.displayEndTime = displayEndTime;
}
}
|
parseVersionAndFlags(content);
compositionOffsetToDisplayOffsetShift = content.getInt();
leastDisplayOffset = content.getInt();
greatestDisplayOffset = content.getInt();
displayStartTime = content.getInt();
displayEndTime = content.getInt();
| 609
| 70
| 679
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/DataEntryUrnBox.java
|
DataEntryUrnBox
|
toString
|
class DataEntryUrnBox extends AbstractFullBox {
public static final String TYPE = "urn ";
private String name;
private String location;
public DataEntryUrnBox() {
super(TYPE);
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
protected long getContentSize() {
return Utf8.utf8StringLengthInBytes(name) + 1 + Utf8.utf8StringLengthInBytes(location) + 1;
}
@Override
public void _parseDetails(ByteBuffer content) {
name = IsoTypeReader.readString(content);
location = IsoTypeReader.readString(content);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.put(Utf8.convert(name));
byteBuffer.put((byte) 0);
byteBuffer.put(Utf8.convert(location));
byteBuffer.put((byte) 0);
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "DataEntryUrlBox[name=" + getName() + ";location=" + getLocation() + "]";
| 285
| 32
| 317
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/DataReferenceBox.java
|
DataReferenceBox
|
parse
|
class DataReferenceBox extends AbstractContainerBox implements FullBox {
public static final String TYPE = "dref";
private int version;
private int flags;
public DataReferenceBox() {
super(TYPE);
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt8(versionFlagNumOfChildBoxes, version);
IsoTypeWriter.writeUInt24(versionFlagNumOfChildBoxes, flags);
IsoTypeWriter.writeUInt32(versionFlagNumOfChildBoxes, getBoxes().size());
writableByteChannel.write((ByteBuffer) ((Buffer)versionFlagNumOfChildBoxes).rewind());
writeContainer(writableByteChannel);
}
@Override
public long getSize() {
long s = getContainerSize();
long t = 8;
return s + t + ((largeBox || (s + t + 8) >= (1L << 32)) ? 16 : 8);
}
}
|
ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(8);
int required = versionFlagNumOfChildBoxes.limit();
while (required > 0){
int read = dataSource.read(versionFlagNumOfChildBoxes);
required -= read;
}
((Buffer)versionFlagNumOfChildBoxes).rewind();
version = IsoTypeReader.readUInt8(versionFlagNumOfChildBoxes);
flags = IsoTypeReader.readUInt24(versionFlagNumOfChildBoxes);
// number of child boxes is not required - ignore
initContainer(dataSource, contentSize - 8, boxParser);
| 423
| 164
| 587
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/DegradationPriorityBox.java
|
DegradationPriorityBox
|
_parseDetails
|
class DegradationPriorityBox extends AbstractFullBox {
int[] priorities = new int[0];
public DegradationPriorityBox() {
super("stdp");
}
@Override
protected long getContentSize() {
return 4 + priorities.length * 2;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
for (int priority : priorities) {
IsoTypeWriter.writeUInt16(byteBuffer, priority);
}
}
@Override
protected void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public int[] getPriorities() {
return priorities;
}
public void setPriorities(int[] priorities) {
this.priorities = priorities;
}
/*
aligned(8) class DegradationPriorityBox
extends FullBox(‘stdp’, version = 0, 0) {
int i;
for (i=0; i < sample_count; i++) {
unsigned int(16) priority;
}
}
*/
}
|
parseVersionAndFlags(content);
priorities = new int[content.remaining() / 2];
for (int i = 0; i < priorities.length; i++) {
priorities[i] = IsoTypeReader.readUInt16(content);
}
| 291
| 73
| 364
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/EditListBox.java
|
Entry
|
equals
|
class Entry {
EditListBox editListBox;
private long segmentDuration;
private long mediaTime;
private double mediaRate;
/**
* Creates a new <code>Entry</code> with all values set.
*
* @param editListBox parent <code>EditListBox</code>
* @param segmentDuration duration in movie timescale
* @param mediaTime starting time
* @param mediaRate relative play rate
*/
public Entry(EditListBox editListBox, long segmentDuration, long mediaTime, double mediaRate) {
this.segmentDuration = segmentDuration;
this.mediaTime = mediaTime;
this.mediaRate = mediaRate;
this.editListBox = editListBox;
}
public Entry(EditListBox editListBox, ByteBuffer bb) {
if (editListBox.getVersion() == 1) {
segmentDuration = IsoTypeReader.readUInt64(bb);
mediaTime = bb.getLong();
mediaRate = IsoTypeReader.readFixedPoint1616(bb);
} else {
segmentDuration = IsoTypeReader.readUInt32(bb);
mediaTime = bb.getInt();
mediaRate = IsoTypeReader.readFixedPoint1616(bb);
}
this.editListBox = editListBox;
}
/**
* The segment duration is an integer that specifies the duration
* of this edit segment in units of the timescale in the Movie
* Header Box
*
* @return segment duration in movie timescale
*/
public long getSegmentDuration() {
return segmentDuration;
}
/**
* The segment duration is an integer that specifies the duration
* of this edit segment in units of the timescale in the Movie
* Header Box
*
* @param segmentDuration new segment duration in movie timescale
*/
public void setSegmentDuration(long segmentDuration) {
this.segmentDuration = segmentDuration;
}
/**
* The media time is an integer containing the starting time
* within the media of a specific edit segment(in media time
* scale units, in composition time)
*
* @return starting time
*/
public long getMediaTime() {
return mediaTime;
}
/**
* The media time is an integer containing the starting time
* within the media of a specific edit segment(in media time
* scale units, in composition time)
*
* @param mediaTime starting time
*/
public void setMediaTime(long mediaTime) {
this.mediaTime = mediaTime;
}
/**
* The media rate specifies the relative rate at which to play the
* media corresponding to a specific edit segment.
*
* @return relative play rate
*/
public double getMediaRate() {
return mediaRate;
}
/**
* The media rate specifies the relative rate at which to play the
* media corresponding to a specific edit segment.
*
* @param mediaRate new relative play rate
*/
public void setMediaRate(double mediaRate) {
this.mediaRate = mediaRate;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = (int) (segmentDuration ^ (segmentDuration >>> 32));
result = 31 * result + (int) (mediaTime ^ (mediaTime >>> 32));
return result;
}
public void getContent(ByteBuffer bb) {
if (editListBox.getVersion() == 1) {
IsoTypeWriter.writeUInt64(bb, segmentDuration);
bb.putLong(mediaTime);
} else {
IsoTypeWriter.writeUInt32(bb, CastUtils.l2i(segmentDuration));
bb.putInt(CastUtils.l2i(mediaTime));
}
IsoTypeWriter.writeFixedPoint1616(bb, mediaRate);
}
@Override
public String toString() {
return "Entry{" +
"segmentDuration=" + segmentDuration +
", mediaTime=" + mediaTime +
", mediaRate=" + mediaRate +
'}';
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Entry entry = (Entry) o;
if (mediaTime != entry.mediaTime) {
return false;
}
if (segmentDuration != entry.segmentDuration) {
return false;
}
return true;
| 1,088
| 111
| 1,199
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/FileTypeBox.java
|
FileTypeBox
|
_parseDetails
|
class FileTypeBox extends AbstractBox {
public static final String TYPE = "ftyp";
private String majorBrand;
private long minorVersion;
private List<String> compatibleBrands = Collections.emptyList();
public FileTypeBox() {
super(TYPE);
}
public FileTypeBox(String majorBrand, long minorVersion, List<String> compatibleBrands) {
super(TYPE);
this.majorBrand = majorBrand;
this.minorVersion = minorVersion;
this.compatibleBrands = compatibleBrands;
}
protected long getContentSize() {
return 8 + compatibleBrands.size() * 4;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.put(IsoFile.fourCCtoBytes(majorBrand));
IsoTypeWriter.writeUInt32(byteBuffer, minorVersion);
for (String compatibleBrand : compatibleBrands) {
byteBuffer.put(IsoFile.fourCCtoBytes(compatibleBrand));
}
}
/**
* Gets the brand identifier.
*
* @return the brand identifier
*/
public String getMajorBrand() {
return majorBrand;
}
/**
* Sets the major brand of the file used to determine an appropriate reader.
*
* @param majorBrand the new major brand
*/
public void setMajorBrand(String majorBrand) {
this.majorBrand = majorBrand;
}
/**
* Gets an informative integer for the minor version of the major brand.
*
* @return an informative integer
* @see FileTypeBox#getMajorBrand()
*/
public long getMinorVersion() {
return minorVersion;
}
/**
* Sets the "informative integer for the minor version of the major brand".
*
* @param minorVersion the version number of the major brand
*/
public void setMinorVersion(long minorVersion) {
this.minorVersion = minorVersion;
}
/**
* Gets an array of 4-cc brands.
*
* @return the compatible brands
*/
public List<String> getCompatibleBrands() {
return compatibleBrands;
}
public void setCompatibleBrands(List<String> compatibleBrands) {
this.compatibleBrands = compatibleBrands;
}
@DoNotParseDetail
public String toString() {
StringBuilder result = new StringBuilder();
result.append("FileTypeBox[");
result.append("majorBrand=").append(getMajorBrand());
result.append(";");
result.append("minorVersion=").append(getMinorVersion());
for (String compatibleBrand : compatibleBrands) {
result.append(";");
result.append("compatibleBrand=").append(compatibleBrand);
}
result.append("]");
return result.toString();
}
}
|
majorBrand = IsoTypeReader.read4cc(content);
minorVersion = IsoTypeReader.readUInt32(content);
int compatibleBrandsCount = content.remaining() / 4;
compatibleBrands = new LinkedList<String>();
for (int i = 0; i < compatibleBrandsCount; i++) {
compatibleBrands.add(IsoTypeReader.read4cc(content));
}
| 789
| 110
| 899
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/FreeBox.java
|
FreeBox
|
equals
|
class FreeBox implements ParsableBox {
public static final String TYPE = "free";
ByteBuffer data;
List<ParsableBox> replacers = new LinkedList<ParsableBox>();
private Container parent;
private long offset;
public FreeBox() {
this.data = ByteBuffer.wrap(new byte[0]);
}
public FreeBox(int size) {
this.data = ByteBuffer.allocate(size);
}
public ByteBuffer getData() {
if (data != null) {
return (ByteBuffer) ((Buffer)data.duplicate()).rewind();
} else {
return null;
}
}
public void setData(ByteBuffer data) {
this.data = data;
}
public void getBox(WritableByteChannel os) throws IOException {
for (ParsableBox replacer : replacers) {
replacer.getBox(os);
}
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, 8 + data.limit());
header.put(TYPE.getBytes());
((Buffer)header).rewind();
os.write(header);
((Buffer)header).rewind();
((Buffer)data).rewind();
os.write(data);
((Buffer)data).rewind();
}
public long getSize() {
long size = 8;
for (ParsableBox replacer : replacers) {
size += replacer.getSize();
}
size += data.limit();
return size;
}
public String getType() {
return TYPE;
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
data = ByteBuffer.allocate(CastUtils.l2i(contentSize));
int bytesRead = 0;
int b;
while (((((b = dataSource.read(data))) + bytesRead) < contentSize)) {
bytesRead += b;
}
}
public void addAndReplace(ParsableBox parsableBox) {
((Buffer)data).position(CastUtils.l2i(parsableBox.getSize()));
data = data.slice();
replacers.add(parsableBox);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return data != null ? data.hashCode() : 0;
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FreeBox freeBox = (FreeBox) o;
if (getData() != null ? !getData().equals(freeBox.getData()) : freeBox.getData() != null) return false;
return true;
| 659
| 93
| 752
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/FreeSpaceBox.java
|
FreeSpaceBox
|
toString
|
class FreeSpaceBox extends AbstractBox {
public static final String TYPE = "skip";
byte[] data;
public FreeSpaceBox() {
super(TYPE);
}
protected long getContentSize() {
return data.length;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public void _parseDetails(ByteBuffer content) {
data = new byte[content.remaining()];
content.get(data);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
byteBuffer.put(data);
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "FreeSpaceBox[size=" + data.length + ";type=" + getType() + "]";
| 202
| 31
| 233
|
<methods>public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public byte[] getUserType() ,public boolean isParsed() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public final synchronized void parseDetails() <variables>private static org.slf4j.Logger LOG,protected java.nio.ByteBuffer content,private java.nio.ByteBuffer deadBytes,boolean isParsed,protected java.lang.String type,private byte[] userType
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/HandlerBox.java
|
HandlerBox
|
getContent
|
class HandlerBox extends AbstractFullBox {
public static final String TYPE = "hdlr";
public static final Map<String, String> readableTypes;
static {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("odsm", "ObjectDescriptorStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("crsm", "ClockReferenceStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("sdsm", "SceneDescriptionStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("m7sm", "MPEG7Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("ocsm", "ObjectContentInfoStream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("ipsm", "IPMP Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("mjsm", "MPEG-J Stream - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
hm.put("mdir", "Apple Meta Data iTunes Reader");
hm.put("mp7b", "MPEG-7 binary XML");
hm.put("mp7t", "MPEG-7 XML");
hm.put("vide", "Video Track");
hm.put("soun", "Sound Track");
hm.put("hint", "Hint Track");
hm.put("appl", "Apple specific");
hm.put("meta", "Timed Metadata track - defined in ISO/IEC JTC1/SC29/WG11 - CODING OF MOVING PICTURES AND AUDIO");
readableTypes = Collections.unmodifiableMap(hm);
}
private String handlerType;
private String name = null;
private long a, b, c;
private boolean zeroTerm = true;
private long shouldBeZeroButAppleWritesHereSomeValue;
public HandlerBox() {
super(TYPE);
}
public String getHandlerType() {
return handlerType;
}
public void setHandlerType(String handlerType) {
this.handlerType = handlerType;
}
public String getName() {
return name;
}
/**
* You are required to add a '\0' string termination by yourself.
*
* @param name the new human readable name
*/
public void setName(String name) {
this.name = name;
}
public String getHumanReadableTrackType() {
return readableTypes.get(handlerType) != null ? readableTypes.get(handlerType) : "Unknown Handler Type";
}
protected long getContentSize() {
if (zeroTerm) {
return 25 + Utf8.utf8StringLengthInBytes(name);
} else {
return 24 + Utf8.utf8StringLengthInBytes(name);
}
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
shouldBeZeroButAppleWritesHereSomeValue = IsoTypeReader.readUInt32(content);
handlerType = IsoTypeReader.read4cc(content);
a = IsoTypeReader.readUInt32(content);
b = IsoTypeReader.readUInt32(content);
c = IsoTypeReader.readUInt32(content);
if (content.remaining() > 0) {
name = IsoTypeReader.readString(content, content.remaining());
if (name.endsWith("\0")) {
name = name.substring(0, name.length() - 1);
zeroTerm = true;
} else {
zeroTerm = false;
}
} else {
zeroTerm = false; //No string at all, not even zero term char
}
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
public String toString() {
return "HandlerBox[handlerType=" + getHandlerType() + ";name=" + getName() + "]";
}
}
|
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeUInt32(byteBuffer, shouldBeZeroButAppleWritesHereSomeValue);
byteBuffer.put(IsoFile.fourCCtoBytes(handlerType));
IsoTypeWriter.writeUInt32(byteBuffer, a);
IsoTypeWriter.writeUInt32(byteBuffer, b);
IsoTypeWriter.writeUInt32(byteBuffer, c);
if (name != null) {
byteBuffer.put(Utf8.convert(name));
}
if (zeroTerm) {
byteBuffer.put((byte) 0);
}
| 1,238
| 164
| 1,402
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/HintMediaHeaderBox.java
|
HintMediaHeaderBox
|
toString
|
class HintMediaHeaderBox extends AbstractMediaHeaderBox {
public static final String TYPE = "hmhd";
private int maxPduSize;
private int avgPduSize;
private long maxBitrate;
private long avgBitrate;
public HintMediaHeaderBox() {
super(TYPE);
}
public int getMaxPduSize() {
return maxPduSize;
}
public int getAvgPduSize() {
return avgPduSize;
}
public long getMaxBitrate() {
return maxBitrate;
}
public long getAvgBitrate() {
return avgBitrate;
}
protected long getContentSize() {
return 20;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
maxPduSize = IsoTypeReader.readUInt16(content);
avgPduSize = IsoTypeReader.readUInt16(content);
maxBitrate = IsoTypeReader.readUInt32(content);
avgBitrate = IsoTypeReader.readUInt32(content);
IsoTypeReader.readUInt32(content); // reserved!
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
IsoTypeWriter.writeUInt16(byteBuffer, maxPduSize);
IsoTypeWriter.writeUInt16(byteBuffer, avgPduSize);
IsoTypeWriter.writeUInt32(byteBuffer, maxBitrate);
IsoTypeWriter.writeUInt32(byteBuffer, avgBitrate);
IsoTypeWriter.writeUInt32(byteBuffer, 0);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "HintMediaHeaderBox{" +
"maxPduSize=" + maxPduSize +
", avgPduSize=" + avgPduSize +
", maxBitrate=" + maxBitrate +
", avgBitrate=" + avgBitrate +
'}';
| 485
| 79
| 564
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/HintSampleEntry.java
|
HintSampleEntry
|
parse
|
class HintSampleEntry extends AbstractSampleEntry {
protected byte[] data;
public HintSampleEntry(String type) {
super(type);
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
ByteBuffer byteBuffer = ByteBuffer.allocate(8);
((Buffer)byteBuffer).position(6);
IsoTypeWriter.writeUInt16(byteBuffer, dataReferenceIndex);
((Buffer)byteBuffer).rewind();
writableByteChannel.write(byteBuffer);
writableByteChannel.write(ByteBuffer.wrap(data));
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public long getSize() {
long s = 8 + data.length;
return s + ((largeBox || (s + 8) >= (1L << 32)) ? 16 : 8);
}
}
|
ByteBuffer b1 = ByteBuffer.allocate(8);
dataSource.read(b1);
((Buffer)b1).position(6);
dataReferenceIndex = IsoTypeReader.readUInt16(b1);
data = new byte[CastUtils.l2i(contentSize - 8)];
dataSource.read(ByteBuffer.wrap(data));
| 315
| 95
| 410
|
<methods>public abstract void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public int getDataReferenceIndex() ,public abstract void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setDataReferenceIndex(int) <variables>protected int dataReferenceIndex
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/ItemProtectionBox.java
|
ItemProtectionBox
|
getSize
|
class ItemProtectionBox extends AbstractContainerBox implements FullBox {
public static final String TYPE = "ipro";
private int version;
private int flags;
public ItemProtectionBox() {
super(TYPE);
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
public SchemeInformationBox getItemProtectionScheme() {
if (!getBoxes(SchemeInformationBox.class).isEmpty()) {
return getBoxes(SchemeInformationBox.class).get(0);
} else {
return null;
}
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(6);
dataSource.read(versionFlagNumOfChildBoxes);
((Buffer)versionFlagNumOfChildBoxes).rewind();
version = IsoTypeReader.readUInt8(versionFlagNumOfChildBoxes);
flags = IsoTypeReader.readUInt24(versionFlagNumOfChildBoxes);
// number of child boxes is not required
initContainer(dataSource, contentSize - 6, boxParser);
}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(6);
IsoTypeWriter.writeUInt8(versionFlagNumOfChildBoxes, version);
IsoTypeWriter.writeUInt24(versionFlagNumOfChildBoxes, flags);
IsoTypeWriter.writeUInt16(versionFlagNumOfChildBoxes, getBoxes().size());
writableByteChannel.write((ByteBuffer) ((Buffer)versionFlagNumOfChildBoxes).rewind());
writeContainer(writableByteChannel);
}
@Override
public long getSize() {<FILL_FUNCTION_BODY>}
}
|
long s = getContainerSize();
long t = 6; // bytes to container start
return s + t + ((largeBox || (s + t) >= (1L << 32)) ? 16 : 8);
| 567
| 56
| 623
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MediaDataBox.java
|
MediaDataBox
|
parse
|
class MediaDataBox implements ParsableBox, Closeable {
public static final String TYPE = "mdat";
ByteBuffer header;
File dataFile;
public String getType() {
return TYPE;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write((ByteBuffer) ((Buffer)header).rewind());
try (FileInputStream fis = new FileInputStream(dataFile);
FileChannel fc = fis.getChannel()) {
fc.transferTo(0, dataFile.lastModified(), writableByteChannel);
}
}
public long getSize() {
return header.limit() + dataFile.length();
}
/**
* {@inheritDoc}
*/
@DoNotParseDetail
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void close() throws IOException {
if (dataFile != null) {
dataFile.delete();
}
}
}
|
dataFile = File.createTempFile("MediaDataBox", super.toString());
// make sure to clean up temp file
dataFile.deleteOnExit();
this.header = ByteBuffer.allocate(header.limit());
this.header.put(header);
try (RandomAccessFile raf = new RandomAccessFile(dataFile, "rw")) {
raf.getChannel().transferFrom(dataSource, 0, contentSize);
}
| 282
| 117
| 399
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MediaHeaderBox.java
|
MediaHeaderBox
|
getContentSize
|
class MediaHeaderBox extends AbstractFullBox {
public static final String TYPE = "mdhd";
private static Logger LOG = LoggerFactory.getLogger(MediaHeaderBox.class);
private Date creationTime = new Date();
private Date modificationTime = new Date();
private long timescale;
private long duration;
private String language = "eng";
public MediaHeaderBox() {
super(TYPE);
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public long getTimescale() {
return timescale;
}
public void setTimescale(long timescale) {
this.timescale = timescale;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
protected long getContentSize() {<FILL_FUNCTION_BODY>}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
if (getVersion() == 1) {
creationTime = DateHelper.convert(IsoTypeReader.readUInt64(content));
modificationTime = DateHelper.convert(IsoTypeReader.readUInt64(content));
timescale = IsoTypeReader.readUInt32(content);
duration = content.getLong();
} else {
creationTime = DateHelper.convert(IsoTypeReader.readUInt32(content));
modificationTime = DateHelper.convert(IsoTypeReader.readUInt32(content));
timescale = IsoTypeReader.readUInt32(content);
duration = content.getInt();
}
if (duration < -1) {
LOG.warn("mdhd duration is not in expected range");
}
language = IsoTypeReader.readIso639(content);
IsoTypeReader.readUInt16(content);
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append("MediaHeaderBox[");
result.append("creationTime=").append(getCreationTime());
result.append(";");
result.append("modificationTime=").append(getModificationTime());
result.append(";");
result.append("timescale=").append(getTimescale());
result.append(";");
result.append("duration=").append(getDuration());
result.append(";");
result.append("language=").append(getLanguage());
result.append("]");
return result.toString();
}
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
if (getVersion() == 1) {
IsoTypeWriter.writeUInt64(byteBuffer, DateHelper.convert(creationTime));
IsoTypeWriter.writeUInt64(byteBuffer, DateHelper.convert(modificationTime));
IsoTypeWriter.writeUInt32(byteBuffer, timescale);
byteBuffer.putLong(duration);
} else {
IsoTypeWriter.writeUInt32(byteBuffer, DateHelper.convert(creationTime));
IsoTypeWriter.writeUInt32(byteBuffer, DateHelper.convert(modificationTime));
IsoTypeWriter.writeUInt32(byteBuffer, timescale);
byteBuffer.putInt((int) duration);
}
IsoTypeWriter.writeIso639(byteBuffer, language);
IsoTypeWriter.writeUInt16(byteBuffer, 0);
}
}
|
long contentSize = 4;
if (getVersion() == 1) {
contentSize += 8 + 8 + 4 + 8;
} else {
contentSize += 4 + 4 + 4 + 4;
}
contentSize += 2;
contentSize += 2;
return contentSize;
| 1,014
| 77
| 1,091
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MediaInformationBox.java
|
MediaInformationBox
|
getMediaHeaderBox
|
class MediaInformationBox extends AbstractContainerBox {
public static final String TYPE = "minf";
public MediaInformationBox() {
super(TYPE);
}
public SampleTableBox getSampleTableBox() {
return Path.getPath(this, "stbl[0]");
}
public AbstractMediaHeaderBox getMediaHeaderBox() {<FILL_FUNCTION_BODY>}
}
|
for (Box box : getBoxes()) {
if (box instanceof AbstractMediaHeaderBox) {
return (AbstractMediaHeaderBox) box;
}
}
return null;
| 102
| 49
| 151
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MetaBox.java
|
MetaBox
|
parse
|
class MetaBox extends AbstractContainerBox {
public static final String TYPE = "meta";
private int version;
private int flags;
private boolean quickTimeFormat;
public MetaBox() {
super(TYPE);
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
/**
* Parses the version/flags header and returns the remaining box size.
*
* @param content the <code>ByteBuffer</code> that contains the version & flag
* @return number of bytes read
*/
protected final long parseVersionAndFlags(ByteBuffer content) {
version = IsoTypeReader.readUInt8(content);
flags = IsoTypeReader.readUInt24(content);
return 4;
}
protected final void writeVersionAndFlags(ByteBuffer bb) {
IsoTypeWriter.writeUInt8(bb, version);
IsoTypeWriter.writeUInt24(bb, flags);
}
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
writableByteChannel.write(getHeader());
if (!quickTimeFormat) {
ByteBuffer bb = ByteBuffer.allocate(4);
writeVersionAndFlags(bb);
writableByteChannel.write((ByteBuffer) ((Buffer)bb).rewind());
}
writeContainer(writableByteChannel);
}
@Override
public long getSize() {
long s = getContainerSize();
long t = quickTimeFormat ? 0 : 4; // bytes to container start
return s + t + ((largeBox || (s + t) >= (1L << 32)) ? 16 : 8);
}
}
|
// Read first 20 bytes to determine whether the file is formatted according to QuickTime File Format.
RewindableReadableByteChannel rewindableDataSource = new RewindableReadableByteChannel(dataSource, 20);
ByteBuffer bb = ByteBuffer.allocate(20);
int bytesRead = rewindableDataSource.read(bb);
if (bytesRead == 20) {
// If the second and the fifth 32-bit integers encode 'hdlr' and 'mdta' respectively then the MetaBox is
// formatted according to QuickTime File Format.
// See https://developer.apple.com/library/content/documentation/QuickTime/QTFF/Metadata/Metadata.html
((Buffer)bb).position(4);
String second4cc = IsoTypeReader.read4cc(bb);
((Buffer)bb).position(16);
String fifth4cc = IsoTypeReader.read4cc(bb);
if ("hdlr".equals(second4cc) && "mdta".equals(fifth4cc)) {
quickTimeFormat = true;
}
}
rewindableDataSource.rewind();
if (!quickTimeFormat) {
bb = ByteBuffer.allocate(4);
rewindableDataSource.read(bb);
parseVersionAndFlags((ByteBuffer) ((Buffer)bb).rewind());
}
int bytesUsed = quickTimeFormat ? 0 : 4;
initContainer(rewindableDataSource, contentSize - bytesUsed, boxParser);
| 543
| 382
| 925
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MovieBox.java
|
MovieBox
|
getTrackNumbers
|
class MovieBox extends AbstractContainerBox {
public static final String TYPE = "moov";
public MovieBox() {
super(TYPE);
}
public int getTrackCount() {
return getBoxes(TrackBox.class).size();
}
/**
* Returns the track numbers associated with this <code>MovieBox</code>.
*
* @return the tracknumbers (IDs) of the tracks in their order of appearance in the file
*/
public long[] getTrackNumbers() {<FILL_FUNCTION_BODY>}
public MovieHeaderBox getMovieHeaderBox() {
return Path.getPath(this, "mvhd");
}
}
|
List<TrackBox> trackBoxes = this.getBoxes(TrackBox.class);
long[] trackNumbers = new long[trackBoxes.size()];
for (int trackCounter = 0; trackCounter < trackBoxes.size(); trackCounter++) {
trackNumbers[trackCounter] = trackBoxes.get(trackCounter).getTrackHeaderBox().getTrackId();
}
return trackNumbers;
| 178
| 106
| 284
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MovieExtendsHeaderBox.java
|
MovieExtendsHeaderBox
|
_parseDetails
|
class MovieExtendsHeaderBox extends AbstractFullBox {
public static final String TYPE = "mehd";
private long fragmentDuration;
public MovieExtendsHeaderBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return getVersion() == 1 ? 12 : 8;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
if (getVersion() == 1) {
IsoTypeWriter.writeUInt64(byteBuffer, fragmentDuration);
} else {
IsoTypeWriter.writeUInt32(byteBuffer, fragmentDuration);
}
}
public long getFragmentDuration() {
return fragmentDuration;
}
public void setFragmentDuration(long fragmentDuration) {
this.fragmentDuration = fragmentDuration;
}
}
|
parseVersionAndFlags(content);
fragmentDuration = getVersion() == 1 ? IsoTypeReader.readUInt64(content) : IsoTypeReader.readUInt32(content);
| 251
| 50
| 301
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MovieFragmentBox.java
|
MovieFragmentBox
|
getTrackNumbers
|
class MovieFragmentBox extends AbstractContainerBox {
public static final String TYPE = "moof";
public MovieFragmentBox() {
super(TYPE);
}
public List<Long> getSyncSamples(SampleDependencyTypeBox sdtp) {
List<Long> result = new ArrayList<Long>();
final List<SampleDependencyTypeBox.Entry> sampleEntries = sdtp.getEntries();
long i = 1;
for (SampleDependencyTypeBox.Entry sampleEntry : sampleEntries) {
if (sampleEntry.getSampleDependsOn() == 2) {
result.add(i);
}
i++;
}
return result;
}
public int getTrackCount() {
return getBoxes(TrackFragmentBox.class, false).size();
}
/**
* Returns the track numbers associated with this <code>MovieBox</code>.
*
* @return the tracknumbers (IDs) of the tracks in their order of appearance in the file
*/
public long[] getTrackNumbers() {<FILL_FUNCTION_BODY>}
public List<TrackFragmentHeaderBox> getTrackFragmentHeaderBoxes() {
return Path.getPaths((Container) this, "tfhd");
}
public List<TrackRunBox> getTrackRunBoxes() {
return getBoxes(TrackRunBox.class, true);
}
}
|
List<TrackFragmentBox> trackBoxes = this.getBoxes(TrackFragmentBox.class, false);
long[] trackNumbers = new long[trackBoxes.size()];
for (int trackCounter = 0; trackCounter < trackBoxes.size(); trackCounter++) {
TrackFragmentBox trackBoxe = trackBoxes.get(trackCounter);
trackNumbers[trackCounter] = trackBoxe.getTrackFragmentHeaderBox().getTrackId();
}
return trackNumbers;
| 359
| 124
| 483
|
<methods>public void <init>(java.lang.String) ,public void getBox(java.nio.channels.WritableByteChannel) throws java.io.IOException,public long getSize() ,public java.lang.String getType() ,public void parse(java.nio.channels.ReadableByteChannel, java.nio.ByteBuffer, long, org.mp4parser.BoxParser) throws java.io.IOException,public void setParent(org.mp4parser.Container) <variables>protected boolean largeBox,org.mp4parser.Container parent,protected java.lang.String type
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/MovieHeaderBox.java
|
MovieHeaderBox
|
_parseDetails
|
class MovieHeaderBox extends AbstractFullBox {
public static final String TYPE = "mvhd";
private static Logger LOG = LoggerFactory.getLogger(MovieHeaderBox.class);
private Date creationTime;
private Date modificationTime;
private long timescale;
private long duration;
private double rate = 1.0;
private float volume = 1.0f;
private Matrix matrix = Matrix.ROTATE_0;
private long nextTrackId;
private int previewTime;
private int previewDuration;
private int posterTime;
private int selectionTime;
private int selectionDuration;
private int currentTime;
public MovieHeaderBox() {
super(TYPE);
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
if (DateHelper.convert(creationTime) >= (1L << 32)) {
setVersion(1);
}
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
if (DateHelper.convert(modificationTime) >= (1L << 32)) {
setVersion(1);
}
}
public long getTimescale() {
return timescale;
}
public void setTimescale(long timescale) {
this.timescale = timescale;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
if (duration >= (1L << 32)) {
setVersion(1);
}
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public float getVolume() {
return volume;
}
public void setVolume(float volume) {
this.volume = volume;
}
public Matrix getMatrix() {
return matrix;
}
public void setMatrix(Matrix matrix) {
this.matrix = matrix;
}
public long getNextTrackId() {
return nextTrackId;
}
public void setNextTrackId(long nextTrackId) {
this.nextTrackId = nextTrackId;
}
protected long getContentSize() {
long contentSize = 4;
if (getVersion() == 1) {
contentSize += 28;
} else {
contentSize += 16;
}
contentSize += 80;
return contentSize;
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public String toString() {
StringBuilder result = new StringBuilder();
result.append("MovieHeaderBox[");
result.append("creationTime=").append(getCreationTime());
result.append(";");
result.append("modificationTime=").append(getModificationTime());
result.append(";");
result.append("timescale=").append(getTimescale());
result.append(";");
result.append("duration=").append(getDuration());
result.append(";");
result.append("rate=").append(getRate());
result.append(";");
result.append("volume=").append(getVolume());
result.append(";");
result.append("matrix=").append(matrix);
result.append(";");
result.append("nextTrackId=").append(getNextTrackId());
result.append("]");
return result.toString();
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
if (getVersion() == 1) {
IsoTypeWriter.writeUInt64(byteBuffer, DateHelper.convert(creationTime));
IsoTypeWriter.writeUInt64(byteBuffer, DateHelper.convert(modificationTime));
IsoTypeWriter.writeUInt32(byteBuffer, timescale);
byteBuffer.putLong(duration);
} else {
IsoTypeWriter.writeUInt32(byteBuffer, DateHelper.convert(creationTime));
IsoTypeWriter.writeUInt32(byteBuffer, DateHelper.convert(modificationTime));
IsoTypeWriter.writeUInt32(byteBuffer, timescale);
byteBuffer.putInt((int) duration);
}
IsoTypeWriter.writeFixedPoint1616(byteBuffer, rate);
IsoTypeWriter.writeFixedPoint88(byteBuffer, volume);
IsoTypeWriter.writeUInt16(byteBuffer, 0);
IsoTypeWriter.writeUInt32(byteBuffer, 0);
IsoTypeWriter.writeUInt32(byteBuffer, 0);
matrix.getContent(byteBuffer);
byteBuffer.putInt(previewTime);
byteBuffer.putInt(previewDuration);
byteBuffer.putInt(posterTime);
byteBuffer.putInt(selectionTime);
byteBuffer.putInt(selectionDuration);
byteBuffer.putInt(currentTime);
IsoTypeWriter.writeUInt32(byteBuffer, nextTrackId);
}
public int getPreviewTime() {
return previewTime;
}
public void setPreviewTime(int previewTime) {
this.previewTime = previewTime;
}
public int getPreviewDuration() {
return previewDuration;
}
public void setPreviewDuration(int previewDuration) {
this.previewDuration = previewDuration;
}
public int getPosterTime() {
return posterTime;
}
public void setPosterTime(int posterTime) {
this.posterTime = posterTime;
}
public int getSelectionTime() {
return selectionTime;
}
public void setSelectionTime(int selectionTime) {
this.selectionTime = selectionTime;
}
public int getSelectionDuration() {
return selectionDuration;
}
public void setSelectionDuration(int selectionDuration) {
this.selectionDuration = selectionDuration;
}
public int getCurrentTime() {
return currentTime;
}
public void setCurrentTime(int currentTime) {
this.currentTime = currentTime;
}
}
|
parseVersionAndFlags(content);
if (getVersion() == 1) {
creationTime = DateHelper.convert(IsoTypeReader.readUInt64(content));
modificationTime = DateHelper.convert(IsoTypeReader.readUInt64(content));
timescale = IsoTypeReader.readUInt32(content);
duration = content.getLong();
} else {
creationTime = DateHelper.convert(IsoTypeReader.readUInt32(content));
modificationTime = DateHelper.convert(IsoTypeReader.readUInt32(content));
timescale = IsoTypeReader.readUInt32(content);
duration = content.getInt();
}
if (duration < -1) {
LOG.warn("mvhd duration is not in expected range");
}
rate = IsoTypeReader.readFixedPoint1616(content);
volume = IsoTypeReader.readFixedPoint88(content);
IsoTypeReader.readUInt16(content);
IsoTypeReader.readUInt32(content);
IsoTypeReader.readUInt32(content);
matrix = Matrix.fromByteBuffer(content);
previewTime = content.getInt();
previewDuration = content.getInt();
posterTime = content.getInt();
selectionTime = content.getInt();
selectionDuration = content.getInt();
currentTime = content.getInt();
nextTrackId = IsoTypeReader.readUInt32(content);
| 1,644
| 384
| 2,028
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/ProgressiveDownloadInformationBox.java
|
ProgressiveDownloadInformationBox
|
getContent
|
class ProgressiveDownloadInformationBox extends AbstractFullBox {
public static final String TYPE = "pdin";
List<Entry> entries = Collections.emptyList();
public ProgressiveDownloadInformationBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 4 + entries.size() * 8;
}
@Override
protected void getContent(ByteBuffer byteBuffer) {<FILL_FUNCTION_BODY>}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
entries = new LinkedList<Entry>();
while (content.remaining() >= 8) {
Entry entry = new Entry(IsoTypeReader.readUInt32(content), IsoTypeReader.readUInt32(content));
entries.add(entry);
}
}
@Override
public String toString() {
return "ProgressiveDownloadInfoBox{" +
"entries=" + entries +
'}';
}
public static class Entry {
long rate;
long initialDelay;
public Entry(long rate, long initialDelay) {
this.rate = rate;
this.initialDelay = initialDelay;
}
public long getRate() {
return rate;
}
public void setRate(long rate) {
this.rate = rate;
}
public long getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(long initialDelay) {
this.initialDelay = initialDelay;
}
@Override
public String toString() {
return "Entry{" +
"rate=" + rate +
", initialDelay=" + initialDelay +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
if (initialDelay != entry.initialDelay) return false;
if (rate != entry.rate) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (rate ^ (rate >>> 32));
result = 31 * result + (int) (initialDelay ^ (initialDelay >>> 32));
return result;
}
}
}
|
writeVersionAndFlags(byteBuffer);
for (Entry entry : entries) {
IsoTypeWriter.writeUInt32(byteBuffer, entry.getRate());
IsoTypeWriter.writeUInt32(byteBuffer, entry.getInitialDelay());
}
| 667
| 69
| 736
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
sannies_mp4parser
|
mp4parser/isoparser/src/main/java/org/mp4parser/boxes/iso14496/part12/SampleAuxiliaryInformationOffsetsBox.java
|
SampleAuxiliaryInformationOffsetsBox
|
_parseDetails
|
class SampleAuxiliaryInformationOffsetsBox extends AbstractFullBox {
public static final String TYPE = "saio";
private long[] offsets = new long[0];
private String auxInfoType;
private String auxInfoTypeParameter;
public SampleAuxiliaryInformationOffsetsBox() {
super(TYPE);
}
@Override
protected long getContentSize() {
return 8 + (getVersion() == 0 ? 4 * offsets.length : 8 * offsets.length) + ((getFlags() & 1) == 1 ? 8 : 0);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
if ((getFlags() & 1) == 1) {
byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoType));
byteBuffer.put(IsoFile.fourCCtoBytes(auxInfoTypeParameter));
}
IsoTypeWriter.writeUInt32(byteBuffer, offsets.length);
for (Long offset : offsets) {
if (getVersion() == 0) {
IsoTypeWriter.writeUInt32(byteBuffer, offset);
} else {
IsoTypeWriter.writeUInt64(byteBuffer, offset);
}
}
}
@Override
public void _parseDetails(ByteBuffer content) {<FILL_FUNCTION_BODY>}
public String getAuxInfoType() {
return auxInfoType;
}
public void setAuxInfoType(String auxInfoType) {
this.auxInfoType = auxInfoType;
}
public String getAuxInfoTypeParameter() {
return auxInfoTypeParameter;
}
public void setAuxInfoTypeParameter(String auxInfoTypeParameter) {
this.auxInfoTypeParameter = auxInfoTypeParameter;
}
public long[] getOffsets() {
return offsets;
}
public void setOffsets(long[] offsets) {
this.offsets = offsets;
}
}
|
parseVersionAndFlags(content);
if ((getFlags() & 1) == 1) {
auxInfoType = IsoTypeReader.read4cc(content);
auxInfoTypeParameter = IsoTypeReader.read4cc(content);
}
int entryCount = CastUtils.l2i(IsoTypeReader.readUInt32(content));
offsets = new long[entryCount];
for (int i = 0; i < entryCount; i++) {
if (getVersion() == 0) {
offsets[i] = IsoTypeReader.readUInt32(content);
} else {
offsets[i] = IsoTypeReader.readUInt64(content);
}
}
| 521
| 187
| 708
|
<methods>public int getFlags() ,public int getVersion() ,public void setFlags(int) ,public void setVersion(int) <variables>protected int flags,protected int version
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.