code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.greysh.donation.model;
import java.util.Date;
public class Donation{
// Fields
private Integer donationPid;
private String donationTitle;
private Date donationDate;
private String donationContent;
// Constructors
/** default constructor */
public Donation() {
}
public Integer getDonationPid() {
return donationPid;
}
public void setDonationPid(Integer donationPid) {
this.donationPid = donationPid;
}
public String getDonationTitle() {
return donationTitle;
}
public void setDonationTitle(String donationTitle) {
this.donationTitle = donationTitle;
}
public Date getDonationDate() {
return donationDate;
}
public void setDonationDate(Date donationDate) {
this.donationDate = donationDate;
}
public String getDonationContent() {
return donationContent;
}
public void setDonationContent(String donationContent) {
this.donationContent = donationContent;
}
} | 07bjtu | trunk/BJTU/src/com/greysh/donation/model/Donation.java | Java | asf20 | 975 |
package com.greysh.donation.service;
public interface DonationService {
}
| 07bjtu | trunk/BJTU/src/com/greysh/donation/service/DonationService.java | Java | asf20 | 81 |
package com.greysh.donation.action;
/**
*
*后台管理
*
*/
public class DonationAdminAction {
/**
*
* @return 后台显示捐献列表
*/
public String showDonationList(){
return null;
}
/**
*
* @return 后台显示单个捐献
*/
public String showDonation(){
return null;
}
/**
*
* @return 修改捐献前的页面
*/
public String beforeUpdateDonation(){
return null;
}
/**
*
* @return 跟新捐献,跳转到结果页面
*/
public String updateDonation(){
return null;
}
/**
*
* @return 删除捐献,跳转到结果页面
*/
public String deleteDonation(){
return null;
}
}
| 07bjtu | trunk/BJTU/src/com/greysh/donation/action/DonationAdminAction.java | Java | asf20 | 701 |
package com.greysh.donation.action;
/**
*
* 前台捐赠信息
*
*/
public class DonationAction{
/**
*
* @return 捐赠信息列表
*/
public String showDonationList(){
return null;
}
/**
*
* @return 显示单个捐赠信息
*/
public String showDonation(){
return null;
}
} | 07bjtu | trunk/BJTU/src/com/greysh/donation/action/DonationAction.java | Java | asf20 | 333 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>登录面板</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<s:form action="admin!login.action" method="post" namespace="/admin">
<s:textfield name="admin.adminName" size="15" theme="simple"
tabindex="1" label="用户" />
<s:password name="admin.adminPassword" size="17" theme="simple"
tabindex="2" label="密码" />
<s:submit />
</s:form>
</body>
</html>
| 07bjtu | trunk/BJTU/WebRoot/admin_login.jsp | Java Server Pages | asf20 | 708 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>登录面板</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
HELLO ${member.memberName}
</body>
</html>
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/members/loginSuccess.jsp | Java Server Pages | asf20 | 427 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="sx" uri="/struts-dojo-tags"%>
<sx:head extraLocales="en-us,nl-nl,de-de" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>注册面板</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
你好!
<s:form action="member!join" method="post" namespace="/member">
<s:textfield name="member.memberName" size="15" tabindex="1"
label="姓名" />
<s:password name="member.memberPassword" size="17" tabindex="2"
label="密码" />
<s:textfield name="member.memberUniversity" size="15" tabindex="1"
label="大学" />
<s:select label="主修"
list="%{#{0:'数学', 1:'物理', 2:'英语'}}"
name="member.memberMajor" emptyOption="false" headerKey="None"
headerValue="--选择你的主修课程--" />
<s:textfield name="member.memberEmail" size="15" tabindex="1"
label="邮箱" />
<s:select label="状态"
list="%{#{0:'教学', 1:'学习', 2:'工作'}}"
name="member.memberState" emptyOption="false" headerKey="None"
headerValue="--选择你的声明--" />
<s:textfield name="member.memberHobby" size="15" tabindex="1"
label="业余爱好" />
<s:textfield name="member.memberMsn" size="15" tabindex="1"
label="MSN" />
<s:textfield name="member.memberRealName" size="15" tabindex="1"
label="真实姓名" />
<s:textfield name="member.memberBirthPlace" size="15" tabindex="1"
label="出生地址" />
<s:textfield name="member.memberCardId" size="15" tabindex="1"
label="卡号" />
<s:select label="学位"
list="%{#{0:'硕士', 1:'博士', 2:'博士后'}}"
name="member.memberDegree" emptyOption="false" headerKey="None"
headerValue="--选择你的学位--" />
<s:textfield name="member.memberSchoolAge" size="15" tabindex="1"
label="学龄" />
<s:select label="入学年份" list="{2000,1999,1998}"
name="member.memberEnterYear" emptyOption="false" headerKey="None"
headerValue="--选择你的入学年份 --" />
<s:select label="毕业年份" list="{2000,1999,1998}"
name="member.memberGradYear" emptyOption="false" headerKey="None"
headerValue="--选择你的毕业年份 --" />
<s:select label="学习陈述"
list="%{#{0:'硕士', 1:'博士', 2:'博士后'}}"
name="member.memberStudyState" emptyOption="false" headerKey="None"
headerValue="--选择你的学习陈述--" />
<s:textfield name="member.memberClass" size="15" tabindex="1"
label="班级" />
<s:textfield name="member.memberWorkspace" size="15" tabindex="1"
label="工作空间" />
<s:textfield name="member.memberDuty" size="15" tabindex="1"
label="职责" />
<s:textfield name="member.memberTitle" size="15" tabindex="1"
label="头衔" />
<s:textfield name="member.memberPlace" size="15" tabindex="1"
label="职务" />
<s:textfield name="member.memberPostcode" size="15" tabindex="1"
label="邮政编码" />
<s:textfield name="member.memberWorkPhone" size="15" tabindex="1"
label="单位电话" />
<s:textfield name="member.memberHomePhone" size="15" tabindex="1"
label="家庭电话" />
<s:textfield name="member.memberTelephone" size="15" tabindex="1"
label="手机" />
<sx:datetimepicker label="出生日期"
name="member.memberBirthday" displayFormat="yyyy-MM-dd"
value="%{'today'}" />
<s:textfield name="member.memberQq" size="15" tabindex="1"
label="QQ" />
<s:textarea name="member.memberDescription" tabindex="1"
label="说明" />
<s:submit label="提交"/>
</s:form>
</body>
</html>
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/members/register.jsp | Java Server Pages | asf20 | 3,873 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>登录面板</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<s:form action="memberLogin!login" method="post" namespace="/member">
<s:textfield name="member.memberName" size="15"
tabindex="1" label="用户" />
<s:password name="member.memberPassword" size="17"
tabindex="2" label="密码" />
<s:submit />
</s:form>
</body>
</html>
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/members/login.jsp | Java Server Pages | asf20 | 689 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>登录面板</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
ERROR
<a href='<s:url value="/member/member!beforeJoin" />'>注册面板</a><br />
</body>
</html>
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/members/error.jsp | Java Server Pages | asf20 | 486 |
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%response.sendRedirect("member/memberLogin!beforeLogin"); %>
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/index.jsp | Java Server Pages | asf20 | 154 |
Success
| 07bjtu | trunk/BJTU/WebRoot/WEB-INF/pages/success.jsp | Java Server Pages | asf20 | 9 |
#!/bin/sh
# START-COMMIT HOOK
#
# The start-commit hook is invoked before a Subversion txn is created
# in the process of doing a commit. Subversion runs this hook
# by invoking a program (script, executable, binary, etc.) named
# 'start-commit' (for which this file is a template)
# with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the authenticated user attempting to commit)
# [3] CAPABILITIES (a colon-separated list of capabilities reported
# by the client; see note below)
#
# Note: The CAPABILITIES parameter is new in Subversion 1.5, and 1.5
# clients will typically report at least the "mergeinfo" capability.
# If there are other capabilities, then the list is colon-separated,
# e.g.: "mergeinfo:some-other-capability" (the order is undefined).
#
# The list is self-reported by the client. Therefore, you should not
# make security assumptions based on the capabilities list, nor should
# you assume that clients reliably report every capability they have.
#
# The working directory for this hook program's invocation is undefined,
# so the program should set one explicitly if it cares.
#
# If the hook program exits with success, the commit continues; but
# if it exits with failure (non-zero), the commit is stopped before
# a Subversion txn is created, and STDERR is returned to the client.
#
# On a Unix system, the normal procedure is to have 'start-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'start-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'start-commit.bat' or 'start-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
USER="$2"
commit-allower.pl --repository "$REPOS" --user "$USER" || exit 1
special-auth-check.py --user "$USER" --auth-level 3 || exit 1
# All checks passed, so allow the commit.
exit 0
| 0871128qlchbs | trunk/hooks/start-commit.tmpl | Shell | asf20 | 2,845 |
#!/bin/sh
# POST-REVPROP-CHANGE HOOK
#
# The post-revprop-change hook is invoked after a revision property
# has been added, modified or deleted. Subversion runs this hook by
# invoking a program (script, executable, binary, etc.) named
# 'post-revprop-change' (for which this file is a template), with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REV (the revision that was tweaked)
# [3] USER (the username of the person tweaking the property)
# [4] PROPNAME (the property that was changed)
# [5] ACTION (the property was 'A'dded, 'M'odified, or 'D'eleted)
#
# [STDIN] PROPVAL ** the old property value is passed via STDIN.
#
# Because the propchange has already completed and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# new property value.
#
# On a Unix system, the normal procedure is to have 'post-revprop-change'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-revprop-change' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-revprop-change.bat' or 'post-revprop-change.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"
mailer.py propchange2 "$REPOS" "$REV" "$USER" "$PROPNAME" "$ACTION" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/post-revprop-change.tmpl | Shell | asf20 | 2,345 |
#!/bin/sh
# POST-LOCK HOOK
#
# The post-lock hook is run after a path is locked. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-lock' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the user who created the lock)
#
# The paths that were just locked are passed to the hook via STDIN (as
# of Subversion 1.2, only one path is passed per invocation, but the
# plan is to pass all locked paths at once, so the hook program
# should be written accordingly).
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the lock has already been created and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# newly-created lock.
#
# On a Unix system, the normal procedure is to have 'post-lock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-lock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-lock.bat' or 'post-lock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
USER="$2"
# Send email to interested parties, let them know a lock was created:
mailer.py lock "$REPOS" "$USER" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/post-lock.tmpl | Shell | asf20 | 1,682 |
#!/bin/sh
# POST-LOCK HOOK
#
# The post-lock hook is run after a path is locked. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-lock' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the user who created the lock)
#
# The paths that were just locked are passed to the hook via STDIN (as
# of Subversion 1.2, only one path is passed per invocation, but the
# plan is to pass all locked paths at once, so the hook program
# should be written accordingly).
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the lock has already been created and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# newly-created lock.
#
# On a Unix system, the normal procedure is to have 'post-lock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-lock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-lock.bat' or 'post-lock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
USER="$2"
# Send email to interested parties, let them know a lock was created:
mailer.py lock "$REPOS" "$USER" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/.svn/text-base/post-lock.tmpl.svn-base | Shell | asf20 | 1,682 |
#!/bin/sh
# PRE-LOCK HOOK
#
# The pre-lock hook is invoked before an exclusive lock is
# created. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-lock' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] PATH (the path in the repository about to be locked)
# [3] USER (the user creating the lock)
# [4] COMMENT (the comment of the lock)
# [5] STEAL-LOCK (1 if the user is trying to steal the lock, else 0)
#
# If the hook program outputs anything on stdout, the output string will
# be used as the lock token for this lock operation. If you choose to use
# this feature, you must guarantee the tokens generated are unique across
# the repository each time.
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the lock is created; but
# if it exits with failure (non-zero), the lock action is aborted
# and STDERR is returned to the client.
# On a Unix system, the normal procedure is to have 'pre-lock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-lock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-lock.bat' or 'pre-lock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
PATH="$2"
USER="$3"
# If a lock exists and is owned by a different person, don't allow it
# to be stolen (e.g., with 'svn lock --force ...').
# (Maybe this script could send email to the lock owner?)
SVNLOOK=/usr/local/bin/svnlook
GREP=/bin/grep
SED=/bin/sed
LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \
$GREP '^Owner: ' | $SED 's/Owner: //'`
# If we get no result from svnlook, there's no lock, allow the lock to
# happen:
if [ "$LOCK_OWNER" = "" ]; then
exit 0
fi
# If the person locking matches the lock's owner, allow the lock to
# happen:
if [ "$LOCK_OWNER" = "$USER" ]; then
exit 0
fi
# Otherwise, we've got an owner mismatch, so return failure:
echo "Error: $PATH already locked by ${LOCK_OWNER}." 1>&2
exit 1
| 0871128qlchbs | trunk/hooks/.svn/text-base/pre-lock.tmpl.svn-base | Shell | asf20 | 2,487 |
#!/bin/sh
# POST-UNLOCK HOOK
#
# The post-unlock hook runs after a path is unlocked. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-unlock' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the user who destroyed the lock)
#
# The paths that were just unlocked are passed to the hook via STDIN
# (as of Subversion 1.2, only one path is passed per invocation, but
# the plan is to pass all unlocked paths at once, so the hook program
# should be written accordingly).
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the lock has already been destroyed and cannot be undone,
# the exit code of the hook program is ignored.
#
# On a Unix system, the normal procedure is to have 'post-unlock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-unlock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-unlock.bat' or 'post-unlock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
USER="$2"
# Send email to interested parties, let them know a lock was removed:
mailer.py unlock "$REPOS" "$USER" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/.svn/text-base/post-unlock.tmpl.svn-base | Shell | asf20 | 1,609 |
#!/bin/sh
# PRE-COMMIT HOOK
#
# The pre-commit hook is invoked before a Subversion txn is
# committed. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-commit' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] TXN-NAME (the name of the txn about to be committed)
#
# [STDIN] LOCK-TOKENS ** the lock tokens are passed via STDIN.
#
# If STDIN contains the line "LOCK-TOKENS:\n" (the "\n" denotes a
# single newline), the lines following it are the lock tokens for
# this commit. The end of the list is marked by a line containing
# only a newline character.
#
# Each lock token line consists of a URI-escaped path, followed
# by the separator character '|', followed by the lock token string,
# followed by a newline.
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the txn is committed; but
# if it exits with failure (non-zero), the txn is aborted, no commit
# takes place, and STDERR is returned to the client. The hook
# program can use the 'svnlook' utility to help it examine the txn.
#
# On a Unix system, the normal procedure is to have 'pre-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# *** NOTE: THE HOOK PROGRAM MUST NOT MODIFY THE TXN, EXCEPT ***
# *** FOR REVISION PROPERTIES (like svn:log or svn:author). ***
#
# This is why we recommend using the read-only 'svnlook' utility.
# In the future, Subversion may enforce the rule that pre-commit
# hooks should not modify the versioned data in txns, or else come
# up with a mechanism to make it safe to do so (by informing the
# committing client of the changes). However, right now neither
# mechanism is implemented, so hook writers just have to be careful.
#
# Note that 'pre-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-commit.bat' or 'pre-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
TXN="$2"
# Make sure that the log message contains some text.
SVNLOOK=/usr/local/bin/svnlook
$SVNLOOK log -t "$TXN" "$REPOS" | \
grep "[a-zA-Z0-9]" > /dev/null || exit 1
# Check that the author of this commit has the rights to perform
# the commit on the files and directories being modified.
commit-access-control.pl "$REPOS" "$TXN" commit-access-control.cfg || exit 1
# All checks passed, so allow the commit.
exit 0
| 0871128qlchbs | trunk/hooks/.svn/text-base/pre-commit.tmpl.svn-base | Shell | asf20 | 3,513 |
#!/bin/sh
# PRE-UNLOCK HOOK
#
# The pre-unlock hook is invoked before an exclusive lock is
# destroyed. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-unlock' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] PATH (the path in the repository about to be unlocked)
# [3] USER (the user destroying the lock)
# [4] TOKEN (the lock token to be destroyed)
# [5] BREAK-UNLOCK (1 if the user is breaking the lock, else 0)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the lock is destroyed; but
# if it exits with failure (non-zero), the unlock action is aborted
# and STDERR is returned to the client.
# On a Unix system, the normal procedure is to have 'pre-unlock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-unlock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-unlock.bat' or 'pre-unlock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
PATH="$2"
USER="$3"
# If a lock is owned by a different person, don't allow it be broken.
# (Maybe this script could send email to the lock owner?)
SVNLOOK=/usr/local/bin/svnlook
GREP=/bin/grep
SED=/bin/sed
LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \
$GREP '^Owner: ' | $SED 's/Owner: //'`
# If we get no result from svnlook, there's no lock, return success:
if [ "$LOCK_OWNER" = "" ]; then
exit 0
fi
# If the person unlocking matches the lock's owner, return success:
if [ "$LOCK_OWNER" = "$USER" ]; then
exit 0
fi
# Otherwise, we've got an owner mismatch, so return failure:
echo "Error: $PATH locked by ${LOCK_OWNER}." 1>&2
exit 1
| 0871128qlchbs | trunk/hooks/.svn/text-base/pre-unlock.tmpl.svn-base | Shell | asf20 | 2,169 |
#!/bin/sh
# POST-REVPROP-CHANGE HOOK
#
# The post-revprop-change hook is invoked after a revision property
# has been added, modified or deleted. Subversion runs this hook by
# invoking a program (script, executable, binary, etc.) named
# 'post-revprop-change' (for which this file is a template), with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REV (the revision that was tweaked)
# [3] USER (the username of the person tweaking the property)
# [4] PROPNAME (the property that was changed)
# [5] ACTION (the property was 'A'dded, 'M'odified, or 'D'eleted)
#
# [STDIN] PROPVAL ** the old property value is passed via STDIN.
#
# Because the propchange has already completed and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# new property value.
#
# On a Unix system, the normal procedure is to have 'post-revprop-change'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-revprop-change' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-revprop-change.bat' or 'post-revprop-change.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"
mailer.py propchange2 "$REPOS" "$REV" "$USER" "$PROPNAME" "$ACTION" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/.svn/text-base/post-revprop-change.tmpl.svn-base | Shell | asf20 | 2,345 |
#!/bin/sh
# POST-COMMIT HOOK
#
# The post-commit hook is invoked after a commit. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-commit' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REV (the number of the revision just committed)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the commit has already completed and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# newly-committed tree.
#
# On a Unix system, the normal procedure is to have 'post-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-commit.bat' or 'post-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/.svn/text-base/post-commit.tmpl.svn-base | Shell | asf20 | 2,027 |
#!/bin/sh
# START-COMMIT HOOK
#
# The start-commit hook is invoked before a Subversion txn is created
# in the process of doing a commit. Subversion runs this hook
# by invoking a program (script, executable, binary, etc.) named
# 'start-commit' (for which this file is a template)
# with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the authenticated user attempting to commit)
# [3] CAPABILITIES (a colon-separated list of capabilities reported
# by the client; see note below)
#
# Note: The CAPABILITIES parameter is new in Subversion 1.5, and 1.5
# clients will typically report at least the "mergeinfo" capability.
# If there are other capabilities, then the list is colon-separated,
# e.g.: "mergeinfo:some-other-capability" (the order is undefined).
#
# The list is self-reported by the client. Therefore, you should not
# make security assumptions based on the capabilities list, nor should
# you assume that clients reliably report every capability they have.
#
# The working directory for this hook program's invocation is undefined,
# so the program should set one explicitly if it cares.
#
# If the hook program exits with success, the commit continues; but
# if it exits with failure (non-zero), the commit is stopped before
# a Subversion txn is created, and STDERR is returned to the client.
#
# On a Unix system, the normal procedure is to have 'start-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'start-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'start-commit.bat' or 'start-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
USER="$2"
commit-allower.pl --repository "$REPOS" --user "$USER" || exit 1
special-auth-check.py --user "$USER" --auth-level 3 || exit 1
# All checks passed, so allow the commit.
exit 0
| 0871128qlchbs | trunk/hooks/.svn/text-base/start-commit.tmpl.svn-base | Shell | asf20 | 2,845 |
#!/bin/sh
# PRE-REVPROP-CHANGE HOOK
#
# The pre-revprop-change hook is invoked before a revision property
# is added, modified or deleted. Subversion runs this hook by invoking
# a program (script, executable, binary, etc.) named 'pre-revprop-change'
# (for which this file is a template), with the following ordered
# arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REVISION (the revision being tweaked)
# [3] USER (the username of the person tweaking the property)
# [4] PROPNAME (the property being set on the revision)
# [5] ACTION (the property is being 'A'dded, 'M'odified, or 'D'eleted)
#
# [STDIN] PROPVAL ** the new property value is passed via STDIN.
#
# If the hook program exits with success, the propchange happens; but
# if it exits with failure (non-zero), the propchange doesn't happen.
# The hook program can use the 'svnlook' utility to examine the
# existing value of the revision property.
#
# WARNING: unlike other hooks, this hook MUST exist for revision
# properties to be changed. If the hook does not exist, Subversion
# will behave as if the hook were present, but failed. The reason
# for this is that revision properties are UNVERSIONED, meaning that
# a successful propchange is destructive; the old value is gone
# forever. We recommend the hook back up the old value somewhere.
#
# On a Unix system, the normal procedure is to have 'pre-revprop-change'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-revprop-change' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-revprop-change.bat' or 'pre-revprop-change.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"
if [ "$ACTION" = "M" -a "$PROPNAME" = "svn:log" ]; then exit 0; fi
echo "Changing revision properties other than svn:log is prohibited" >&2
exit 1
| 0871128qlchbs | trunk/hooks/.svn/text-base/pre-revprop-change.tmpl.svn-base | Shell | asf20 | 2,852 |
#!/bin/sh
# PRE-LOCK HOOK
#
# The pre-lock hook is invoked before an exclusive lock is
# created. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-lock' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] PATH (the path in the repository about to be locked)
# [3] USER (the user creating the lock)
# [4] COMMENT (the comment of the lock)
# [5] STEAL-LOCK (1 if the user is trying to steal the lock, else 0)
#
# If the hook program outputs anything on stdout, the output string will
# be used as the lock token for this lock operation. If you choose to use
# this feature, you must guarantee the tokens generated are unique across
# the repository each time.
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the lock is created; but
# if it exits with failure (non-zero), the lock action is aborted
# and STDERR is returned to the client.
# On a Unix system, the normal procedure is to have 'pre-lock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-lock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-lock.bat' or 'pre-lock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
PATH="$2"
USER="$3"
# If a lock exists and is owned by a different person, don't allow it
# to be stolen (e.g., with 'svn lock --force ...').
# (Maybe this script could send email to the lock owner?)
SVNLOOK=/usr/local/bin/svnlook
GREP=/bin/grep
SED=/bin/sed
LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \
$GREP '^Owner: ' | $SED 's/Owner: //'`
# If we get no result from svnlook, there's no lock, allow the lock to
# happen:
if [ "$LOCK_OWNER" = "" ]; then
exit 0
fi
# If the person locking matches the lock's owner, allow the lock to
# happen:
if [ "$LOCK_OWNER" = "$USER" ]; then
exit 0
fi
# Otherwise, we've got an owner mismatch, so return failure:
echo "Error: $PATH already locked by ${LOCK_OWNER}." 1>&2
exit 1
| 0871128qlchbs | trunk/hooks/pre-lock.tmpl | Shell | asf20 | 2,487 |
#!/bin/sh
# PRE-UNLOCK HOOK
#
# The pre-unlock hook is invoked before an exclusive lock is
# destroyed. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-unlock' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] PATH (the path in the repository about to be unlocked)
# [3] USER (the user destroying the lock)
# [4] TOKEN (the lock token to be destroyed)
# [5] BREAK-UNLOCK (1 if the user is breaking the lock, else 0)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the lock is destroyed; but
# if it exits with failure (non-zero), the unlock action is aborted
# and STDERR is returned to the client.
# On a Unix system, the normal procedure is to have 'pre-unlock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-unlock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-unlock.bat' or 'pre-unlock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
PATH="$2"
USER="$3"
# If a lock is owned by a different person, don't allow it be broken.
# (Maybe this script could send email to the lock owner?)
SVNLOOK=/usr/local/bin/svnlook
GREP=/bin/grep
SED=/bin/sed
LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \
$GREP '^Owner: ' | $SED 's/Owner: //'`
# If we get no result from svnlook, there's no lock, return success:
if [ "$LOCK_OWNER" = "" ]; then
exit 0
fi
# If the person unlocking matches the lock's owner, return success:
if [ "$LOCK_OWNER" = "$USER" ]; then
exit 0
fi
# Otherwise, we've got an owner mismatch, so return failure:
echo "Error: $PATH locked by ${LOCK_OWNER}." 1>&2
exit 1
| 0871128qlchbs | trunk/hooks/pre-unlock.tmpl | Shell | asf20 | 2,169 |
#!/bin/sh
# POST-COMMIT HOOK
#
# The post-commit hook is invoked after a commit. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-commit' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REV (the number of the revision just committed)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the commit has already completed and cannot be undone,
# the exit code of the hook program is ignored. The hook program
# can use the 'svnlook' utility to help it examine the
# newly-committed tree.
#
# On a Unix system, the normal procedure is to have 'post-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-commit.bat' or 'post-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/post-commit.tmpl | Shell | asf20 | 2,027 |
#!/bin/sh
# PRE-COMMIT HOOK
#
# The pre-commit hook is invoked before a Subversion txn is
# committed. Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-commit' (for which
# this file is a template), with the following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] TXN-NAME (the name of the txn about to be committed)
#
# [STDIN] LOCK-TOKENS ** the lock tokens are passed via STDIN.
#
# If STDIN contains the line "LOCK-TOKENS:\n" (the "\n" denotes a
# single newline), the lines following it are the lock tokens for
# this commit. The end of the list is marked by a line containing
# only a newline character.
#
# Each lock token line consists of a URI-escaped path, followed
# by the separator character '|', followed by the lock token string,
# followed by a newline.
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# If the hook program exits with success, the txn is committed; but
# if it exits with failure (non-zero), the txn is aborted, no commit
# takes place, and STDERR is returned to the client. The hook
# program can use the 'svnlook' utility to help it examine the txn.
#
# On a Unix system, the normal procedure is to have 'pre-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# *** NOTE: THE HOOK PROGRAM MUST NOT MODIFY THE TXN, EXCEPT ***
# *** FOR REVISION PROPERTIES (like svn:log or svn:author). ***
#
# This is why we recommend using the read-only 'svnlook' utility.
# In the future, Subversion may enforce the rule that pre-commit
# hooks should not modify the versioned data in txns, or else come
# up with a mechanism to make it safe to do so (by informing the
# committing client of the changes). However, right now neither
# mechanism is implemented, so hook writers just have to be careful.
#
# Note that 'pre-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-commit.bat' or 'pre-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
TXN="$2"
# Make sure that the log message contains some text.
SVNLOOK=/usr/local/bin/svnlook
$SVNLOOK log -t "$TXN" "$REPOS" | \
grep "[a-zA-Z0-9]" > /dev/null || exit 1
# Check that the author of this commit has the rights to perform
# the commit on the files and directories being modified.
commit-access-control.pl "$REPOS" "$TXN" commit-access-control.cfg || exit 1
# All checks passed, so allow the commit.
exit 0
| 0871128qlchbs | trunk/hooks/pre-commit.tmpl | Shell | asf20 | 3,513 |
#!/bin/sh
# PRE-REVPROP-CHANGE HOOK
#
# The pre-revprop-change hook is invoked before a revision property
# is added, modified or deleted. Subversion runs this hook by invoking
# a program (script, executable, binary, etc.) named 'pre-revprop-change'
# (for which this file is a template), with the following ordered
# arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] REVISION (the revision being tweaked)
# [3] USER (the username of the person tweaking the property)
# [4] PROPNAME (the property being set on the revision)
# [5] ACTION (the property is being 'A'dded, 'M'odified, or 'D'eleted)
#
# [STDIN] PROPVAL ** the new property value is passed via STDIN.
#
# If the hook program exits with success, the propchange happens; but
# if it exits with failure (non-zero), the propchange doesn't happen.
# The hook program can use the 'svnlook' utility to examine the
# existing value of the revision property.
#
# WARNING: unlike other hooks, this hook MUST exist for revision
# properties to be changed. If the hook does not exist, Subversion
# will behave as if the hook were present, but failed. The reason
# for this is that revision properties are UNVERSIONED, meaning that
# a successful propchange is destructive; the old value is gone
# forever. We recommend the hook back up the old value somewhere.
#
# On a Unix system, the normal procedure is to have 'pre-revprop-change'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'pre-revprop-change' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'pre-revprop-change.bat' or 'pre-revprop-change.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process. For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# the Subversion repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/
REPOS="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"
if [ "$ACTION" = "M" -a "$PROPNAME" = "svn:log" ]; then exit 0; fi
echo "Changing revision properties other than svn:log is prohibited" >&2
exit 1
| 0871128qlchbs | trunk/hooks/pre-revprop-change.tmpl | Shell | asf20 | 2,852 |
#!/bin/sh
# POST-UNLOCK HOOK
#
# The post-unlock hook runs after a path is unlocked. Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-unlock' (for which this file is a template) with the
# following ordered arguments:
#
# [1] REPOS-PATH (the path to this repository)
# [2] USER (the user who destroyed the lock)
#
# The paths that were just unlocked are passed to the hook via STDIN
# (as of Subversion 1.2, only one path is passed per invocation, but
# the plan is to pass all unlocked paths at once, so the hook program
# should be written accordingly).
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the lock has already been destroyed and cannot be undone,
# the exit code of the hook program is ignored.
#
# On a Unix system, the normal procedure is to have 'post-unlock'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-unlock' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-unlock.bat' or 'post-unlock.exe',
# but the basic idea is the same.
#
# Here is an example hook script, for a Unix /bin/sh interpreter:
REPOS="$1"
USER="$2"
# Send email to interested parties, let them know a lock was removed:
mailer.py unlock "$REPOS" "$USER" /path/to/mailer.conf
| 0871128qlchbs | trunk/hooks/post-unlock.tmpl | Shell | asf20 | 1,609 |
/*-
* Copyright (C) 2010 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.client.android.vlcremote;
import junit.framework.TestCase;
public class VLCTest extends TestCase {
public void testFileUri() {
assertEquals("file:///C%3A/Users/Peter/Music/Fran%C3%A7ais",
VLC.fileUri("C:\\Users\\Peter\\Music/Français"));
}
}
| 091420009-my | tests/src/org/peterbaldwin/client/android/vlcremote/VLCTest.java | Java | gpl3 | 988 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.intent;
import org.peterbaldwin.vlcremote.model.Status;
import android.content.Intent;
import android.graphics.Bitmap;
public final class Intents {
/**
* Plays a media URI with VLC (usually streaming audio/video).
* <p>
* For example, {@code http://www.example.com/video.mp4}
*/
public static final String ACTION_VIEW = "org.peterbaldwin.vlcremote.intent.action.VIEW";
/**
* Plays a browse URI (local file).
* <p>
* For example,
* {@code http://mediaserver/requests/browse.xml?dir=...&file=...}
*/
public static final String ACTION_PLAY = "org.peterbaldwin.vlcremote.intent.action.PLAY";
/**
* Streams a media file.
*/
public static final String ACTION_STREAM = "org.peterbaldwin.vlcremote.intent.action.STREAM";
/**
* Enqueues a browse URI (local file).
* <p>
* For example,
* {@code http://mediaserver/requests/browse.xml?dir=...&file=...}
*/
public static final String ACTION_ENQUEUE = "org.peterbaldwin.vlcremote.intent.action.ENQUEUE";
public static final String ACTION_MANUAL_APPWIDGET_UPDATE = "org.peterbaldwin.vlcremote.intent.action.MANUAL_APPWIDGET_UPDATE";
public static final String ACTION_STATUS = "org.peterbaldwin.vlcremote.intent.action.STATUS";
public static final String ACTION_PLAYLIST = "org.peterbaldwin.vlcremote.intent.action.PLAYLIST";
public static final String ACTION_ART = "org.peterbaldwin.vlcremote.intent.action.ART";
public static final String ACTION_ERROR = "org.peterbaldwin.vlcremote.intent.action.ERROR";
public static final String EXTRA_STATUS = "org.peterbaldwin.vlcremote.intent.extra.STATUS";
public static final String EXTRA_PLAYLIST = "org.peterbaldwin.vlcremote.intent.extra.PLAYLIST";
public static final String EXTRA_BITMAP = "org.peterbaldwin.vlcremote.intent.extra.BITMAP";
public static final String EXTRA_THROWABLE = "org.peterbaldwin.vlcremote.intent.extra.THROWABLE";
public static final String EXTRA_FLAGS = "org.peterbaldwin.vlcremote.intent.extra.FLAGS";
public static final String ACTION_REMOTE_VIEW = "org.openintents.remote.intent.action.VIEW";
public static final String EXTRA_REMOTE_HOST = "org.openintents.remote.intent.extra.HOST";
public static final String EXTRA_REMOTE_PORT = "org.openintents.remote.intent.extra.PORT";
/**
* Indicates if the command was generated by the user or programmatically.
* <p>
* This value is echoed back in the broadcast response.
* <p>
* The value can be used to determine whether or not it is appropriate to
* display an error message to the user.
*/
public static final int FLAG_PROGRAMMATIC = 1 << 0;
/**
* Instructs the service to only run the command if the media is playing.
*/
public static final int FLAG_ONLY_IF_PLAYING = 1 << 1;
/**
* Instructs the service to only run the command if the media is paused.
*/
public static final int FLAG_ONLY_IF_PAUSED = 1 << 2;
/**
* Instructs the service to call {@link VLC#setResumeOnIdle()} if and only
* if the command is executed successfully.
*/
public static final int FLAG_SET_RESUME_ON_IDLE = 1 << 3;
public static Intent status(Status status) {
Intent intent = new Intent(ACTION_STATUS);
intent.putExtra(EXTRA_STATUS, status);
return intent;
}
public static Intent art(Bitmap bitmap) {
Intent intent = new Intent(ACTION_ART);
intent.putExtra(EXTRA_BITMAP, bitmap);
return intent;
}
public static Intent error(Throwable t) {
Intent intent = new Intent(ACTION_ERROR);
intent.putExtra(EXTRA_THROWABLE, t);
return intent;
}
private Intents() {
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/intent/Intents.java | Java | gpl3 | 4,525 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.service;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Preferences;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Sends commands to a VLC server and receives & broadcasts the status.
*/
public class StatusService extends Service implements Handler.Callback {
private static final String TAG = "StatusService";
private static final int HANDLE_STATUS = 1;
private static final int HANDLE_ALBUM_ART = 2;
private static final int HANDLE_STOP = 3;
private static boolean isCommand(Uri uri) {
return uri.getQueryParameters("command").size() != 0;
}
/**
* Erases any commands from the URI.
*/
private static Uri readOnly(Uri uri) {
Uri.Builder builder = uri.buildUpon();
builder.encodedQuery("");
return builder.build();
}
private static boolean isSeek(Uri uri) {
return "seek".equals(uri.getQueryParameter("command"));
}
private static boolean isVolume(Uri uri) {
return "volume".equals(uri.getQueryParameter("command"));
}
private static boolean isAbsoluteValue(Uri uri) {
String value = uri.getQueryParameter("val");
return value != null && !value.startsWith("+") && !value.startsWith("-");
}
private Handler mStatusHandler;
private Handler mAlbumArtHandler;
private Handler mCommandHandler;
private AtomicInteger mSequenceNumber;
@Override
public void onCreate() {
super.onCreate();
mSequenceNumber = new AtomicInteger();
mStatusHandler = startHandlerThread("StatusThread");
// Create a separate thread for album art requests
// because the request can be very slow.
mAlbumArtHandler = startHandlerThread("AlbumArtThread");
// Create a separate thread for commands to improve latency
// (commands shouldn't have to wait for partially complete reads).
mCommandHandler = startHandlerThread("CommandThread");
}
@Override
public void onDestroy() {
stopHandlerThread(mStatusHandler);
stopHandlerThread(mCommandHandler);
stopHandlerThread(mAlbumArtHandler);
super.onDestroy();
}
private Handler startHandlerThread(String name) {
HandlerThread thread = new HandlerThread(name, Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
Looper looper = thread.getLooper();
Handler.Callback callback = this;
return new Handler(looper, callback);
}
private void stopHandlerThread(Handler handler) {
Looper looper = handler.getLooper();
looper.quit();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
String action = (intent != null) ? intent.getAction() : null;
Uri uri = (intent != null) ? intent.getData() : null;
if (Intents.ACTION_STATUS.equals(action) && uri != null) {
if (isCommand(uri)) {
// A command will change the status,
// so cancel any unsent requests to
// query the status
mStatusHandler.removeMessages(HANDLE_STATUS);
}
if (isSeek(uri) || isVolume(uri)) {
if (isAbsoluteValue(uri)) {
// Seeking to an absolute position or volume
// invalidates any existing requests to change
// the position or volume.
mCommandHandler.removeMessages(HANDLE_STATUS);
}
}
Handler handler = isCommand(uri) ? mCommandHandler : mStatusHandler;
if (isCommand(uri) || !handler.hasMessages(HANDLE_STATUS)) {
int sequenceNumber = isCommand(uri) ? mSequenceNumber.incrementAndGet()
: mSequenceNumber.get();
int flags = intent.getIntExtra(Intents.EXTRA_FLAGS, 0);
Message msg = handler.obtainMessage(HANDLE_STATUS, sequenceNumber, flags, uri);
handler.sendMessage(msg);
}
} else if (Intents.ACTION_ART.equals(action) && uri != null) {
int sequenceNumber = mSequenceNumber.get();
Message msg = mAlbumArtHandler.obtainMessage(HANDLE_ALBUM_ART, sequenceNumber, -1, uri);
msg.sendToTarget();
}
{
// Stop the service if no new Intents are received for 20 seconds
Handler handler = mCommandHandler;
Message msg = handler.obtainMessage(HANDLE_STOP, startId, -1);
handler.sendMessageDelayed(msg, 20 * 1000);
}
}
/** {@inheritDoc} */
public boolean handleMessage(Message msg) {
switch (msg.what) {
case HANDLE_STATUS: {
Uri uri = (Uri) msg.obj;
MediaServer server = new MediaServer(this, uri);
int sequenceNumber = msg.arg1;
int flags = msg.arg2;
if (sequenceNumber == mSequenceNumber.get()) {
boolean setResumeOnIdle = ((flags & Intents.FLAG_SET_RESUME_ON_IDLE) != 0);
boolean onlyIfPlaying = ((flags & Intents.FLAG_ONLY_IF_PLAYING) != 0);
boolean onlyIfPaused = ((flags & Intents.FLAG_ONLY_IF_PAUSED) != 0);
boolean conditional = onlyIfPlaying || onlyIfPaused;
try {
if (conditional) {
Status status = server.status().read();
if (onlyIfPlaying && !status.isPlaying()) {
return true;
}
if (onlyIfPaused && !status.isPaused()) {
return true;
}
}
Status status = server.status(uri).read();
if (sequenceNumber == mSequenceNumber.get()) {
sendBroadcast(Intents.status(status));
if (isCommand(uri)) {
// Check the status again after the command
// has had time to take effect.
msg = mStatusHandler.obtainMessage(HANDLE_STATUS, sequenceNumber,
0, readOnly(uri));
mStatusHandler.sendMessageDelayed(msg, 500);
}
} else {
Log.d(TAG, "Dropped stale status response: " + uri);
}
if (setResumeOnIdle) {
Preferences.get(this).setResumeOnIdle();
}
} catch (Throwable tr) {
String message = String.valueOf(tr);
Log.e(TAG, message, tr);
Intent broadcast = Intents.error(tr);
broadcast.putExtra(Intents.EXTRA_FLAGS, flags);
sendBroadcast(broadcast);
}
} else {
Log.d(TAG, "Dropped stale status request: " + uri);
}
return true;
}
case HANDLE_ALBUM_ART: {
Uri uri = (Uri) msg.obj;
MediaServer server = new MediaServer(this, uri);
int sequenceNumber = msg.arg1;
if (sequenceNumber == mSequenceNumber.get()) {
try {
Bitmap bitmap = server.image(uri).read();
if (sequenceNumber == mSequenceNumber.get()) {
sendBroadcast(Intents.art(bitmap));
} else {
Log.d(TAG, "Dropped stale album art response: " + uri);
}
} catch (Throwable tr) {
String message = String.valueOf(tr);
Log.e(TAG, message, tr);
sendBroadcast(Intents.error(tr));
}
} else {
Log.d(TAG, "Dropped stale album art request: " + uri);
}
return true;
}
case HANDLE_STOP: {
int startId = msg.arg1;
stopSelf(startId);
return true;
}
default:
return false;
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/service/StatusService.java | Java | gpl3 | 9,794 |
/*-
* Copyright (C) 2010 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.receiver;
import org.peterbaldwin.vlcremote.model.Preferences;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
/**
* Automatically pauses media when there is an incoming call.
*/
public class PhoneStateChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) {
Preferences preferences = Preferences.get(context);
String authority = preferences.getAuthority();
if (authority != null) {
MediaServer server = new MediaServer(context, authority);
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)
|| TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
// Pause for both incoming and outgoing calls
server.status().onlyIfPlaying().setResumeOnIdle().command.playback.pause();
} else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
if (preferences.isResumeOnIdleSet()) {
server.status().onlyIfPaused().command.playback.pause();
preferences.clearResumeOnIdle();
}
}
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/receiver/PhoneStateChangedReceiver.java | Java | gpl3 | 2,320 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.app;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.fragment.ArtFragment;
import org.peterbaldwin.vlcremote.fragment.BrowseFragment;
import org.peterbaldwin.vlcremote.fragment.ButtonsFragment;
import org.peterbaldwin.vlcremote.fragment.HotkeyDialog;
import org.peterbaldwin.vlcremote.fragment.HotkeyListener;
import org.peterbaldwin.vlcremote.fragment.InfoFragment;
import org.peterbaldwin.vlcremote.fragment.NavigationFragment;
import org.peterbaldwin.vlcremote.fragment.PlaybackFragment;
import org.peterbaldwin.vlcremote.fragment.PlaylistFragment;
import org.peterbaldwin.vlcremote.fragment.ServicesDiscoveryFragment;
import org.peterbaldwin.vlcremote.fragment.StatusFragment;
import org.peterbaldwin.vlcremote.fragment.VolumeFragment;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Preferences;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.net.MediaServer;
import org.peterbaldwin.vlcremote.widget.VolumePanel;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Browser;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SlidingDrawer;
import android.widget.TabHost;
import android.widget.ViewFlipper;
import java.util.ArrayList;
public class PlaybackActivity extends FragmentActivity implements TabHost.OnTabChangeListener,
View.OnClickListener, HotkeyListener {
private static final String TAG = "PlaybackActivity";
private static final int REQUEST_PICK_SERVER = 1;
private static final Uri URI_TROUBLESHOOTING = Uri
.parse("http://code.google.com/p/android-vlc-remote/wiki/Troubleshooting");
private static final String FRAGMENT_STATUS = "vlc:status";
private static final int VOLUME_LEVEL_UNKNOWN = -1;
private static final String STATE_INPUT = "vlc:input";
private static final String STATE_TAB = "vlc:tab";
private static final String TAB_MEDIA = "media";
private static final String TAB_PLAYLIST = "playlist";
private static final String TAB_BROWSE = "browse";
private static final String TAB_NAVIGATION = "navigation";
private static final int MAX_VOLUME = 1024;
private MediaServer mMediaServer;
private TabHost mTabHost;
private PlaybackFragment mPlayback;
private ArtFragment mArt;
private ButtonsFragment mButtons;
private VolumeFragment mVolume;
@SuppressWarnings("unused")
private InfoFragment mInfo;
private PlaylistFragment mPlaylist;
private BrowseFragment mBrowse;
private ServicesDiscoveryFragment mServicesDiscovery;
private NavigationFragment mNavigation;
private StatusFragment mStatus;
private VolumePanel mVolumePanel;
private BroadcastReceiver mStatusReceiver;
private int mVolumeLevel = VOLUME_LEVEL_UNKNOWN;
private int mLastNonZeroVolume = VOLUME_LEVEL_UNKNOWN;
private String mInput;
private SlidingDrawer mDrawer;
private ViewFlipper mFlipper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set the control stream to STREAM_MUSIC to suppress system beeps
// that sound even when the activity handles volume key events.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mStatus = findOrAddFragment(FRAGMENT_STATUS, StatusFragment.class);
mPlayback = findFragmentById(R.id.fragment_playback);
mArt = findFragmentById(R.id.fragment_art);
mButtons = findFragmentById(R.id.fragment_buttons);
mVolume = findFragmentById(R.id.fragment_volume);
mInfo = findFragmentById(R.id.fragment_info);
mPlaylist = findFragmentById(R.id.fragment_playlist);
mBrowse = findFragmentById(R.id.fragment_browse);
mServicesDiscovery = findFragmentById(R.id.fragment_services_discovery);
mNavigation = findFragmentById(R.id.fragment_navigation);
Context context = this;
mVolumePanel = new VolumePanel(context);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
if (mTabHost != null) {
mTabHost.setup();
addTab(TAB_MEDIA, R.id.tab_media, R.string.nowplaying_title, R.drawable.ic_tab_artists);
addTab(TAB_PLAYLIST, R.id.tab_playlist, R.string.tab_playlist,
R.drawable.ic_tab_playlists);
addTab(TAB_BROWSE, R.id.tab_browse, R.string.goto_start, R.drawable.ic_tab_playback);
addTab(TAB_NAVIGATION, R.id.tab_navigation, R.string.tab_dvd, R.drawable.ic_tab_albums);
mTabHost.setOnTabChangedListener(this);
onTabChanged(mTabHost.getCurrentTabTag());
} else {
onTabChanged(null);
}
mDrawer = (SlidingDrawer) findViewById(R.id.drawer);
if (mDrawer != null) {
assert Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
BrowseDrawerListener listener = new BrowseDrawerListener(this, mDrawer, mBrowse);
mDrawer.setOnDrawerOpenListener(listener);
mDrawer.setOnDrawerCloseListener(listener);
}
mFlipper = (ViewFlipper) findViewById(R.id.flipper);
Preferences preferences = Preferences.get(context);
String authority = preferences.getAuthority();
if (authority != null) {
changeServer(authority);
}
if (savedInstanceState == null) {
onNewIntent(getIntent());
}
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof HotkeyDialog) {
((HotkeyDialog) fragment).setHotkeyListener(this);
}
}
private void addTab(String tag, int content, int label, int icon) {
if (mTabHost.findViewById(content) != null) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(content);
spec.setIndicator(getText(label), getResources().getDrawable(icon));
mTabHost.addTab(spec);
} else {
// Tab does not exist in this layout
}
}
/** {@inheritDoc} */
public void onTabChanged(String tabId) {
if (TAB_PLAYLIST.equals(tabId)) {
mPlaylist.selectCurrentTrack();
}
mPlaylist.setHasOptionsMenu(TAB_PLAYLIST.equals(tabId) || mTabHost == null);
mBrowse.setHasOptionsMenu(TAB_BROWSE.equals(tabId) && mDrawer == null);
if (Build.VERSION.SDK_INT > 11) {
try {
getClass().getMethod("invalidateOptionsMenu").invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** {@inheritDoc} */
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_navigation:
mFlipper.showNext();
updateNavigationButton(v);
break;
}
}
/** {@inheritDoc} */
public void onHotkey(String keycode) {
if ("toggle-fullscreen".equals(keycode)) {
mMediaServer.status().command.fullscreen();
} else {
mMediaServer.status().command.key(keycode);
}
}
private void updateNavigationButton(View v) {
ImageButton button = (ImageButton) v;
boolean on = (mFlipper.getDisplayedChild() != 0);
int icon = on ? R.drawable.ic_navigation_on : R.drawable.ic_navigation_off;
button.setImageResource(icon);
}
@Override
public boolean onSearchRequested() {
String initialQuery = mInput;
boolean selectInitialQuery = true;
Bundle appSearchData = null;
boolean globalSearch = false;
startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.playback_options, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String tabId = mTabHost != null ? mTabHost.getCurrentTabTag() : null;
boolean visible = tabId == null || TAB_MEDIA.equals(tabId);
menu.findItem(R.id.menu_preferences).setVisible(visible);
menu.findItem(R.id.menu_help).setVisible(visible);
return menu.hasVisibleItems();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_preferences:
pickServer();
return true;
case R.id.menu_help:
Intent intent = new Intent(Intent.ACTION_VIEW, URI_TROUBLESHOOTING);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void pickServer() {
Preferences preferences = Preferences.get(this);
ArrayList<String> remembered = preferences.getRememberedServers();
Intent intent = new Intent(this, PickServerActivity.class);
intent.putExtra(PickServerActivity.EXTRA_PORT, 8080);
intent.putExtra(PickServerActivity.EXTRA_FILE, "/requests/status.xml");
intent.putStringArrayListExtra(PickServerActivity.EXTRA_REMEMBERED, remembered);
startActivityForResult(intent, REQUEST_PICK_SERVER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_PICK_SERVER:
Preferences preferences = Preferences.get(this);
if (resultCode == RESULT_OK) {
String authority = data.getData().getAuthority();
changeServer(authority);
preferences.setAuthority(authority);
mBrowse.openDirectory("~");
}
if (data != null) {
// Update remembered servers even if
// (resultCode == RESULT_CANCELED)
String key = PickServerActivity.EXTRA_REMEMBERED;
ArrayList<String> remembered = data.getStringArrayListExtra(key);
if (remembered != null) {
preferences.setRemeberedServers(remembered);
}
}
if (mMediaServer == null) {
finish();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
private void changeServer(String authority) {
Context context = this;
mMediaServer = new MediaServer(context, authority);
mPlayback.setMediaServer(mMediaServer);
mButtons.setMediaServer(mMediaServer);
mVolume.setMediaServer(mMediaServer);
if (mArt != null) {
mArt.setMediaServer(mMediaServer);
}
mPlaylist.setMediaServer(mMediaServer);
mBrowse.setMediaServer(mMediaServer);
mStatus.setMediaServer(mMediaServer);
if (mServicesDiscovery != null) {
mServicesDiscovery.setMediaServer(mMediaServer);
}
if (mNavigation != null) {
mNavigation.setMediaServer(mMediaServer);
}
}
@Override
protected void onNewIntent(Intent intent) {
String host = intent.getStringExtra(Intents.EXTRA_REMOTE_HOST);
if (host != null) {
int port = intent.getIntExtra(Intents.EXTRA_REMOTE_PORT, 8080);
String authority = host + ":" + port;
changeServer(authority);
}
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) || Intents.ACTION_REMOTE_VIEW.equals(action)
|| Intents.ACTION_VIEW.equals(action)) {
Uri data = intent.getData();
if (data != null) {
changeInput(data.toString());
}
} else if (Intent.ACTION_SEARCH.equals(action)) {
String input = intent.getStringExtra(SearchManager.QUERY);
changeInput(input);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(STATE_INPUT, mInput);
if (mTabHost != null) {
outState.putString(STATE_TAB, mTabHost.getCurrentTabTag());
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mInput = savedInstanceState.getString(STATE_INPUT);
if (mTabHost != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString(STATE_TAB));
}
}
private void changeInput(String input) {
if (mMediaServer == null) {
Log.w(TAG, "No server selected");
return;
}
mInput = input;
if (mInput != null) {
mMediaServer.status().command.input.play(mInput);
}
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
registerReceiver(mStatusReceiver, filter);
if (mMediaServer == null) {
pickServer();
}
}
@Override
public void onPause() {
unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
void onVolumeChanged(int volume) {
if (!hasVolumeFragment() && mVolumeLevel != VOLUME_LEVEL_UNKNOWN && mVolumeLevel != volume) {
mVolumePanel.onVolumeChanged(volume);
}
mVolumeLevel = volume;
if (0 != volume) {
mLastNonZeroVolume = volume;
}
}
private boolean hasVolumeFragment() {
return mVolume != null && mVolume.isInLayout();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int c = event.getUnicodeChar();
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (mVolumeLevel != VOLUME_LEVEL_UNKNOWN) {
setVolume(mVolumeLevel + 20);
} else {
mMediaServer.status().command.volumeUp();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (mVolumeLevel != VOLUME_LEVEL_UNKNOWN) {
setVolume(mVolumeLevel - 20);
} else {
mMediaServer.status().command.volumeDown();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (event.isAltPressed()) {
mMediaServer.status().command.seek(Uri.encode("-10"));
return true;
} else if (event.isShiftPressed()) {
mMediaServer.status().command.seek(Uri.encode("-3"));
return true;
} else {
mMediaServer.status().command.key("nav-left");
return true;
}
} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (event.isAltPressed()) {
mMediaServer.status().command.seek(Uri.encode("+10"));
return true;
} else if (event.isShiftPressed()) {
mMediaServer.status().command.seek(Uri.encode("+3"));
return true;
} else {
mMediaServer.status().command.key("nav-right");
return true;
}
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
mMediaServer.status().command.key("nav-up");
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
mMediaServer.status().command.key("nav-down");
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
mMediaServer.status().command.key("nav-activate");
return true;
} else if (c == ' ') {
mMediaServer.status().command.playback.pause();
return true;
} else if (c == 's') {
mMediaServer.status().command.playback.stop();
return true;
} else if (c == 'p') {
mMediaServer.status().command.playback.previous();
return true;
} else if (c == 'n') {
mMediaServer.status().command.playback.next();
return true;
} else if (c == '+') {
// TODO: Play faster
return super.onKeyDown(keyCode, event);
} else if (c == '-') {
// TODO: Play slower
return super.onKeyDown(keyCode, event);
} else if (c == 'f') {
mMediaServer.status().command.fullscreen();
return true;
} else if (c == 'm') {
mute();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
private void setVolume(int volume) {
volume = Math.max(volume, 0);
volume = Math.min(volume, MAX_VOLUME);
mMediaServer.status().command.volume(volume);
onVolumeChanged(volume);
}
private void mute() {
// The web interface doesn't have a documented mute command.
if (mVolumeLevel != 0) {
// Set the volume to zero
mMediaServer.status().command.volume(0);
} else if (mLastNonZeroVolume != VOLUME_LEVEL_UNKNOWN) {
// Restore the volume to the last known value
mMediaServer.status().command.volume(mLastNonZeroVolume);
}
}
@SuppressWarnings("unchecked")
private <T extends Fragment> T findFragmentById(int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
return (T) fragmentManager.findFragmentById(id);
}
@SuppressWarnings("unchecked")
private <T extends Fragment> T findOrAddFragment(String tag, Class<T> fragmentClass) {
try {
FragmentManager fragmentManager = getSupportFragmentManager();
T fragment = (T) fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = fragmentClass.newInstance();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(fragment, FRAGMENT_STATUS);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
}
return fragment;
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onVolumeChanged(status.getVolume());
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/app/PlaybackActivity.java | Java | gpl3 | 20,724 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.app;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.fragment.BrowseFragment;
import android.app.Activity;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SlidingDrawer;
final class BrowseDrawerListener implements SlidingDrawer.OnDrawerOpenListener,
SlidingDrawer.OnDrawerCloseListener {
private final Activity mActivity;
private final SlidingDrawer mDrawer;
private final BrowseFragment mBrowse;
private ActionMode mActionMode;
public BrowseDrawerListener(Activity activity, SlidingDrawer drawer, BrowseFragment browse) {
mActivity = activity;
mDrawer = drawer;
mBrowse = browse;
}
/** {@inheritDoc} */
public void onDrawerOpened() {
startActionMode();
mDrawer.getHandle().setVisibility(View.INVISIBLE);
}
/** {@inheritDoc} */
public void onDrawerClosed() {
finishActionMode();
mDrawer.getHandle().setVisibility(View.VISIBLE);
}
private void startActionMode() {
if (mActionMode == null) {
mActionMode = mActivity.startActionMode(new ActionModeCallback());
}
}
private void finishActionMode() {
if (mActionMode != null) {
mActionMode.finish();
mActionMode = null;
}
}
// BrowseDrawerListener can't be referenced by code running
// on Android 1.6 if it implements ActionMode.Callback directly,
// so implement ActionMode.Callback with a nested class instead.
private class ActionModeCallback implements ActionMode.Callback {
/** {@inheritDoc} */
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return mBrowse.onOptionsItemSelected(item);
}
/** {@inheritDoc} */
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mActivity.getMenuInflater().inflate(R.menu.browse_options, menu);
return true;
}
/** {@inheritDoc} */
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
/** {@inheritDoc} */
public void onDestroyActionMode(ActionMode mode) {
if (mode == mActionMode) {
if (mDrawer.isOpened()) {
mDrawer.animateClose();
}
mActionMode = null;
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/app/BrowseDrawerListener.java | Java | gpl3 | 3,243 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.app;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.preference.ProgressCategory;
import org.peterbaldwin.vlcremote.receiver.PhoneStateChangedReceiver;
import org.peterbaldwin.vlcremote.sweep.PortSweeper;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.SystemClock;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListAdapter;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
public final class PickServerActivity extends PreferenceActivity implements PortSweeper.Callback,
DialogInterface.OnClickListener, OnPreferenceChangeListener {
private static final String TAG = "PickServer";
private static final String PACKAGE_NAME = R.class.getPackage().getName();
private static final ComponentName PHONE_STATE_RECEIVER = new ComponentName(PACKAGE_NAME,
PhoneStateChangedReceiver.class.getName());
public static final String EXTRA_PORT = "org.peterbaldwin.portsweep.intent.extra.PORT";
public static final String EXTRA_FILE = "org.peterbaldwin.portsweep.intent.extra.FILE";
public static final String EXTRA_WORKERS = "org.peterbaldwin.portsweep.intent.extra.WORKERS";
public static final String EXTRA_REMEMBERED = "org.peterbaldwin.portsweep.intent.extra.REMEMBERED";
private static final String KEY_WIFI = "wifi";
private static final String KEY_SERVERS = "servers";
private static final String KEY_ADD_SERVER = "add_server";
private static final String KEY_PAUSE_FOR_CALL = "pause_for_call";
public static final String STATE_HOSTS = "hosts";
public static final int DEFAULT_WORKERS = 16;
private static final int DIALOG_ADD_SERVER = 1;
private static final int MENU_SCAN = Menu.FIRST;
private static final int CONTEXT_FORGET = Menu.FIRST;
private static byte[] toByteArray(int i) {
int i4 = (i >> 24) & 0xFF;
int i3 = (i >> 16) & 0xFF;
int i2 = (i >> 8) & 0xFF;
int i1 = i & 0xFF;
return new byte[] {
(byte) i1, (byte) i2, (byte) i3, (byte) i4
};
}
private PortSweeper mPortSweeper;
private BroadcastReceiver mReceiver;
private AlertDialog mDialogAddServer;
private EditText mEditHostname;
private EditText mEditPort;
private EditText mEditUser;
private EditText mEditPassword;
private String mFile;
private int mPort;
private int mWorkers;
private long mCreateTime;
private ArrayList<String> mRemembered;
private CheckBoxPreference mPreferenceWiFi;
private CheckBoxPreference mPreferencePauseForCall;
private ProgressCategory mProgressCategory;
private Preference mPreferenceAddServer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.server_settings);
PreferenceScreen preferenceScreen = getPreferenceScreen();
mPreferenceWiFi = (CheckBoxPreference) preferenceScreen.findPreference(KEY_WIFI);
mPreferencePauseForCall = (CheckBoxPreference) preferenceScreen.findPreference(KEY_PAUSE_FOR_CALL);
mProgressCategory = (ProgressCategory) preferenceScreen.findPreference(KEY_SERVERS);
mPreferenceAddServer = preferenceScreen.findPreference(KEY_ADD_SERVER);
mPreferencePauseForCall.setOnPreferenceChangeListener(this);
mPreferencePauseForCall.setChecked(getPauseForCall());
Intent intent = getIntent();
mPort = intent.getIntExtra(EXTRA_PORT, 0);
if (mPort == 0) {
throw new IllegalArgumentException("Port must be specified");
}
mFile = intent.getStringExtra(EXTRA_FILE);
if (mFile == null) {
throw new IllegalArgumentException("File must be specified");
}
mRemembered = intent.getStringArrayListExtra(EXTRA_REMEMBERED);
if (mRemembered == null) {
mRemembered = new ArrayList<String>();
}
registerForContextMenu(getListView());
mWorkers = intent.getIntExtra(EXTRA_WORKERS, DEFAULT_WORKERS);
mPortSweeper = (PortSweeper) getLastNonConfigurationInstance();
if (mPortSweeper == null) {
mPortSweeper = createPortSweeper();
startSweep();
}
mPortSweeper.setCallback(this);
// Registering the receiver triggers a broadcast with the initial state.
// To tell the difference between a broadcast triggered by registering a
// receiver and a broadcast triggered by a true network event, note the
// time and ignore all broadcasts for one second.
mCreateTime = SystemClock.uptimeMillis();
mReceiver = new MyBroadcastReceiver();
// For robustness, update the connection status for all types of events.
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
updateWifiInfo();
}
boolean isInitialBroadcast() {
return (SystemClock.uptimeMillis() - mCreateTime) < 1000;
}
@Override
public Object onRetainNonConfigurationInstance() {
Object nonConfigurationInstance = mPortSweeper;
// TODO: Set callback to null without triggering NullPointerException in
// the event that a callback happens while the Activity is recreating
// itself.
mPortSweeper = null;
return nonConfigurationInstance;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int n = mProgressCategory.getPreferenceCount();
ArrayList<String> hosts = new ArrayList<String>(n * 2);
for (int i = 0; i < n; i++) {
Preference preference = mProgressCategory.getPreference(i);
String hostname = preference.getTitle().toString();
String responseCode = preference.getKey();
if (!mRemembered.contains(hostname)) {
hosts.add(hostname);
hosts.add(responseCode);
}
}
outState.putStringArrayList(STATE_HOSTS, hosts);
}
private Preference createServerPreference(String server, int responseCode) {
Preference preference = new Preference(this);
preference.setKey(Integer.toString(responseCode));
preference.setTitle(server);
preference.setPersistent(false);
switch (responseCode) {
case HttpURLConnection.HTTP_FORBIDDEN:
preference.setSummary(getText(R.string.summary_forbidden));
break;
}
return preference;
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
List<String> hosts = state.getStringArrayList(STATE_HOSTS);
for (int i = 0; i < hosts.size(); i += 2) {
String hostname = hosts.get(i);
String key = hosts.get(i + 1);
int responseCode = (key != null) ? Integer.parseInt(key) : HttpURLConnection.HTTP_OK;
Preference preference = createServerPreference(hostname, responseCode);
mProgressCategory.addPreference(preference);
}
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
mReceiver = null;
if (mPortSweeper != null) {
mPortSweeper.destory();
}
super.onDestroy();
}
private PortSweeper createPortSweeper() {
PortSweeper.Callback callback = this;
Looper looper = Looper.myLooper();
return new PortSweeper(mPort, mFile, mWorkers, callback, looper);
}
private WifiInfo getConnectionInfo() {
Object service = getSystemService(WIFI_SERVICE);
WifiManager manager = (WifiManager) service;
WifiInfo info = manager.getConnectionInfo();
if (info != null) {
SupplicantState state = info.getSupplicantState();
if (state.equals(SupplicantState.COMPLETED)) {
return info;
}
}
return null;
}
private byte[] getIpAddress() {
WifiInfo info = getConnectionInfo();
if (info != null) {
return toByteArray(info.getIpAddress());
}
return null;
}
void startSweep() {
byte[] ipAddress = getIpAddress();
if (ipAddress != null) {
mPortSweeper.sweep(ipAddress);
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
/** {@inheritDoc} */
public void onHostFound(String hostname, int responseCode) {
String server = hostname + ":" + mPort;
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_FORBIDDEN:
if (!mRemembered.contains(server)) {
Preference preference = createServerPreference(server, responseCode);
mProgressCategory.addPreference(preference);
}
break;
default:
Log.d(TAG, "Unexpected response code: " + responseCode);
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ADD_SERVER:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_server);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.add_server, null);
mEditHostname = (EditText) view.findViewById(R.id.edit_hostname);
mEditPort = (EditText) view.findViewById(R.id.edit_port);
mEditUser = (EditText) view.findViewById(R.id.edit_user);
mEditPassword = (EditText) view.findViewById(R.id.edit_password);
builder.setView(view);
builder.setPositiveButton(R.string.ok, this);
builder.setNegativeButton(R.string.cancel, this);
mDialogAddServer = builder.create();
return mDialogAddServer;
default:
return super.onCreateDialog(id);
}
}
/** {@inheritDoc} */
public void onClick(DialogInterface dialog, int which) {
if (dialog == mDialogAddServer) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
String hostname = getHostname();
int port = getPort();
String user = getUser();
String password = getPassword();
StringBuilder server = new StringBuilder();
if (!TextUtils.isEmpty(user)) {
server.append(user).append(':').append(password).append('@');
}
server.append(hostname).append(':').append(port);
pick(server.toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
}
private void pick(String server) {
Intent data = new Intent();
Uri uri = Uri.parse("http://" + server);
data.setData(uri);
if (!mRemembered.contains(server)) {
mRemembered.add(server);
}
data.putStringArrayListExtra(EXTRA_REMEMBERED, mRemembered);
setResult(RESULT_OK, data);
finish();
}
private void forget(String server) {
mRemembered.remove(server);
int count = mProgressCategory.getPreferenceCount();
for (int i = 0; i < count; i++) {
Preference preference = mProgressCategory.getPreference(i);
if (server.equals(preference.getTitle().toString())) {
mProgressCategory.removePreference(preference);
break;
}
}
// Send the updated list of remembered servers even if the activity is
// canceled
Intent data = new Intent();
data.putStringArrayListExtra(EXTRA_REMEMBERED, mRemembered);
setResult(RESULT_CANCELED, data);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mPreferenceAddServer) {
showDialog(DIALOG_ADD_SERVER);
return true;
} else if (preference == mPreferenceWiFi) {
Intent intent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
startActivity(intent);
// Undo checkbox toggle
updateWifiInfo();
return true;
} else if (preference == mPreferencePauseForCall) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
} else {
String server = preference.getTitle().toString();
pick(server);
return true;
}
}
/** {@inheritDoc} */
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mPreferencePauseForCall) {
setPauseForCall(Boolean.TRUE.equals(newValue));
return true;
} else {
return false;
}
}
private Preference getPreferenceFromMenuInfo(ContextMenuInfo menuInfo) {
if (menuInfo != null) {
if (menuInfo instanceof AdapterContextMenuInfo) {
AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo) menuInfo;
PreferenceScreen screen = getPreferenceScreen();
ListAdapter root = screen.getRootAdapter();
Object item = root.getItem(adapterMenuInfo.position);
return (Preference) item;
}
}
return null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Preference preference = getPreferenceFromMenuInfo(menuInfo);
if (preference != null) {
String server = preference.getTitle().toString();
if (mRemembered.contains(server)) {
menu.add(Menu.NONE, CONTEXT_FORGET, Menu.NONE, R.string.context_forget);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_FORGET:
ContextMenuInfo menuInfo = item.getMenuInfo();
Preference preference = getPreferenceFromMenuInfo(menuInfo);
if (preference != null) {
String server = preference.getTitle().toString();
forget(server);
}
return true;
default:
return super.onContextItemSelected(item);
}
}
/** {@inheritDoc} */
public void onProgress(int progress, int max) {
if (progress == 0) {
mProgressCategory.removeAll();
for (String server : mRemembered) {
Preference preference = createServerPreference(server, HttpURLConnection.HTTP_OK);
preference.setSummary(R.string.summary_remembered);
mProgressCategory.addPreference(preference);
}
}
mProgressCategory.setProgress(progress != max);
}
private String getHostname() {
return mEditHostname.getText().toString();
}
private String getUser() {
return mEditUser.getText().toString();
}
private String getPassword() {
return mEditPassword.getText().toString();
}
private int getPort() {
String value = String.valueOf(mEditPort.getText());
if (!TextUtils.isEmpty(value)) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
Log.w(TAG, "Invalid port number: " + value);
}
}
return mPort;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem scan = menu.add(0, MENU_SCAN, 0, R.string.scan);
scan.setIcon(R.drawable.ic_menu_scan_network);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SCAN:
startSweep();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateWifiInfo() {
WifiInfo info = getConnectionInfo();
if (info != null) {
mPreferenceWiFi.setChecked(true);
String ssid = info.getSSID();
String template = getString(R.string.summary_wifi_connected);
Object[] objects = {
ssid != null ? ssid : ""
};
CharSequence summary = MessageFormat.format(template, objects);
mPreferenceWiFi.setSummary(summary);
} else {
mPreferenceWiFi.setChecked(false);
mPreferenceWiFi.setSummary(R.string.summary_wifi_disconnected);
}
}
private boolean getPauseForCall() {
switch (getPackageManager().getComponentEnabledSetting(PHONE_STATE_RECEIVER)) {
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
return true;
default:
return false;
}
}
private void setPauseForCall(boolean enabled) {
getPackageManager().setComponentEnabledSetting(
PHONE_STATE_RECEIVER,
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo = extras.getParcelable(WifiManager.EXTRA_NETWORK_INFO);
NetworkInfo.State state = networkInfo.getState();
if (state == NetworkInfo.State.CONNECTED) {
if (isInitialBroadcast()) {
// Don't perform a sweep if the broadcast was triggered
// as a result of a receiver being registered.
} else {
startSweep();
}
}
}
updateWifiInfo();
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/app/PickServerActivity.java | Java | gpl3 | 21,046 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Connect to VLC server instead of media service
* -Listen for VLC status events
* -Schedule status updates for time at which current track is expected to end
*/
package org.peterbaldwin.vlcremote.appwidget;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Preferences;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.model.Track;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
/**
* Simple widget to show currently playing album art along with play/pause and
* next track buttons.
*/
public class MediaAppWidgetProvider extends AppWidgetProvider {
static final String LOG_TAG = "VlcRemoteAppWidgetProvider";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
String noMedia = context.getString(R.string.no_media);
String text1;
String text2;
if (status.isStopped()) {
text1 = noMedia;
text2 = "";
} else {
Track track = status.getTrack();
text1 = track.getTitle();
text2 = track.getArtist();
if (TextUtils.isEmpty(text1) && TextUtils.isEmpty(text2)) {
text1 = track.getName();
}
}
int[] appWidgetIds = null;
performUpdate(context, text1, text2, status.isPlaying(), appWidgetIds);
long time = status.getTime();
long length = status.getLength();
if (status.isPlaying() && time >= 0L && length > 0L && time <= length) {
// Schedule an update shortly after the current track is
// expected to end.
long delay = length - time + 1000;
scheduleUpdate(context, delay);
}
} else if (Intents.ACTION_ERROR.equals(action)) {
CharSequence text1 = context.getText(R.string.connection_error);
Throwable t = (Throwable) intent.getSerializableExtra(Intents.EXTRA_THROWABLE);
String text2 = t.getMessage();
if (text2 == null) {
text2 = t.getClass().getName();
}
Boolean playing = null;
int[] appWidgetIds = null;
performUpdate(context, text1, text2, playing, appWidgetIds);
cancelPendingUpdate(context);
} else if (Intents.ACTION_MANUAL_APPWIDGET_UPDATE.equals(action)
|| ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
int[] appWidgetIds = null;
update(context, appWidgetIds);
} else {
super.onReceive(context, intent);
}
}
private static PendingIntent createManualAppWidgetUpdateIntent(Context context) {
int requestCode = 0;
Intent intent = new Intent(Intents.ACTION_MANUAL_APPWIDGET_UPDATE);
int flags = 0;
return PendingIntent.getBroadcast(context, requestCode, intent, flags);
}
private void scheduleUpdate(Context context, long delay) {
Object service = context.getSystemService(Context.ALARM_SERVICE);
AlarmManager alarmManager = (AlarmManager) service;
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long triggerAtTime = SystemClock.elapsedRealtime() + delay;
PendingIntent operation = createManualAppWidgetUpdateIntent(context);
alarmManager.set(type, triggerAtTime, operation);
}
private void cancelPendingUpdate(Context context) {
Object service = context.getSystemService(Context.ALARM_SERVICE);
AlarmManager alarmManager = (AlarmManager) service;
PendingIntent operation = createManualAppWidgetUpdateIntent(context);
alarmManager.cancel(operation);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetIds);
}
private void update(Context context, int[] appWidgetIds) {
Preferences preferences = Preferences.get(context);
String authority = preferences.getAuthority();
if (authority != null) {
MediaServer server = new MediaServer(context, authority);
server.status().get();
} else {
CharSequence text1 = context.getText(R.string.noserver);
CharSequence text2 = "";
Boolean playing = null;
performUpdate(context, text1, text2, playing, appWidgetIds);
}
}
private void pushUpdate(Context context, int[] appWidgetIds, RemoteViews views) {
// Update specific list of appWidgetIds if given,
// otherwise default to all
AppWidgetManager manager = AppWidgetManager.getInstance(context);
if (appWidgetIds != null) {
manager.updateAppWidget(appWidgetIds, views);
} else {
Class<? extends AppWidgetProvider> cls = getClass();
ComponentName provider = new ComponentName(context, cls);
manager.updateAppWidget(provider, views);
}
}
/**
* Update all active widget instances by pushing changes
*/
void performUpdate(Context context, CharSequence title, CharSequence artist, Boolean playing,
int[] appWidgetIds) {
String packageName = context.getPackageName();
RemoteViews views = new RemoteViews(packageName, R.layout.album_appwidget);
views.setViewVisibility(R.id.title, View.VISIBLE);
views.setTextViewText(R.id.title, title);
views.setTextViewText(R.id.artist, artist);
if (playing != null) {
views.setImageViewResource(R.id.control_play,
playing ? R.drawable.ic_appwidget_music_pause
: R.drawable.ic_appwidget_music_play);
} else {
views.setImageViewResource(R.id.control_play, R.drawable.ic_popup_sync_2);
}
views.setViewVisibility(R.id.control_next, playing != null ? View.VISIBLE : View.GONE);
// Link actions buttons to intents
linkButtons(context, views, playing);
pushUpdate(context, appWidgetIds, views);
}
/**
* Link up various button actions using {@link PendingIntent}.
*/
private void linkButtons(Context context, RemoteViews views, Boolean playing) {
{
int requestCode = 0;
Intent intent = getLaunchIntent(context);
int flags = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent,
flags);
views.setOnClickPendingIntent(R.id.album_appwidget, pendingIntent);
}
Preferences preferences = Preferences.get(context);
String authority = preferences.getAuthority();
if (authority == null) {
return;
}
MediaServer server = new MediaServer(context, authority);
if (playing != null) {
PendingIntent intent = server.status().command.playback.pendingPause();
views.setOnClickPendingIntent(R.id.control_play, intent);
} else {
PendingIntent intent = server.status().pendingGet();
views.setOnClickPendingIntent(R.id.control_play, intent);
}
{
PendingIntent intent = server.status().command.playback.pendingNext();
views.setOnClickPendingIntent(R.id.control_next, intent);
}
}
/**
* Returns the {@link Intent} to launch VLC Remote.
*/
private static Intent getLaunchIntent(Context context) {
return context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/appwidget/MediaAppWidgetProvider.java | Java | gpl3 | 8,978 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import org.apache.http.Header;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.protocol.HTTP;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Directory;
import org.peterbaldwin.vlcremote.model.Playlist;
import org.peterbaldwin.vlcremote.model.Remote;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.service.StatusService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;
import java.io.IOException;
import java.net.ContentHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class MediaServer {
private static final String TAG = "VLC";
private final Context mContext;
private final String mAuthority;
public MediaServer(Context context, String authority) {
mContext = context;
mAuthority = authority;
}
public MediaServer(Context context, Uri data) {
mContext = context;
mAuthority = data.getAuthority();
}
public String getAuthority() {
return mAuthority;
}
public StatusRequest status() {
return new StatusRequest(mContext, mAuthority);
}
public StatusRequest status(Uri uri) {
return new StatusRequest(mContext, uri);
}
public PlaylistRequest playlist(String search) {
return new PlaylistRequest(mContext, mAuthority, search);
}
public BrowseRequest browse(String dir) {
return new BrowseRequest(mContext, mAuthority, dir);
}
public ImageRequest image(Uri uri) {
return new ImageRequest(mContext, uri);
}
public ImageRequest art() {
return new ImageRequest(mContext, mAuthority);
}
static class Request {
/**
* Time to wait between network requests when sending multiple commands.
*/
protected static final int DELAY = 500;
private final Context mContext;
private final Uri mUri;
protected int mFlags;
protected boolean mNotifyPlaylist;
protected long mDelay;
protected Request(Context context, String authority, String path) {
mContext = context;
mUri = Uri.parse("http://" + authority + path);
}
protected Request(Context context, Uri uri) {
mContext = context;
mUri = uri;
}
protected final Intent intent(String encodedQuery) {
Intent intent = new Intent(Intents.ACTION_STATUS);
intent.setClass(mContext, StatusService.class);
Uri data = mUri.buildUpon().encodedQuery(encodedQuery).build();
intent.setData(data);
intent.putExtra(Intents.EXTRA_FLAGS, mFlags);
return intent;
}
protected final PendingIntent pending(Intent intent) {
return PendingIntent.getService(mContext, 0, intent, 0);
}
protected final void start(Intent intent) {
if (mDelay == 0L) {
mContext.startService(intent);
} else {
Object service = mContext.getSystemService(Context.ALARM_SERVICE);
AlarmManager manager = (AlarmManager) service;
long triggerAtTime = SystemClock.elapsedRealtime() + mDelay;
int requestCode = (int) triggerAtTime;
int flags = 0;
PendingIntent op = PendingIntent.getService(mContext, requestCode, intent, flags);
manager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, op);
}
}
protected final void execute(String encodedQuery) {
start(intent(encodedQuery));
}
protected final <T> Remote<T> load(ContentHandler handler) {
String spec = mUri.toString();
try {
T data = read(handler);
return Remote.data(data);
} catch (Throwable t) {
Log.e(TAG, "Unable to load: " + spec, t);
return Remote.error(t);
}
}
@SuppressWarnings("unchecked")
protected final <T> T read(ContentHandler handler) throws IOException {
String spec = mUri.toString();
URL url = new URL(spec);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
try {
String usernamePassword = mUri.getUserInfo();
if (usernamePassword != null) {
Header authorization = BasicScheme.authenticate(
new UsernamePasswordCredentials(usernamePassword), HTTP.UTF_8, false);
http.setRequestProperty(authorization.getName(), authorization.getValue());
}
return (T) handler.getContent(http);
} finally {
http.disconnect();
}
}
}
public static final class StatusRequest extends Request {
StatusRequest(Context context, String authority) {
super(context, authority, "/requests/status.xml");
}
public StatusRequest(Context context, Uri uri) {
super(context, uri);
}
public final CommandInterface command = new CommandInterface();
/**
* Loads the server status synchronously.
*/
public Remote<Status> load() {
return load(new StatusContentHandler());
}
public Status read() throws IOException {
return read(new StatusContentHandler());
}
/**
* Loads the server status asynchronously.
*/
public void get() {
execute("");
}
public PendingIntent pendingGet() {
return pending(intent(""));
}
public StatusRequest programmatic() {
mFlags |= Intents.FLAG_PROGRAMMATIC;
return this;
}
public StatusRequest onlyIfPlaying() {
mFlags |= Intents.FLAG_ONLY_IF_PLAYING;
return this;
}
public StatusRequest onlyIfPaused() {
mFlags |= Intents.FLAG_ONLY_IF_PAUSED;
return this;
}
public StatusRequest setResumeOnIdle() {
mFlags |= Intents.FLAG_SET_RESUME_ON_IDLE;
return this;
}
public final class CommandInterface {
public final InputInterface input = new InputInterface();
public class InputInterface {
private InputInterface() {
}
public void play(String input) {
List<String> options = Collections.emptyList();
play(input, options);
}
public void play(String input, String... options) {
play(input, Arrays.asList(options));
}
public void play(String input, List<String> options) {
// Options are appended to the MRL
// for VLC 1.1.10 and earlier
for (String option : options) {
input += " " + option;
}
String query = "command=in_play&input=" + Uri.encode(input);
// Options are appended as query parameters
// for VLC 1.1.11 and later
for (String option : options) {
query += ("&option=" + Uri.encode(option));
}
execute(query);
}
public void enqueue(String input) {
execute("command=in_enqueue&input=" + Uri.encode(input));
}
}
public final PlaybackInterface playback = new PlaybackInterface();
public class PlaybackInterface {
private PlaybackInterface() {
}
public void play(int id) {
execute("command=pl_play&id=" + id);
}
public void pause() {
execute("command=pl_pause");
}
public PendingIntent pendingPause() {
return pending(intent("command=pl_pause"));
}
public void stop() {
execute("command=pl_stop");
}
public void next() {
execute("command=pl_next");
}
public PendingIntent pendingNext() {
return pending(intent("command=pl_next"));
}
public void previous() {
execute("command=pl_previous");
}
public void delete(int id) {
mNotifyPlaylist = true;
execute("command=pl_delete&id=" + id);
}
public void empty() {
execute("command=pl_empty");
}
public void sort(int sort, int order) {
execute("command=pl_sort&id=" + order + "&val=" + sort);
}
public void shuffle() {
execute("command=pl_random");
}
public PlaybackInterface loop() {
execute("command=pl_loop");
mDelay += DELAY;
return this;
}
public PlaybackInterface repeat() {
execute("command=pl_repeat");
mDelay += DELAY;
return this;
}
public void random() {
execute("command=pl_random");
}
public void sd(String value) {
execute("command=pl_sd&val=" + value);
}
}
public void volume(int value) {
execute("command=volume&val=" + value);
}
public void adjustVolume(int amount) {
String val = amount < 0 ? Integer.toString(amount) : "+" + amount;
execute("command=volume&val=" + Uri.encode(val));
}
public void volumeDown() {
execute("command=volume&val=-20");
}
public void volumeUp() {
execute("command=volume&val=%2B20");
}
public void seek(String pos) {
execute("command=seek&val=" + pos);
}
public void key(String keycode) {
// Use hotkey name (without the "key-" part)
// as the argument to simulate a hotkey press
execute("command=key&val=" + keycode);
}
public void fullscreen() {
execute("command=fullscreen");
}
public void snapshot() {
execute("command=snapshot");
}
}
}
public static final class PlaylistRequest extends Request {
PlaylistRequest(Context context, String authority, String search) {
super(context, authority, "/requests/playlist.xml?search=" + Uri.encode(search));
}
public Remote<Playlist> load() {
return load(new PlaylistContentHandler());
}
}
public static final class BrowseRequest extends Request {
BrowseRequest(Context context, String authority, String dir) {
super(context, authority, "/requests/browse.xml?dir=" + Uri.encode(dir));
}
public Remote<Directory> load() {
return load(new DirectoryContentHandler());
}
}
public static final class ImageRequest extends Request {
ImageRequest(Context context, Uri uri) {
super(context, uri);
}
ImageRequest(Context context, String authority) {
super(context, authority, "/art");
}
public Bitmap read() throws IOException {
return read(new BitmapContentHandler());
}
public Remote<Bitmap> load() throws IOException {
return load(new BitmapContentHandler());
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/MediaServer.java | Java | gpl3 | 13,267 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import org.peterbaldwin.vlcremote.model.Directory;
import org.peterbaldwin.vlcremote.model.File;
import org.xml.sax.Attributes;
import android.sax.Element;
import android.sax.RootElement;
import android.sax.StartElementListener;
import java.io.IOException;
import java.net.URLConnection;
final class DirectoryContentHandler extends XmlContentHandler<Directory> {
private File createFile(Attributes attributes) {
String type = attributes.getValue("", "type");
String sizeString = attributes.getValue("", "size");
Long size = null;
try {
if (sizeString != null && !sizeString.equals("unknown")) {
size = Long.parseLong(sizeString);
}
} catch (NumberFormatException e) {
// Ignore unexpected value
}
String date = attributes.getValue("", "date");
String path = attributes.getValue("", "path");
String name = attributes.getValue("", "name");
String extension = attributes.getValue("", "extension");
if (path != null && !path.startsWith("/")) { // Windows path
// Work-around: Replace front-slash
// appended by server with back-slash.
path = path.replace('/', '\\');
}
return new File(type, size, date, path, name, extension);
}
@Override
public Object getContent(URLConnection connection) throws IOException {
final Directory directory = new Directory();
RootElement root = new RootElement("", "root");
Element element = root.getChild("", "element");
element.setStartElementListener(new StartElementListener() {
/** {@inheritDoc} */
public void start(Attributes attributes) {
File file = createFile(attributes);
directory.add(file);
}
});
parse(connection, root.getContentHandler());
return directory;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/DirectoryContentHandler.java | Java | gpl3 | 2,695 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Work-around for <a
* href="http://code.google.com/p/android/issues/detail?id=6066">Issue 6066</a>
*/
final class BlockingFilterInputStream extends FilterInputStream {
public BlockingFilterInputStream(InputStream input) {
super(input);
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
int total = 0;
while (total < count) {
int read = super.read(buffer, offset + total, count - total);
if (read == -1) {
return (total != 0) ? total : -1;
}
total += read;
}
return total;
}
@Override
public int read(byte[] buffer) throws IOException {
int total = 0;
while (total < buffer.length) {
int offset = total;
int count = buffer.length - total;
int read = super.read(buffer, offset, count);
if (read == -1) {
return (total != 0) ? total : -1;
}
total += read;
}
return total;
}
@Override
public long skip(long count) throws IOException {
long total = 0L;
while (total < count) {
long skipped = super.skip(count - total);
if (skipped == 0L) {
int b = super.read();
if (b < 0) {
break;
} else {
skipped += 1;
}
}
total += skipped;
}
return total;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/BlockingFilterInputStream.java | Java | gpl3 | 2,385 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import org.peterbaldwin.vlcremote.model.Playlist;
import org.peterbaldwin.vlcremote.model.Track;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import android.text.Html;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Stack;
final class PlaylistContentHandler extends XmlContentHandler<Playlist> implements ContentHandler {
private static final String[] TEXT_ELEMENTS = {
"title", "artist", "genre", "copyright", "album", "track", "description", "rating",
"date", "url", "language", "now_playing", "publisher", "encoded_by", "art_url",
"track_id"
};
private static final Playlist EMPTY_PLAYLIST = new Playlist(1, "Undefined");
private final Stack<Playlist> mNodeStack;
private final StringBuilder mBuilder;
private Playlist mRoot;
private boolean mCapture = false;
private Track mTrack;
private boolean mFlatten = true;
public PlaylistContentHandler() {
mNodeStack = new Stack<Playlist>();
mBuilder = new StringBuilder();
}
/** {@inheritDoc} */
public void startElement(String uri, String localName, String name, Attributes attributes)
throws SAXException {
if ("leaf".equals(localName)) {
mTrack = createTrack(attributes);
if ("vlc://nop".equals(attributes.getValue("uri"))) {
// Don't include nop tracks in the output
} else {
if (mFlatten) {
mRoot.add(mTrack);
} else {
mNodeStack.peek().add(mTrack);
}
}
} else if ("node".equals(localName)) {
Playlist playlist = createPlaylist(attributes);
if (mNodeStack.isEmpty()) {
mRoot = playlist;
} else if (!mFlatten) {
mNodeStack.peek().add(playlist);
}
mNodeStack.push(playlist);
} else if (mTrack != null && isTextElement(localName)) {
mBuilder.setLength(0);
mCapture = true;
}
}
private static String unescape(CharSequence text) {
// TODO: Do this more efficiently
return Html.fromHtml(text.toString()).toString();
}
private String getText() {
if (mBuilder.length() == 0) {
return null;
} else {
if (mBuilder.indexOf("&") != -1) {
// Text is escaped twice so that it can be used in HTML.
return unescape(mBuilder);
} else {
return mBuilder.toString();
}
}
}
/** {@inheritDoc} */
public void endElement(String uri, String localName, String name) throws SAXException {
if ("node".equals(localName)) {
mNodeStack.pop();
} else if ("leaf".equals(localName)) {
mTrack = null;
} else if (mTrack != null) {
if ("title".equals(localName)) {
mTrack.setTitle(getText());
} else if ("artist".equals(localName)) {
mTrack.setArtist(getText());
} else if ("genre".equals(localName)) {
mTrack.setGenre(getText());
} else if ("copyright".equals(localName)) {
mTrack.setCopyright(getText());
} else if ("album".equals(localName)) {
mTrack.setAlbum(getText());
} else if ("track".equals(localName)) {
mTrack.setTrack(getText());
} else if ("description".equals(localName)) {
mTrack.setDescription(getText());
} else if ("rating".equals(localName)) {
mTrack.setRating(getText());
} else if ("date".equals(localName)) {
mTrack.setDate(getText());
} else if ("url".equals(localName)) {
mTrack.setUrl(getText());
} else if ("language".equals(localName)) {
mTrack.setLanguage(getText());
} else if ("now_playing".equals(localName)) {
mTrack.setNowPlaying(getText());
} else if ("publisher".equals(localName)) {
mTrack.setPublisher(getText());
} else if ("encoded_by".equals(localName)) {
mTrack.setEncodedBy(getText());
} else if ("art_url".equals(localName)) {
mTrack.setArtUrl(getText());
} else if ("track_id".equals(localName)) {
mTrack.setTrackId(getText());
}
}
mCapture = false;
}
private static boolean isTextElement(String localName) {
for (int i = 0; i < TEXT_ELEMENTS.length; i++) {
if (TEXT_ELEMENTS[i].equals(localName)) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public void characters(char[] ch, int start, int length) throws SAXException {
if (mCapture) {
mBuilder.append(ch, start, length);
}
}
/** {@inheritDoc} */
public void endDocument() throws SAXException {
}
/** {@inheritDoc} */
public void endPrefixMapping(String prefix) throws SAXException {
}
/** {@inheritDoc} */
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
}
/** {@inheritDoc} */
public void processingInstruction(String target, String data) throws SAXException {
}
/** {@inheritDoc} */
public void setDocumentLocator(Locator locator) {
}
/** {@inheritDoc} */
public void skippedEntity(String name) throws SAXException {
}
/** {@inheritDoc} */
public void startDocument() throws SAXException {
}
/** {@inheritDoc} */
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
private static Playlist createPlaylist(Attributes attributes) {
int id = Integer.parseInt(attributes.getValue("", "id"));
String name = attributes.getValue("", "name");
return new Playlist(id, name);
}
private static Track createTrack(Attributes attributes) {
Track track = new Track();
int id = Integer.parseInt(attributes.getValue("", "id"));
track.setId(id);
boolean current = "current".equals(attributes.getValue("", "current"));
track.setCurrent(current);
String uri = attributes.getValue("", "uri");
track.setUri(uri);
String name = attributes.getValue("", "name");
track.setName(name);
long duration = Long.parseLong(attributes.getValue("", "duration"));
track.setDuration(duration);
return track;
}
@Override
public Object getContent(URLConnection connection) throws IOException {
parse(connection, this);
return (mRoot != null) ? mRoot : EMPTY_PLAYLIST;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/PlaylistContentHandler.java | Java | gpl3 | 7,704 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.model.Track;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import android.sax.Element;
import android.sax.ElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.sax.TextElementListener;
import android.text.Html;
import java.io.IOException;
import java.net.URLConnection;
final class StatusContentHandler extends XmlContentHandler<Status> {
private static String unescape(String text) {
// The response text is escaped twice so that it can be used in HTML.
if (text.indexOf("&") != -1) {
// TODO: Use more efficient unescaping
return Html.fromHtml(text.toString()).toString();
} else {
return text;
}
}
private static boolean parseBoolean(String text) {
try {
// Booleans are represented as integers in VLC 1.0
return Integer.parseInt(text) != 0;
} catch (NumberFormatException e) {
// Booleans are represented as strings in VLC 1.1
return Boolean.parseBoolean(text);
}
}
private Status mStatus = new Status();
private Track mTrack = mStatus.getTrack();
private String mCategoryName;
private String mInfoName;
public ContentHandler getContentHandler() {
RootElement root = new RootElement("", "root");
root.getChild("", "volume").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
int volume = Integer.parseInt(body);
mStatus.setVolume(volume);
}
});
root.getChild("", "length").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
int length = Integer.parseInt(body);
mStatus.setLength(length);
}
});
root.getChild("", "time").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
int time = Integer.parseInt(body);
mStatus.setTime(time);
}
});
root.getChild("", "state").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mStatus.setState(body);
}
});
root.getChild("", "position").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
double position = Double.parseDouble(body);
mStatus.setPosition(position);
}
});
root.getChild("", "fullscreen").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
boolean fullscreen = parseBoolean(body);
mStatus.setFullscreen(fullscreen);
}
});
root.getChild("", "random").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
boolean random = parseBoolean(body);
mStatus.setRandom(random);
}
});
root.getChild("", "loop").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
boolean loop = parseBoolean(body);
mStatus.setLoop(loop);
}
});
root.getChild("", "repeat").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
boolean repeat = parseBoolean(body);
mStatus.setRepeat(repeat);
}
});
Element information = root.getChild("", "information");
Element meta = information.getChild("", "meta-information");
meta.getChild("", "title").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setTitle(unescape(body));
}
});
meta.getChild("", "artist").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setArtist(unescape(body));
}
});
meta.getChild("", "genre").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setGenre(unescape(body));
}
});
meta.getChild("", "copyright").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setCopyright(unescape(body));
}
});
meta.getChild("", "album").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setAlbum(unescape(body));
}
});
meta.getChild("", "track").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setTrack(unescape(body));
}
});
meta.getChild("", "description").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setDescription(unescape(body));
}
});
meta.getChild("", "rating").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setRating(unescape(body));
}
});
meta.getChild("", "date").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setDate(unescape(body));
}
});
meta.getChild("", "url").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setUrl(unescape(body));
}
});
meta.getChild("", "language").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setLanguage(unescape(body));
}
});
meta.getChild("", "now_playing").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setNowPlaying(unescape(body));
}
});
meta.getChild("", "publisher").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setPublisher(unescape(body));
}
});
meta.getChild("", "encoded_by").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setEncodedBy(unescape(body));
}
});
meta.getChild("", "art_url").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setArtUrl(unescape(body));
}
});
meta.getChild("", "track_id").setEndTextElementListener(new EndTextElementListener() {
/** {@inheritDoc} */
public void end(String body) {
mTrack.setTrackId(unescape(body));
}
});
// VLC 1.1
Element category = information.getChild("", "category");
category.setElementListener(new ElementListener() {
/** {@inheritDoc} */
public void start(Attributes attributes) {
mCategoryName = attributes.getValue("", "name");
}
/** {@inheritDoc} */
public void end() {
mCategoryName = null;
}
});
Element info = category.getChild("", "info");
info.setTextElementListener(new TextElementListener() {
/** {@inheritDoc} */
public void start(Attributes attributes) {
mInfoName = attributes.getValue("", "name");
}
/** {@inheritDoc} */
public void end(String body) {
if ("meta".equalsIgnoreCase(mCategoryName)) {
if ("artist".equalsIgnoreCase(mInfoName)) {
mTrack.setArtist(unescape(body));
} else if ("title".equalsIgnoreCase(mInfoName)) {
mTrack.setTitle(unescape(body));
} else if ("album".equalsIgnoreCase(mInfoName)) {
mTrack.setAlbum(unescape(body));
} else if ("genre".equalsIgnoreCase(mInfoName)) {
mTrack.setGenre(unescape(body));
} else if ("description".equalsIgnoreCase(mInfoName)) {
mTrack.setDescription(unescape(body));
} else if ("filename".equalsIgnoreCase(mInfoName)) {
mTrack.setName(unescape(body));
} else if ("artwork_url".equalsIgnoreCase(mInfoName)) {
mTrack.setArtUrl(unescape(body));
}
}
mInfoName = null;
}
});
return root.getContentHandler();
}
@Override
public Object getContent(URLConnection connection) throws IOException {
parse(connection, getContentHandler());
return mStatus;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/StatusContentHandler.java | Java | gpl3 | 10,941 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import android.util.Xml;
import java.io.IOException;
import java.io.InputStream;
import java.net.ContentHandler;
import java.net.HttpURLConnection;
import java.net.URLConnection;
/**
* Reads an XML response from an {@link HttpURLConnection}.
*
* @param <T>
*/
abstract class XmlContentHandler<T> extends ContentHandler {
protected final void parse(URLConnection connection, org.xml.sax.ContentHandler handler)
throws IOException {
InputStream input = connection.getInputStream();
try {
// The server sends UTF-8 instead of the HTTP default (ISO-8859-1).
Xml.Encoding encoding = Xml.Encoding.UTF_8;
Xml.parse(input, encoding, handler);
} catch (Exception e) {
IOException ioe = new IOException("Invalid XML");
ioe.initCause(e);
throw ioe;
} finally {
input.close();
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/XmlContentHandler.java | Java | gpl3 | 1,674 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.net;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.ContentHandler;
import java.net.URLConnection;
final class BitmapContentHandler extends ContentHandler {
private static final int TIMEOUT = 2000;
@Override
public Bitmap getContent(URLConnection connection) throws IOException {
// In some versions of VLC, album art requests can take a long time
// to return if there is no album art available for the current track.
// Set a short timeout to prevent a backlog of requests in this queue.
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
InputStream input = connection.getInputStream();
try {
input = new BlockingFilterInputStream(input);
Bitmap bitmap = BitmapFactory.decodeStream(input);
if (bitmap == null) {
throw new IOException("Decoding failed");
}
return bitmap;
} finally {
input.close();
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/net/BitmapContentHandler.java | Java | gpl3 | 1,853 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.loader;
import org.peterbaldwin.vlcremote.model.Directory;
import org.peterbaldwin.vlcremote.model.Remote;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.Context;
public class DirectoryLoader extends ModelLoader<Remote<Directory>> {
private final MediaServer mMediaServer;
private final String mDir;
public DirectoryLoader(Context context, MediaServer mediaServer, String dir) {
super(context);
mMediaServer = mediaServer;
mDir = dir;
}
@Override
public Remote<Directory> loadInBackground() {
return mMediaServer.browse(mDir).load();
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/loader/DirectoryLoader.java | Java | gpl3 | 1,377 |
package org.peterbaldwin.vlcremote.loader;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import java.io.IOException;
public class ImageLoader extends ModelLoader<Drawable> {
private final MediaServer mMediaServer;
private final Uri mUri;
public ImageLoader(Context context, MediaServer mediaServer, Uri uri) {
super(context);
mMediaServer = mediaServer;
mUri = uri;
}
@Override
public Drawable loadInBackground() {
Resources res = getContext().getResources();
if (mUri != null && "http".equals(mUri.getScheme())) {
try {
return new BitmapDrawable(res, mMediaServer.image(mUri).read());
} catch (IOException e) {
return res.getDrawable(R.drawable.albumart_mp_unknown);
}
} else {
return res.getDrawable(R.drawable.albumart_mp_unknown);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/loader/ImageLoader.java | Java | gpl3 | 1,157 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.loader;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
abstract class ModelLoader<D> extends AsyncTaskLoader<D> {
private D mModel;
protected ModelLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mModel != null) {
deliverResult(mModel);
} else {
forceLoad();
}
}
@Override
public void deliverResult(D model) {
if (!isReset()) {
super.deliverResult(model);
mModel = model;
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
cancelLoad();
mModel = null;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/loader/ModelLoader.java | Java | gpl3 | 1,542 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.loader;
import org.peterbaldwin.vlcremote.model.Playlist;
import org.peterbaldwin.vlcremote.model.Remote;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.Context;
public class PlaylistLoader extends ModelLoader<Remote<Playlist>> {
private final MediaServer mMediaServer;
private final String mSearch;
public PlaylistLoader(Context context, MediaServer mediaServer, String search) {
super(context);
mMediaServer = mediaServer;
mSearch = search;
}
@Override
public Remote<Playlist> loadInBackground() {
return mMediaServer.playlist(mSearch).load();
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/loader/PlaylistLoader.java | Java | gpl3 | 1,390 |
package org.peterbaldwin.vlcremote.loader;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.io.IOException;
public class ArtLoader extends ModelLoader<Drawable> {
private final MediaServer mMediaServer;
public ArtLoader(Context context, MediaServer mediaServer) {
super(context);
mMediaServer = mediaServer;
}
@Override
public Drawable loadInBackground() {
Resources res = getContext().getResources();
try {
return new BitmapDrawable(res, mMediaServer.art().read());
} catch (IOException e) {
return res.getDrawable(R.drawable.albumart_mp_unknown);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/loader/ArtLoader.java | Java | gpl3 | 887 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* 1. Changed package name
* 2. Don't send change notifications unless something actually changed.
*/
package org.peterbaldwin.vlcremote.preference;
import org.peterbaldwin.client.android.vlcremote.R;
import android.content.Context;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import android.view.View;
public class ProgressCategory extends PreferenceCategory {
private boolean mProgress = false;
public ProgressCategory(Context context, AttributeSet attrs) {
super(context, attrs);
setLayoutResource(R.layout.preference_progress_category);
}
@Override
public void onBindView(View view) {
super.onBindView(view);
View textView = view.findViewById(R.id.scanning_text);
View progressBar = view.findViewById(R.id.scanning_progress);
int visibility = mProgress ? View.VISIBLE : View.INVISIBLE;
textView.setVisibility(visibility);
progressBar.setVisibility(visibility);
}
/**
* Turn on/off the progress indicator and text on the right.
*
* @param progressOn whether or not the progress should be displayed
*/
public void setProgress(boolean progressOn) {
if (mProgress != progressOn) {
mProgress = progressOn;
notifyChanged();
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/preference/ProgressCategory.java | Java | gpl3 | 1,974 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.sweep;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
final class Worker extends Thread {
public interface Manager {
/**
* Retrieves and removes the next IP address, or returns {@code null} if
* there are not more addresses to scan.
*/
byte[] pollIpAddress();
}
public interface Callback {
/**
* Indicates that an address is reachable.
*/
void onReachable(InetAddress address, int port, String hostname, int responseCode);
/**
* Indicates that an address is unreachable.
*/
void onUnreachable(byte[] ipAddress, int port, IOException e);
}
private final int mPort;
private final String mPath;
private Manager mManager;
private Callback mCallback;
public Worker(int port, String path) {
mPort = port;
mPath = path;
}
public void setManager(Manager manager) {
mManager = manager;
}
public void setCallback(Callback callback) {
mCallback = callback;
}
private static URL createUrl(String scheme, String host, int port, String path) {
try {
return new URL("http", host, port, path);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public void run() {
// Note: InetAddress#isReachable(int) always returns false for Windows
// hosts because applications do not have permission to perform ICMP
// echo requests.
for (;;) {
byte[] ipAddress = mManager.pollIpAddress();
if (ipAddress == null) {
break;
}
try {
InetAddress address = InetAddress.getByAddress(ipAddress);
String hostAddress = address.getHostAddress();
URL url = createUrl("http", hostAddress, mPort, mPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(1000);
try {
int responseCode = connection.getResponseCode();
String hostname = address.getHostName();
mCallback.onReachable(address, mPort, hostname, responseCode);
} finally {
connection.disconnect();
}
} catch (IOException e) {
mCallback.onUnreachable(ipAddress, mPort, e);
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/sweep/Worker.java | Java | gpl3 | 3,369 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.sweep;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public final class PortSweeper {
public interface Callback {
void onHostFound(String hostname, int responseCode);
void onProgress(int progress, int max);
}
private static final String TAG = "Scanner";
private static final int HANDLE_SCAN = 1;
private static final int HANDLE_START = 1;
private static final int HANDLE_REACHABLE = 2;
private static final int HANDLE_UNREACHABLE = 3;
private static final int HANDLE_COMPLETE = 4;
private final Queue<byte[]> mAddressQueue;
/**
* Queue for scan requests.
*/
private final Handler mScanHandler;
/**
* Processes scan requests.
* <p>
* No real work is done on this thread; it just waits for the workers to
* finish using {@link Thread#join()}.
*/
private final HandlerThread mScanThread;
/**
* Dispatches callbacks on the main thread.
*/
private final Handler mCallbackHandler;
/**
* Provides work for worker threads.
*/
private final Worker.Manager mWorkerManager;
/**
* Handles results from worker threads.
*/
private final Worker.Callback mWorkerCallback;
/**
* The port to scan.
*/
private final int mPort;
/**
* The HTTP path to scan.
*/
private final String mPath;
/**
* The number of workers to allocate.
*/
private final int mWorkerCount;
/**
* Callback for port sweep progress and results.
*/
private Callback mCallback;
/**
* The current progress.
*/
private int mProgress;
/**
* The maximum progress.
*/
private int mMax;
/**
* Indicates that the sweep is complete.
*/
private boolean mComplete;
public PortSweeper(int port, String file, int threadCount, Callback callback, Looper looper) {
mPort = port;
mPath = file;
mWorkerCount = threadCount;
mCallback = callback;
mAddressQueue = new ConcurrentLinkedQueue<byte[]>();
mWorkerManager = new MyWorkerManager();
mWorkerCallback = new MyWorkerCallback();
mScanThread = new HandlerThread("Scanner", Process.THREAD_PRIORITY_BACKGROUND);
mScanThread.start();
Handler.Callback callbackHandlerCallback = new MyCallbackHandlerCallback();
mCallbackHandler = new Handler(looper, callbackHandlerCallback);
Handler.Callback scanHandlerCallback = new MyScanHandlerCallback();
mScanHandler = new Handler(mScanThread.getLooper(), scanHandlerCallback);
}
public void setCallback(Callback callback) {
mCallback = callback;
if (mCallback != null) {
// Replay progress for new callback receiver
mCallback.onProgress(0, mMax);
mCallback.onProgress(mProgress, mMax);
}
}
public void sweep(byte[] ipAddress) {
abort();
// Schedule a new sweep. The new sweep will not start until all previous
// sweeps have been fully aborted.
mScanHandler.obtainMessage(HANDLE_SCAN, ipAddress).sendToTarget();
}
public void abort() {
// Clear pending jobs
mScanHandler.removeMessages(HANDLE_SCAN);
// Abort the job in progress
mAddressQueue.clear();
}
public void destory() {
abort();
Looper looper = mScanThread.getLooper();
looper.quit();
}
/**
* Scans all local IP addresses using a pool of worker threads and waits for
* the all of the workers to finish scanning before returning.
*/
private void handleScan(byte[] interfaceAddress) {
Worker[] workers = new Worker[mWorkerCount];
for (int i = 0; i < workers.length; i++) {
Worker worker = workers[i] = new Worker(mPort, mPath);
worker.setPriority(Thread.MIN_PRIORITY);
worker.setManager(mWorkerManager);
worker.setCallback(mWorkerCallback);
}
int count = 0;
// Scan outwards from the interface IP address for best results
// with DHCP servers that allocate addresses sequentially.
byte start = interfaceAddress[interfaceAddress.length - 1];
for (int delta = 1; delta < 128; delta++) {
for (int sign = -1; sign <= 1; sign += 2) {
int b = (256 + start + sign * delta) % 256;
if (b != 0) {
byte[] ipAddress = interfaceAddress.clone();
ipAddress[ipAddress.length - 1] = (byte) b;
mAddressQueue.add(ipAddress);
count += 1;
} else {
// Skip broadcast address
}
}
}
mCallbackHandler.obtainMessage(HANDLE_START, 0, count).sendToTarget();
for (int i = 0; i < workers.length; i++) {
Worker worker = workers[i];
worker.start();
}
try {
for (int i = 0; i < workers.length; i++) {
Worker worker = workers[i];
worker.join();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
mCallbackHandler.sendEmptyMessage(HANDLE_COMPLETE);
}
}
private class MyScanHandlerCallback implements Handler.Callback {
/** {@inheritDoc} */
public boolean handleMessage(Message msg) {
switch (msg.what) {
case HANDLE_SCAN:
byte[] interfaceAddress = (byte[]) msg.obj;
handleScan(interfaceAddress);
return true;
default:
return false;
}
}
}
private class MyWorkerManager implements Worker.Manager {
/** {@inheritDoc} */
public byte[] pollIpAddress() {
return mAddressQueue.poll();
}
}
private class MyWorkerCallback implements Worker.Callback {
/** {@inheritDoc} */
public void onReachable(InetAddress address, int port, String hostname, int responseCode) {
Message m = mCallbackHandler.obtainMessage(HANDLE_REACHABLE);
m.obj = hostname;
m.arg1 = responseCode;
m.sendToTarget();
}
/** {@inheritDoc} */
public void onUnreachable(byte[] ipAddress, int port, IOException e) {
Message m = mCallbackHandler.obtainMessage(HANDLE_UNREACHABLE);
m.obj = e;
m.sendToTarget();
}
}
private class MyCallbackHandlerCallback implements Handler.Callback {
/** {@inheritDoc} */
public boolean handleMessage(Message msg) {
if (mComplete && msg.what != HANDLE_START) {
Log.w(TAG, "unexpected callback");
return true;
}
try {
switch (msg.what) {
case HANDLE_START:
mComplete = false;
mProgress = msg.arg1;
mMax = msg.arg2;
return true;
case HANDLE_REACHABLE:
String hostname = (String) msg.obj;
int responseCode = msg.arg1;
Log.d(TAG, "found: " + hostname);
mCallback.onHostFound(hostname, responseCode);
mProgress++;
return true;
case HANDLE_UNREACHABLE:
IOException e = (IOException) msg.obj;
Log.d(TAG, "unreachable", e);
mProgress++;
return true;
case HANDLE_COMPLETE:
mComplete = true;
mProgress = mMax;
return true;
default:
return false;
}
} finally {
mProgress = Math.min(mProgress, mMax);
mCallback.onProgress(mProgress, mMax);
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/sweep/PortSweeper.java | Java | gpl3 | 9,177 |
package org.peterbaldwin.vlcremote.widget;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.model.PlaylistItem;
import org.peterbaldwin.vlcremote.model.Track;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public final class PlaylistAdapter extends BaseAdapter {
private List<PlaylistItem> mItems;
/** {@inheritDoc} */
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.playlist_list_item, parent, false);
}
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
View icon = view.findViewById(android.R.id.icon);
PlaylistItem item = getItem(position);
if (item instanceof Track) {
Track track = (Track) item;
if (!TextUtils.isEmpty(track.getTitle())) {
text1.setText(track.getTitle());
text2.setText(track.getArtist());
} else {
text1.setText(item.getName());
text2.setText("");
}
icon.setVisibility(track.isCurrent() ? View.VISIBLE : View.GONE);
} else {
text1.setText(item.getName());
text2.setText("");
icon.setVisibility(View.GONE);
}
return view;
}
/** {@inheritDoc} */
public int getCount() {
return mItems != null ? mItems.size() : 0;
}
/** {@inheritDoc} */
public PlaylistItem getItem(int position) {
return mItems.get(position);
}
@Override
public boolean hasStableIds() {
return true;
}
/** {@inheritDoc} */
public long getItemId(int position) {
if (position < getCount()) {
PlaylistItem item = getItem(position);
return item.getId();
} else {
return AdapterView.INVALID_ROW_ID;
}
}
public void setItems(List<PlaylistItem> items) {
mItems = items;
if (mItems != null) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
public List<PlaylistItem> getItems() {
int count = getCount();
List<PlaylistItem> items = new ArrayList<PlaylistItem>(count);
for (int position = 0; position < count; position++) {
PlaylistItem item = getItem(position);
items.add(item);
}
return items;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/widget/PlaylistAdapter.java | Java | gpl3 | 2,955 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.widget;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.model.Directory;
import org.peterbaldwin.vlcremote.model.File;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import java.util.ArrayList;
import java.util.List;
public class DirectoryAdapter extends ArrayAdapter<File> implements SectionIndexer {
private Object[] mSections = new Object[0];
private Integer[] mPositionForSection = new Integer[0];
private Integer[] mSectionForPosition = new Integer[0];
public DirectoryAdapter(Context context) {
super(context, R.layout.file_list_item, android.R.id.text1);
}
/** {@inheritDoc} */
public int getPositionForSection(int section) {
if (section < 0) {
section = 0;
}
if (section >= mPositionForSection.length) {
section = mPositionForSection.length - 1;
}
return mPositionForSection[section];
}
/** {@inheritDoc} */
public int getSectionForPosition(int position) {
if (position < 0) {
position = 0;
}
if (position >= mSectionForPosition.length) {
position = mSectionForPosition.length - 1;
}
return mSectionForPosition[position];
}
/** {@inheritDoc} */
public Object[] getSections() {
return mSections;
}
@Override
public void add(File object) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
super.clear();
mSections = new Object[0];
mPositionForSection = new Integer[0];
mSectionForPosition = new Integer[0];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
File file = getItem(position);
ImageView icon = (ImageView) v.findViewById(android.R.id.icon);
if (file.isDirectory()) {
String name = file.getName();
if ("..".equals(name)) {
icon.setImageResource(R.drawable.ic_up);
} else {
icon.setImageResource(R.drawable.ic_directory);
}
} else {
String contentType = file.getMimeType();
if (contentType != null) {
contentType = contentType.toLowerCase();
if (contentType.startsWith("audio/")) {
icon.setImageResource(R.drawable.ic_mime_audio);
} else if (contentType.startsWith("image/")) {
icon.setImageResource(R.drawable.ic_mime_image);
} else if (contentType.startsWith("video/")) {
icon.setImageResource(R.drawable.ic_mime_video);
} else {
icon.setImageResource(R.drawable.ic_file);
}
} else {
icon.setImageResource(R.drawable.ic_file);
}
}
return v;
}
private String getSection(File file) {
String name = file.getName();
if (name.equals("..")) {
Context context = getContext();
return context.getString(R.string.section_parent);
} else if (name.length() > 0) {
char c = name.charAt(0);
c = Character.toUpperCase(c);
return String.valueOf(c);
} else {
// This shouldn't happen
return "";
}
}
public void setDirectory(Directory items) {
super.clear();
if (items != null) {
int count = items.size();
// Space for every letter and digit, plus a couple symbols
int capacity = 48;
Integer lastSection = null;
List<String> sections = new ArrayList<String>(capacity);
List<Integer> positionForSection = new ArrayList<Integer>(capacity);
List<Integer> sectionForPosition = new ArrayList<Integer>(count);
for (int position = 0; position < count; position++) {
File file = items.get(position);
String section = getSection(file);
if (!sections.contains(section)) {
lastSection = Integer.valueOf(sections.size());
sections.add(section);
positionForSection.add(Integer.valueOf(position));
}
sectionForPosition.add(lastSection);
super.add(file);
}
mSections = sections.toArray();
mPositionForSection = toArray(positionForSection);
mSectionForPosition = toArray(sectionForPosition);
} else {
mSections = new Object[0];
mPositionForSection = new Integer[0];
mSectionForPosition = new Integer[0];
}
}
private static Integer[] toArray(List<Integer> list) {
return list.toArray(new Integer[list.size()]);
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/widget/DirectoryAdapter.java | Java | gpl3 | 5,842 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.widget;
import org.peterbaldwin.client.android.vlcremote.R;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
/**
* Displays the current volume level as a {@link Toast}.
*/
public class VolumePanel {
private final Toast mToast;
private final View mView;
private final ImageView mIcon;
private final ProgressBar mProgress;
public VolumePanel(Context context) {
mToast = new Toast(context);
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.volume_adjust, null);
mIcon = (ImageView) mView.findViewById(android.R.id.icon);
mProgress = (ProgressBar) mView.findViewById(android.R.id.progress);
}
public void onVolumeChanged(int level) {
mIcon.setImageResource(level == 0 ? R.drawable.ic_volume_off_small
: R.drawable.ic_volume_small);
mProgress.setProgress(level);
mToast.setView(mView);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setGravity(Gravity.TOP, 0, 0);
mToast.show();
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/widget/VolumePanel.java | Java | gpl3 | 1,978 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.AdapterView;
public final class HotkeyDialog extends DialogFragment implements AdapterView.OnItemClickListener {
private String[] mCodes;
private HotkeyListener mHotkeyListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCodes = getResources().getStringArray(R.array.hotkey_codes);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setItems(R.array.hotkey_labels, null);
builder.setNeutralButton(R.string.close, null);
AlertDialog dialog = builder.create();
// Handle ListView item clicks directly so that dialog is not dismissed
dialog.getListView().setOnItemClickListener(this);
return dialog;
}
public void setHotkeyListener(HotkeyListener hotkeyListener) {
mHotkeyListener = hotkeyListener;
}
/** {@inheritDoc} */
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mHotkeyListener != null) {
mHotkeyListener.onHotkey(mCodes[position]);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/HotkeyDialog.java | Java | gpl3 | 2,266 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.loader.PlaylistLoader;
import org.peterbaldwin.vlcremote.model.Playlist;
import org.peterbaldwin.vlcremote.model.PlaylistItem;
import org.peterbaldwin.vlcremote.model.Remote;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.model.Track;
import org.peterbaldwin.vlcremote.net.MediaServer;
import org.peterbaldwin.vlcremote.widget.PlaylistAdapter;
import android.app.Activity;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PlaylistFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Remote<Playlist>> {
private static final int LOADER_PLAYLIST = 1;
private Context mContext;
private MediaServer mMediaServer;
private TextView mEmptyView;
private PlaylistAdapter mAdapter;
private BroadcastReceiver mStatusReceiver;
private String mCurrent;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playlist, container, false);
mAdapter = new PlaylistAdapter();
setListAdapter(mAdapter);
mEmptyView = (TextView) view.findViewById(android.R.id.empty);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
if (mMediaServer != null) {
getLoaderManager().initLoader(LOADER_PLAYLIST, null, this);
}
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.playlist_options, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
reload();
return true;
case R.id.menu_clear_playlist:
mMediaServer.status().command.playback.empty();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (menuInfo instanceof AdapterContextMenuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
PlaylistItem item = mAdapter.getItem(info.position);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.playlist_context, menu);
MenuItem searchItem = menu.findItem(R.id.playlist_context_search);
searchItem.setVisible(isSearchable(item));
}
}
private boolean isSearchable(PlaylistItem item) {
if (item instanceof Track) {
Track track = (Track) item;
boolean hasTitle = !TextUtils.isEmpty(track.getTitle());
boolean hasArtist = !TextUtils.isEmpty(track.getArtist());
return hasTitle && hasArtist;
} else {
return false;
}
}
@Override
public boolean onContextItemSelected(MenuItem menuItem) {
ContextMenuInfo menuInfo = menuItem.getMenuInfo();
if (menuInfo instanceof AdapterContextMenuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position < mAdapter.getCount()) {
PlaylistItem item = mAdapter.getItem(info.position);
switch (menuItem.getItemId()) {
case R.id.playlist_context_play:
selectItem(item);
return true;
case R.id.playlist_context_dequeue:
removeItem(item);
return true;
case R.id.playlist_context_search:
searchForItem(item);
return true;
}
}
}
return super.onContextItemSelected(menuItem);
}
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
reload();
}
private void removeItem(PlaylistItem item) {
int id = item.getId();
// TODO: Register observer and notify observers when playlist item is
// deleted
mMediaServer.status().command.playback.delete(id);
}
private void searchForItem(PlaylistItem item) {
if (item instanceof Track) {
Track track = (Track) item;
String title = track.getTitle();
String artist = track.getArtist();
String query = artist + " " + title;
Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
intent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, title);
intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
intent.putExtra(SearchManager.QUERY, query);
String chooserTitle = getString(R.string.mediasearch, title);
startActivity(Intent.createChooser(intent, chooserTitle));
}
}
private void showError(CharSequence message) {
Context context = getActivity();
Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
toast.show();
}
private void selectItem(PlaylistItem item) {
mMediaServer.status().command.playback.play(item.getId());
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
PlaylistItem item = (PlaylistItem) l.getItemAtPosition(position);
selectItem(item);
}
public void selectCurrentTrack() {
final int count = mAdapter.getCount();
for (int position = 0; position < count; position++) {
PlaylistItem item = mAdapter.getItem(position);
if (item instanceof Track) {
Track track = (Track) item;
if (track.isCurrent()) {
// Scroll to current track
ListView listView = getListView();
listView.setSelection(position);
break;
}
}
}
}
@Override
public void setEmptyText(CharSequence text) {
mEmptyView.setText(text);
}
/** {@inheritDoc} */
public Loader<Remote<Playlist>> onCreateLoader(int id, Bundle args) {
setEmptyText(getText(R.string.loading));
String search = "";
return new PlaylistLoader(mContext, mMediaServer, search);
}
/** {@inheritDoc} */
public void onLoadFinished(Loader<Remote<Playlist>> loader, Remote<Playlist> remote) {
boolean wasEmpty = mAdapter.isEmpty();
boolean hasError = (remote.error != null);
mAdapter.setItems(remote.data);
if (hasError) {
setEmptyText(getText(R.string.connection_error));
showError(String.valueOf(remote.error));
} else {
setEmptyText(getText(R.string.emptyplaylist));
}
if (wasEmpty) {
selectCurrentTrack();
}
}
/** {@inheritDoc} */
public void onLoaderReset(Loader<Remote<Playlist>> loader) {
mAdapter.setItems(null);
}
void onStatusChanged(Status status) {
String title = status.getTrack().getTitle();
if (!TextUtils.equals(title, mCurrent)) {
// Reload the playlist and scroll to the new current track
mCurrent = title;
reload();
}
}
public void reload() {
if (mMediaServer != null) {
getLoaderManager().restartLoader(LOADER_PLAYLIST, null, this);
}
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onStatusChanged(status);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/PlaylistFragment.java | Java | gpl3 | 10,555 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
public class NavigationFragment extends Fragment implements View.OnTouchListener,
GestureDetector.OnGestureListener {
private MediaServer mMediaServer;
private GestureDetector mGestureDetector;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.navigation_fragment, root, false);
Context context = view.getContext();
GestureDetector.OnGestureListener listener = this;
mGestureDetector = new GestureDetector(context, listener);
view.findViewById(R.id.overlay).setOnTouchListener(this);
return view;
}
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
}
/** {@inheritDoc} */
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
/** {@inheritDoc} */
public boolean onSingleTapUp(MotionEvent e) {
mMediaServer.status().command.key("nav-activate");
vibrate();
return true;
}
/** {@inheritDoc} */
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(velocityX) > Math.abs(velocityY)) {
if (velocityX > 0) {
mMediaServer.status().command.key("nav-right");
vibrate();
return true;
} else if (velocityX < 0) {
mMediaServer.status().command.key("nav-left");
vibrate();
return true;
}
} else if (Math.abs(velocityY) > Math.abs(velocityX)) {
if (velocityY > 0) {
mMediaServer.status().command.key("nav-down");
vibrate();
return true;
} else if (velocityY < 0) {
mMediaServer.status().command.key("nav-up");
vibrate();
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
private <T> T getSystemService(String name) {
Context context = getActivity();
return (T) context.getSystemService(Context.VIBRATOR_SERVICE);
}
private void vibrate() {
Vibrator v = getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate(100);
}
}
/** {@inheritDoc} */
public boolean onDown(MotionEvent e) {
return false;
}
/** {@inheritDoc} */
public void onShowPress(MotionEvent e) {
}
/** {@inheritDoc} */
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
/** {@inheritDoc} */
public void onLongPress(MotionEvent e) {
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/NavigationFragment.java | Java | gpl3 | 3,943 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public final class ButtonsFragment extends Fragment implements View.OnClickListener {
private static final String DIALOG_HOTKEYS = "hotkeys";
private MediaServer mMediaServer;
private BroadcastReceiver mStatusReceiver;
private ImageButton mButtonShuffle;
private ImageButton mButtonRepeat;
private boolean mRandom;
private boolean mRepeat;
private boolean mLoop;
private View mHotkeysButton;
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
return inflater.inflate(R.layout.frame_layout, parent, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
mButtonShuffle = (ImageButton) view.findViewById(R.id.playlist_button_shuffle);
mButtonRepeat = (ImageButton) view.findViewById(R.id.playlist_button_repeat);
mHotkeysButton = view.findViewById(R.id.button_hotkeys);
mButtonShuffle.setOnClickListener(this);
mButtonRepeat.setOnClickListener(this);
mHotkeysButton.setOnClickListener(this);
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
/** {@inheritDoc} */
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_hotkeys:
DialogFragment dialog = new HotkeyDialog();
dialog.show(getFragmentManager(), DIALOG_HOTKEYS);
break;
case R.id.playlist_button_shuffle:
mMediaServer.status().command.playback.random();
mRandom = !mRandom;
updateButtons();
break;
case R.id.playlist_button_repeat:
// Order: Normal -> Repeat -> Loop
if (mRepeat) {
// Switch to loop
if (mLoop) {
// Turn-off repeat
mMediaServer.status().command.playback.repeat();
mRepeat = false;
} else {
// Manual transition:
// This needs to be a two step process
// because the commands will conflict
// if they are issued too close together.
// The transition is optimized when
// switching from normal mode to repeat
// to avoid the two step process when possible.
// The UI is not updated until the
// server responds to hide the
// intermediate state.
// Turn-on loop then turn-off repeat shortly after.
mMediaServer.status().command.playback.loop().repeat();
}
} else if (mLoop) {
// Switch to normal
// Turn-off loop
mMediaServer.status().command.playback.loop();
mLoop = false;
} else {
// Turn-on repeat and turn-on loop to make the transition
// from repeat to loop one step instead of two steps.
// Loop has no effect when repeat is on.
mMediaServer.status().command.playback.repeat().loop();
mRepeat = true;
mLoop = true;
}
updateButtons();
break;
}
}
private int getShuffleResId() {
if (mRandom) {
return R.drawable.ic_mp_shuffle_on_btn;
} else {
return R.drawable.ic_mp_shuffle_off_btn;
}
}
private int getRepeatResId() {
if (mRepeat) {
return R.drawable.ic_mp_repeat_once_btn;
} else if (mLoop) {
return R.drawable.ic_mp_repeat_all_btn;
} else {
return R.drawable.ic_mp_repeat_off_btn;
}
}
private void updateButtons() {
mButtonShuffle.setImageResource(getShuffleResId());
mButtonRepeat.setImageResource(getRepeatResId());
}
void onStatusChanged(Status status) {
mRandom = status.isRandom();
mLoop = status.isLoop();
mRepeat = status.isRepeat();
updateButtons();
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onStatusChanged(status);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/ButtonsFragment.java | Java | gpl3 | 6,514 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.net.MediaServer;
import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest;
import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest.CommandInterface;
import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest.CommandInterface.PlaybackInterface;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
/**
* Controls playback and displays progress.
*/
public class PlaybackFragment extends Fragment implements View.OnClickListener,
OnSeekBarChangeListener {
private BroadcastReceiver mStatusReceiver;
private ImageButton mButtonPlaylistPause;
private ImageButton mButtonPlaylistStop;
private ImageButton mButtonPlaylistSkipForward;
private ImageButton mButtonPlaylistSkipBackward;
private ImageButton mButtonPlaylistSeekForward;
private ImageButton mButtonPlaylistSeekBackward;
private SeekBar mSeekPosition;
private TextView mTextTime;
private TextView mTextLength;
private MediaServer mMediaServer;
public void setMediaServer(MediaServer server) {
mMediaServer = server;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.audio_player_common, container, false);
mButtonPlaylistPause = setupImageButton(v, R.id.button_pause);
mButtonPlaylistStop = setupImageButton(v, R.id.button_stop);
mButtonPlaylistSkipForward = setupImageButton(v, R.id.button_skip_forward);
mButtonPlaylistSkipBackward = setupImageButton(v, R.id.button_skip_backward);
mButtonPlaylistSeekForward = setupImageButton(v, R.id.button_seek_forward);
mButtonPlaylistSeekBackward = setupImageButton(v, R.id.button_seek_backward);
mSeekPosition = (SeekBar) v.findViewById(R.id.seek_progress);
mSeekPosition.setMax(100);
mSeekPosition.setOnSeekBarChangeListener(this);
mTextTime = (TextView) v.findViewById(R.id.text_time);
mTextLength = (TextView) v.findViewById(R.id.text_length);
return v;
}
private ImageButton setupImageButton(View v, int viewId) {
ImageButton button = (ImageButton) v.findViewById(viewId);
if (button != null) {
button.setOnClickListener(this);
}
return button;
}
private StatusRequest status() {
return mMediaServer.status();
}
private CommandInterface command() {
return status().command;
}
private PlaybackInterface playlist() {
return command().playback;
}
/** {@inheritDoc} */
public void onClick(View v) {
if (v == mButtonPlaylistPause) {
playlist().pause();
} else if (v == mButtonPlaylistStop) {
playlist().stop();
} else if (v == mButtonPlaylistSkipBackward) {
playlist().previous();
} else if (v == mButtonPlaylistSkipForward) {
playlist().next();
} else if (v == mButtonPlaylistSeekBackward) {
command().seek(Uri.encode("-10"));
} else if (v == mButtonPlaylistSeekForward) {
command().seek(Uri.encode("+10"));
}
}
/** {@inheritDoc} */
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar == mSeekPosition) {
if (fromUser) {
seekPosition();
}
}
}
/** {@inheritDoc} */
public void onStartTrackingTouch(SeekBar seekBar) {
}
/** {@inheritDoc} */
public void onStopTrackingTouch(SeekBar seekBar) {
if (seekBar == mSeekPosition) {
seekPosition();
}
}
private void seekPosition() {
int position = mSeekPosition.getProgress();
command().seek(String.valueOf(position));
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
void onStatusChanged(Status status) {
int resId = status.isPlaying() ? R.drawable.ic_media_playback_pause
: R.drawable.ic_media_playback_start;
mButtonPlaylistPause.setImageResource(resId);
int time = status.getTime();
int length = status.getLength();
mSeekPosition.setMax(length);
mSeekPosition.setProgress(time);
// Call setKeyProgressIncrement after calling setMax because the
// implementation of setMax will automatically adjust the increment.
mSeekPosition.setKeyProgressIncrement(3);
String formattedTime = formatTime(time);
mTextTime.setText(formattedTime);
String formattedLength = formatTime(length);
mTextLength.setText(formattedLength);
}
private static void doubleDigit(StringBuilder builder, long value) {
builder.insert(0, value);
if (value < 10) {
builder.insert(0, '0');
}
}
/**
* Formats a time.
*
* @param time the time (in seconds)
* @return the formatted time.
*/
private static String formatTime(int time) {
long seconds = time % 60;
time /= 60;
long minutes = time % 60;
time /= 60;
long hours = time;
StringBuilder builder = new StringBuilder(8);
doubleDigit(builder, seconds);
builder.insert(0, ':');
if (hours == 0) {
builder.insert(0, minutes);
} else {
doubleDigit(builder, minutes);
builder.insert(0, ':');
builder.insert(0, hours);
}
return builder.toString();
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onStatusChanged(status);
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/PlaybackFragment.java | Java | gpl3 | 7,693 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
/**
* Polls the server for status updates.
*/
public class StatusFragment extends Fragment implements Handler.Callback {
private static final int TIMER = 1;
private static final long INTERVAL = DateUtils.SECOND_IN_MILLIS;
private Handler mHandler;
private MediaServer mMediaServer;
public void setMediaServer(MediaServer server) {
mMediaServer = server;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler(this);
}
@Override
public void onResume() {
super.onResume();
startTimer();
}
@Override
public void onPause() {
stopTimer();
super.onPause();
}
private void startTimer() {
mHandler.sendEmptyMessage(TIMER);
}
private void stopTimer() {
mHandler.removeMessages(TIMER);
}
/** {@inheritDoc} */
public boolean handleMessage(Message msg) {
switch (msg.what) {
case TIMER:
onTimerEvent();
return true;
default:
return false;
}
}
private void onTimerEvent() {
if (mMediaServer != null) {
mMediaServer.status().programmatic().get();
}
// Schedule the next timer event
mHandler.sendEmptyMessageDelayed(TIMER, INTERVAL);
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/StatusFragment.java | Java | gpl3 | 2,371 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.loader.ImageLoader;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.model.Track;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ArtFragment extends Fragment implements LoaderCallbacks<Drawable> {
private static final int LOADER_IMAGE = 1;
private BroadcastReceiver mStatusReceiver;
private MediaServer mMediaServer;
private ImageView mImageView;
private String mArtUrl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.art_fragment, root, false);
mImageView = (ImageView) view.findViewById(android.R.id.icon);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mMediaServer != null) {
getLoaderManager().initLoader(LOADER_IMAGE, Bundle.EMPTY, this);
}
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
/** {@inheritDoc} */
public Loader<Drawable> onCreateLoader(int id, Bundle args) {
Context context = getActivity();
Uri uri = mArtUrl != null ? Uri.parse(mArtUrl) : null;
if (uri != null) {
uri = resizeImage(uri);
}
return new ImageLoader(context, mMediaServer, uri);
}
/** {@inheritDoc} */
public void onLoadFinished(Loader<Drawable> loader, Drawable data) {
mImageView.setImageDrawable(data);
}
/** {@inheritDoc} */
public void onLoaderReset(Loader<Drawable> loader) {
mImageView.setImageResource(R.drawable.albumart_mp_unknown);
}
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
if (mMediaServer != null) {
getLoaderManager().restartLoader(LOADER_IMAGE, Bundle.EMPTY, this);
}
}
private void onStatusChanged(Status status) {
Track track = status.getTrack();
String artUrl = track.getArtUrl();
if (mArtUrl == null || !mArtUrl.equals(artUrl)) {
mArtUrl = artUrl;
getLoaderManager().restartLoader(LOADER_IMAGE, null, this);
}
}
private static Uri resizeImage(Uri uri) {
if (isJamendoImage(uri)) {
return resizeJamendoImage(uri);
} else {
return uri;
}
}
private static boolean isJamendoImage(Uri uri) {
return "imgjam.com".equals(uri.getAuthority()) && uri.getPathSegments().size() != 0
&& uri.getLastPathSegment().matches("1\\.\\d+\\.jpg");
}
private static Uri resizeJamendoImage(Uri uri) {
String path = uri.getPath();
path = path.replace("/" + uri.getLastPathSegment(), "/1.400.jpg");
return uri.buildUpon().path(path).build();
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (this != mStatusReceiver) {
// TODO: Determine why this receiver is not unregistered
return;
}
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onStatusChanged(status);
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/ArtFragment.java | Java | gpl3 | 5,219 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.loader.DirectoryLoader;
import org.peterbaldwin.vlcremote.model.Directory;
import org.peterbaldwin.vlcremote.model.File;
import org.peterbaldwin.vlcremote.model.Preferences;
import org.peterbaldwin.vlcremote.model.Remote;
import org.peterbaldwin.vlcremote.net.MediaServer;
import org.peterbaldwin.vlcremote.widget.DirectoryAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BrowseFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Remote<Directory>> {
private interface Data {
int DIRECTORY = 1;
}
private interface State {
String DIRECTORY = "vlc:directory";
}
private DirectoryAdapter mAdapter;
private MediaServer mMediaServer;
private String mDirectory = "~";
private Preferences mPreferences;
private TextView mTitle;
private TextView mEmpty;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Context context = getActivity();
mPreferences = Preferences.get(context);
if (savedInstanceState == null) {
mDirectory = mPreferences.getBrowseDirectory();
} else {
mDirectory = savedInstanceState.getString(State.DIRECTORY);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.browse, root, false);
mTitle = (TextView) view.findViewById(android.R.id.title);
mEmpty = (TextView) view.findViewById(android.R.id.empty);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(State.DIRECTORY, mDirectory);
}
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
}
@Override
public void setEmptyText(CharSequence text) {
mEmpty.setText(text);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Context context = getActivity();
mAdapter = new DirectoryAdapter(context);
setListAdapter(mAdapter);
registerForContextMenu(getListView());
if (mMediaServer != null) {
getLoaderManager().initLoader(Data.DIRECTORY, Bundle.EMPTY, this);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
File file = mAdapter.getItem(position);
if (file.isDirectory()) {
openDirectory(file);
} else {
mMediaServer.status().command.input.play(file.getMrl(), file.getOptions());
}
}
private void openDirectory(File file) {
openDirectory(file.getPath());
}
public void openDirectory(String path) {
mDirectory = path;
mAdapter.clear();
getLoaderManager().restartLoader(Data.DIRECTORY, null, this);
}
private boolean isDirectory(ContextMenuInfo menuInfo) {
if (menuInfo instanceof AdapterContextMenuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position < mAdapter.getCount()) {
File file = mAdapter.getItem(info.position);
return file.isDirectory();
}
}
return false;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.browse_options, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
getLoaderManager().restartLoader(Data.DIRECTORY, Bundle.EMPTY, this);
return true;
case R.id.menu_parent:
openParentDirectory();
return true;
case R.id.menu_home:
mDirectory = mPreferences.getHomeDirectory();
getLoaderManager().restartLoader(Data.DIRECTORY, Bundle.EMPTY, this);
return true;
case R.id.menu_set_home:
mPreferences.setHomeDirectory(mDirectory);
showSetHomeToast();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openParentDirectory() {
for (int position = 0, n = mAdapter.getCount(); position < n; position++) {
File file = mAdapter.getItem(position);
if (file.isDirectory() && "..".equals(file.getName())) {
openDirectory(file);
return;
}
}
// Open the list of drives if there is no parent directory entry
openDirectory("");
}
private void showSetHomeToast() {
Context context = getActivity();
CharSequence message = getString(R.string.sethome, getTitle());
Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.browse_context, menu);
menu.findItem(R.id.browse_context_open).setVisible(isDirectory(menuInfo));
menu.findItem(R.id.browse_context_stream).setVisible(!isDirectory(menuInfo));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
ContextMenuInfo menuInfo = item.getMenuInfo();
if (menuInfo instanceof AdapterContextMenuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position < mAdapter.getCount()) {
File file = mAdapter.getItem(info.position);
switch (item.getItemId()) {
case R.id.browse_context_open:
openDirectory(file);
return true;
case R.id.browse_context_play:
mMediaServer.status().command.input.play(file.getMrl(), file.getOptions());
return true;
case R.id.browse_context_stream:
mMediaServer.status().command.input.play(file.getMrl(),
file.getStreamingOptions());
Intent intent = file.getIntentForStreaming(mMediaServer.getAuthority());
startActivity(intent);
return true;
case R.id.browse_context_enqueue:
mMediaServer.status().command.input.enqueue(file.getMrl());
return true;
}
}
}
return super.onContextItemSelected(item);
}
/** {@inheritDoc} */
public Loader<Remote<Directory>> onCreateLoader(int id, Bundle args) {
Context context = getActivity();
mPreferences.setBrowseDirectory(mDirectory);
setEmptyText(getText(R.string.loading));
return new DirectoryLoader(context, mMediaServer, mDirectory);
}
/** {@inheritDoc} */
public void onLoadFinished(Loader<Remote<Directory>> loader, Remote<Directory> result) {
mAdapter.setDirectory(result.data);
setEmptyText(getText(R.string.connection_error));
setTitle(result.data != null ? result.data.getPath() : null);
if (isEmptyDirectory(result.data)) {
handleEmptyDirectory();
}
}
private void setTitle(CharSequence title) {
mTitle.setText(title);
}
public CharSequence getTitle() {
return mTitle.getText();
}
private boolean isEmptyDirectory(Directory directory) {
if (directory != null) {
return directory.isEmpty();
} else {
// The directory could not be retrieved
return false;
}
}
private void handleEmptyDirectory() {
showEmptyDirectoryError();
openDirectory("~");
}
private void showEmptyDirectoryError() {
Context context = getActivity();
Toast toast = Toast.makeText(context, R.string.browse_empty, Toast.LENGTH_LONG);
toast.show();
}
/** {@inheritDoc} */
public void onLoaderReset(Loader<Remote<Directory>> loader) {
mAdapter.setDirectory(null);
}
// TODO: Automatically reload directory when connection is restored
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/BrowseFragment.java | Java | gpl3 | 10,186 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class ServicesDiscoveryFragment extends ListFragment {
private MediaServer mMediaServer;
private String[] mServiceValues;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mServiceValues = getResources().getStringArray(R.array.service_values);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
return inflater.inflate(R.layout.services_discovery_fragment, root, false);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String value = mServiceValues[position];
mMediaServer.status().command.playback.sd(value);
}
public void setMediaServer(MediaServer server) {
mMediaServer = server;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/ServicesDiscoveryFragment.java | Java | gpl3 | 1,895 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
public interface HotkeyListener {
void onHotkey(String key);
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/HotkeyListener.java | Java | gpl3 | 823 |
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Status;
import org.peterbaldwin.vlcremote.net.MediaServer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
public class VolumeFragment extends Fragment implements SeekBar.OnSeekBarChangeListener {
private static final int MAX_VOLUME = 1024;
private ImageView mIcon;
private SeekBar mSeekBar;
private MediaServer mMediaServer;
private BroadcastReceiver mStatusReceiver;
public void setMediaServer(MediaServer mediaServer) {
mMediaServer = mediaServer;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.volume_fragment, root, false);
mIcon = (ImageView) view.findViewById(android.R.id.icon);
mSeekBar = (SeekBar) view.findViewById(android.R.id.progress);
mSeekBar.setOnSeekBarChangeListener(this);
return view;
}
/** {@inheritDoc} */
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
setVolume(progress);
}
}
/** {@inheritDoc} */
public void onStartTrackingTouch(SeekBar seekBar) {
}
/** {@inheritDoc} */
public void onStopTrackingTouch(SeekBar seekBar) {
setVolume(seekBar.getProgress());
}
private void setVolume(int value) {
mMediaServer.status().command.volume(value);
}
void onVolumeChanged(int value) {
mIcon.setImageResource(getVolumeImage(value));
mSeekBar.setProgress(value);
}
private static int getVolumeImage(int volume) {
if (volume == 0) {
return R.drawable.ic_media_volume_muted;
} else if (volume < (MAX_VOLUME / 3)) {
return R.drawable.ic_media_volume_low;
} else if (volume < (2 * MAX_VOLUME / 3)) {
return R.drawable.ic_media_volume_medium;
} else {
return R.drawable.ic_media_volume_high;
}
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onVolumeChanged(status.getVolume());
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/VolumeFragment.java | Java | gpl3 | 3,346 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.fragment;
import org.peterbaldwin.client.android.vlcremote.R;
import org.peterbaldwin.vlcremote.intent.Intents;
import org.peterbaldwin.vlcremote.model.Status;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class InfoFragment extends Fragment {
private BroadcastReceiver mStatusReceiver;
private TextView mArtist;
private TextView mAlbum;
private TextView mTrack;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.info_fragment, root, false);
mArtist = (TextView) view.findViewById(R.id.artist);
mAlbum = (TextView) view.findViewById(R.id.album);
mTrack = (TextView) view.findViewById(R.id.track);
return view;
}
@Override
public void onResume() {
super.onResume();
mStatusReceiver = new StatusReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_STATUS);
getActivity().registerReceiver(mStatusReceiver, filter);
}
@Override
public void onPause() {
getActivity().unregisterReceiver(mStatusReceiver);
mStatusReceiver = null;
super.onPause();
}
void onStatusChanged(Status status) {
setText(mArtist, status.getTrack().getArtist());
setText(mAlbum, status.getTrack().getAlbum());
setText(mTrack, status.getTrack().getTitle());
}
private static void setText(TextView textView, String value) {
textView.setText(value);
}
private class StatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_STATUS.equals(action)) {
// TODO: Filter by authority
Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS);
onStatusChanged(status);
}
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/fragment/InfoFragment.java | Java | gpl3 | 3,053 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
/**
* Light-weight wrapper for data that is loaded from a remote server.
* <p>
* Holds the remote data, or an error if there was a problem receiving the data.
*/
public final class Remote<T> {
public final T data;
public final Throwable error;
private Remote(T data, Throwable error) {
this.data = data;
this.error = error;
}
public static <T> Remote<T> data(T data) {
return new Remote<T>(data, null);
}
public static <T> Remote<T> error(Throwable t) {
return new Remote<T>(null, t);
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Remote.java | Java | gpl3 | 1,314 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import android.text.TextUtils;
import java.io.Serializable;
public final class Track implements PlaylistItem, Serializable {
private static final long serialVersionUID = 1L;
private int mId;
private boolean mCurrent;
private String mUri;
private String mName;
private long mDuration;
private String mTitle;
private String mArtist;
private String mGenre;
private String mCopyright;
private String mAlbum;
private String mTrack;
private String mDescription;
private String mRating;
private String mDate;
private String mUrl;
private String mLanguage;
private String mNowPlaying;
private String mPublisher;
private String mEncodedBy;
private String mArtUrl;
private String mTrackId;
public int getId() {
return mId;
}
public void setId(int id) {
mId = id;
}
/** {@inheritDoc} */
public boolean isCurrent() {
return mCurrent;
}
/** {@inheritDoc} */
public CharSequence getText1() {
return isNotEmpty(mTitle) ? mTitle : isNotEmpty(mName) ? mName : "";
}
/** {@inheritDoc} */
public CharSequence getText2() {
return isNotEmpty(mArtist) ? mArtist : "";
}
public void setCurrent(boolean current) {
mCurrent = current;
}
public String getUri() {
return mUri;
}
public void setUri(String uri) {
mUri = uri;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public long getDuration() {
return mDuration;
}
public void setDuration(long duration) {
mDuration = duration;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
this.mTitle = title;
}
public String getArtist() {
return mArtist;
}
public void setArtist(String artist) {
this.mArtist = artist;
}
public String getGenre() {
return mGenre;
}
public void setGenre(String genre) {
this.mGenre = genre;
}
public String getCopyright() {
return mCopyright;
}
public void setCopyright(String copyright) {
this.mCopyright = copyright;
}
public String getAlbum() {
return mAlbum;
}
public void setAlbum(String album) {
this.mAlbum = album;
}
public String getTrack() {
return mTrack;
}
public void setTrack(String track) {
this.mTrack = track;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
this.mDescription = description;
}
public String getRating() {
return mRating;
}
public void setRating(String rating) {
this.mRating = rating;
}
public String getDate() {
return mDate;
}
public void setDate(String date) {
this.mDate = date;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String url) {
this.mUrl = url;
}
public String getLanguage() {
return mLanguage;
}
public void setLanguage(String language) {
this.mLanguage = language;
}
public String getNowPlaying() {
return mNowPlaying;
}
public void setNowPlaying(String nowPlaying) {
this.mNowPlaying = nowPlaying;
}
public String getPublisher() {
return mPublisher;
}
public void setPublisher(String publisher) {
this.mPublisher = publisher;
}
public String getEncodedBy() {
return mEncodedBy;
}
public void setEncodedBy(String encodedBy) {
this.mEncodedBy = encodedBy;
}
public String getArtUrl() {
return mArtUrl;
}
public void setArtUrl(String art_url) {
this.mArtUrl = art_url;
}
public String getTrackId() {
return mTrackId;
}
public void setTrackId(String trackId) {
this.mTrackId = trackId;
}
@Override
public String toString() {
// XSPF playlists set the title, but use a URL for the name.
// M3U playlists don't have a title, but set a good name.
return mTitle != null ? mTitle : mName;
}
private static boolean isNotEmpty(CharSequence text) {
return !TextUtils.isEmpty(text);
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Track.java | Java | gpl3 | 5,208 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import java.util.ArrayList;
@SuppressWarnings("serial")
public final class Directory extends ArrayList<File> {
public Directory() {
}
public Directory(int capacity) {
super(capacity);
}
public String getPath() {
// Compute the path from the .. entry
for (File file : this) {
String name = file.getName();
String path = file.getPath();
if (name != null && path != null && name.equals("..") && path.endsWith("..")) {
int length = path.length();
length -= "..".length();
return path.substring(0, length);
}
}
return null;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Directory.java | Java | gpl3 | 1,440 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import java.io.Serializable;
public final class Status implements Serializable {
private static final long serialVersionUID = 1L;
private int mVolume;
private int mLength;
private int mTime;
private String mState;
private double mPosition;
private boolean mFullscreen;
private boolean mRandom;
private boolean mLoop;
private boolean mRepeat;
private final Track mTrack = new Track();
public int getVolume() {
return mVolume;
}
/**
* Returns the length of the media in seconds.
*/
public int getLength() {
return mLength;
}
public int getTime() {
return mTime;
}
public boolean isPlaying() {
return "playing".equals(mState);
}
public boolean isPaused() {
return "paused".equals(mState);
}
public boolean isStopped() {
return "stop".equals(mState);
}
public String getState() {
return mState;
}
/**
* Returns the playback position as a percentage.
*/
public double getPosition() {
return mPosition;
}
public boolean isFullscreen() {
return mFullscreen;
}
public boolean isRandom() {
return mRandom;
}
public boolean isLoop() {
return mLoop;
}
public boolean isRepeat() {
return mRepeat;
}
public void setVolume(int volume) {
mVolume = volume;
}
public void setLength(int length) {
mLength = length;
}
public void setTime(int time) {
mTime = time;
}
public void setState(String state) {
mState = state;
}
public void setPosition(double position) {
mPosition = position;
}
public void setFullscreen(boolean fullscreen) {
mFullscreen = fullscreen;
}
public void setRandom(boolean random) {
mRandom = random;
}
public void setLoop(boolean loop) {
mLoop = loop;
}
public void setRepeat(boolean repeat) {
mRepeat = repeat;
}
public Track getTrack() {
return mTrack;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Status.java | Java | gpl3 | 2,865 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import android.content.Intent;
import android.net.Uri;
import android.webkit.MimeTypeMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class File {
private static final MimeTypeMap sMimeTypeMap = MimeTypeMap.getSingleton();
private static String parseExtension(String path) {
int index = path.lastIndexOf('.');
if (index != -1) {
return path.substring(index + 1);
} else {
return null;
}
}
private String mType;
private Long mSize;
private String mDate;
private String mPath;
private String mName;
private String mExtension;
public File(String type, Long size, String date, String path, String name, String extension) {
mType = type;
mSize = size;
mDate = date;
mPath = path;
mName = name;
mExtension = extension != null ? extension : path != null ? parseExtension(path) : null;
}
public String getType() {
return mType;
}
public void setType(String type) {
mType = type;
}
public boolean isDirectory() {
// Type is "directory" in VLC 1.0 and "dir" in VLC 1.1
return "directory".equals(mType) || "dir".equals(mType);
}
public boolean isImage() {
String mimeType = getMimeType();
return mimeType != null && mimeType.startsWith("image/");
}
public Long getSize() {
return mSize;
}
public void setSize(Long size) {
mSize = size;
}
public String getDate() {
return mDate;
}
public void setDate(String date) {
mDate = date;
}
public String getPath() {
return mPath;
}
public String getMrl() {
if (isImage()) {
return "fake://";
} else {
java.io.File file = new java.io.File(mPath);
Uri uri = Uri.fromFile(file);
return uri.toString();
}
}
public List<String> getOptions() {
if (isImage()) {
return Collections.singletonList(":fake-file=" + getPath());
} else {
return Collections.emptyList();
}
}
public List<String> getStreamingOptions() {
List<String> options = new ArrayList<String>(getOptions());
String mimeType = getMimeType();
if (mimeType != null && mimeType.startsWith("audio/")) {
options.add(":sout=#transcode{acodec=vorb,ab=128}:standard{access=http,mux=ogg,dst=0.0.0.0:8000}");
} else {
options.add(":sout=#transcode{vcodec=mp4v,vb=384,acodec=mp4a,ab=64,channels=2,fps=25,venc=x264{profile=baseline,keyint=50,bframes=0,no-cabac,ref=1,vbv-maxrate=4096,vbv-bufsize=1024,aq-mode=0,no-mbtree,partitions=none,no-weightb,weightp=0,me=dia,subme=0,no-mixed-refs,no-8x8dct,trellis=0,level1.3},vfilter=canvas{width=320,height=180,aspect=320:180,padd},senc,soverlay}:rtp{sdp=rtsp://0.0.0.0:5554/stream.sdp,caching=4000}}");
}
return options;
}
public Intent getIntentForStreaming(String authority) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = getMimeType();
if (mimeType != null && mimeType.startsWith("audio/")) {
Uri.Builder builder = new Uri.Builder();
builder.scheme("rtsp");
builder.encodedAuthority(swapPortNumber(authority, 5554));
builder.path("stream.sdp");
Uri data = builder.build();
intent.setData(data);
} else {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.encodedAuthority(swapPortNumber(authority, 8000));
Uri data = builder.build();
intent.setDataAndType(data, "application/ogg");
}
return intent;
}
public void setPath(String path) {
mPath = path;
if (mExtension == null && path != null) {
mExtension = parseExtension(path);
}
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getExtension() {
return mExtension;
}
public void setExtension(String extension) {
mExtension = extension;
}
public String getMimeType() {
if (mExtension != null) {
// See http://code.google.com/p/android/issues/detail?id=8806
String extension = mExtension.toLowerCase();
return sMimeTypeMap.getMimeTypeFromExtension(extension);
} else {
return null;
}
}
@Override
public String toString() {
return mName;
}
private static String removePortNumber(String authority) {
int index = authority.lastIndexOf(':');
if (index != -1) {
// Remove port number
authority = authority.substring(0, index);
}
return authority;
}
private static String swapPortNumber(String authority, int port) {
return removePortNumber(authority) + ":" + port;
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/File.java | Java | gpl3 | 5,865 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.DateUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Convenience class for reading and writing application preferences.
*/
public final class Preferences {
private static final String PREFERENCES = "preferences";
private static final String PREFERENCE_SERVER = "server";
private static final String PREFERENCE_REMEMBERED_SERVERS = "remembered_servers";
private static final String PREFERENCE_BROWSE_DIRECTORY = "browse_directory";
private static final String PREFERENCE_HOME_DIRECTORY = "home_directory";
private static final String PREFERENCE_RESUME_ON_IDLE = "resume_on_idle";
private SharedPreferences mPreferences;
public Preferences(SharedPreferences preferences) {
mPreferences = preferences;
}
public static Preferences get(Context context) {
return new Preferences(context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE));
}
public boolean setResumeOnIdle() {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(PREFERENCE_RESUME_ON_IDLE, System.currentTimeMillis());
return editor.commit();
}
/**
* Returns {@code true} if {@link #setResumeOnIdle()} was called in the last
* hour.
*/
public boolean isResumeOnIdleSet() {
long start = mPreferences.getLong(PREFERENCE_RESUME_ON_IDLE, 0L);
long end = System.currentTimeMillis();
return start < end && (end - start) < DateUtils.HOUR_IN_MILLIS;
}
public boolean clearResumeOnIdle() {
SharedPreferences.Editor editor = mPreferences.edit();
editor.remove(PREFERENCE_RESUME_ON_IDLE);
return editor.commit();
}
public String getAuthority() {
return mPreferences.getString(PREFERENCE_SERVER, null);
}
public String getHomeDirectory() {
return mPreferences.getString(PREFERENCE_HOME_DIRECTORY, "~");
}
public String getBrowseDirectory() {
return mPreferences.getString(PREFERENCE_BROWSE_DIRECTORY, "~");
}
public boolean setAuthority(String authority) {
return mPreferences.edit().putString(PREFERENCE_SERVER, authority).commit();
}
public boolean setHomeDirectory(String dir) {
return mPreferences.edit().putString(PREFERENCE_HOME_DIRECTORY, dir).commit();
}
public boolean setBrowseDirectory(String dir) {
return mPreferences.edit().putString(PREFERENCE_BROWSE_DIRECTORY, dir).commit();
}
public ArrayList<String> getRememberedServers() {
return fromJSONArray(mPreferences.getString(PREFERENCE_REMEMBERED_SERVERS, "[]"));
}
public boolean setRemeberedServers(List<String> rememberedServers) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(PREFERENCE_REMEMBERED_SERVERS, toJSONArray(rememberedServers));
return editor.commit();
}
private static String toJSONArray(List<String> list) {
JSONArray array = new JSONArray(list);
return array.toString();
}
private static ArrayList<String> fromJSONArray(String json) {
try {
JSONArray array = new JSONArray(json);
int n = array.length();
ArrayList<String> list = new ArrayList<String>(n);
for (int i = 0; i < n; i++) {
String element = array.getString(i);
list.add(element);
}
return list;
} catch (JSONException e) {
return new ArrayList<String>(0);
}
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Preferences.java | Java | gpl3 | 4,455 |
/*-
* Copyright (C) 2009 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
import java.util.ArrayList;
public final class Playlist extends ArrayList<PlaylistItem> implements PlaylistItem {
private static final long serialVersionUID = 1L;
private final int mId;
private final String mName;
public Playlist(int id, String name) {
mId = id;
mName = name;
}
public int getId() {
return mId;
}
public String getName() {
return mName;
}
/** {@inheritDoc} */
public boolean isCurrent() {
return false;
}
/** {@inheritDoc} */
public CharSequence getText1() {
return mName;
}
/** {@inheritDoc} */
public CharSequence getText2() {
return "";
}
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/Playlist.java | Java | gpl3 | 1,452 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.vlcremote.model;
/**
* Abstraction for any item that can appear in a playlist.
*/
public interface PlaylistItem {
int getId();
String getName();
boolean isCurrent();
CharSequence getText1();
CharSequence getText2();
}
| 091420009-my | src/org/peterbaldwin/vlcremote/model/PlaylistItem.java | Java | gpl3 | 980 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.client.android.vlcremote;
/**
* Alias for backwards-compatibility.
*/
public class PlaybackActivity extends org.peterbaldwin.vlcremote.app.PlaybackActivity {
}
| 091420009-my | src/org/peterbaldwin/client/android/vlcremote/PlaybackActivity.java | Java | gpl3 | 898 |
/*-
* Copyright (C) 2011 Peter Baldwin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.peterbaldwin.client.android.vlcremote;
/**
* Alias for backwards-compatibility.
*/
public class MediaAppWidgetProvider extends
org.peterbaldwin.vlcremote.appwidget.MediaAppWidgetProvider {
}
| 091420009-my | src/org/peterbaldwin/client/android/vlcremote/MediaAppWidgetProvider.java | Java | gpl3 | 924 |
public class Profesor extends Persona implements Evaluar
{
private
String titulo_acam;
public Profesor(){}
public Profesor(long cedula, String nombre, String apellido,String t)
{
super(cedula, nombre, apellido);
this.titulo_acam = t;
}
public String getTitulo_acam()
{
return titulo_acam;
}
public void setTitulo_acam(String titulo_acam)
{
this.titulo_acam = titulo_acam;
}
public void EvaluarEstudiante(Estudiante e)
{
float t = 0;
float []n = e.getNotas();
for(int i = 0;i < 3;i++)
t += n[i];
e.setNota_final(t/3);
e.setEstado((e.getNota_final() >= 10 ? true : false));
}
} | 03-3-segundaentrega | trunk/Segunda_Entrega/src/Profesor.java | Java | asf20 | 639 |
import java.awt.*;
import javax.swing.*;
import com.cloudgarden.layout.AnchorLayout;
import info.clearthought.layout.TableLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.SwingUtilities;
import java.awt.*;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
* @param <JPanelConFondo>
*/
public class Acceso_pantalla extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton jButton1;
private JPasswordField Txtpass;
private JTextArea jTextArea2;
private JTextArea jTextArea1;
private JTextField txtlog;
private Acceso acc = new Acceso();
ActionListener Permitir = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if((txtlog.getText().compareTo(acc.getLog()) == 0 ) &&
(txtlog.getText().compareTo(acc.getLog())) == 0)
Cerrar();
else JOptionPane.showMessageDialog(null,"Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
};
public void Cerrar()
{
FrameSeccion fs = new FrameSeccion();
fs.setVisible(true);
fs.setLocationRelativeTo(null);
this.dispose();
}
public Acceso_pantalla() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
this.setTitle("Acceso al Sistema");
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1);
jPanel1.setBounds(32, 20, 230, 152);
jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
jPanel1.setOpaque(false);
jPanel1.setLayout(null);
jPanel1.addFocusListener(new FocusAdapter() {
});
{
txtlog = new JTextField();
jPanel1.add(txtlog);
txtlog.setBounds(43, 30, 138, 21);
txtlog.addFocusListener(new FocusAdapter() {
});
}
{
jTextArea1 = new JTextArea();
jPanel1.add(jTextArea1);
jTextArea1.setText("Login");
jTextArea1.setBounds(81, 12, 60, 19);
jTextArea1.setOpaque(false);
jTextArea1.setFont(new java.awt.Font("Courier 10 Pitch",1,16));
jTextArea1.setEditable(false);
}
{
jTextArea2 = new JTextArea();
jPanel1.add(jTextArea2);
jTextArea2.setText("Password");
jTextArea2.setOpaque(false);
jTextArea2.setBounds(68, 58, 90, 19);
jTextArea2.setFont(new java.awt.Font("Courier 10 Pitch",1,16));
jTextArea2.setEditable(false);
}
{
jButton1 = new JButton();
jPanel1.add(jButton1);
jButton1.setText("Aceptar");
jButton1.setBounds(63, 107, 102, 25);
jButton1.addActionListener(Permitir);
}
{
Txtpass = new JPasswordField();
jPanel1.add(Txtpass);
Txtpass.setBounds(43, 75, 138, 21);
Txtpass.addFocusListener(new FocusAdapter() {
});
}
}
pack();
this.setSize(306, 227);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Acceso_pantalla.java | Java | asf20 | 3,851 |
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Control
{
private
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean prof_registrado = false;
Seccion sec;
public Control()
{
super();
this.sec = new Seccion();
}
//*************************************** PROCESAR SECCION ********************************************
public void ProcesarSeccion()
{
int opt = 0;
boolean seg;
System.out.print("Ingrese el numero de la seccion : ");
try
{
String num_sec = in.readLine();
this.sec.setNum_secc(num_sec);
}catch(IOException e){}
do
{
do
{
System.out.println("\nRegistro Academico\n");
System.out.print("(1)Incluir Profesor."
+ "\n(2)Inscribir Estudiantes."
+ "\n(3)Mostar Profesor."
+ "\n(4)Aplicar Evaluacion."
+ "\n(5)Retirar Estudiante."
+ "\n(6)Buscar Estudiante."
+ "\n(7)Promedio de notas."
+ "\n(8)Listado de Estudiantes."
+ "\n(9)Listado de Estudiantes Aprobados."
+ "\n(10)Listado de Estudiantes Aplazados."
+ "\n(0)Salir."
+"\nOpcion :");
seg = false;
try
{
opt = Integer.parseInt(in.readLine());
if(opt < 0 || opt > 10)
{
System.out.println("Opcion invalida!");
seg = true;
}
}
catch(Exception e)
{
System.out.println("Opcion invalida!");
seg = true;
}
}while(seg);
limpiar();
switch(opt)
{
case 1:
IncluirProfesor();
break;
case 2:
InscribirEstudiante();
break;
case 3:
Mostar_Profesor();
break;
case 4:
AplicarEvaluacion();
break;
case 5:
RetirarEstudiante();
break;
case 6:
BuscarEstudiante();
break;
case 7:
MostrarPromedio();
break;
case 8:
ListarEstudiante();
break;
case 9:
ListarEstudiantesAprob();
break;
case 10:
ListarEstudiantesAplazados();
break;
}
}while(opt != 0);
}
public void limpiar()
{
for (int i=0; i<15;i++)
System.out.println();
}
public void MostrarPromedio()
{
if(this.sec.NumeroEstudiante() == 0)
System.out.println("No existen estudiantes registrados!");
else
System.out.println("Promedio de la seccion : " + this.sec.Promedio());
}
public void AplicarEvaluacion()
{
if(!prof_registrado)
System.out.println("Debe registrar un Profesor!");
else if(this.sec.NumeroEstudiante() == 0)
System.out.println("No existen estudiantes registrados!");
else
{
this.sec.AplicarEvaluaciones();
this.sec.EvaluarEstuduantes();
System.out.println("La evaluacion fue realizada con exito!");
}
}
public void BuscarEstudiante()
{
if(this.sec.NumeroEstudiante() == 0)
System.out.println("No existen estudiantes registrados!");
else
{
System.out.println("Ingrese la cedula : ");
try
{
int i = this.sec.Buscar((long)Integer.parseInt(in.readLine()));
if(i == -1)
JOptionPane.showMessageDialog(null,"El estudiante no existe!", "Advertencia", JOptionPane.WARNING_MESSAGE);
else
{
System.out.println("Cedula : " + this.sec.getEstudiante(i).getCedula());
System.out.println("Nombre : " + this.sec.getEstudiante(i).getNombre());
System.out.println("Apellido : " + this.sec.getEstudiante(i).getApellido());
}
}
catch(Exception e)
{
System.out.println("Se produjo un ERROR!.");
}
}
}
public void RetirarEstudiante()
{
if(this.sec.NumeroEstudiante() == 0)
System.out.println("No existen estudiantes registrados!");
else
{
System.out.println("Ingrese la cedula : ");
try
{
int i = this.sec.Buscar((long)Integer.parseInt(in.readLine()));
if(i == -1)
System.out.println("El estudiante no existe!");
else
{
this.sec.RetirarEstudiante(i);
System.out.println("Estudiante eliminado correctamente!");
}
}
catch(Exception e)
{
System.out.println("Se produjo un ERROR!.");
}
}
}
public void ListarEstudiantesAprob()
{
boolean imp = true;
if(this.sec.NumeroEstudiante() == 0)
{
System.out.println("No existen estudiantes registrados!");
Imprimir_en_TXT("Estudiantes Aprobados.txt","No existen estudiantes Aprobados!",true);
}
else
{
System.out.println("Estudiantes Aprobados :");
Imprimir_en_TXT("Estudiantes Aprobados.txt","Estudiantes Aprobados :",true);
Vector<Estudiante> Est = sec.getEstudiantes();
for(int i = 0;i < Est.size();i++)
if(Est.elementAt(i).getEstado())
{
System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final());
Imprimir_en_TXT("Estudiantes Aprobados.txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false);
imp = false;
}
if(imp)System.out.println("No existen estudiantes Aprobados!");
}
}
public void ListarEstudiantesAplazados()
{
boolean imp = true;
if(this.sec.NumeroEstudiante() == 0)
{
System.out.println("No existen estudiantes registrados!");
Imprimir_en_TXT("Estudiantes Aplazados.txt","No existen estudiantes registrados!",true);
}
else
{
System.out.println("Estudiantes Aplazados :");
Imprimir_en_TXT("Estudiantes Aplazados.txt","Estudiantes Aplazados :",true);
Vector<Estudiante> Est = sec.getEstudiantes();
for(int i = 0;i < Est.size();i++)
if(!Est.elementAt(i).getEstado())
{
System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final());
Imprimir_en_TXT("Estudiantes Aplazados.txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false);
imp = false;
}
if(imp)System.out.println("No existen estudiantes Aplazados!");
}
}
public void ListarEstudiante()
{
if(this.sec.NumeroEstudiante() == 0)
System.out.println("No existen estudiantes registrados!");
else
{
String str = "";
int x;
boolean seg;
do
{
seg = false;
System.out.println("Estudiantes ordenados por :"
+ "\n(1)Cedula"
+ "\n(2)Notas"
+ "\nOpcion :");
try
{
x = Integer.parseInt(in.readLine());
if(x <= 0)
{
System.out.println("Debe ingresar un numero valido!");
seg = true;
}
else if(x == 1)
{
sec.OrdenarEstudianteCed();
str = "Cedula:";
}
else
{
sec.OrdenarEstudianteNota();
str = "Notas:";
}
}
catch(Exception e)
{
System.out.println("Debe ingresar un numero valido!");
seg = true;
}
}while(seg);
System.out.println("Estudiantes Inscritos ordenados por " + str + " :");
Imprimir_en_TXT("Estudiantes ordenados por " + str + ".txt","Estudiantes Inscritos ordenados por " + str + " :",true);
Vector<Estudiante> Est = sec.getEstudiantes();
for(int i = 0;i < Est.size();i++)
{
System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final());
Imprimir_en_TXT("Estudiantes ordenados por " + str + ".txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido()
+ " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false);
}
}
}
public void InscribirEstudiante()
{
int n = 0;
String c = "",nomb = "",a = "";
boolean seg;
do
{
System.out.print("Ingrese el numero de estudiantes a inscribir :");
seg = false;
try
{
n = Integer.parseInt(in.readLine());
if(n <= 0)
{
System.out.println("Debe ingresar un numero valido!");
seg = true;
}
}
catch(Exception e)
{
System.out.println("Debe ingresar un numero valido!");
seg = true;
}
}while(seg);
while(n-- > 0)
{
System.out.println("Ingrese los datos del Estudiante:");
try
{
System.out.print("Cedula : ");c = in.readLine();
if(this.sec.Buscar((long)Integer.parseInt(c)) == -1)
{
System.out.print("Nombre : ");nomb = in.readLine();
System.out.print("Apellido : ");a = in.readLine();
Estudiante e = new Estudiante((long)Integer.parseInt(c),nomb,a);
this.sec.InscribirEstudiantes(e);
}
else
{
System.out.println("Ya existe un estudiante con cedula " + c);
n++;
}
}
catch(Exception e)
{
System.out.println("Se produjo un ERROR en la lectura de los datos.");
n++;
}
}
}
public void IncluirProfesor()
{
if(prof_registrado)
{
System.out.println("El profesor ya fue registrado!");
}
else
{
String c,n,a,t;
System.out.println("Ingrese los datos del profesor:");
try
{
System.out.print("Cedula : ");c = in.readLine();
System.out.print("Nombre : ");n = in.readLine();
System.out.print("Apellido : ");a = in.readLine();
System.out.print("Titulo Academico : ");t = in.readLine();
this.sec.setProf((long)Integer.parseInt(c),n,a,t);
prof_registrado = true;
}
catch(Exception e)
{
System.out.println("Se produjo un ERROR en la lectura de los datos.");
}
}
}
public void Mostar_Profesor()
{
if(!prof_registrado)
System.out.println("Debe registrar un Profesor!");
else
System.out.println("Prof. " + this.sec.getProf().getApellido() + ' '
+ this.sec.getProf().getNombre() + ", " + this.sec.getProf().getTitulo_acam());
}
public void Imprimir_en_TXT(String archivo,String texto,boolean nuevo)
{
try
{
FileWriter fw = new FileWriter(archivo,!nuevo);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(texto);
out.close();
}catch(Exception e)
{
System.out.println("No se pudo imprimir en el archivo + \"" + archivo + "\"");
}
}
} | 03-3-segundaentrega | trunk/Segunda_Entrega/src/Control.java | Java | asf20 | 10,300 |
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.SwingUtilities;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FrameProfesor extends javax.swing.JFrame {
private JTextField TxtNombre;
private JTextField TxtCedula;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JButton BTBorrar;
private JPanel jPanel1;
private JButton BTCancelar;
private JButton BTIncluir;
private JLabel jLabel1;
private JTextField TxtTituloAcad;
private JTextField TxtApellido;
private Seccion sec;
public FrameProfesor() {
super();
initGUI();
}
public FrameProfesor(Seccion sec) {
super();
this.sec = sec;
initGUI();
}
ActionListener AccIncluir = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
IncluirProfersor();
}
};
public void MostrarProfesor()
{
if(this.sec.getProfReg())
{
Profesor p = this.sec.getProf();
this.TxtApellido.setText(p.getApellido());
this.TxtNombre.setText(p.getNombre());
this.TxtTituloAcad.setText(p.getTitulo_acam());
this.TxtCedula.setText(Long.toString(p.getCedula()));
this.BTIncluir.setEnabled(false);
this.BTBorrar.setEnabled(false);
this.BTCancelar.setEnabled(true);
}
}
public void IncluirProfersor()
{
try
{
if(this.TxtApellido.getText().equals("") || this.TxtNombre.getText().equals("")
|| this.TxtCedula.getText().equals("") || this.TxtTituloAcad.getText().equals(""))
JOptionPane.showMessageDialog(null,"Debe llenar todos los datos para poder inscribir al profesor", "Faltan Datos", JOptionPane.ERROR_MESSAGE);
else
{
sec.setProf((long)Integer.parseInt(TxtCedula.getText()),
TxtNombre.getText(),TxtApellido.getText(),TxtTituloAcad.getText());
sec.setProfReg(true);
JOptionPane.showMessageDialog(null,"El profesor fué incluido con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE);
MostrarProfesor();
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE);
Borrar();
}
}
ActionListener Borrar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
BTBorrar.setMnemonic(KeyEvent.VK_B);
Borrar();
}
};
public void Borrar()
{
TxtCedula.setText("");
TxtNombre.setText("");
TxtApellido.setText("");
TxtTituloAcad.setText("");
}
ActionListener Cancelar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Cerrar();
}
};
public void Cerrar()
{
this.dispose();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(Color.white);
this.setName("Profesor");
this.setTitle("Profesor");
this.setFont(new java.awt.Font("Courier 10 Pitch",0,28));
{
jLabel5 = new JLabel();
getContentPane().add(jLabel5);
jLabel5.setText("Datos del Profesor");
jLabel5.setBounds(103, 8, 241, 35);
jLabel5.setFont(new java.awt.Font("Bitstream Charter",1,28));
}
{
BTIncluir = new JButton();
getContentPane().add(BTIncluir);
BTIncluir.setText("Incluir");
BTIncluir.setBounds(62, 255, 85, 28);
BTIncluir.addActionListener(AccIncluir);
}
{
BTCancelar = new JButton();
getContentPane().add(BTCancelar);
BTCancelar.setText("Salir");
BTCancelar.setBounds(298, 255, 100, 28);
BTCancelar.addActionListener(Cancelar);
}
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1);
jPanel1.setBounds(34, 46, 389, 192);
jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
jPanel1.setName("Datos del Profesor");
jPanel1.setOpaque(false);
jPanel1.setLayout(null);
{
jLabel1 = new JLabel();
jPanel1.add(jLabel1);
jLabel1.setText("Cedula");
jLabel1.setBounds(56, 30, 66, 15);
jLabel1.setFont(new java.awt.Font("Dialog",0,14));
}
{
TxtCedula = new JTextField();
jPanel1.add(TxtCedula);
TxtCedula.setBounds(155, 24, 132, 22);
TxtCedula.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
{
jLabel2 = new JLabel();
jPanel1.add(jLabel2);
jLabel2.setText("Nombre");
jLabel2.setBounds(53, 68, 66, 15);
jLabel2.setFont(new java.awt.Font("Dialog",0,14));
}
{
TxtNombre = new JTextField();
jPanel1.add(TxtNombre);
TxtNombre.setBounds(155, 61, 132, 22);
TxtNombre.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
{
jLabel3 = new JLabel();
jPanel1.add(jLabel3);
jLabel3.setText("Apellido");
jLabel3.setBounds(53, 106, 66, 15);
jLabel3.setFont(new java.awt.Font("Dialog",0,14));
}
{
TxtApellido = new JTextField();
jPanel1.add(TxtApellido);
TxtApellido.setBounds(155, 99, 132, 22);
TxtApellido.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
{
jLabel4 = new JLabel();
jPanel1.add(jLabel4);
jLabel4.setText("Titulo Academico");
jLabel4.setBounds(19, 134, 130, 35);
jLabel4.setFont(new java.awt.Font("Dialog",0,14));
}
{
TxtTituloAcad = new JTextField();
jPanel1.add(TxtTituloAcad);
TxtTituloAcad.setBounds(155, 139, 132, 22);
TxtTituloAcad.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
}
}
{
BTBorrar = new JButton();
getContentPane().add(BTBorrar);
BTBorrar.setText("Borrar");
BTBorrar.setBounds(185, 255, 84, 28);
BTBorrar.addActionListener(Borrar);
}
pack();
this.setSize(465, 338);
MostrarProfesor();
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/FrameProfesor.java | Java | asf20 | 6,928 |
import java.awt.*;
import javax.swing.*;
import java.awt.Dimension;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Vector;
import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class JTableDemo extends javax.swing.JApplet
{
private Vector<Estudiante> Est;
private String titulo = "";
public JTableDemo() {
super();
initGUI();
}
public JTableDemo(Vector<Estudiante> Est,String t)
{
super();
this.titulo = t;
this.Est = Est;
initGUI();
}
private Object Valor(Estudiante e,int i)
{
switch(i)
{
case 0:return e.getCedula();
case 1:return e.getNombre();
case 2:return e.getApellido();
case 3:return e.getNota_final();
}
return 0;
}
public void Imprimir_en_TXT(String archivo,String texto,boolean nuevo)
{
try
{
FileWriter fw = new FileWriter(archivo,!nuevo);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(texto);
out.close();
}catch(Exception e)
{
System.out.println("No se pudo imprimir en el archivo + \"" + archivo + "\"");
}
}
private void initGUI() {
try {
setSize(new Dimension(600, 300));
Container c = getContentPane();
c.setLayout(new BorderLayout());
final String[] colHeads = {"Cedula","Nombre","Apellido","Nota Final"};
//Inicializar Tabla
Object[][] Datos = new Object[Est.size()][4];
Estudiante e;
Imprimir_en_TXT(titulo + ".txt",titulo + '\n',true);
titulo += ".txt";
Imprimir_en_TXT(titulo,"Cedula Nombre Apellido Nota Final\n\n",false);
for(int j,i = 0;i < Est.size();i++)
{
e = Est.elementAt(i);
for(j = 0;j < 4;j++)
{
Datos[i][j] = Valor(e,j);
Imprimir_en_TXT(titulo,Datos[i][j].toString() + " ",false);
}
Imprimir_en_TXT(titulo,"\n",false);
}
JTable table = new JTable(Datos, colHeads);
// añadir a la tabla el panel con scroll
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
// añadir el panel con scroll al content pane
c.add(jsp, BorderLayout.CENTER);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/JTableDemo.java | Java | asf20 | 2,364 |
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Panel extends JPanel {
private int anchoImagen, altoImagen;
private Image image;
public Panel(String rutaImagen, int ancho, int alto) {
super();
image = new ImageIcon(getClass().getResource(rutaImagen)).getImage();
this.anchoImagen = ancho;
this.altoImagen = alto;
this.setLayout(null);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this.anchoImagen, this.altoImagen, null);
setOpaque(false);
super.paintComponent(g);
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Panel.java | Java | asf20 | 640 |
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
/*Desarrolladores:
* Arrieche, Andrés C.I V- 19.423.804
* Fernández, Jhoswar C.I V- 19.779.296
* Ramírez, Jeniree C.I V- 18.619.418
Sección 3. */
public class Principal
{
public static void main(String[] args)
{
Acceso_pantalla acc = new Acceso_pantalla();
acc.setVisible(true);
acc.setLocationRelativeTo(null);
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Principal.java | Java | asf20 | 450 |
public abstract class Persona
{
private
long cedula;
String nombre;
String apellido;
public Persona()
{
super();
}
public Persona(long cedula, String nombre, String apellido)
{
super();
this.cedula = cedula;
this.nombre = nombre;
this.apellido = apellido;
}
public long getCedula()
{
return cedula;
}
public void setCedula(long cedula)
{
this.cedula = cedula;
}
public String getNombre()
{
return nombre;
}
public void setNombre(String nombre)
{
this.nombre = nombre;
}
public String getApellido()
{
return apellido;
}
public void setApellido(String apellido)
{
this.apellido = apellido;
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Persona.java | Java | asf20 | 723 |
public interface Evaluado
{
public abstract void presentarEvaluacion();
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Evaluado.java | Java | asf20 | 75 |
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Acceso
{
private
String log,pass;
public Acceso()
{
super();
this.log = "usuario";
this.pass = "123456";
}
public Acceso(String log, String pass)
{
super();
this.log = log;
this.pass = pass;
}
public String getLog()
{
return log;
}
public void setLog(String log)
{
this.log = log;
}
public String getPass()
{
return pass;
}
public void setPass(String pass)
{
this.pass = pass;
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Acceso.java | Java | asf20 | 513 |
public interface Evaluar
{
public abstract void EvaluarEstudiante(Estudiante e);
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/Evaluar.java | Java | asf20 | 84 |
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Vector;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FramePrincipal extends javax.swing.JFrame {
private JMenuBar jMenuBar1;
private JMenu jMenu1;
private JMenu jMenu3;
private JMenu jMenu4;
private JMenu jMenu6;
private JMenuItem Estudiante;
private JMenuItem RProfesor;
private JMenuItem AplicarEvaluaciones;
private JRadioButtonMenuItem jRadioButtonOrdenarNot;
private JMenuItem LGeneral;
private JMenuItem LAprobados;
private JMenuItem LAplazados;
private JMenuItem Salir;
private JMenuItem jMenuItem2;
private JPopupMenu jPopupMenu1;
private JRadioButtonMenuItem jRadioButtonOrdenarCed;
private JMenu jMenu2;
private JDesktopPane jDesktopPane1;
private Image image;
private Seccion sec;
private int opc_ordenar = 0;
ActionListener opc_ced = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
opc_ordenar = 0;
}
};
ActionListener opc_nota = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
opc_ordenar = 1;
}
};
ActionListener rep_general = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String t = "Listado General ordenado por " + Ordenar();
Reporte(sec.getEstudiantes(),t);
}
};
ActionListener rep_aprob = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String t = "Listado de Aprobados ordenado por " + Ordenar();
Reporte(sec.getEstudiantesAprob(),t);
}
};
ActionListener rep_aplaz = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String t = "Listado de Aplazados ordenado por " + Ordenar();
Reporte(sec.getEstudiantesAplaz(),t);
}
};
public String Ordenar()
{
if(opc_ordenar == 0)
{
this.sec.OrdenarEstudianteCed();
return "Cedula";
}
else
{
this.sec.OrdenarEstudianteNota();
return "Nota Final";
}
}
public void Reporte(Vector<Estudiante> Est,String t)
{
if(this.sec.NumeroEstudiante() == 0)
JOptionPane.showMessageDialog(null,"No Existen estudiantes registrados", "Advertencia", JOptionPane.INFORMATION_MESSAGE);
else if(Est.size() != 0)
{
JFrame frame = new JFrame();
JTableDemo inst = new JTableDemo(Est,t);
frame.getContentPane().add(inst);
((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
frame.pack();
frame.setVisible(true);
frame.setTitle(t);
frame.setLocationRelativeTo(null);
inst.setSize(new Dimension(600, 300));
}
else
JOptionPane.showMessageDialog(null,"No Existen estudiantes que cumplan la condicion", "Advertencia", JOptionPane.INFORMATION_MESSAGE);
}
ActionListener Ventprof = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FrameProfesor ventProf = new FrameProfesor(sec);
ventProf.setVisible(true);
ventProf.setLocationRelativeTo(null);
}
};
ActionListener VentEst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FrameEstudiante ventEstud = new FrameEstudiante(sec);
ventEstud.setVisible(true);
ventEstud.setLocationRelativeTo(null);
}
};
ActionListener Evaluar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AplicarEvaluacion();
}
};
public void AplicarEvaluacion()
{
if(this.sec.NumeroEstudiante() == 0)
JOptionPane.showMessageDialog(null,"No Existen estudiantes registrados", "Advertencia", JOptionPane.INFORMATION_MESSAGE);
else if(!this.sec.getProfReg())
JOptionPane.showMessageDialog(null,"No Existe profesor registrado", "Advertencia", JOptionPane.INFORMATION_MESSAGE);
else
{
this.sec.AplicarEvaluaciones();
this.sec.EvaluarEstuduantes();
JOptionPane.showMessageDialog(null,"La evaluacion fue realizada con exito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE);
}
}
public FramePrincipal() {
super();
initGUI();
Panel pan = new Panel("/Imagenes/imagen2.jpg", this.getWidth(), this.getHeight());
this.add(pan, BorderLayout.CENTER);
pan.setPreferredSize(new java.awt.Dimension(486, 273));
}
public FramePrincipal(Seccion sec) {
super();
this.sec = sec;
initGUI();
this.setTitle("Registro Academico (Seccion " + this.sec.getNum_secc() + ")");
Panel pan = new Panel("/Imagenes/imagen2.jpg", this.getWidth(), this.getHeight());
this.add(pan, BorderLayout.CENTER);
pan.setPreferredSize(new java.awt.Dimension(486, 273));
}
private void initGUI() {
try {
{
this.setFont(new java.awt.Font("DejaVu Sans Mono",0,10));
getContentPane().setForeground(new java.awt.Color(255,255,255));
this.setJMenuBar(jMenuBar1);
}
{
this.setJMenuBar(jMenuBar1);
}
{
jDesktopPane1 = new JDesktopPane();
getContentPane().add(jDesktopPane1, BorderLayout.CENTER);
jDesktopPane1.setPreferredSize(new java.awt.Dimension(390, 159));
{
jPopupMenu1 = new JPopupMenu();
setComponentPopupMenu(jDesktopPane1, jPopupMenu1);
}
{
jMenuItem2 = new JMenuItem();
jDesktopPane1.add(jMenuItem2, JLayeredPane.DEFAULT_LAYER);
jMenuItem2.setText("jMenuItem2");
}
}
this.setSize(598, 433);
{
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
{
jMenu1 = new JMenu();
jMenuBar1.add(jMenu1);
jMenu1.setText("Registrar");
{
Estudiante = new JMenuItem();
jMenu1.add(Estudiante);
Estudiante.setText("Estudiante");
Estudiante.addActionListener(VentEst);
}
{
RProfesor = new JMenuItem();
jMenu1.add(RProfesor);
RProfesor.setText("Profesor");
RProfesor.addActionListener(Ventprof);
}
}
{
jMenu4 = new JMenu();
jMenuBar1.add(jMenu4);
jMenu4.setText("Evaluar");
{
AplicarEvaluaciones = new JMenuItem();
jMenu4.add(AplicarEvaluaciones);
AplicarEvaluaciones.addActionListener(Evaluar);
AplicarEvaluaciones.setText("Aplicar Evaluaciones");
}
}
{
jMenu3 = new JMenu();
jMenu3.setText("Reportes");
jMenuBar1.add(jMenu3);
{
jMenu4 = new JMenu();
jMenu4.setText("Estudiantes");
jMenu3.add(jMenu4);
{
LGeneral = new JMenuItem();
jMenu4.add(LGeneral);
LGeneral.setText("General");
LGeneral.addActionListener(rep_general);
}
{
LAprobados = new JMenuItem();
jMenu4.add(LAprobados);
LAprobados.setText("Aprobados");
LAprobados.addActionListener(rep_aprob);
}
{
LAplazados = new JMenuItem();
jMenu4.add(LAplazados);
LAplazados.setText("Aplazados");
LAplazados.addActionListener(rep_aplaz);
}
{
jMenu2 = new JMenu();
jMenu4.add(jMenu2);
jMenu2.setText("Ordenar Por");
{
jRadioButtonOrdenarCed = new JRadioButtonMenuItem();
jMenu2.add(jRadioButtonOrdenarCed);
jRadioButtonOrdenarCed.setText("Cedula");
}
{
jRadioButtonOrdenarNot = new JRadioButtonMenuItem();
jMenu2.add(jRadioButtonOrdenarNot);
jRadioButtonOrdenarNot.setText("Nota Final");
}
}
}
}
{
jMenu6 = new JMenu();
jMenuBar1.add(jMenu6);
jMenu6.setText("Salir");
jRadioButtonOrdenarCed.addActionListener(opc_ced);
jRadioButtonOrdenarNot.addActionListener(opc_nota);
{
JMenuItem Salir = new JMenuItem("Salir");
jMenu6.add(Salir);
Salir.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent evento )
{
System.exit( 0 );
}
}
);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Auto-generated method for setting the popup menu for a component
*/
private void setComponentPopupMenu(final java.awt.Component parent, final javax.swing.JPopupMenu menu) {
parent.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent e) {
if(e.isPopupTrigger())
menu.show(parent, e.getX(), e.getY());
}
public void mouseReleased(java.awt.event.MouseEvent e) {
if(e.isPopupTrigger())
menu.show(parent, e.getX(), e.getY());
}
});
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/FramePrincipal.java | Java | asf20 | 9,180 |
public class Estudiante extends Persona implements Evaluado
{
private
float notas[] = new float[3];
float nota_final;
boolean estado;
public Estudiante(){}
public Estudiante(long cedula, String nombre, String apellido)
{
super(cedula, nombre, apellido);
}
public float[] getNotas()
{
return notas;
}
public void setNotas(float[] notas)
{
this.notas = notas;
}
public float getNota_final()
{
return nota_final;
}
public void setNota_final(float nota_final)
{
this.nota_final = nota_final;
}
public boolean getEstado()
{
return estado;
}
public void setEstado(boolean estado)
{
this.estado = estado;
}
public void presentarEvaluacion()
{
for(int i=0; i<=2; i++)
notas[i] = (float)Math.floor(Math.random()*20);
}
} | 03-3-segundaentrega | trunk/Segunda_Entrega/src/Estudiante.java | Java | asf20 | 820 |
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.SwingUtilities;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FrameSeccion extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton BTRegistrar;
private JTextField TXTnumero;
private JLabel jLabel1;
public FrameSeccion() {
super();
initGUI();
}
ActionListener Registrar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Cerrar();
}
};
private void Cerrar()
{
Seccion sec = new Seccion(this.TXTnumero.getText());
FramePrincipal Principal = new FramePrincipal(sec);
Principal.setVisible(true);
Principal.setLocationRelativeTo(null);
this.dispose();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
this.setTitle("Registrar Seccion");
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1);
jPanel1.setBounds(41, 20, 264, 112);
jPanel1.setLayout(null);
jPanel1.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
{
jLabel1 = new JLabel();
jPanel1.add(jLabel1);
jLabel1.setText("Ingrese el número de la Seccion");
jLabel1.setBounds(21, 13, 254, 15);
}
{
TXTnumero = new JTextField();
jPanel1.add(TXTnumero);
TXTnumero.setBounds(48, 42, 168, 22);
}
{
BTRegistrar = new JButton();
jPanel1.add(BTRegistrar);
BTRegistrar.setText("Registrar");
BTRegistrar.setBounds(75, 73, 104, 27);
BTRegistrar.setFont(new java.awt.Font("Bitstream Charter",1,12));
BTRegistrar.addActionListener(Registrar);
}
}
pack();
this.setSize(353, 188);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/FrameSeccion.java | Java | asf20 | 2,593 |
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.SwingUtilities;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FrameEstudiante extends javax.swing.JFrame {
private JPanel jPanel1;
private JLabel jLabel1;
private JButton BTBuscar;
private JWindow jWindow1;
private JTextField TxtApellido;
private JLabel jLabel8;
private JLabel jLabel7;
private JTextField TxtNombre;
private JTextField TxtCedula;
private JLabel jLabel6;
private JButton BTCancelar;
private JButton BTEliminar;
private JButton BTIncluir;
private JButton BTBorrar;
private Seccion sec;
public FrameEstudiante(Seccion sec) {
super();
this.sec = sec;
initGUI();
}
public FrameEstudiante() {
super();
initGUI();
}
ActionListener AccBuscar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Buscar();
}
};
public void Buscar()
{
if(this.TxtCedula.getText().equals(""))
JOptionPane.showMessageDialog(null,"Debe ingresar una cedula", "Error", JOptionPane.ERROR_MESSAGE);
else
{
try
{
int x = this.sec.Buscar((long)Integer.parseInt(TxtCedula.getText()));
if(x == -1)
{
this.BTIncluir.setEnabled(true);
this.BTEliminar.setEnabled(false);
this.BTBuscar.setEnabled(false);
this.BTBorrar.setEnabled(true);
this.TxtCedula.setEditable(false);
this.TxtApellido.setEditable(true);
this.TxtNombre.setEditable(true);
this.TxtNombre.setFocusable(true);
}
else
{
Estudiante e = this.sec.getEstudiante(x);
TxtCedula.setText(Long.toString(this.sec.getEstudiante(x).getCedula()));
TxtNombre.setText(e.getNombre());
TxtApellido.setText(e.getApellido());
this.BTIncluir.setEnabled(false);
this.BTBuscar.setEnabled(false);
this.BTBorrar.setEnabled(true);
this.BTEliminar.setEnabled(true);
this.TxtCedula.setEditable(false);
this.TxtApellido.setEditable(true);
this.TxtNombre.setEditable(true);
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE);
Borrar();
}
}
}
ActionListener Incluir = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
IncluirEst();
}
};
public void IncluirEst()
{
try
{
if(this.TxtApellido.getText().equals("") || this.TxtNombre.getText().equals(""))
JOptionPane.showMessageDialog(null,"Debe llenar todos los datos para poder inscribir un estudiante", "Faltan Datos", JOptionPane.ERROR_MESSAGE);
else
{
Estudiante e = new Estudiante((long)Integer.parseInt(TxtCedula.getText()),
TxtNombre.getText(),TxtApellido.getText());
this.sec.InscribirEstudiantes(e);
JOptionPane.showMessageDialog(null,"El Estudiante fué incluido con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE);
Borrar();
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE);
Borrar();
}
}
ActionListener Borrar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
BTBorrar.setMnemonic(KeyEvent.VK_B);
Borrar();
}
};
public void Borrar()
{
TxtCedula.setText("");
TxtNombre.setText("");
TxtApellido.setText("");
this.BTIncluir.setEnabled(false);
this.BTBuscar.setEnabled(true);
this.BTBorrar.setEnabled(true);
this.BTEliminar.setEnabled(false);
this.TxtCedula.setEditable(true);
this.TxtApellido.setEditable(false);
this.TxtNombre.setEditable(false);
}
ActionListener Eliminar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Elimina();
}
};
public void Elimina()
{
this.sec.RetirarEstudiante(this.sec.Buscar((long)Integer.parseInt(this.TxtCedula.getText())));
JOptionPane.showMessageDialog(null,"El Estudiante fué Eliminado con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE);
Borrar();
}
ActionListener Cancelar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Cerrar();
}
};
public void Cerrar()
{
this.dispose();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(Color.white);
this.setTitle("Estudiante");
{
BTIncluir = new JButton();
getContentPane().add(BTIncluir);
BTIncluir.setText("Incluir");
BTIncluir.setBounds(24, 212, 79, 29);
BTIncluir.addActionListener(Incluir);
}
{
BTCancelar = new JButton();
getContentPane().add(BTCancelar);
BTCancelar.setText("Salir");
BTCancelar.setBounds(344, 212, 79, 29);
BTCancelar.addActionListener(Cancelar);
}
{
BTBorrar = new JButton();
getContentPane().add(BTBorrar);
BTBorrar.setText("Borrar");
BTBorrar.setBounds(230, 212, 80, 29);
BTBorrar.addActionListener(Borrar);
}
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1);
jPanel1.setBounds(34, 50, 372, 139);
jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
jPanel1.setLayout(null);
jPanel1.setOpaque(false);
{
jLabel8 = new JLabel();
jPanel1.add(jLabel8);
jLabel8.setText("Cedula");
jLabel8.setBounds(25, 28, 64, 15);
jLabel8.setFont(new java.awt.Font("DejaVu Sans",0,14));
}
{
jLabel6 = new JLabel();
jPanel1.add(jLabel6);
jLabel6.setText("Apellido");
jLabel6.setBounds(23, 100, 79, 15);
jLabel6.setFont(new java.awt.Font("DejaVu Sans",0,14));
}
{
jLabel7 = new JLabel();
jPanel1.add(jLabel7);
jLabel7.setText("Nombre");
jLabel7.setBounds(23, 62, 79, 15);
jLabel7.setFont(new java.awt.Font("DejaVu Sans",0,14));
}
{
TxtCedula = new JTextField();
jPanel1.add(TxtCedula);
TxtCedula.setBounds(105, 22, 137, 22);
}
{
TxtNombre = new JTextField();
jPanel1.add(TxtNombre);
TxtNombre.setBounds(105, 57, 137, 22);
}
{
TxtApellido = new JTextField();
jPanel1.add(TxtApellido);
TxtApellido.setBounds(105, 95, 137, 22);
}
{
BTBuscar = new JButton();
jPanel1.add(BTBuscar);
BTBuscar.setText("Buscar");
BTBuscar.setBounds(266, 22, 83, 22);
BTBuscar.addActionListener(AccBuscar);
}
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("Datos del Estudiante");
jLabel1.setBounds(69, 12, 310, 32);
jLabel1.setFont(new java.awt.Font("Bitstream Charter",1,26));
}
{
BTEliminar = new JButton();
getContentPane().add(BTEliminar);
BTEliminar.setText("Eliminar");
BTEliminar.setBounds(125, 212, 80, 29);
BTEliminar.addActionListener(Eliminar);
}
pack();
this.setSize(448, 306);
Borrar();
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
| 03-3-segundaentrega | trunk/Segunda_Entrega/src/FrameEstudiante.java | Java | asf20 | 8,125 |
import java.util.*;
public class Seccion
{
private
Profesor prof;
String num_secc;
boolean prof_reg = false;
Vector<Estudiante> Estudiantes = new Vector<Estudiante>(0);
public Seccion()
{
super();
prof = new Profesor();
}
public Seccion(String s)
{
super();
num_secc = s;
prof = new Profesor();
}
public boolean getProfReg()
{
return prof_reg;
}
public void setProfReg(boolean c)
{
prof_reg = c;
}
public String getNum_secc()
{
return num_secc;
}
public void setNum_secc(String num_secc)
{
this.num_secc = num_secc;
}
public Profesor getProf()
{
return prof;
}
public void setProf(long c,String n,String a,String t)
{
this.prof = new Profesor(c,n,a,t);
}
public Estudiante getEstudiante(int i)
{
return Estudiantes.elementAt(i);
}
public Vector<Estudiante> getEstudiantes()
{
return Estudiantes;
}
public Vector<Estudiante> getEstudiantesAprob()
{
Vector<Estudiante> Est = new Vector<Estudiante>(0);
for(int i = 0;i < NumeroEstudiante();i++)
if(Estudiantes.elementAt(i).getEstado())
Est.add(Estudiantes.elementAt(i));
return Est;
}
public Vector<Estudiante> getEstudiantesAplaz()
{
Vector<Estudiante> Est = new Vector<Estudiante>(0);
for(int i = 0;i < NumeroEstudiante();i++)
if(!Estudiantes.elementAt(i).getEstado())
Est.add(Estudiantes.elementAt(i));
return Est;
}
public void InscribirEstudiantes(Estudiante e)
{
Estudiantes.add(e);
}
public int Buscar(long ced)
{
for(int i = 0;i < NumeroEstudiante();i++)
if(Estudiantes.elementAt(i).getCedula() == ced)
return i;
return -1;
}
public void RetirarEstudiante(int x)
{
Estudiantes.removeElementAt(x);
}
public int NumeroEstudiante(){
return Estudiantes.size();
}
public void AplicarEvaluaciones()
{
for(int i = 0;i < NumeroEstudiante();i++)
Estudiantes.elementAt(i).presentarEvaluacion();
}
public void EvaluarEstuduantes()
{
for(int i = 0;i < NumeroEstudiante();i++)
this.prof.EvaluarEstudiante(Estudiantes.elementAt(i));
}
public float Promedio()
{
float t = 0;
for(int i = 0;i < NumeroEstudiante();i++)
t += Estudiantes.elementAt(i).getNota_final();
return t / NumeroEstudiante();
}
public void OrdenarEstudianteNota()
{
int x = 1;
Estudiante est = new Estudiante();
boolean ordenar;
do
{
ordenar = false;
for(int i = 0;i < NumeroEstudiante()-x;i++)
if(Estudiantes.elementAt(i).getNota_final() < Estudiantes.elementAt(i+1).getNota_final())
{
est = Estudiantes.elementAt(i);
Estudiantes.setElementAt(Estudiantes.elementAt(i+1),i);
Estudiantes.setElementAt(est,i+1);
ordenar = true;
}
x++;
}while(ordenar);
}
public void OrdenarEstudianteCed()
{
int x = 1;
Estudiante est = new Estudiante();
boolean ordenar;
do
{
ordenar = false;
for(int i = 0;i < NumeroEstudiante()-x;i++)
if(Estudiantes.elementAt(i).getCedula() > Estudiantes.elementAt(i+1).getCedula())
{
est = Estudiantes.elementAt(i);
Estudiantes.setElementAt(Estudiantes.elementAt(i+1),i);
Estudiantes.setElementAt(est,i+1);
ordenar = true;
}
x++;
}while(ordenar);
}
} | 03-3-segundaentrega | trunk/Segunda_Entrega/src/Seccion.java | Java | asf20 | 3,334 |
package com.risk.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The async counterpart of <code>GreetingService</code>.
*/
public interface GreetingServiceAsync
{
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
}
| 11durong-test | src/com/risk/client/GreetingServiceAsync.java | Java | mit | 300 |
package com.risk.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService
{
String greetServer(String name) throws IllegalArgumentException;
}
| 11durong-test | src/com/risk/client/GreetingService.java | Java | mit | 362 |
package com.risk.client;
import com.risk.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Risk_online implements EntryPoint
{
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler
{
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event)
{
sendNameToServer();
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event)
{
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
{
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer()
{
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer))
{
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer,
new AsyncCallback<String>()
{
public void onFailure(Throwable caught)
{
// Show the RPC error message to the user
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel
.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result)
{
dialogBox
.setText("Remote Procedure Call");
serverResponseLabel
.removeStyleName("serverResponseLabelError");
serverResponseLabel
.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
| 11durong-test | src/com/risk/client/Risk_online.java | Java | mit | 7,279 |
package com.risk.shared;
/**
* <p>
* FieldVerifier validates that the name the user enters is valid.
* </p>
* <p>
* This class is in the <code>shared</code> packing because we use it in both
* the client code and on the server. On the client, we verify that the name is
* valid before sending an RPC request so the user doesn't have to wait for a
* network round trip to get feedback. On the server, we verify that the name is
* correct to ensure that the input is correct regardless of where the RPC
* originates.
* </p>
* <p>
* When creating a class that is used on both the client and the server, be sure
* that all code is translatable and does not use native JavaScript. Code that
* is note translatable (such as code that interacts with a database or the file
* system) cannot be compiled into client side JavaScript. Code that uses native
* JavaScript (such as Widgets) cannot be run on the server.
* </p>
*/
public class FieldVerifier
{
/**
* Verifies that the specified name is valid for our service.
*
* In this example, we only require that the name is at least four
* characters. In your application, you can use more complex checks to ensure
* that usernames, passwords, email addresses, URLs, and other fields have the
* proper syntax.
*
* @param name the name to validate
* @return true if valid, false if invalid
*/
public static boolean isValidName(String name)
{
if (name == null)
{
return false;
}
return name.length() > 3;
}
}
| 11durong-test | src/com/risk/shared/FieldVerifier.java | Java | mit | 1,584 |
package com.risk.server;
import com.risk.client.GreetingService;
import com.risk.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService
{
public String greetServer(String input) throws IllegalArgumentException
{
// Verify that the input is valid.
if (!FieldVerifier.isValidName(input))
{
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException(
"Name must be at least 4 characters long");
}
String serverInfo = getServletContext().getServerInfo();
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
// Escape data from the client to avoid cross-site script vulnerabilities.
input = escapeHtml(input);
userAgent = escapeHtml(userAgent);
return "Hello, " + input + "!<br><br>I am running " + serverInfo +
".<br><br>It looks like you are using:<br>" + userAgent;
}
/**
* Escape an html string. Escaping data received from the client helps to
* prevent cross-site script vulnerabilities.
*
* @param html the html string to escape
* @return the escaped string
*/
private String escapeHtml(String html)
{
if (html == null)
{
return null;
}
return html.replaceAll("&", "&").replaceAll("<", "<")
.replaceAll(">", ">");
}
}
| 11durong-test | src/com/risk/server/GreetingServiceImpl.java | Java | mit | 1,733 |
/** Add css rules here for your application. */
/** Example rules used by the template application (remove for your app) */
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.sendButton {
display: block;
font-size: 16pt;
}
/** Most GWT widgets already have a style name defined */
.gwt-DialogBox {
width: 400px;
}
.dialogVPanel {
margin: 5px;
}
.serverResponseLabelError {
color: red;
}
/** Set ids using widget.getElement().setId("idOfElement") */
#closeButton {
margin: 15px 6px 6px;
}
| 11durong-test | war/Risk_online.css | CSS | mit | 568 |
<!doctype html>
<!-- The DOCTYPE declaration above will set the -->
<!-- browser's rendering engine into -->
<!-- "Standards Mode". Replacing this declaration -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout. -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!-- -->
<link type="text/css" rel="stylesheet" href="Risk_online.css">
<!-- -->
<!-- Any title is fine -->
<!-- -->
<title>Web Application Starter Project</title>
<!-- -->
<!-- This script loads your compiled module. -->
<!-- If you add any GWT meta tags, they must -->
<!-- be added before this line. -->
<!-- -->
<script type="text/javascript" language="javascript" src="risk_online/risk_online.nocache.js"></script>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic UI. -->
<!-- -->
<body>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
<h1>Web Application Starter Project</h1>
<table align="center">
<tr>
<td colspan="2" style="font-weight:bold;">Please enter your name:</td>
</tr>
<tr>
<td id="nameFieldContainer"></td>
<td id="sendButtonContainer"></td>
</tr>
<tr>
<td colspan="2" style="color:red;" id="errorLabelContainer"></td>
</tr>
</table>
</body>
</html>
| 11durong-test | war/Risk_online.html | HTML | mit | 2,611 |